Wednesday, December 31, 2014

RealBengine Ported to OpenFL

Quite a long time since I released the first demo of RealBengine, which is written in HaXe and based on NME. Now I ported the demo to the newest OpenFL, almost with no extra effort. The good thing is now it can compile to the HTML5 target directly, thanks to jgranick's setPixels fix for the HTML5 target:

RealBengine is the candidate of the future version of my voxel render Bengine, it is based on software ray tracing and it has 6 degree of freedom.

However, there is almost no noticeable performance improvement from NME to OpenFL. The Win32 binary still runs at 10~15 FPS, Flash target is about 5 FPS, and HTML5 target is only 0~1 FPS, so lots of optimizations are needed. I'm planning to re-implement to algorithm in LIME/GLSL shaders for a speedup.

DEMO (Win32 binary):


W/S Arrow UP/Down - Move Forward/Back
Arrow Left/Right - Move Left/Right
Q/E - Move Up/Down
A/D - Look Up/Down

Sunday, November 23, 2014

Open Source and Free Voxel Editors

goxel (update on 2019/Feb/12) (

A free and open source voxel editor, available on Mac, iOS, Android, Windows and Linux. This one is currently my favorite, very simple to use and has all the basic practical functions. It also supports procedural generation ( Compared with another popular software MagicaVoxel, I think this one is more suitable as a pure voxel modeling tool.

Ken Silverman's open source voxlap engine. It has a real-time WYSIWYG editor - VOXED for editing the game map.
Source Code:
see also Ken Silverman's EVALDRAW: 
and Ken Silverman's PND3D demo, an abandoned successor to the famous voxel engine Voxlap:

Strip to Voxel
A program to convert an image strip, or series of pictures in a long film strip like image, into a raw voxel model for later editing.

Slab6 & POLY2VOX
An open source 6-degree of freedom viewer and editor for KVX and VOX voxel files.
The utility POLY2VOX is a polygon to voxel model converter.
See also (Poly2Vox UNLIMITED, onverts textured .3DS files to voxels over size 256.)
and (3D mesh voxelizer).

An open source FPS game inspired by Wolfenstein 3D using Ken Silverman's VOXLAP engine to render voxels. The game package contains a animator tool for editing voxel animations.

Includes tools for VOX - a file format that describes an object built with voxels.
Source Code:

A free lightweight 8-bit voxel editor and renderer with lots of functionalities.

A cross-platform open-source voxel editor and tool chain that supports per-frame animation.
Source Code (MIT):

A voxel editor written in C#.
Source Code:
Note:  This tool seems sophisticated, however, not much information can be found about it. You may need to contact the author for more details.

Sprite Voxel Editor
Sproxel (short for "Sprite Voxel Editor") is a 3d interface designed to let the user quickly create and edit voxel-based 3d models. The creation process and resulting geometry can be thought of as an extension to 2d pixel art.
Source Code(New BSD):

Voxel Builder
Voxel Builder is an open source tool for that lets anyone design and edit 3D voxel (cube) models easily, right in their web browser.
Source Code (BSD):
Similar tools and

Cube Kingdom
Cube Kingdom is an application that can be used to create 3D models out of blocks with the same size and dimension.

VoxelDesc is a voxel editor driven by a command line with 2.5D graphics and powerful scripting.
Source Code (Artistic License version 2):

Zoxel is a voxel editor designed for small models. Like a sprite editor, but in 3D.
Source Code (GNU GPL):

VoxelShop is an extremely intuitive and powerful software for OSX, Windows and Linux to modify and create voxel objects. It was designed from the ground up in close collaboration with artists.

Simple voxel editor based on .NET framework.

Cube Construct
3D Pixel Editor for iPad with source code.
Source code:
See also

Painting in 3D with voxels in the cloud using WebGL or the Android app.

An all-3D 3D terrain editor which enables you to simply interactively draw and manipulate terrains in 3D space. Since this is not based on height fields, you can easily create steep hills, overhangs or even tunnels.

A Minecraft level editor.

Import kv6 format voxel to Minecraft.

Voxel Section Editor
Open source voxel creation and editing tool for Command & Conquer Tiberian Sun and Command & Conquer Red Alert 2 voxel files.
See also

RadED is an experimental voxel editor for Doom circa 1993.
Source Code:
See also
Note: this tool is rather old and no binary available - you need to compile for yourself.

Polygon modelling tools support sculpting (For High-Resolution realistic Voxel model creation):

The free and open source 3D animation suite also has sculpt mode:

Lite version of ZBrush, the ideal ground on which to get started with digital sculpting.

SculptyPaint is a low polygon 3D creation tool original written for creating sculpts.

SharpConstruct is a 3D modeling program designed to let users paint depth on to polygon models in real-time. Unlike traditional modeling programs, SharpConstruct makes it easy to quickly model organic shapes.
See also and FiberMesh (Designing Freeform Surfaces with 3D Curves)

Open source (GPL) 3D sculpting application that provides an intuitive workflow for Windows and Linux.

Small but powerful 3D editor for 3D concept art, fast modeling and sculpting. One great feature is 3D poly brushes, which makes 3D modeling like 2D drawing.

Sculpt+ (discontinued)
Very easy to use free 3D modeling and animation tool by Autodesk. Starting from stick figures, you can sculpt the details, paint the textures and pose your models. Available for iOS, Android and Windows.

Rocket 3F
A user-friendly 3D modeling tool which supports sculpting and mesh drawing.

Create quickly and easily your 3D head from just two 2D photos:
see also

Sketch-based shape creation & free-form modeling tool:

truesculpt (Virtual sculpture for Android)
Mathematical models: 
2D/3D free generative art application:

MeshMixer: and
Voxel Paint in 3D with Oculus VR: (Free, WebGL based)


Friday, November 21, 2014

Open Source and Free Pixel Editors

A simple online web-based (HTML5) Sprite and Pixel art Editor. Offline version is also available.
Source Code:

A free online (Flash) app for creating pixel art.
See also

The famous open source alternative to Photoshop.
See this note for using GIMP as a pixel art editor.

A free powerful image and photo editing software.

A bitmap paint program specialized in 256-color drawing.
Source Code (GNU GPL):

A painting program to create pixel art and manipulate digital photos.
Source Code (GNU GPL):

A open source (but not 'free') pixel art editor for Mac OS X.
Source Code:

An open source animated sprite editor & pixel art tool.
Source Code (GNU GPL):
Note: Aseprite is open source but not 'free' since donation is required for downloading the pre-built binaries. However, it is open source so you can compile for the binary by yourself.


Tuesday, November 18, 2014

Get URL and Read URL Parameters in JavaScript, HaXe and AS3

Find the URL of the embedding page of a swf is a very basic way for domain locking flash games. Similar things can be done for JavaScript based online games. To get the URL, in JavaScript you can use

var myURL=document.URL;
In HaXe (targeting JavaScript or HTML5), you can use
var myURL:String=js.Browser.window.document;
In AS3, to find the path url of the swf, you can use
and for finding the path url of the embedding page, you can use"window.location.href");
Besides, it's common to see url parameters, for example: "" To read the parameters, in the above example, that is "1234", "somestr" and "someotherstr", in JavaScript, you can use the snippet provided by or the function given at
In HaXe, you can use the following HaXe function
//translated from
function getQueryVariable(variable):String
       var query:String =;
       var vars:Array = query.split("&");
       for ( i in 0...vars.length) {
               var pair:Array = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
In AS3, if the parameters are given in the path of the swf' url, for example, "", or if the parameters are declared in flashvars, then you can simply use "root.loaderInfo.parameters" object to access all the parameters, for example,
var myStr:String = root.loaderInfo.parameters.param1;
However, to read parameters of the embedding page' url, you still need the help of JavaScript, see the following pages for an example:


Saturday, November 15, 2014

Create a SWC for Flash & AS3 Projects from OpenFL

If your code is pure haxe, it's easy to generate an AS3 library swc file for your AS3 projects, as documented at

haxe -swf mylib.swc MyLibClasses --macro include('mypackage')
For example, to generate the "TextParser.swc" from "TextParser.hx", I used
haxe -swf TextParser.swc TextParser.hx
However, if your project is based on the OpenFL library, more efforts may be needed. Anyway, since you can compile your project to a swf, one ultimated way is to load the external swf at run time and get all public classes and methods inside using the "getDefinition" function from the "ApplicationDomain" class, see for example However, this way is not the most efficient and need you to write more code. For the most cases, it is possible to generate a swc file from your OpenFL based code. Things you need to do are
1. Rename the package name "openfl" to "flash", e.g., "openfl.display.Sprite" to "flash.display.Sprite".
2. Make your code independent of the openfl only classes and methods. For example, don't use "openfl.Assets.getBitmapData" directly in your code, use a external wrapper object as the assets host such as "myAssetsHost" and redirect all function calls to its public method which wraps "openfl.Assets.getBitmapData". Then in your AS3 project, you can reimplement the wrapper object using AS3 methods for handling assets.
An example is the JiuGongGe.swc, I refactored the original source code to make it independent of "openfl.Assets". It also depends on the library "Actuate", so I copied the library folder "motion" from the installed path "D:\HaxeToolkit\haxe\lib\actuate\1,7,5\motion" to the folder contains the source code of JiuGongGe, then use the command
haxe -swf JiuGongGe.swc JGG.hx  --no-traces --macro include('motion.Actuate')
to get the swc file.


Tuesday, November 11, 2014

TextParser - A Simple Class for Parsing Text Files

TextParser is a simple utility HaXe class for parsing text files. You can use this class to read String, Int variables from a text file. For example, the JiuGongGe UI uses a text file to configure the UI layout, so it needs to parse the text configuration file to do the set up.

The source code of the class is released with the JiuGongGe UI:
TextParser is also available in AS3 as a swc:
To use the class, add the following line in your main class first:


The following is a simple AS3 example for using the TextParser class to parse a text file line by line and read some strings and integers needed:
var myUILayout:ByteArray = new myUILayoutClass() as ByteArray;
var myTextParser:TextParser = new TextParser(myUILayout.toString());
while (!myTextParser.EndofFile())
var Name:String = myTextParser.ReadString();
if (Name == "#") //comment line
var CallBackStr:String = myTextParser.ReadString();
var IconStr:String = myTextParser.ReadString();
var Color:uint = myTextParser.ReadInteger();
var Label:String = myTextParser.ReadString();
var LevelStr:String = myTextParser.ReadString();
Basically, you need to put the parsing process inside a while loop. Where the function EndofFile() is used to check whether it is the end of the text file. The function GotoNextLine() will move the position of the file pointer to the next line. The functions ReadString() and ReadInteger() are used to read string and integer from the text file and update the file pointer's position.

Full source code for the example:

For a HaXe code example, please check the JiuGongGe UI's source code. 

Monday, November 10, 2014

JiuGongGe.swc - JiuGongGe UI for Flash AS3 Projects

For using the JiuGongGe UI in your Flash/AS3 projects, here is the pre-compiled swc file:
An example FlashDevelop project:

To use "JiuGongGe.swc", first add the swc file to your project's library (path). Since the swc is built directly from original HaXe source code, there're two requirements:
1. Your main class must be a sub-class of "MovieClip" instead of "Sprite".
2. Add the following code before using the "JGG" class:


Check the post for how to using the UI library - most of the HaXe code in the post also works in Flash. Note that the function "Assets.getText()" and "Assets.getBitmapData()" are provided by OpenFL, so you may need to embed the assets in your AS3 code like the example Flash project.

Wednesday, November 5, 2014

JiuGongGe UI - A Simple Open Source UI Framework in HaXe

JiuGongGe (means 9-cell) UI is a UI framework written in HaXe with OpenFL for all platforms, including Flash, HTML5, Android/iOS and Windows. This UI framework is designed to be lightweight and mobile friendly.

The framework is actually a set of buttons (clickable cells) in a nested hierarchy, with each level containing at most 9 cells. The UI framework is firstly created for the BNote application.

Basic Usage
The framework contains two main classes, "JGGCell" represents a single cell and "JGG" is the whole set of cells. You can customize the look and feel for the cells by modifying and extending the first class. For the most time, you're working with the second class. Firstly, you need to create an instance of the "JGG" class, which is a subclass of "Sprite", so you can add it to the stage and set the positions:

var myJGG:JGG = new JGG();
myJGG.x = 300;
myJGG.y = 200;
But nothing happens until you initialize the UI:
Where the first parameter is the UI host,usually the parent of the the UI object. All event handler function of the click event triggered by cells should be declared in the UI host as public functions. For example, if you use the stage as the UI host, the following function in your Main class can be used as on click event handler:
public function CallBack(event:Event)

The second parameter is the assets host, which will provide the UI framework with icons. The assets host must implement the function "getIcon(ID:String):DisplayObject" as a public method, which will be called by the JGG class to fetch icon resources. For example:
public function getIcon(ID:String)
  return new Bitmap(Assets.getBitmapData("assets/" + ID));
The return value can be a Bitmap, Sprite, or any other display object.

The third parameter is the String of the config file. The cells' hierarchy is declared in the string. Usually, it's better to write the config file in a text file, then you can use "Assets.getText" to get the string and pass it to the JGG's init function, other than directly embed the string content in your code. For each line of the config file, you declare one cell and specify the cell's property. It's not necessary to give all the 9 cells for a level. Just declare used cells only. You should give the following things (with out the "[" and "]") in order and delimited by space:
[name_of_cell] [on_click_callback_function_name] [background_color] [icon] [text_label] [index][newline] 
Note strictly one row for one cell, and no spaces within [...] - use "_" or "-" instead. For example,
StartCell JGG_ChangeLevel 0xffffff null Start 0
You can use "#" at the beginning of the line to comment:
# This is a comment line.

Now about some details of each property declaration.
[name_of_cell]: Will be used as the name of the JGGCell class instance. [on_click_callback_function_name]: Use the same name of the public method in the UI host. When the cell is clicked by user, this function will be called. You can use the shortcut string "JGG_ChangeLevel" for folding (for non-center cell)or unfolding (if it is the center cell) levels, without implementing the function in the UI host.
[background_color]: Background color of the cell, e.g., 0xffffff.
[icon]: An ID string used as a parameter of Assets host's public function "getIcon". Use the shortcut string "null" if you want to simply use a text label instead.
[text_label]: This is usually used for debugging or quick prototyping purpose. It's recommended use an icon instead of a text label. You can use "_" for space, "/" for newline in the label string. The label text will shown only if the icon string is "null".
[index]: To give the level information of the cell. For example "0,1,0" - integer sequence separated by ','. It is an array of indices for different levels. "0,1,0" means the cell's index in the root level is "0", in the first level is "1" and in the second level is "0". For each level, there're at most 9 cells, so the indices are all staring from "0" to "8". The cell's position is determined by the index of its last level. Starting from center as "0", go left as "1" then up as "2", then along a clockwise circle to "8".
How to interpret the index: Take "0,2,4,3,5" as an example. Look at the last (5-th) integer "5", it means the cell is in the 4-th level with index "5", so it's position is the center one on the right panel. Now the second last (4-th) integer "3", it means the cell's parent's index (in the 3-rd level) is 3. And the integer "4" means the cells' parent' parent's index is 4... In short, you can think the indices as an index of a multidimensional array, which specifies the position of the the cell in the hierarchy.

For a complete example of the config file, please check:

Advanced Usage
To change cells' behavior, customize cell's look and feel etc.: You can use public functions foldLevel() and unfoldLevel(TargetCell:JGGCell) to change the levels manually, and getCell(name:String) to get a specific cell. The JGGCell class is a subclass of Sprite, so you can redraw the cell using its Graphics property. See the example's source code for more details:

Although the UI framework is very simple, I believe it can satisfy the most needs for a simple application with some customization. For example, check the BNote app. However, if you're looking for a more feature complete UI framework in HaXe, try or

Flash demo:
HTML5 demo:
Real Example (BNote):
Source Code v0.2 (MIT):
SWC for Flash/AS3:

Tuesday, October 28, 2014

BNote - A Free Online Simple Application for Taking Handwriting Notes

BNote is a simple note-taking app based on the the smooth drawing application by Dan Gries at The application is specially designed for touch enabled screen notebooks/tablets to take handwriting notes.


Smooth Strokes: Thanks to the smooth drawing function by Dan Gries.
Double Input Modes: Pen Input Mode for multi-touch enabled devices and Mouse Input Mode for non-touch screens.
Experimental Software Palm Rejection: Based on input pad, allowing users to rest part of their hands on the screen. Works only in Pen Input Mode and designed for capacitive touchscreen devices without hardware palm detection function and build-in stylus support.

Note the current release (Version 0.1) may contain bugs and deficiencies. Report of bugs, suggestions and feature requests are welcomed, just leave a comment below!

User Guides:

Writing: The app will switch between Pen Input Mode and Mouse Input Mode according to whether the device supports multi-touch mode.
For the Mouse Input Mode, you can use the mouse to write the notes just as any common graffiti board app.
For the Pen Input Mode, you can use a stylus or your finger to write on the board. The input pad (transparent circle) is the area where input/strokes will be accepted while any moves of pen or finger outside the input pad will not produce any stroke on the canvas. This is how the palm rejection works. This allows you to rest part of your hand on the screen, however, too much part of palm on the screen may prevent the app from detecting any moves inside the input pad. So if you find that you can't write anything inside the input pad (while the pen tip is out), try to lift your hand off the screen a bit to let the input pad get focus. It is recommended to use a small point tip stylus pen instead of rubber nib, such as Adonit JOT pro/mini for better writing experience.
How to move the input pad (for Pen Input Mode): During the writing when you want to reposition the input pad (e.g., when starting a new line), tap the pen icon (above the input pad) to stretch back the pen tip. Now you're in protection mode and you can tap any place to move the input pad there. Finally tap the pen icon to stretch out the tip and you can write again.
Settings: Tap the setting icon in the top-right corner to open the setting menu. In the setting menu you can Load/Save notes as a .png picture, switch to full screen, change pen color and thickness, undo last stroke and erase the notes.


Smooth drawing application by By Dan Gries (
UI Framework: JiuGongGeUI-v0.1 By Bruce Jawn
Icon Artist: Austin Andrews (@templarian)

Support this Free Sofware!

Thursday, August 14, 2014

AS3 Eval/Scripting Engines

AS3 Scripting Lib:

Compile AS3/JavaScript at runtime within the Flash Player
Execute compiled code in the scope of any object
Control which classes and functions are exposed to the script domain

The D.eval API brings the eval() functionality to ActionScript3 programming.

Runtime expression evaluation in ActionScript:

ActionScript 3 Mathematics Expression Parser:

Lua for Flash: (Lua for Flash via Alchemy) (Lua for Flash via CrossBridge) (Another Lua for Flash port using CrossBridge) (Lua for Flash in pure AS3)

ActionScript 3 Eval Library:
As3Eval is a library that packages the Tamarin ESC compiler to work within a run-of-the-mill flash player.

Governor is a script engine written in AS3. It provides all functions and operators you know from AS3; operators, math functions, math constants. Additionally it provides multithreading functionality for parallel execution of code. !The flash player is design as a single thread application, so governor is providing green threads!

BISE Scripting Engine:(Recommended)
The AS2-based engine could run a subset of ECMAScript, and it allowed users to write interpreted scripting for Flash games or applications. It also had some useful features, such as coroutines, a type of function that had the ability to suspend in the middle of its scripting. (AS3 Port) (AS2)

eval() for Actionscript 3:

AS3 Commons Bytecode:
AS3Commons-bytecode is an open-source library providing a ABC bytecode parsing and publishing and bytecode based reflection API for ActionScript 3.0.

XML to ActionScript(asXML):

TinyBasicAS: Flex version of TinyBasic

Java runs in Flash-Waba VM Alchemy:

The brainfuck programming language interpreter:


Parse and evalutate Haxe expressions. Haxe script is a complete subset of the Haxe language.

Simplified JavaScript interpreter:
A JavaScript interpreter you can embed in your Flash ActionScript 3 projects. Can parse and execute most JavaScript and support async "await" statement that pauses the VM until a Promise is fulfilled.

Wednesday, August 13, 2014

Test Notes on Emscripten

Recently, I tried the Emscripten compiler, which can compile C/C++ to HTML5/JavaScript. Also based on LLVM, it is a similar tool as the Adobe CrossBridge, but targeting a different platform. With Emscripten, it's possible not to write even a single line of JS for creating an HTML5 application. But for CrossBridge, you may still need to write some AS3 to make things work. Emscripten has very good SDL and OpenGL support, so you can compile your SDL/OpenGL application into JS without getting hands dirty of JavaScript.

Emscripten is similar to CrossBridge, in may aspects. For Emscripten, like the CrossBridge, you also need to break the C/C++ main infinite loop and use "emscripten_set_main_loop()" to run the loop content frame by frame. However, CrossBridge supports multi-threads and background workers, which is actually an advantage of AS3 over current JS. Both use similar inline asm (AT&T style) for interlope with the targeting languages. Their ways of dealing with the file system are similar - both use a virtual system to simulate C/C++ reading & writing processes and both provide tools for packaging assets. Besides, both CrossBridge and Emscripten can be used as code obfuscators, Emscripten even use the closure compiler for optimizing and obfuscating the generated JavaScript.

I thought the Emscripten SDK is mature enough. Even Unity3D and Unreal engine are using it for publishing HTML5, after they abandoning FlasCC and the flash platform. Also see the Porting Examples and Demos, especially the amazing Cube2 engine demo (The CrossBridge Cube2 port is not yet rendering correctly). However, in my test, for the latest Emscripten SDK (emsdk-1.21.0-web-64bit.exe), if you want to port your SDL applications or games, very likely, you will fail. That's because the support of SDL, although is working for many cases, is far from complete. What's more, the officially supported SDL version is SDL 1.3, while most old games/application are based on SDL 1.2 and most new ones are based on the latest SDL 2 (There're many API differences among these versions). Many SDL functions are not supported or implemented, such as very commonly used "SDL_DisplayFormat", "SDL_ConvertSurface". So when you compile, you may get "unresolved symbols" warnings and a black screen - the compiled application will just not run. Although there is an unofficial SDL port for Emscripten, I'm not sure whether it is worthy of trying.

Fortunately, Emscripten SDK is under very active development, unlike the almost abandoned CrossBridge. I'm looking forward to a future version with more features and great improvements. By the way, there is an unofficial fork of the CrossBridge SDK, which pulled many things together and collected lots of  examples:, I'm also watching on the project, hope it will continue to involve.

I think, the same problem for both CrossBridge and Emscripten is, there are not many games/applications written in C/C++ there waiting to be ported to the browser platform, so only a few people are actually using these cross language compilers. The reason is most games written in C/C++ are not designed for the browser platform. So if there exists a tool can compile AS3 to JavaScript, I believe it will be very, very popular. And one factor that Emscripten will be more popular than CrossBridge is that JavaScript is not a suitable language for programming large scale games and applications, but AS3 itself is good enough to handle many large projects.

Sunday, August 3, 2014

Using CrossBridge/FlasCC for Code Obfuscation

One advantage of using CrossBridge is that, because your source code is written in C/C++, it's very hard to decompile.Although some decompilers can give you the decompiled ActionScript code from the swf file, it is impossible to recover the original C/C++ source code. What's more, the decompiled ActionScript code is almost unreadable.

See what the official CrossBridge document says:

FlasCC is not designed to be an obfuscator for either ActionScript or C/C++ code. Although the generated ActionScript bytecode should be no easier to reverse engineer than natively compiled machine code the FlasCC engineering team makes no strong claims about this, nor do they test whether this is true.
By default the mangled C++ name of every source function will be trivially visible in both the decompiled output and also in ActionScript debugger and profilers. To hide the names of any generated C/C++ functions you can pass -fllvm-opt-opt=-strip to gcc so that any function names not listed in your exports.txt file will be renamed to a symbol of the form __unnamed_N. Functions that need to be called from ActionScript, which you must protect by listing in exports.txt, will not be renamed.
So to ensure the encryption strength of CrossBridge, you can just pass the option "-fllvm-opt-opt=-strip" to gcc when compiling, this will obfuscate all the function names. By the way, it's possible to use some C/C++ source code obfuscators first before compiling with CrossBridge.


Wednesday, July 30, 2014

Migrating from Alchemy to CrossBridge/FlasCC - Interop between C/C++ and ActionScript

Part I - Calling C/C++ functions from AS3

For calling C/C++ functions from AS3, one way is use the "as3sig:" annotation to expose some C/C++ functions to AS3. See the CrossBridge Sample 5 SWC and my previous post Another way is to use "CModule.callI(CModule.getPublicSymbol("youCfunctionname"), args)", see the Sample 4 Animation, where for C++, you will need "extern" declaration before your function definition to prevent the compiler renaming the function.

Part II - Calling AS3 functions from C/C++

To call build-in AS3 functions, you can either use "inline_as3" (see Sample 2 Interop between C/C++ and ActionScript. Actually, asm was also available in Alchemy, although not officially documented) or the API provided by "AS3.h" and "Flash++.h". You can also define local AS3 functions or equivalent C/C++ functions using the two methods in your C/C++ source file. However, if you want to call an AS3 function outside your C/C++ file, e.g., in the "", you may need to pass the reference of your AS3 function or the function host - your main AS3 class to C/C++. There are two different cases depending whether your run the C/C++ code in the background worker.

Case 1 - C/C++ code in UI worker.

If you invoke your C/C++'s main function using "CModule.start()", or "CModule.startAsync()", or just simply call some C/C++ function using the methods in Part I without executing the C/C++ main function, the C/C++ code will run in the UI worker, the same domain as your main AS3 console class. Then things are easy and there are various ways for passing your Main class's reference, see my examples:

Case 2 - C/C++ code in background worker.

If you invoke your C/C++'s main function using "CModule.startBackground()", and want to call some outside AS3 function from your C/C++'s main function, then the thing become a little tricky, because you're not able to share a function reference between workers, i.e., there is no way to pass a function reference from the UI worker - your Main/Console class to the background worker - your C/C++ code, as the class/function reference can't be serialized in AMF3 format. There is one way to circumvent the problem, using MessageChannels:

In other situations, you can access your Main UI class's properties from the background worker by the "avm2_ui_thunk" and "CModule.serviceUIRequests" combinations, see for details.


Tuesday, July 15, 2014

Crossbridge Quake1 Example Simplified

I made some minor modifications of the official Crossbridge Quake1 example so that the source code is easier to use and mod. The original source code uses a very different workflow from the old Alchemy, that is, compile everything, including the C/C++ code, AS code and data file, into the final swf file directly via a single Makefile. Although this approach is elegant and simple as a sample of the Crossbrige SDK, it will cause several inconveniences for a real project. The drawback is obvious, once you changed something, either the C/C++ code, AS code or the data file, you need to recompile everything.

On the other hand, the old Alchemy workflow, that is, compile all the C/C++ code into an independent swc first, then import the swc in the AS project, is more efficient. Although it is possible to use several separated makefiles for different steps of the whole compiling process, the old Alchemy workflow is more friendly to Flash developers.

So what I did in the simplified version is

1. Changed Makefile to compile the swc instead of swf.
The original Makefile mixes gcc and asc, where gcc is used to compile all the C source files into .o files and the final swf file, and asc is used to compile the "" file. I just removed the part for compiling the "" file. (The modified "" file will be used as the Main class for the AS project, in which it will be linked with the swc file later.) Then, changed the option "-emit-swf" for gcc to "-emit-swc" so the swc file, instead of the swf file, will be created.

2. Simplified the way for supplying the file "pak0.pak" to C/C++, so no "genfs" needed.
Crossbrige introduces genfs for the file system. This can be seen as an advantage over Alchemy, but personally, I feel it is not so easy to use. Crossbrige uses the genfs tool to convert all your files/folders needed in your C/C++ code into plain AS text files so the compiler can compile the converted data files into your swf. However, this is a disaster for modding - every time you change the data files, you need to genfs them into AS files first before they can be used in your Corssbrige projects. Fortunately, there is a simple alternative way (the Alchemy-like way, not officially documented, but actually use the same API as the genfs way) for supplying data to C/C++, see this post for details. In this way, you handle all the data using AS3 only, so you can embed files using AS3 code, or load them on the run using a URLLoader.

There is one problem, beyond the quake example. That is when you need to supply many files or folders to C/C++. Manually embedding them in pure AS3 is troublesome. In this scenario, it seems the genfs tool will save your the trouble. However, this can also be solved by pure AS3. My solution is zip everything as one package first, then use some AS3 zip library (such as, to supply all files programmably. (Actually, the quake data file is a zipped package of many files and folders in a custom format ".pak", and the engine itself takes care of all the unzipping, parsing and loading processes.)

3. Created the FlashDevelop project.
Added the swc file generated previously to lib, modified the "" file, which imports classes/packages needed from the swc file, and embed the game data file in the Main class "". Besides, an unimplemented preloader class is added in the AS project. The official way for adding preloader directly for Crossbrige generated swf is also not very handy. With an AS project, it's trivial work to implement the preloader.

You can find the source code:
(SVN, source code only)
(All in One Package, everything you need to compile)

What I learned from the original quake example

The most important files in the example are "", "sys_sdl.c", "snd_mix.c". The file "sys_sdl.c" is where you can find the C main function, besides, in the file "sys_sdl.c", function
engineTick() is the main game loop, and
engineTickSound() is the main sound loop.

The sdlquake example almost answers most questions when you want to port an SDL based application or game to Flash with Crossbridge.

Q1. How to start the main game loop?
There are two ways showed in the example to run the main game loop in each frame. The first one is to call the C/C++ main loop function engineTick() from AS3 in an EnterFrame event handler, see the line

CModule.callI(enginetickptr, emptyArgs)
in "". This is single threaded and everything, including both the main game loop and the screen buffer rendering, runs in the main UI worker only.
The second one is to use a background worker, so you can put the main loop function in an infinite while(true) loop in the C main function. In this case, you need two threads, the background worker (all C code) is running the main game loop and does the blitting job while the main UI worker only renders the screen buffer in the EnterFrame event handler. see this post for more.

Q2. How to render the ScreenBuffer?
As I explained in, all you need to do is to get pointer to the Screen Buffer(data/array of colour values) of your C/C++ code, see the line
vbuffer = CModule.getPublicSymbol("__avm2_vgl_argb_buffer")
in "", then create a BitmapData and use the setPixels method to render the buffer.

Q3. How to get the Keyboard input?
Of course you need to listen the KEY_UP and KEY_DOWN events in AS3. Then you can implement the "read" function in "", so that key inputs can be read by C using normal C IO.

Q4. How to get the Mouse input?
The example showed how to let C know the mouse position. Firstly, mouse position "mx" and "my" can be captured in AS3.
If you're running the main loop in the UI worker (ST), get the pointer of the C variables for storing mouse position:
vgl_mx = CModule.getPublicSymbol("vgl_cur_mx")
vgl_my = CModule.getPublicSymbol("vgl_cur_my")
Then use domain memory to update the values of the two C variables directly in AS3:
CModule.write32(vgl_mx, mx)
CModule.write32(vgl_my, my)

If you're in MT mode, things are a little tricky. The "handleFrame()" in "sys_sdl.c" is for getting mouse input. The function used inline asm to get the values for the mouse positions.
"import com.adobe.flascc.CModule;\n"
"%0 =\n"
"%1 =\n"
: "=r"(vgl_cur_mx),"=r"(vgl_cur_my) :
Since you're running the main loop in the background and mouse position can only be retrieved from the UI worker, you need the
avm2_ui_thunk(handleFrame, NULL);
(in C, the main game loop, where you need to update the mouse position, to queue up uiThunk request for calling handleFrame on the UI Worker)
(in AS3, the EnterFrame handler, to service the pending uiThunk request) combination.

Q5. How to play the sound data?
Use Sound and SoundChannel class in AS3 to play sound data. To get the sound sample data, use inline asm to writeFloat, and the proxy variable "sndDataBuffer" in AS3, see "snd_mix.c" and "" for details.

Q6. How to supply the files to C?
See the previous section where I talked about the file system.

Some other notes:

1. If you're using 32-bit system with 32-bit java, you need to pass the option -jvmopt="-Xmx1G" to gcc/g++, otherwise, you may get the error "LLVM ERROR: Error: Unable to launch the Java Virtual Machine. This usually means you have a 32bit JVM installed or have set your Java heap size too large. Try lowering the Java heap size by passing "-jvmopt=-Xmx1G" to gcc/g++."

2. On windows, when compiling the original source code, if the compiler complains that "" is locked and not accessible, try to use some software to unlock the file "", then compile again.

Special thanks to Michael Guidry (MadGypsy on for motivating me to write this post.

Thursday, May 1, 2014

Migrating from Alchemy to FlasCC/CrossBridge - The flyield() Method Alternative

In Alchemy, when you're compiling and reusing C/C++ code in Flash, you may encounter the problem caused by loops. In C/C++, it's very common to use a infinity loop such as

where we will put everything such as main game logic, into the loop and break the loop when certain conditions are satisfied. However, this way doesn't work for Flash. At the time of Alchemy, Flash/Action Script 3 was still 'single' threaded. This infinity loop will block everything - no UI updates, no interaction responses, the Flash program looks like dead - as everything else is waiting for the loop to finish. One way to solve the problem is to break this C/C++ run-loop into frame by frame calls on the AS3 side (See CrossBridge SDK's "Sample 4: Animation" for details). At that time, we have one handy function called "flyield()" in the Alchemy C/C++ API, to simplify the solution. All you need is to stuff such function into those infinity loops, and declare the functions contains those infinity loops as "AS3_FunctionAsync". And when Flash sees this "flyield()" function, it will know that it should freeze the loop for a while, jump out to update the UI and let other things work, then come back to run the loop again.

However, there is no such function "flyield()" any more in FlasCC/CrossBridge. But now, we have two ways to deal with such infinity loops. One is the way provided by the newly introduced concurrency API, the other is the classical "flyield()"-like way.

Thanks to the new concurrency API of Action Script 3, you will never need to worry about the error that "Error #1502: A script has executed for longer than the default timeout period of 15 seconds". With workers, you can do all the computation intensive calculations in the background, and let the UI runs in main thread. So those intensive calculations will not block your whole program any more. And the concurrency API is also available in FlasCC/CrossBridge. To use the concurrency API, you can check the "Sample 9 - Pthreads" in the CrossBridge SDK.

In FlasCC/CrossBridge, you simply can run all the C/C++ code in the background worker by the following line in your "".
CModule.startBackground(this, new [], new [])
The most common case is in your Main loop, you need to pause the logic and let the UI listen to the user input. In many C/C++ applications, the waiting for user input model is an infinity loop. In this case, you can use "avm2_self_msleep" to pause the loop and add an input event listener, once get the user input, use "avm2_wake" to resume the loop and the main logic.
See the following source code of for more details:
(especially the file "FlasCCPortLayer.cpp". Update: (2014/7/18) Alternative way for getting input is to use the "avm2_ui_thunk" and "CModule.serviceUIRequests" combination, see the Crossbridge quake1 example for details.)

The above way works for some cases, for example when the C/C++ function consume a lot time to run, but is not so convenient for many C/C++ game logic as the old " flyield()" function in the aforementioned case. You need to reorganize the code structure using workers. To make things easy, actually, there is an almost equivalent function in FlasCC/CrossBridge - "avm2_wait_for_ui_frame".
To use this "flyield()" alternative, you must also run your C/C++ code in the background. In other words, you need the following code in your "" again:
CModule.startBackground(this, new [], new [])
Then, all you need to do is to insert the following code
somewhere in the infinity loop.

One drawback of this method is that you need to put the C/C++ loop in your main function. This is not very convenient as the old "AS3_FunctionAsync" declaration in Alchemy when you want to pass some parameters into the loop. One way is to initialize parameter as global variables in C/C++ by passing values from AS3 side before call the C/C++ main function(CModule.startBackground), another way is to use the C/C++ "argv" - the second parameter of CModule.startBackground. Well, this may solve the problem to pass parameters, another important issue is that how to return values from C/C++ main to AS3? So you can see this workaround, which only works with the C/C++ main function, is still not so convenient as the old asynchronous functions in Alchemy. In this case, different from the main logic loop, actually you usually want a C/C++ function to do some time consuming calculation and return the result, while not be restricted by the Flash script execution time limit. To resolve all the difficulties and troubles fundamentally, you'd better use the more advanced and complicated Pthreads (See "Sample 9: Pthreads") and Workers (run the FlasCC/CrossBridge wrapper function in the background as what you can do with a time consuming AS3 function, see for example with FlasCC/CrossBridge.

Source code of an example using avm2_wait_for_ui_frame:


Thursday, April 24, 2014

Free JavaScript Obfuscators

A List of Free JavaScript Obfuscators Compressors, Packers, Encryptors, Protectors, Optimizers!

A free and efficient obfuscator for JavaScript (including ES6):

Web based tool to protect JavaScript code from stealing and shrinks size:

JavaScript Obfuscator - JS Packer:

Convert human readable javascript to a more shrouded code:

ObfuscateJS - Javascript Obfuscator:

Inline JavaScript Obfuscator:
JavaScript Obfuscator, Minifier, and Packer:

YUI Compressor by Yahoo:

JavaScript Utility:

A JavaScript Compressor, version 3.0:


Javascript Obfuscation and Compression: 

Free online javascript and html obfuscator:


Free online html/js obfuscator:

JSMin - The JavaScript Minifier:

HaxMin - JavaScript obfuscator, powered by Haxe, intended for use with Haxe-generated JavaScript code:

JavaScript minification:

The impressive js segment compiler:

A JavaScript optimizer by Google:

A JavaScript optimizer by Facebook (update on 2017/5/4):

Want to test the results? Try the following de-obfuscator (Via

A review and how to combine the power of multiple obfuscators:

Code Protection and Packaging for Node.js Projects with JXCore:

JS & CSS Minifier:


Feel free to share your tools/opinions in the comments!

Saturday, April 12, 2014

RealBengine - When Bengine Goes to Real 3D

This maybe the future version of my voxel based rendering engine Bengine, code name "RealBengine". Different from the current version of Bengine, which use ray-casting and is 2.5D, RealBengine will use ray-tracing and hence you will have 6 degree of freedom instead only 4. That means you can look up and down freely without any limit. The current version of Bengine can simulate look up and down a little bit using the distorted projection trick, but this is very limited - about +/-30 degree rotation around the X-Y plane at most. What's more, in RealBengine, you're working with real 3D, so most of the algorithm has been simplified because now you're using 3D vectors rather than fake 3D trick math.

And because of the essential difference in the rendering core, RealBengine will be a totally different engine and will be written from scratch in the future. However, RealBengine is not my priority for now. A similar example with source code using ray-tracing for voxel rendering can be found at:

An old working demo of RealBengine(Win32 binary):

This demo was written in HaXe/NME and compiled to the CPP target some time ago. This is just a simple quick proof of the ray-tracing voxel rendering algorithm. The demo needs optimization as it is slow (about 10~15 FPS in my test). A Flash/SWF version exists but too slow now.

Sunday, March 30, 2014

Use Adobe Air to build a mobile APP for your Blog

With Adobe Air, you can easily create a mobile APP for your Blogger powered blog site. What you need is the StageWebView class, which can load and show any html/javascript based web site on the stage within your APP.

But firstly, go to your Blogger dashboard, in the Template tab, enable the Mobile template. (See this post for more details: After this, when visit your Blogger site from mobile device (via mobile browser or APP), your blog will be displayed in a mobile friendly way.

Next, all we need to do is to load your blog url and display it on the stage using the StageWebView class. Here are some code:

var webBrowser:StageWebView = new StageWebView();
webBrowser.stage = this.stage;
webBrowser.viewPort = new Rectangle(0, 0, this.stage.stageWidth, this.stage.stageHeight);

With these code, the Air APP can load and display your blog by itself. Sometimes, you want to call the device's browser for opening the external links - links not belong to your blog, so the APP behaves more like a blog APP other than a simple browser for viewing any url. To do this, you can use the LOCATION_CHANGING event of the StageWebView class. Whenever a user clicked a link, check if it is an external link, then decide whether to display it within the APP using StageWebView class or use the navigateToURL method to open the link by external web browsers. The code:
webBrowser.addEventListener(LocationChangeEvent.LOCATION_CHANGING, onLocationChanging);
function onLocationChanging(event:LocationChangeEvent):void
                   var newURL:String = event.location;
                   if ('blogspot.') == -1)
                   navigateToURL(new URLRequest(newURL));

Besides, we may also interested in the "historyBack()" and "historyForward()" methods. With these two methods, you can navigate to the previous/next page in the browsing history. Actually, you can even create a fake mobile browser using the API provided by StageWebView class after adding UIs.

Finally, if you want, you can publish your Blogger site with the mobile app to Google Play or the App Store.

The Demo of my Blog (APK for Android):

Full FlashDevelop project with source code: