Flash loading first external swf loaded - actionscript-3

I am making an application to test art from a game I volunteered for. Right now the example I am posting will only touch the armors but the loading process is the same throughout the program. I have a movieclip ready to hold the loaded file but it adds it to the container via the class. It works how it should however my issue is that if you use another file with the same classes then it will default to the first file loaded. Even i use loaderr.unloadAndStop() and remove everything from the stage, it will always load the first file that corresponds to the class I am loading by. Since the armor pieces are loaded by class it makes it a hassle to test multiple changes to an armor file without changing the classes on each export. Here is an example of the code that is being used and I am curious if there is any way that I can improve this. `
public class Test extends MovieClip
{
public var mcChar:Display;
public var btnTest:SimpleButton;
public var btnTest2:SimpleButton;
public var ldr:Loader = new Loader();
public var strSkinLinkage:String;
public var strGender:String;
public function Test()
{
btnTest.addEventListener(MouseEvent.CLICK, TestP);
btnTest2.addEventListener(MouseEvent.CLICK, TestP2);
}
public function TestP(e:MouseEvent)
{
mcChar = new Display();
stage.addChild(mcChar);
mcChar.x = 789.6;
mcChar.y = 604.75;
mcChar.width = 667.15;
mcChar.height = 478.55;
strSkinLinkage = "CNC";
strGender = "M"
this.ldr.load(new URLRequest("CNC.SWF"), new LoaderContext(false, ApplicationDomain.currentDomain));
this.ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, this.onLoadSkinComplete);
}
public function TestP2(e:MouseEvent)
{
mcChar = new Display();
stage.addChild(mcChar);
mcChar.x = 789.6;
mcChar.y = 604.75;
mcChar.width = 667.15;
mcChar.height = 478.55;
strSkinLinkage = "CNC";
strGender = "M"
this.ldr.load(new URLRequest("CNC2.SWF"), new LoaderContext(false, ApplicationDomain.currentDomain));
this.ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, this.onLoadSkinComplete);
}
public function onLoadSkinComplete(e:Event):*
{
var AssetClass:Class;
try
{
AssetClass = (getDefinitionByName(((strSkinLinkage + strGender) + "Head")) as Class);
mcChar.head.addChildAt(new (AssetClass)(), 0);
}
catch(err:Error)
{
AssetClass = (getDefinitionByName(("mcHead" + strGender)) as Class);
mcChar.head.addChildAt(new (AssetClass)(), 0);
};
AssetClass = (getDefinitionByName(((strSkinLinkage + strGender) + "Chest")) as Class);
chest.addChild(ldr.content (AssetClass)());
mcChar.chest.addChild(new (chest)());
this.ldr.contentLoaderInfo.removeEventListener(Event.COMPLETE, this.onLoadSkinComplete);
}
}
`
I don't think its well formatted on this site but this is the core code. I have separate removal functions and my imports are all there. Like I said I cant seem to get it to format correctly. This is my test scenario and isn't my full dynamic tester where I can choose the file. Any help in figuring out how to use the most recent file is appreciated. Also for some background I am more of a self taught novice in as3.

When it gets to loading and unloading assets in AS3, there are several things to learn.
ApplicationDomain is a container for class definitions. The getDefinitionByName(...) method is basically the same as calling the ApplicationDomain.getDefinition(...) on the current ApplicationDomain (or maybe on the main ApplicationDomain, I never tried to do it in the loaded content). As the side result, you cannot have two classes with the same names inside the same ApplicationDomain (or rather you can, but one of them is inaccessible, who knows).
When you load another SWF which falls into the "same domain" category (same www domain, or same/nested local folder), AS3 automatically mixes all the definitions from the loaded SWF into the main ApplicationDomain. If you are willing to have some advanced control over loading/unloading stuff, or/and there are "skin" libraries that have similar sets of classes, you need to put the loaded files into separate ApplicationDomains or their definitions will collide and the result will be unpredictable (yet obviously not satisfactory).
The Loader.load(...) method has a second argument that allows you to do so:
// If there are no mandatory constructor arguments,
// you are free to omit the () brackets. I like doing so.
var aLoader:Loader = new Loader;
var aRequest:URLRequest = new URLRequest("mylibrary.swf");
// Documentation states that passing no argument here is
// the same as passing ApplicationDomain.currentDomain.
var childDomain:ApplicationDomain = new ApplicationDomain;
var aContext:LoaderContext = new LoaderContext(false, childDomain);
aLoader.load(aRequest, aContext);
Thus, when external SWF library is loaded, you can obtain its classes/definitions as following:
var aClass:Class;
// If you get things from the loaded SWF's Library
// then it is Sprite or MovieClip for the most cases.
var anAsset:Sprite;
aClass = aLoader.contentLoaderInfo.applicationDomain.getDefinition("MyAssetClass") as Class;
anAsset = new aClass;
When you do not longer need some of the loaded libraries, you call the Loader.unloadAndStop(...) method on the relevant Loader instance. Combined with the loading SWF into separate ApplicationDomain you can be sure that all of the loaded content (graphics, classes, sounds) is unloaded, destroyed and removed (that one I actually checked):
// Passing "true" also forces the Garbage Collector
// to actually do its job for a change.
aLoader.unloadAndStop(true);

Related

Using a Numeric Stepper from one Flash file to affect gamespeed in an external Flash file? Actionscript 3.0

Currently I have an intro screen to my flash file which has two objects.
A button which will load an external flash file using:
var myLoader:Loader = new Loader();
var url:URLRequest = new URLRequest("flashgame.swf");
The second thing is a Numeric Stepper, which will be from 1 to 10. If the user selects a number e.g. 3 then the game speed I have set in the flashgame.swf should be changed
Such as:
var gameSpeed:uint = 10 * numericStepper.value;
But I think my problem is coming into place because the stepper and gamespeed are from different files.
Anyone got any idea please?
I have also tried creating a stepper in the game file and used this code:
var gameLevel:NumericStepper = new NumericStepper();
gameLevel.maximum = 10;
gameLevel.minimum = 1;
addChild(gameLevel);
var gameSpeed:uint = 10 * gameLevel.value;
For some reason the stepper just flashes on the stage, no errors come up and the game doesn't work
When you execute you code, the stepper has no chance to wait for user input.
There is no time between theese two instructions.
addChild(gameLevel);
var gameSpeed:uint = 10 * gameLevel.value;
You should wait for user input in your NumericStepper, and then, on user event, set the game speed.
Edit: Yeah I know it's kinda sad to type out all this code (especially since some people wouldn't even be grateful enough to say thanks) but I think this question is important enough to justify the code as it may be helpful to others in future also.
Hi,
You were close. In your game file you could have put a var _setgameSpeed and then from Intro you could adjust it by flashgame._setgameSpeed = gameSpeed; It's a bit more complicated though since you also have to setup a reference to flashgame in the first place. Let me explain...
Ideally you want to put all your code in one place (an .as file would be best but...) if you would rather use timeline then you should create a new empty layer called "actions" and put all your code in the first frame of that.
Also change your button to a movieClip type and remove any code within it since everything will be controlled by the code in "actions" layer. In the example I have that movieclip on the stage with instance name of "btn_load_SWF"
Intro.swf (Parent SWF file)
var my_Game_Swf:MovieClip; //reference name when accessing "flashgame.swf"
var _SWF_is_loaded:Boolean = false; //initial value
var set_gameSpeed:int; //temp value holder for speed
var swf_loader:Loader = new Loader();
btn_load_SWF.buttonMode = true; //instance name of movieclip used as "load" button
btn_load_SWF.addEventListener(MouseEvent.CLICK, load_Game_SWF);
function load_Game_SWF (event:MouseEvent) : void
{
//set_gameSpeed = 10 * numericStepper.value;
set_gameSpeed = 100; //manual set cos I dont have the above numericStepper
if ( _SWF_is_loaded == true)
{
stage.removeChild(swf_loader);
swf_loader.load ( new URLRequest ("flashgame.swf") );
}
else
{ swf_loader.load ( new URLRequest ("flashgame.swf") ); }
swf_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, Game_SWF_ready);
}
function Game_SWF_ready (evt:Event) : void
{
swf_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, Game_SWF_ready);
//Treat the Loader contents (flashgame.swf) as a MovieClip named "my_Game_Swf"
my_Game_Swf = swf_loader.content as MovieClip;
my_Game_Swf.gameSpeed = set_gameSpeed; //update gameSpeed variable in flashgame.swf
//also adjust SWF placement (.x and .y positions etc) here if necessary
stage.addChild(my_Game_Swf);
_SWF_is_loaded = true;
}
Now in you flashgame file make sure the there's also an actions layers and put in code like this below then compile it first before debugging the Intro/Parent file. When your Intro loads the flashgame.swf it should load an swf that already has the code below compiled.
flashgame.swf
var gameSpeed:int;
gameSpeed = 0; //initial value & will be changed by parent
addEventListener(Event.ADDED_TO_STAGE, onAdded_toStage);
function onAdded_toStage (e:Event):void
{
trace("trace gameSpeed is.." + String(gameSpeed)); //confirm speed in Debugger
//*** Example usage ***
var my_shape:Shape = new Shape();
my_shape.graphics.lineStyle(5, 0xFF0000, 5);
my_shape.graphics.moveTo(10, 50);
my_shape.graphics.lineTo(gameSpeed * 10, 50); //this line length is affected by gameSpeed as set in parent SWF
addChild(my_shape);
}
The key line in intro.swf is this: my_Game_Swf.gameSpeed = set_gameSpeed; as it updates a variable in flashgame.swf (referred as my_Game_Swf) with an amount that is taken from a variable in the Parent SWF.
This is just one way you can access information between two separate SWF files. Hope it helps out.

embedding a font in a swf using as3

I have a project using flash (and AIR for android and eventuall iOS) for translating some phrases. Although most fonts are fine there are some that I have to load after the user has chosen the languages. Over a year ago I generated a couple of swf files (Bengali and Urdu) and put them on my web server. The flash application then loads them when required and everything is OK...
However as I am nearing implementing the project I thought I should generate the swf files for the other languages that are in the pipeline and for some reason I can't manage it! Needless to say I have misplaced (tidied) the original AS3 source for the two fonts I have done.
package
{
import flash.display.Sprite;
import flash.events.Event;
public class ArabicF extends Sprite
{
[Embed(source = "trado.ttf",
fontName = "ArabicX",
fontFamily = "ArabicY",
fontWeight = "normal",
fontStyle = "normal",
mimeType = "application/x-font",
advancedAntiAliasing="true",
embedAsCFF="true")]
public static const ArabicZ:Class;
}
}
This has expanded from a much simpler form as I added things to get it to work and I must have tried all permutations of true and false. I load the swf ok but then can't extract the class. With the two fonts I embedded before the swf class and the parameter all have the same name and they work fine (i.e.
Urdu.swf
then later:
var FontClass:Class = evt.target.applicationDomain.getDefinition("Urdu") as Class;
and then
Font.registerFont(FontClass.Urdu);
in the calling .as application with the above Arabic.swf I try
trace("1 Arabic "+evt.target.applicationDomain.hasDefinition("ArabicF"));
trace("2 Arabic "+evt.target.applicationDomain.hasDefinition("Arabic"));
trace("3 ArabicX "+evt.target.applicationDomain.hasDefinition("ArabicX"));
trace("4 ArabicY "+evt.target.applicationDomain.hasDefinition("ArabicY"));
trace("5 ArabicZ "+evt.target.applicationDomain.hasDefinition("ArabicZ"));
but all return false
PS also tried generating the Arabic.swf using fontswf.bat which again seems to make a very similar swf file which is loaded but I can't extract the class from it
PPS I'm using flashdevelop and the font swf are set up as AS3 standard project compiler options.
I don't use Flash Develop, but perhaps I can offer some perspective from my implementation.
If I wanted to embed Arial, the embedding swf would "Export for ActionScript" the embedded font. In its document class, use registerFont() as below:
Font.registerFont(Arial);
Like every other swf, you'd use a Loader to import it into your runtime, and at that point, the font will be available to your global table. You can query the complete list of registered fonts using enumerateFonts().
var fontList:Array = Font.enumerateFonts();
for (var i:int = 0; i < fontList.length; i++) {
trace(fontList[i].fontName);
}
Assuming we've got a TextField called "txt", you can then implement that font with setTextFormat() like so:
var format:TextFormat = new TextFormat();
format.font = "Arial";
txt.embedFonts = true;
txt.antiAliasType = AntiAliasType.ADVANCED;
txt.setTextFormat(format);
txt.defaultTextFormat = format;
A disclaimer from Adobe on the use of these last two settings:
"When you apply a TextFormat object to a text field using the
TextField.defaultTextFormat property or the TextField.setTextFormat()
method, only its defined properties are applied. Use the
TextField.defaultTextFormat property to apply formatting BEFORE you
add text to the TextField, and the setTextFormat() method to add
formatting AFTER you add text to the TextField."
As I said before, my workflow doesn't utilize Flash Develop, but rather Flash IDE to embed the fonts into the swfs. Your results may vary, but be aware you must set embedFonts to true, or it won't respond to your embedded font. I've lost hair on that issue before.
Hope that helps. Cheers,
OK In case someone else runs into similar problems this is stage one of the answer (really the answer to my original question) still have to sort out how to get the font to be used in the flash.font.engine apparatus!
The critical parts are:
Point #1. the embedded font swf must have a name that doesn't clash with ANY name registered in the calling script. Bizzare and (as far as I could search) undocumented. i.e. I have a list of languages uploaded via xml services to an xml object and that includes for instance 'English' however the font loading doesn't work until I make the loadable font file into 'EnglishF.swf' The obvious choice of just 'English.swf' fails. So my embedded font source is now called EnglishF.swf and reads:
package
{
import flash.display.Sprite;
import flash.text.Font;
import flash.system.Security;
Security.allowDomain("*");
/**
* ...
* #author patrick
*/
public class EnglishF extends Sprite
{
[Embed(source = "Kingthings Exeter.ttf",
fontName = "EnglishF",
fontFamily = "EnglishF",
fontWeight = "normal",
fontStyle = "normal",
mimeType = "application/x-font",
advancedAntiAliasing="true",
embedAsCFF="true")]
public static var myFont:Class;
}
}
and the using script goes:
private function fontLoaded(evt:Event):void {
var FontClass:Class
if (evt.target.applicationDomain.hasDefinition(font1Name)) FontClass = evt.target.applicationDomain.getDefinition(font1Name) as Class;
else if (evt.target.applicationDomain.hasDefinition(font2Name)) FontClass = evt.target.applicationDomain.getDefinition(font2Name) as Class;
try {
Font.registerFont(FontClass.myFont);
trace("successfully loaded " + FontClass);
} catch (err:Error) {
trace("couldn't register font "+FontClass.myFont+" =>"+err);
}
}
The line in the embedded script about security is because of point #2: the registerFont doesn't work across domains. In fact the Security.allowDomain() didn't work and to debug this I have had to copy/paste the swf files on the PC and change the loader.load(URLRequest()) accordingly
There is still an issue that although the font is registered and claims to be compatible with the flash.text.engine TextElement requirements it still fails to be used as in:
_tl = new Array();
var block:TextBlock = new TextBlock();
var font:FontDescription = new FontDescription(fontName);
var formt:ElementFormat = new ElementFormat(font, fontSize);
//following gives 'true EnglishF'
trace(FontDescription.isFontCompatible(fontName,"normal","normal"), formt.fontDescription.fontName);
formt.color = colr;
var span:TextElement = new TextElement(text, formt);
block.content = span;
_tl[0] = null;
_tl[0] = block.createTextLine(null, width);
var tl:TextLine;
// after here justification and addition lines
I will post something if and when I sort out why this doesn't work (Unless some kind person does it for me!)

AS#3 loading SWF Multiple

Im loading multiple SWF of the same file
Example:
var movies:Array = new Array ("Symbols/00.swf","Symbols/00.swf","Symbols/00.swf");
My loading method works fine, below im using:
var perc:int = (event.bytesLoaded / event.bytesTotal) * 100;
Loading.text = "loading " +perc + "%";
The Problem im having is the the loading text is at %100 after iv downloaded one item from the Movies:Array.
This would be happening because the remainder files are already in the catch.
The question is:
How would I be able to slow this loading text to determine if all the items are ready.Basically the problem is that the loading text saids complete but all my other files
are not ready yet...
First, why do you ever load one SWF multiple times? You can use the following trick: How to display multiple instances of loaded SWF. And second, you are using your Loader object to load one SWF at a time, and its progress will be related to that single SWF. So, you first load all unique SWFs and store their Loader references somewhere, in order to instantiate more of those if you need to, and second, you are to collect total percentage from progress event listener. The latter is slightly complicated, because you are most likely using a single progress event listener for all the loaders. You, for example, can do something like this:
public static var ALL_LOADERS:Object;
public static var PROGRESS_DATA:Object; // we need associative arrays here
public static var BYTES_LOADED:int=0;
public static var TOTAL_BYTES:int=0;
public static function RegisterLoader(path:String,loader:Loader):void {
if (!ALL_LOADERS) ALL_LOADERS=new Object();
if (!PROGRESS_DATA) PROGRESS_DATA=new Object();
ALL_LOADERS[path]=loader;
PROGRESS_DATA[loader]=new Object();
PROGRESS_DATA[loader].bytesLoaded=0;
PROGRESS_DATA[loader].bytesTotal=-1;
}
// now a listener
public static function progressListener(e:Event):void {
var l:Loader=e.target as Loader;
if (!l) return; // that wasn't a loader that sent the event. Uh oh
var plo:Object=PROGRESS_DATA[l];
if (!plo) return; // unregistered loader. Ignore
if (plo.bytesTotal<0) {
plo.bytesTotal=e.bytesTotal;
TOTAL_BYTES+=e.bytesTotal;
}
var pbl:int=plo.bytesLoaded;
plo.bytesLoaded=e.bytesLoaded;
LOADED_BYTES+=(e.bytesLoaded-pbl);
var perc:int = (LOADED_BYTES / TOTAL_BYTES) * 100;
Loading.text = "loading " +perc + "%";
}
Note, as the loading process is designed to be run only once, all initialization is made once, and this code does not have error handling - you can, however, write it yourself.

How to duplicate loaded *.swf without setting a class name

I have read this article about abstracting assets from ActionScript:
Abstracting Assets from Actionscript in AS3.0 – Asset Libraries and DuplicateMovieClip
But it requires to set the Linkage Class name. How can I get the same result without setting the linkage class name?
What I want to do is to cache a loaded asset, and use the cached version every time I request the same URL. A solution is to clone the loaded DisplayObject, but I think it's unnecessary since I only want a new copy.
I think the way to do that is to use byte arrays
here's a quick sample
// once you load your data...
private function loaderComplete(event:Event):void
{
var loaderInfo:LoaderInfo = LoaderInfo(event.target);
var byteArray:ByteArray = loaderInfo.bytes; //<- this will create your byte array
}
you can then use byteArray.readObject(); to generate the new class;
look at senocular's post at http://www.kirupa.com/forum/showthread.php?p=1897368
where he's got a function like this:
function clone(source:Object):* {
var copier:ByteArray = new ByteArray();
copier.writeObject(source);
copier.position = 0;
return(copier.readObject());
}
//that you use with
newObjectCopy = clone(originalObject);
hope this gets you started
As of Flash 11.3, there's a function named getQualifiedDefinitionNames that tells me exactly what linkage names should I use with getDefinition, so there's no need to know the values beforehand.

Managing Singletons in external swfs

I'm dealing with the scenario whereby my code might be included in other Flash content either included via import .as commands and then referenced as a Singleton, e.g.
import com.as3.Singleton;
...
...
Singleton.birth();
Singleton.getInstance().test();
...but also imported as a runtime library; with the Singleton class exported as a .swf beforehand (instead of pre-baking the class).
How should I reference the Singleton once Event.COMPLETE has fired off from the Loader that brings in the swf? Normally I'd code something like:
public function singletonCompleteHandler(event:Event):void {
var mySing:Singleton = _loader.contentLoaderInfo.content as Singleton;
}
...but I know I don't want to be referencing the singleton via a "var" reference. I'm not explaining very well, but basically once the singleton.swf has loaded in I need to use the code within it within a singleton model (i.e. ensure there's only one instance of it throughout my application).
Copy of the Singleton class included below (thanks for any thoughts on this by the way).
package
{
public class Singleton extends Sprite
{
private static var instance:Singleton;
public function Singleton() {
if (instance) {
throw new Error("Singleton can only be accessed through Singleton.getInstance()");
}
}
public static function birth() {
if (instance == null) {
instance = new Singleton();
}
}
public static function getInstance():Singleton {
return instance;
}
public function test():void {
trace("Testing our singleton.");
}
}
}
First of all, if you're loading it dynamically, then you don't want to have a reference to it in your loading SWF (otherwise it would defeat the point).
So I'm guessing you're looking to do something like this:
function completeHandler(event:Event):void
{
var singleton:Object = loader.contentLoaderInfo.content;
var instance:IMyObject = singleton.getInstance();
instance.test();
}
IMyObject is of course optional here. If you do it like this, your singleton instance will have to implement IMyObject.
interface IMyObject
{
function test():void;
}
This is all to avoid having to reference the actual class in your loading SWF. Like I said, the interface is optional: you can just use Object instead.
... and now on to the main point: load the singleton SWF into the loading SWF's own "application domain".
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/system/LoaderContext.html#applicationDomain
var lc:LoaderContext = new LoaderContext();
lc.applicationDomain = ApplicationDomain.currentDomain;
loader.load(new URLRequest("Singleton.swf"), lc);
You see, normally when you load a SWF, it gets loaded into its own application domain. But this makes it impossible to enforce the singleton pattern on the loaded SWF, because each instance of the class can live in its own application domain (hence you can end up with multiple instances). So if you want to enforce this across multiple SWF loads then you want to load it into the loading SWF's application domain.
If your question is "How should I reference the Singleton once Event.COMPLETE has fired off from the Loader that brings in the swf?", then you can do it with:
var Singleton:Object = _loader.contentLoaderInfo.applicationDomain.getDefinition('Singleton');
But, I'm not sure what you mean about not wanting to use a "var" reference.
On a side-note, there's a good chance a global variable would be a better option than a Singleton class for an API.
package myPackage
{
public var myGlobal:MyGlobal = new MyGlobal();
}
Which you can access with myPackage.myGlobal