Preloading example with Haxe and SamHaxe

Let's see how can we create a preloaded swf for our flash game, widget or website using pure Haxe. For embedding the assets, we will use SamHaxe, our new flash asset tool.

Our goal is to have heavy assets in our swf, but would like to show a progress bar until all these assets have loaded.

Assembling the asset library using SamHaxe

Let's see the resource.xml asset descriptor that we will feed for SamHaxe:

<?xml version="1.0" encoding="utf-8"?>
<shx:resources version="9" compress="false" package="resources.classes"
   xmlns:shx="http://mindless-labs.com/samhaxe"
   xmlns:snd="http://mindless-labs.com/samhaxe/modules/Sound">

   <!-- 
      Empty first frame. You may put resources
      required in preloader animation here. 
   -->
   <shx:frame/>

   <!-- Frame with heavy assets -->
   <shx:frame>
      <snd:sound class="Music" import="path/to/a/large.mp3"/>
   </shx:frame>

</shx:resources>

The package attribute of the shx:resources tag is prepended to all classnames, so we will be able to access our sound asset from flash now as resources.classes.Music. Feel free to substitute your own asset package name.

Now we assemble the asset lib with SamHaxe by executing SamHaXe --config /path/to/samhaxe.conf.xml resources.xml resources.swf

Embedding the asset library in flash with Haxe

Here is the Haxe code which draw a progress bar until the whole flash file is loaded:

class PreloadingDemo {

   // progress bar
   var progress: flash.display.Shape;
   var fully_loaded: Bool;

   public function new() {
      // background for the progress bar
      var progressBg = new flash.display.Shape();
      var g = progressBg.graphics;
      g.beginFill(0x002288);
      g.drawRect(-2, -2, 104, 14);
      flash.Lib.current.addChild(progressBg);
      progressBg.x = 10;
      progressBg.y = 10;

      // the progress bar itself
      progress = new flash.display.Shape();
      g = progress.graphics;
      g.beginFill(0x00ff88);
      g.drawRect(0, 0, 100, 10);
      flash.Lib.current.addChild(progress);
      progress.x = 10;
      progress.y = 10;

      fully_loaded = false;
      flash.Lib.current.addEventListener(flash.events.Event.ENTER_FRAME,
            onEnterFrame);
   }

   function onEnterFrame(e: flash.events.Event) {
      var totalBytes = flash.Lib.current.loaderInfo.bytesTotal;
      var actBytes = flash.Lib.current.loaderInfo.bytesLoaded;

      if (!fully_loaded && actBytes <= totalBytes) {
         // animate progress bar
         progress.scaleX = 1.0 * actBytes / totalBytes;
      }

      if (!fully_loaded && actBytes == totalBytes) {
         fully_loaded = true;

         var music: flash.media.Sound = Type.createInstance(
              Type.resolveClass("resources.classes.Music"), []
         );
         music.play();
      }
   }

   public static function main() {
      new PreloadingDemo();
   }
}

Now we can build this by issuing:
haxe -swf preloadingDemo.swf -swf-header 100:100:20:ffffff -swf-version 9 -swf-lib resources.swf --flash-strict -main PreloadingDemo

Discussion

This example can be found in the demos directory of the SamHaxe distribution. This is a minimal example, there is plenty of space for implementing fancier preloader animation, or splitting the resources over more frames, if certain resources may only be needed later in the game.

Note that all program code still resides in the first frame - a possible workaround for this is to compile a preloder-less fully functional swf, and embed it into a small preloader shell on the second frame as a binary object using shx:binary, and using flash.display.Loader.loadBytes() to load and execute it.

Have fun coding :)

Comments

Comment by Dobos Bence, () (URL) on 09.09.20. 16:09
Cool. I want to try it now.

Comment by [yfan], on 09.09.21. 14:25
thanks a lot, great work.

i am using flashdevelop, which is very convinient, but as far as i know i cannot acces the underhood resource magic, that is being brandished using swfmill.

at the end of the article you seem to say that there is a way to attach a preloader to an already working swf? this code would be very useful for the flashdevelop+haxe crowd, including me.

Thanks for all quick answers and all the great work :).

Comment by [ron], (URL) on 09.09.21. 19:16
Glad you like it. Yes, it is possible to attach a preloader to an already built swf. You have to create an asset lib with samhaxe, where you put the swf to wrap on the second frame with the <binary> import module. Then use this asset lib with -swf-lib in your preloader:

1) wait and animate until everything is loaded.

2) create an instance of the embedded binary object, and load it into a MovieClip using Loader.loadBytes (don’t forget to create a new ApplicationDomain). Put the loaded MC on the display list and that’s it.

However, care must be taken if you would like to load third party API’s from inside the wrapped swf, as these API’s tend to parse flash vars and think that they are loaded into the swf at the outermost "shell".

This may be circumvented by indeed loading these API’s into the outermost shell. Maybe a separate article would be needed to clarify this.

Good luck!

  
Remember personal info?

Emoticons / Textile

To prevent automated commentspam we require you to complete this silly task.
 

  (Register your username / Log in)

Notify:
Hide email:

Small print: All html tags except <b> and <i> will be removed from your comment. You can make links by just typing the url or mail-address.

About

Flash game development using HaXe and pals.

Archives

01 Nov - 30 Nov 2009
01 Oct - 31 Oct 2009
01 Sep - 30 Sep 2009
01 Jul - 31 Jul 2009
01 May - 31 May 2009
01 Apr - 30 Apr 2009
01 Mar - 31 Mar 2009
01 Feb - 28 Feb 2009
01 Jan - 31 Jan 2009
01 Dec - 31 Dec 2008
01 Nov - 30 Nov 2008
01 Oct - 31 Oct 2008
01 Sep - 30 Sep 2008
01 Aug - 31 Aug 2008
01 Sep - 30 Sep 2007

Calendar

« March 2010
S M T W T F S
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31      

Linkdump

Game design document - §

If you are about to create a new game, be sure to read this nice article along with its predecessors.

09.11.24. 13:29 | comment!

VelociRapid game element preview - §

Click the banner to play a preview of prey fleeing, and also take a peek underneath to see the quadtree space partitioning (nodes do not collapse right now). WSAD to control the dino.

09.11.19. 23:18 | comment!

Gambit's response to recent virtual currency changes - §

An interesting read at the Gambit blog.

09.11.05. 10:19 | comment!

Dirty coding tricks of game developers - §

Read it at Gamasutra

09.11.03. 10:02 | comment!

Payment providers - §

Some alternative payment providers for running your own virtual curreny system:

09.07.13. 21:38 | comment!

ssh tunneling in linux - §

To forward the local port X to the local port Y of the remote machine:

ssh -L X:127.0.0.1:Y remote.machine -N

Usage example: Setup a local web proxy (like privoxy) on a remote university machine, and connect to it from home. This way you can access university resources with ease.

09.05.14. 10:28 | comment!

Free flag images - §

http://www.33ff.com/flags/index.htm

09.04.08. 11:52 | comment!

Render text with ImageMagick - §

convert -font font.ttf -background none -geometry +0+0 -fill \#ffffff -pointsize 18 label:"`cat txt`" -set label '' out.png

09.04.02. 15:16 | comment!

Online Latex equation editor - §

Online latex is

09.03.11. 09:02 | comment!

Create swc from a tree of as3 files - §

V1 (thanks to Jarrad Hope!) compc -output my_swc.swc -include-sources .

V2 (the old and hacky :) cd tree_top; compc -source-path . -output my_swc.swc -include-classes `find . -regex .*as | awk '{gsub(/\.\//, "", $0); gsub(/\.as/, "", $0); print $0}'`

09.03.06. 09:58 | two comments

Delete first line from file - §

sed -i '1d' file.txt

09.02.18. 12:28 | comment!

Gentoo: check security holes - §

glsa-check -p $(glsa-check -t all)

09.02.04. 11:30 | comment!

Execution speedup with fifo - §

Speed up the execution of programs that generate massive unwanted log-files by sending those logs to null through a fifo: mkfifo logfile
cat logfile > /dev/null &
./myprogram -log logfile

09.01.19. 14:09 | comment!

ImageMagick PNG background and auto-crop - §

Set background to white and auto-crop with ImageMagick: for i in `ls *png`; do convert -flatten $i x.png; convert -trim x.png out_$i; done

09.01.12. 17:15 | comment!

Linux: split file on pattern - §

awk '/PATTERN/{i++}{print > "file.pdb."i}' file, found here

08.12.15. 17:46 | comment!

Replace in multiple files on Linux - §

perl -pi -w -e 's/search/replace/g;' *.php
Found here.

08.12.10. 10:42 | comment!

XPath in Python - §

A nice summary about options for xpath with python here.

08.12.09. 18:41 | comment!

Christmas Icons - §

Free Chrismtas Icons!

08.12.08. 11:46 | comment!

PS print on WinXP - §

Print to PS on WinXP without any printers! Cool :)

08.12.04. 12:59 | comment!

Sorry, OpenOffice - §

OpenOffice is simply a no-go. Ill UI, missing features. Go for Latex or Crossover Office instead.

08.12.02. 14:31 | comment!

Last Referrers

Miscellany

Powered by Pivot - 1.40.7: 'Dreadwind' 
XML: RSS Feed 
XML: Atom Feed