Animoの書き出しJSFL修正

Animoからタイムラインをかき出すJSFLを修正しました。

```javascript
var doc = fl.getDocumentDOM();

function clearOut() {
    fl.outputPanel.clear();
}

function out(_msg) {
    fl.trace(_msg)
}

var layoutScript = "";

function outl(_s) {
    layoutScript += _s + "\n";
}

function getFolder(_msg) {
    if (_msg == null) {
        _msg = 'Select a folder';
    }
    return fl.browseForFolderURL(_msg);
}

function getFile(_msg) {
    if (_msg == null) {
        _msg = 'Select a file';
    }
    return fl.browseForFileURL("save", _msg);
}

function saveLayout(_msg) {
    if (_msg == null) {
        _msg = 'Select a file';
    }
    var filename = getFile(_msg);
    if (filename != null) {
        fl.outputPanel.save(filename);
        clearOut();
    }
}

String.prototype.escape = function() {
    return this.replace(/[\s|-]/g, "_");
}

String.prototype.nl = function() {
    return this + "\n";
}

function newGroup(_name) {
    return "groups['"+ _name + "'] = display.newGroup()";
}

function insertInGroup(_groupName, _elementName) {
    return "groups['"+ _groupName +"']:insert("+ _elementName +")";
}

function setupElement(_groupName, _element) {
    var output = [];
    var ename = _element.name;
    var gname = _groupName;

    var symbolType = _element.symbolType;
    var libItemType = _element.libItem.itemType;
    var libItemName = _element.libItem.name.split("/").reverse()[0];
    var inIgnore = _element.libItem.name.indexOf("ignore") != -1;

    if (inIgnore) {
        // skipping creation because in ignore folder
        output.unshift("\t-- ignored sprite");
        output.push("\t-- element " +ename+ "'s type: "+ libItemName +" is in ignore folder.");
        
        output.push("\telements."+ename+" = display.newGroup()");

    } else if (symbolType == "button" && libItemType == "button") {

        // create a button using loq_ui_button
        var frameArray = _element.libItem.timeline.layers[0].frames;

        if (frameArray.length > 0) {

            // Check that the frame elements are symbol instances and there's only one.
            if (frameArray[0].elements[0].elementType != "instance") {
                var errorMsg = "Could not create button for  "+ename +".  The 'up' frame must contain only 1 Symbol instance.";
                alert(errorMsg);
                return errorMsg;
            }

            if (frameArray[0].elements.length > 1) {
                var errorMsg = "Could not create button for  "+ename +".  The 'up' frame must contain only 1 Symbol instance.";
                alert(errorMsg);
                return errorMsg;
            }
            var upSpriteName = frameArray[0].elements[0].libraryItem.name.split("/").reverse()[0];

            if (frameArray.length >= 3 && frameArray[2].elements[0].elementType != "instance") {
                var errorMsg = "Could not create button for  "+ename +".  The 'down' frame must contain only 1 Symbol instance.";
                alert(errorMsg);
                return errorMsg;
            }

            if (frameArray.length >= 3 && frameArray[2].elements.length > 1) {
                var errorMsg = "Could not create button for  "+ename +".  The 'down' frame must contain only 1 Symbol instance.";
                alert(errorMsg);
                return errorMsg;
            }
            var downSpriteName = (frameArray.length >= 3 ? frameArray[2].elements[0].libraryItem.name.split("/").reverse()[0] : upSpriteName);

            output.unshift("\t-- new button");
            
            output.push("\telements." + ename + " = loqbutton.newButton {"); 
            output.push("\t\tspriteGroup = _spriteFactory:newSpriteGroup('"+ upSpriteName +"'),"); 
            output.push("\t\tup = '"+ upSpriteName +"',"); 
            output.push("\t\tdown = '"+ downSpriteName +"',"); 
            output.push("\t}"); 

        } else {
            output.unshift("\t-- new button ERROR");
            output.push("\t-- Could not create button for "+ ename +". Missing symbol for up state.");
            output.push("");

            return output.join("\n");
        }

    } else if (ename.toLowerCase().indexOf("btn") != -1 || ename.toLowerCase().indexOf("button") != -1) {

        var upSpriteName = libItemName;
        var downSpriteName = libItemName;
        
        output.unshift("\t-- new button");
        output.push("\telements." + ename + " = loqbutton.newButton {"); 
        output.push("\t\tspriteGroup = _spriteFactory:newSpriteGroup('"+ upSpriteName +"'),"); 
        output.push("\t\tup = '"+ upSpriteName +"',"); 
        output.push("\t\tdown = '"+ downSpriteName +"',"); 
        output.push("\t}"); 

    } else if (symbolType == "movie clip" && !inIgnore) {
        output.unshift("\t-- new sprite");
        output.push("\telements."+ename+" = _spriteFactory:newSpriteGroup(\"" + libItemName + "\")");

    } else if (symbolType == "graphic" && !inIgnore) {
        output.unshift("\t-- new sprite");
        output.push("\telements."+ename+" = _spriteFactory:newSpriteGroup(\"" + libItemName + "\")");
        if (libItemType == "movie clip") {
            output.push("\telements."+ename+":currentFrame(" + _element.firstFrame + ")");
        }
    } 
    output.push("\tgroup = elements."+ename);
    output.push("\tgroups['"+libItemName+"'] = group");    

    output.push("\tgroup.x = "+ Math.round(_element.x));
    output.push("\tgroup.y = "+ Math.round(_element.y));

    
    if (_element.skewY == 180 && _element.rotation != 180) {
        output.push("\tgroup.xScale = -1");
    }else{
        output.push("\tgroup.xScale = "+ (Math.floor(_element.scaleX*100)/100));    
    }
    
    if (_element.skewX == 180 && _element.rotation != 180) {
        output.push("\tgroup.yScale = -1");
    }else{
        output.push("\tgroup.yScale = "+ (Math.floor(_element.scaleY*100)/100));
    }

     if (!isNaN(_element.rotation)) {
        output.push("\tgroup.rotation = "+ (Math.floor(_element.rotation*100)/100));
     }

    if (_element.alpha != 1) {
        output.push("\tgroup.alpha = "+ _element.alpha);
    }
    output.push("");

    return output.join("\n");
}

function clearGroup(_name) {
    return "\tgroups['"+_name+"']:removeSelf()";
}

function clearElement(_name) {
    return "\tremoveElements(groups['"+_name+"'])";    
}

function generateLayout(_tl) {

    clearOut();
    layoutScript = "";

    var tl = _tl;
        
    if (tl == null) {
        tl = doc.getTimeline();
    }

    // go frame by frame creating a layout file for each frame
    // go through each of the layers in reverse and create groups for each of the layers

    var layouts = [];
    var elementIndex = 0;

    for (fdx = 0; fdx < tl.frameCount; ++fdx) {

        var layout = {script: "", groups: []};

        for (ldx = 0; ldx < tl.layerCount; ++ldx) {
            var layer = tl.layers[ldx];

            if (layer.layerType != 'normal') {
                continue;
            }

            var group = {name: layer.name || ("_layer"+(tl.layerCount - ldx +1)), elements: []}

            var frameArray = layer.frames;
            if (fdx < frameArray.length) {
                var frame = frameArray[fdx];
                
                if (fdx == frame.startFrame) {

                    // adds corona script here only for keyframes
                    var scriptlines = frame.actionScript.split("\r");
                    var cleanScript = [];
                    for(sdx = 0; sdx < scriptlines.length; ++sdx) {
                        if (scriptlines[sdx] != "") {
                            cleanScript.push(scriptlines[sdx]);
                        }
                    }
                    layout.script += cleanScript.join("");

                    // we have a keyframe get all the elements, and store it into the group
                    
                    var elements = frame.elements;
                    for (edx = 0; edx < elements.length; ++edx) {
                        var element = elements[edx];
                        if (element.elementType == "instance") {
                            var libItem = element.libraryItem;
                            // filtering the element properties for easier processing
                            var ename = (element.name || ("_element"+elementIndex)); 
                            elementIndex += 1;
                            group.elements.push({
                                name: ename,
                                symbolType: element.symbolType,
                                firstFrame: (element.firstFrame ? element.firstFrame + 1 : 1),
                                libItem: libItem,
                                x: element.x,
                                y: element.y,
                                left: element.left,
                                top: element.top,
                                width: element.width,
                                height: element.height,
                                rotation: element.rotation,
                                scaleX: element.scaleX,
                                scaleY: element.scaleY,
                                alpha: element.colorAlphaPercent / 100,
                                skewX: element.skewX,
                                skewY: element.skewY,
                                matrix: element.matrix,
                                layer: element.layer,
                                depth: element.depth,
                                transformX: element.transformX,
                                transformY: element.transformY
                            });
                        }
                    }
                }
            }

            if (group.elements.length > 0) {
                layout.groups.push(group);
            }
        }

        layouts.push(layout);
    }
    outl("local loqbutton = require(\"loq_ui_button\")");
    outl("");
    outl("local groups = nil ");
    outl("local dimensions = nil ");
    outl("local elements = nil ");
    outl("");
    outl("local function createLayout(_spriteFactory,num)");
    outl("\tassert(_spriteFactory ~= nil, \"Error in createLayout: _spriteFactory argument cannot be nil\")");
    outl("\t--layout");
    
    var stack = [];
    for (ldx = 0; ldx < layouts.length; ++ldx) {
        // create a new layout
        var layoutName = "layout"+ ldx;
        var filename = layoutName+".lua";
        var layout = layouts[ldx]; 

        if (layout.groups.length > 0) {
            //ここから
            if(ldx == 0){
                outl("if "+ldx+" == num then ");    
            }else{
                outl("elseif "+ldx+" == num then "); 
            }
            outl("\t\tgroups = {}");
            outl("\t\tdimensions = {}");
            outl("\t\telements = {}");
            outl("\t\tlocal group = nil")

            var groups = layout.groups.reverse();

            for (gdx = 0; gdx < groups.length; ++gdx) {
                var group = groups[gdx];
                var elements = group.elements;
                outl("\t\t-- new group");
                for (edx = 0; edx < elements.length; edx++) {
                    outl(setupElement(group.name, elements[edx]).nl());
                }
            }
        }
    }
    outl("else return false end\n");    
    
    outl("\t-- end layout");
    outl("\treturn {groups = groups, dimensions = dimensions, elements = elements}");
    outl("end\n");

    outl("return {");
    outl("\tcreateLayout = createLayout");
    outl("\t}");
    
    var layouttxt = layoutScript;
    layoutScript = "";
    return layouttxt;
}

/**
 * ここが初期処理
 */
function generateSelectedLayouts() {
    var fileurl = fl.browseForFileURL('save', "Select a file");
    var layout = generateLayout();
    /*for(var l in layout){
            FLfile.write(fileurl+l+'.lua', layout[l]);
    }*/
    FLfile.write(fileurl, layout);
    clearOut();
    out("created " + fileurl);
}

generateSelectedLayouts();

```

前のバージョンで無駄にたくさんファイルを吐いていたのですが、これでひとつのMCのタイムラインを1ファイルで表現できます。
コレですんげーはやくなりました（曖昧)。

で、実行方法もちょっと変わりました。

```anim.lua
--[[
    単純な演出用
]]--
local loqsprite = require('loq_sprite')

local anim ={
    
    init = function(self,layout,num)
        local animObj = {}
        animObj.anim = require(layout)
        animObj.cnt = num
        animObj.k= function(img,g) 
            return {
                stack ={},
                notUsed ={},
                grp = g,
                i = img,
                newSpriteGroup = function(self,name)
                    if self.stack[name] == nil then
                        self.stack[name] = self.i:newSpriteGroup(name)
                        self.grp:insert(self.stack[name])
                    end
                    if self.notUsed[name] ~= nil then
                        self.notUsed[name] = false
                    end

                    self.stack[name].alpha = 1
                    return self.stack[name]
                end         
            }
            end
       return animObj
    end
    
}
return anim
```

上記をrequireし

```lua
        --格納用Group
        local grp = display.newGroup()

        local a = anim:init('JSFLでかき出したlua',25)
        local img     = loqsprite.newFactory('animoでかき出したlua')
        local obj = self.lvUpAnim.k(img,grp)  

        local num = 0
---として、あとはメインループ的なところで
     
     a.anim.createLayout(obj,num)
    
----という感じでコマを送る。
----numがタイムラインの終わりを超えたら終了になる処理を入れてやる。

```

みたいな感じ…。ちょっと説明が不親切すぎますね…。
まあ、そんな感じで…。