Skip to content

Instantly share code, notes, and snippets.

@Danielku15
Created February 22, 2014 15:42
Show Gist options
  • Save Danielku15/9156802 to your computer and use it in GitHub Desktop.
Save Danielku15/9156802 to your computer and use it in GitHub Desktop.
Haxe Support in Flash Workers - Sample
-swf bin/Main.swf
-main worker.MainTest
-swf-version 11.4
-swf-header 800:600:60:FFFFFF
-cp src
-lib format
package worker;
import flash.display.Sprite;
import flash.system.*;
import haxe.io.*;
import format.swf.*;
/**
* Copied from: https://gist.github.com/profelis/8770024
*/
class HxWorker
{
public static function workerFromClass(clazz:Class<Dynamic>, giveAppPrivileges = false, bytes:BytesData = null, domain:WorkerDomain = null):Worker
{
var type = clazz;
while (type != null && type != Sprite)
{
type = Type.getSuperClass(type);
}
if (type != Sprite)
{
throw 'Class ${Type.getClassName(clazz)} must inherit from Sprite to link to the root';
}
if (bytes == null)
{
bytes = flash.Lib.current.loaderInfo.bytes;
}
var swfReader = new Reader(new BytesInput(Bytes.ofData(bytes)));
var swf = swfReader.read();
for (tag in swf.tags)
{
switch (tag)
{
case TSymbolClass(refs):
for (ref in refs)
{
if (ref.cid == 0)
{
ref.className = Type.getClassName(clazz);
var swfData = new BytesOutput();
new Writer(swfData).write(swf);
if (domain == null)
{
domain = WorkerDomain.current;
}
return domain.createWorker(swfData.getBytes().getData(), giveAppPrivileges);
}
}
case _:
}
}
return null;
}
}
package worker;
import haxe.ds.StringMap;
import flash.display.Sprite;
import flash.system.Worker;
import flash.events.Event;
class MainTest
{
public static function main()
{
var w = worker.HxWorker.workerFromClass(MyWorker);
w.start();
}
}
class ClassWithInit
{
public static var lookup:StringMap<String>;
public static function __init__()
{
lookup = new StringMap<String>();
lookup.set('Test', 'Test2');
lookup.set('Test2', 'Test3');
}
}
class MyWorker extends Sprite
{
public function new()
{
super();
// lookup is null because ClassWithInit.__init__() is not called
trace(ClassWithInit.lookup);
// Math functions are missing too
trace(Math.isFinite);
trace(Math.isNan);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment