Link to home
Start Free TrialLog in
Avatar of _sluimers_
_sluimers_Flag for Netherlands

asked on

How do preload an swf on FlashDevelop?

I've been told by another intern where I work, that I must package the game I'm making in an swf file and then preload it.
So I'm trying that but fail.
I have two issues:

1) I use BitmapImages but don't know anymore what to do with them. Is I preload the swf does that mean all images the game uses are automatically are preloaded as well?

2) When I try to preload my own game, it doesn't show up.

The attached code shows I try to preload my own game:

And here's how I preloaded before:

public function getBitmapData(name:String):BitmapData {
            const i:int = preloadedObjectNames.indexOf(name);
            if (i != -1) return preloadedObjects[i].bitmapData;
            else return new BitmapData(1,1);
        }

package {
    import flash.display.MovieClip;
    import flash.display.Sprite;
    import flash.display.StageAlign;
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.events.KeyboardEvent;
    import flash.events.MouseEvent;
    import flash.events.ProgressEvent;
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.events.HTTPStatusEvent;
    import flash.events.SecurityErrorEvent;
    import flash.text.TextField;
    import flash.net.URLRequest;
    import flash.net.URLLoader;
    import flash.net.URLVariables;
    import flash.net.URLRequestMethod;
    import flash.net.URLLoaderDataFormat;
    import flash.display.Loader;
    import flash.geom.Point;
    import flash.geom.Rectangle;
   
    import nl.obg.www.*;
   
     public class Main extends EMovieClip {
        private static const OK:uint = 200;
        private static const engine:Engine = new Engine();
       
        private var tileSheets:Array;
       
        private var preLoadBar:Widget;
        private var pre:Preloader;
       
        private var loader:URLLoader = new URLLoader();
       
        private var preloadNames:Array;
       
        private var preloadTextId:uint;
       
        public function Main() {
            drawBackGround();
            initLoader();
            addPreloadBar();
        }
       
        private function drawBackGround():void {
            // gray background
            graphics.clear();
            graphics.beginFill( 0x888888 , 1 );
            graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
            graphics.endFill();
        }
       
        private function initLoader():void {
            var request:URLRequest = new URLRequest("http://mywebsite.com/readfromdirectory.php");
            request.method = URLRequestMethod.GET;
           
            loader.dataFormat = URLLoaderDataFormat.VARIABLES;
             //Error handling    
            loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
            loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
            //Could be an error or just a message
            loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);    
            loader.addEventListener(Event.COMPLETE, completeHandler);
           
            loader.load(request);
        }
       
        private function addPreloadBar():void {
            var midW:uint = this.width / 2;
            var midH:uint = this.height / 2;
            preLoadBar = new Widget();
            preLoadBar.center(midW, midH);
           
            preLoadBar.addCenterText("main","Waiting to preload...", 16);
            preLoadBar.addCenterText("progress", " ", 16);
           
            addChild(preLoadBar);
        }
       
        public function completeHandler(evt:Event):void {  
            var i:uint = 0;
            var data:String;
            var a:Array = [];
           
            while(true) {
                data = evt.target.data[i];
                if (!data) break;
                a[i] = data;
               
                i++;
            }
           
            preloadNames = a.slice();
           
            preloadObjects();
        }  
       
        public function preloadObjects():void {
            var preloadAddresses:Array = [];
            var i:uint = preloadNames.length;
            var j:uint = 0;
            var name:String;
            var url:String = "http://catnipika.com/msaobgdatafiles/data/";
           
            while (--i -( -1)) {
                name = preloadNames[j];
                preloadAddresses.push(url + "gfx/" + name);
                j++;
            }
           
            pre = new Preloader(preloadAddresses);                // instantiate and add the files to be preloaded as an array
            //pre.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
            //pre.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
            //pre.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
            pre.addEventListener("preloadProgress", onPreloadProgress);
            pre.addEventListener("preloadComplete", onPreloadComplete); // add listeners for progress
        }
       
        private function onIOError(evt:IOErrorEvent):void {
            trace("IOError: " + evt.text);
        }
       
        private function onHTTPStatus(evt:HTTPStatusEvent):void {
            if(evt.status != OK) trace("HTTPStatus: " + evt.status);
        }
        private function onSecurityError(evt:SecurityErrorEvent):void {
            trace("SecurityError: " + evt.text);
        }
       
        private function onPreloadProgress(e:Event):void {
            preLoadBar.editText("progress", e.target.percLoaded + "% loaded");            //  textfield is a dynamic textfield on the stage
        }    

        private function onPreloadComplete(e:Event):void {
            pre.removeEventListener("preloadProgress", onPreloadProgress);
            pre.removeEventListener("preloadComplete", onPreloadComplete);    // garbage collect
            removeItem(preLoadBar);
            preLoadBar = null;
            //trace(pre.objects); // get the loaded objects as an array
           
            stage.addEventListener(KeyboardEvent.KEY_UP, engine.onKeyUp);
            stage.addEventListener(KeyboardEvent.KEY_DOWN, engine.onKeyDown);
           
            addChild(engine);
            engine.setPreloadObjects(pre.objects, preloadNames);
           
            engine.init();
           
            //var variables:URLVariables = new URLVariables(); //create a variable container  
            //request.data = variables;//add the data to our containers  
            //request.method = URLRequestMethod.POST; //select the method as post
        }
    }
}

package
{    
    import flash.display.Sprite;
    import flash.display.Loader;
    import flash.events.Event;
    import flash.events.ProgressEvent;
    import flash.events.IOErrorEvent;
    import flash.events.HTTPStatusEvent;
    import flash.events.SecurityErrorEvent;
    import flash.net.URLRequest;
   
    public class Preloader extends Sprite {
        private static const OK:uint = 200;
       
        public var objectsArray:Array = new Array();        // holds the the loaded files
        public var pLoaded:int = 0;                            // defaults the loaded percentage to 0
        private var itemsArray:Array = new Array();            // holds all the items to be loaded
        private var totalItems:int;                            // holds the total items to be preloaded
        private var currItem:int = 1;                        // defaults the current preloaded item to 1
       
        public function Preloader(_itemsArray:Array) {
            objectsArray    = [];
            itemsArray    = [];
            pLoaded        = 0;
            itemsArray     = [];
            totalItems     = 0;
            currItem     = 1;

            itemsArray = _itemsArray;
            totalItems = _itemsArray.length;
            loadOne(currItem - 1, itemsArray);        // load the first item
        }
       
        private function loadOne(what:int, _itemsArray:Array):void {
            var ldr:Loader = new Loader();
            ldr.load(new URLRequest(_itemsArray[what].toString()));
           
            ldr.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onInternalProgress);
            ldr.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onInternalIOError);
            ldr.contentLoaderInfo.addEventListener(HTTPStatusEvent.HTTP_STATUS, onInternalHTTPStatus);
            ldr.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onInternalSecurityError);
            ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, onInternalComplete);
        }
   
        private function onInternalProgress(e:Event):void {
            var temp:int = Math.ceil((((e.target.bytesLoaded / e.target.bytesTotal)*100 * currItem) / totalItems));
            if (temp > pLoaded) {
                pLoaded = temp;        // avoid the precentage to drop
            }
            //trace(pLoaded);
            dispatchEvent(new Event("preloadProgress")); // call the parent class with a progress update
        }
       
        private function onInternalIOError(evt:IOErrorEvent):void {
            trace("Preloader IOError: " + evt.text);
        }
       
        private function onInternalHTTPStatus(evt:HTTPStatusEvent):void {
            if(evt.status != OK) trace("HTTPStatus: " + evt.status);
        }
       
        private function onInternalSecurityError(evt:SecurityErrorEvent):void {
            trace("SecurityError: " + evt.text);
        }
       
        private function onInternalComplete(e:Event):void {
            objectsArray.push(e.target.content);    // add a loaded object to the objects array
            currItem += 1;                            // increment the current item to be loaded
            if (objectsArray.length == totalItems) {
                e.target.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onInternalSecurityError);
                e.target.removeEventListener(HTTPStatusEvent.HTTP_STATUS, onInternalHTTPStatus);
                e.target.removeEventListener(IOErrorEvent.IO_ERROR, onInternalIOError);
                e.target.removeEventListener(ProgressEvent.PROGRESS, onInternalProgress);    // garbage collect
                e.target.removeEventListener(Event.COMPLETE, onInternalComplete);
                dispatchEvent(new Event("preloadComplete"));    // when all objects are loaded, call the parent class
            } else {
                loadOne(currItem - 1, itemsArray);    // load the next one
            }
            //trace("complete");
        }
       
        public function get percLoaded():int {
            return pLoaded;            // returns the loaded percentage of all files to be preloaded
        }
       
        public function get objects():Array {
            return objectsArray;    // returns the loaded files as an array
        }
       
    }
   
}



package 
{
    import flash.display.DisplayObject;
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.events.ProgressEvent;
    import flash.display.Loader;
    import flash.net.URLRequest;
    import flash.utils.getDefinitionByName;
    
    import nl.obg.www.*;
    
    public class Preloader extends EMovieClip {
        
        private var progressBar:Widget;
        private var preloadNames:Array;
        private var preloadTextId:uint;
        private var loader:Loader;
        private var loader2:Loader;
        
        public function Preloader() {
            initLoader();
            addProgressBar();
        }
        
        private function initLoader():void {
            loader = new Loader();
            loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progress);
            loader.contentLoaderInfo.addEventListener(Event.COMPLETE, startup);
            loader.load(new URLRequest("Game.swf"));
        }
        
        private function progress(e:Event):void {
            var perc:Number = e.target.bytesLoaded / e.target.bytesTotal;
            progressBar.editText("progress", "LOADING: " + Math.ceil(perc * 100).toString() + "%");
        }
        
        private function addProgressBar():void {
            var midW:uint = this.width / 2;
            var midH:uint = this.height / 2;
            progressBar = new Widget();
            progressBar.center(midW, midH);
            
            progressBar.addCenterText("main","Waiting to preload...", 16);
            progressBar.addCenterText("progress", " ", 16);
            
            addChild(progressBar);
        }
        
        private function startup(e:Event):void {
            // hide loader
            stop();
            loader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, progress);
            loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, startup);
            removeItem(progressBar);
            progressBar = null;
            var mainClass:Class = getDefinitionByName("Main") as Class;
            var main:Main = new mainClass() as Main; 
            main.addChild(loader);
            addChild(main);
        }
    }
}

Open in new window

Avatar of blue-genie
blue-genie
Flag of South Africa image

Hi i didn't look through all your code, but are you just simply wanting to preload a swf file?
with some changes in AS3 it became easier to create a small swf and use URLLoader to load the bigger swf. maybe that's what your intern meant.

Avatar of _sluimers_

ASKER

Yes, that's what he meant, but how would I do that?
You see, I don't get to see my game with the code in the code snippet.
All I see is white.

1.png
2.png
Did you ever get this problem solved?

As I told you on the Kirupa forums (http://www.kirupa.com/forum/showthread.php?t=346988), your code has way too much code that you really don't need. It seems as though you picked up code from the internet and started to use it without fully understanding it.

I don't think that "startup" function is needed at all. It is doing all sorts of stuff that is not neccessary.

Here is at least one link for a good (simple) preloader tutorial. It doesn't need to get more advanced than that.
http://doogog.com/actionscript-3-external-preloader.html

Also, beginnig preloader-users tend to get #1009 errors like the common cold. Look out! Check out the first set of links:
http://iqandreas.blogspot.com/2009/09/most-common-flash-questions-as3-faq.html
ASKER CERTIFIED SOLUTION
Avatar of blue-genie
blue-genie
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
[quote]Did you ever get this problem solved?[/quote]

I received a temporary solution, yes.

[quote]

As I told you on the Kirupa forums (http://www.kirupa.com/forum/showthread.php?t=346988), your code has way too much code that you really don't need. It seems as though you picked up code from the internet and started to use it without fully understanding it.[/quote]

Nope, I wrote it all myself. It's just that it's all external, which causes security issues, so I'm asked to load internally.
okay so do you want to close your question or carry on.
the solution i posted does work.
I would like to add that I accept blue-genie's efforts to help me as good enough to give him the 500 points. The problem with my approach was that I loaded the files externally in order to automatically load all files in a directory. This however causes security issues and thus is not the recommended approach. Files should be loaded internally so another approach is needed to automatically get all files from a directory which was my initial goal.
I have not found a solution to that yet and I fear that this is simply impossible. On a side note, I now know that loading xml files needs a URLLoader instead of a Loader, so perhaps the above code case faces similar issues.
hey google bulkLoader class
that might help. i've just discovered it and i'm busy playing with it.
That's nice, but you know what I'm looking for ;) and only adobe AIR has it, which unfortunately I'm not allowed to use for work. It's like I asking for the right-click mouse button to do something useful.