Showing posts with label HaXe. Show all posts
Showing posts with label HaXe. Show all posts

Friday, February 8, 2019

Four ways for per pixel bitmap manipulation in OpenFL

A BitmapData can be seen as an array of length width*height, holding unsigned int colors values. There are at least four ways to manipulate pixels of a bitmap image(Bitmap/BitmapData) in OpenFL. The first way is using setPixel() or setPixel32() function:

var myBitmapData:BitmapData = new BitmapData(800, 600, true, 0);
myBitmapData.lock();
for (j in 0...600)
    {
    for (i in 0...200)
        {
         myBitmapData.setPixel32(i, j, (i % 255) << 24 | 0x0000ff);
        }
    }
myBitmapData.unlock();
You can use lock() and unlock() function before and after multiple calls of setPixel() function, so the BitmapData will only be updated on Screen after unlock(). The second way is using setVector() function, and a Vector of UInt to hold pixel values:
var myVector:Vector = new Vector(200 * 600, true);
for (j in 0...600)
    {
    for (i in 0...200)
        {
        myVector[j * 200 + i] = (i % 255) << 24 | 0x0000ff;
        }
    }
var myRect2:Rectangle = new Rectangle(200, 0, 200, 600);
myBitmapData.setVector(myRect2,myVector);
The third way is using setPixels() function, and a ByteArray to hold pixel values:
var myByteArray:ByteArray = new ByteArray(200 * 600 * 4);
for (j in 0...600)
   {
   for (i in 0...200)
       {
       //myByteArray.position = (j * 200 + i) * 4;
       myByteArray.writeUnsignedInt((i % 255) << 24 | 0x0000ff);
       }
   }
var myRect4:Rectangle = new Rectangle(400, 0, 200, 600);
myByteArray.position = 0;
myBitmapData.setPixels(myRect4,myByteArray);
Remember to set the position of the ByteArray to 0 before calling setPixels(). The position "(j * width + i) * 4" of the ByteArray is associated with the pixel at (x=i,y=j) in the BitmapData. There is no need to set the position of the ByteArray to "(j * 200 + i) * 4" above since in the double for loops the "writeUnsignedInt()" function will update the position automatically. The fourth way is using the Memoery API, which is similar to the third way. See https://bruce-lab.blogspot.com/2013/03/fast-way-for-per-pixel-bitmap.html for more details.
var myMem:ByteArray = new ByteArray(200 * 600 * 4);
Memory.select(myMem);
for (j in 0...600)
    {
    for (i in 0...200)
        {
        Memory.setI32((j * 200 + i) * 4, (i % 255) << 24 | 0x0000ff);
        }
    }
var myRect4:Rectangle = new Rectangle(600, 0, 200, 600);
myMem.position = 0;
myBitmapData.setPixels(myRect4,myMem);
The full source code: See the result here (HTML5): http://vvv.flaswf.tk/demo/?url=BitmapDataPixel

Sunday, February 15, 2015

CuBengine Ported to OpenFL - New Demo Rendering Voxelstein3D's Map at Full Size

Finally, I finished porting my CuBengine prototype to OpenFL, so the engine now supports more platforms instead of Flash only. Here are some screen shots from the Windows binary, showing the engine rendering the Voxelstein3D's map. Different from the old demo of the original Bengine, which is rendering a scaled Voxelstein3D's map with size 256x256x64, in this new demo, CuBengine is rendering the map with full size (1024x1024x256). This is one advantage of CuBengine over Bengine - Bengine use the raw voxel data format so it only support maximum map size of 256^3, while CuBengine can support very large voxel map with a compressed format, and the maximum size can be 65536^3, subject to hardware limits.

You can download the Win-32 build at https://drive.google.com/file/d/0B5V2PrQ8xX_ENkZsbER6b1UtY2M/view?usp=sharing

Tuesday, January 6, 2015

First Demo of My New Voxel Rendering Engine - CuBengine

CuBengine is the latest derivative of my voxel engine Bengine. The main difference of CuBengine and original Bengine is that CuBengine renders each voxel as a 3D cube while Bengine render each voxel as a 2D pixel square (or 3D billboard). Besides the screen representation of voxels, CuBengine also has many enhanced features over the original Bengine, such as higher resolution, less memory consumption and supporting larger level maps. Actually, CuBengine is a completely rewrite from scratch. Currently CuBengine is written in AS3 with rendering core in HaXe, but it will be soon ported to OpenFL and HaXe.

First Demo of CuBengine (Flash):
https://googledrive.com/host/0B5V2PrQ8xX_EUzI3OGt1S202TVk

Controls:
KeyBoard
WSAD - Move
Arrow Keys - Look
Ctrl - Go Down
Space - Go Up
You can also use the on screen joystick, which is designed for touch enabled devices, to replace all the keyboard controls. To hide/show the joystick, right click and then left click the menu button "◇{On Screen Joystick}".

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: http://community.openfl.org/t/bitmapdata-setpixels-doesnt-work-in-html5/348/3

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):
https://drive.google.com/folderview?id=0B5V2PrQ8xX_Ed0sxQkNFM0RGLWs&usp=sharing

DEMO (HTML5):
https://googledrive.com/host/0B5V2PrQ8xX_Ec3J4VzJYcFhrUzQ
Controls:

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

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
root.loaderInfo.loaderURL;
//or
root.loaderInfo.url;
and for finding the path url of the embedding page, you can use
ExternalInterface.call("window.location.href");
Besides, it's common to see url parameters, for example: "http://mysite.com/index.html?param1=1234&param2=somestr&param2=someotherstr" To read the parameters, in the above example, that is "1234", "somestr" and "someotherstr", in JavaScript, you can use the snippet provided by http://stackoverflow.com/a/979995/1100006 or the function given at http://css-tricks.com/snippets/javascript/get-url-variables
In HaXe, you can use the following HaXe function
//translated from http://css-tricks.com/snippets/javascript/get-url-variables/
function getQueryVariable(variable):String
{
       var query:String = js.Browser.window.location.search.substring(1);
       var vars:Array = query.split("&");
       for ( i in 0...vars.length) {
               var pair:Array = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return("null");
}
In AS3, if the parameters are given in the path of the swf' url, for example, "http://mysite.com/myswf.swf?param1=1234&param2=somestr&param2=someotherstr", 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:
http://snipplr.com/view/44852/how-to-access-query-string-arguments-with-as3/ http://www.abdulqabiz.com/blog/archives/2006/03/06/how-to-get-url-query-string-variables-within-flex-application/

References:
http://stackoverflow.com/questions/979975/how-to-get-the-value-from-url-parameter http://www.javascriptcookbook.com/article/Get-the-current-URL-via-JavaScript
http://stackoverflow.com/questions/2127962/get-current-browser-url-actionscript-3
http://snipplr.com/view/47055/get-url-of-the-page-where-swf-is-embedded/ http://snipplr.com/view/28103/as3-get-url-of-current-flash-movie-swf/

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 http://old.haxe.org/manual/swc:

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 http://flassari.is/2008/07/swf-class-explorer-for-as3/. 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.

Links:
http://old.haxe.org/manual/swc#creating-swc-with-haxe
http://www.openfl.org/archive/community/general-discussion/how-create-swc-openfl/
https://groups.google.com/forum/#!topic/haxelang/sld9ov4D-tA
http://stackoverflow.com/questions/13020201/how-could-i-convert-an-existing-swf-file-to-an-swc-for-using-as-a-library

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:
https://flaswf.googlecode.com/svn/trunk/JiuGongGeUI-v0.2/src/TextParser.hx
TextParser is also available in AS3 as a swc:
https://flaswf.googlecode.com/svn/trunk/JiuGongGeUI-v0.2/swc/TextParser.swc
To use the class, add the following line in your main class first:

haxe.initSwc(this);

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();
trace(Name);
if (Name == "#") //comment line
{
    myTextParser.GotoNextLine();
    continue;
}
var CallBackStr:String = myTextParser.ReadString();
trace(CallBackStr);
var IconStr:String = myTextParser.ReadString();
trace(IconStr);
var Color:uint = myTextParser.ReadInteger();
trace(Color);
var Label:String = myTextParser.ReadString();
trace(Label);
var LevelStr:String = myTextParser.ReadString();
trace(LevelStr);
myTextParser.GotoNextLine();
}
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:
https://flaswf.googlecode.com/svn/trunk/JiuGongGeUI-v0.2/swc/src/Main_TP.as

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

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();
addChild(myJGG);
myJGG.x = 300;
myJGG.y = 200;
But nothing happens until you initialize the UI:
  
myJGG.init(this,this,Assets.getText("assets/UILayout.txt"));
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)
 {   
  trace(event.target.name);
 }

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: https://flaswf.googlecode.com/svn/trunk/JiuGongGeUI-v0.2/assets/UILayout.txt

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: https://flaswf.googlecode.com/svn/trunk/JiuGongGeUI-v0.2/src/Main.hx

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 http://haxeui.org/ or http://ui.stablex.ru.

Links:
Flash demo: http://flaswf.googlecode.com/svn/trunk/JiuGongGeUI-v0.2/bin/flash/bin/JiuGongGe.swf
HTML5 demo: http://flaswf.googlecode.com/svn/trunk/JiuGongGeUI-v0.2/bin/html5/bin/index.html
Real Example (BNote): http://bruce-lab.blogspot.com/2014/10/bnote-free-online-taking-handwriting-notes.html
Source Code v0.2 (MIT): https://flaswf.googlecode.com/svn/trunk/JiuGongGeUI-v0.2
SWC for Flash/AS3: http://bruce-lab.blogspot.com/2014/11/jiugonggeswc-jiugongge-ui-for-flash-as3.html

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:
http://bruce-lab.blogspot.com/2011/08/simple-ray-tracing-voxel-demo.html



An old working demo of RealBengine(Win32 binary):
https://drive.google.com/file/d/0B5V2PrQ8xX_EaEZ0ai1hblMwZGc/edit?usp=sharing

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 24, 2013

Fast way for per pixel bitmap manipulation in HaXe NME

I'm not sure whether this is the fastest way, but the nme.Memory API is something you must know for per pixel bitmap manipulation in NME. I learned the method from the stackoverflow thread here:
http://stackoverflow.com/questions/10157787/haxe-nme-fastest-method-for-per-pixel-bitmap-manipulation
nme.Memory support both flash and cpp targets. For flash, it use the Alchemy fast memory opcodes which can greatly boost the speed.

I ported Ralph Hauwert's Alchemy lookup-table effects to NME as a simple example for showing you how to use nme.Memory API for per pixel bitmap manipulation.

The basic idea is to do everything using a ByteArray. Create a ByteArray to hold your screen buffer, select it and use the getI32/setI32 function of the nme.Memory API. One problem is when you need to use extra data, such as some texture buffer in the process, you may need another ByteArray to hold your data. Because "selecting different memory blocks in cycles may lead to a performance loss", as stated in the API's docs, the simple trick is to create a single ByteArray as the virtual RAM, and write everything into it, while store the different position variables of the data block for later use.

In my example, I use the first part of the virtual RAM ByteArray for screen buffer and the next part for holding the texture. So you can just use the "select" function only once and then get/set values from different data blocks by the position variables you stored as the offsets of the virtual RAM's addresses.

Source Code of the example:
https://flaswf.googlecode.com/svn/trunk/flaswfblog/Tutorials/HXFastBitmapData
Binary:  
(Win-32)https://flaswf.googlecode.com/svn/trunk/flaswfblog/Tutorials/HXFastBitmapData/bin/w32-bin.zip
(Flash)https://flaswf.googlecode.com/svn/trunk/flaswfblog/Tutorials/HXFastBitmapData/bin/HXFastBitmapData.swf 

For pure AS3 projects, the Azoth tool also provides similar memory API for utilizing the Alchemy opcodes. If you don't want any Alchemy opcodes, you may try Vectors in AS3.

Update 2013/04/11: ASC2 now supports using fast memory opcodes in AS3.
Update 2013/05/08: Only AIR SDK 3.6 support those fast opcodes, the latest SDK 3.7 won't compile. You can download the SDK 3.6 here:
http://helpx.adobe.com/air/kb/archived-air-sdk-version.html
http://helpx.adobe.com/flash-player/release-note/fp_116_air_36_release_notes.html

Update 2013/05/07: This method also works on Android platform:
Try this pre-build apk:
https://flaswf.googlecode.com/svn/trunk/flaswfblog/Tutorials/HXFastBitmapData/bin/HXFastBitmapData-debug.apk

Note: When compiling for Android, run "nme setup android" first, you will install Android SDK, Android NDK, Apache ANT and Java SDK.Then open Android SDK manager and install Android 2.2 (API 8), otherwise you may encounter the "Unable to resolve target 'android-8'" problem:
http://www.nme.io/community/forums/installing-nme/unable-to-resolve-target-android-8/

Links:
http://haxe.org/api/flash/memory
http://www.nme.io/api/types/nme/Memory.html
http://stackoverflow.com/questions/10157787/haxe-nme-fastest-method-for-per-pixel-bitmap-manipulation
FlasCC version of the example: http://bruce-lab.blogspot.com/2012/12/migrating-from-alchemy-to-flascc.html
http://philippe.elsass.me/2010/05/as3-fast-memory-access-without-alchemy/
Compile AS3 Fast Memory Opcodes by ASC2:
http://obtw.wordpress.com/2013/04/03/making-bytearray-faster/

TIPS: There is no good tools for auto-formatting HaXe source code as far as I know. (FlashDevelop only supports AS3 formatting.) So I use Emacs. First rename the XXX.hx file to XXX.java, open it in Emacs, C-x h (M-x mark-whole-buffer) C-M-\ (M-x indent-region), rename it back to XXX.hx, that's it.

Sunday, December 23, 2012

Use HxSL/Stage3D to Create 2D Filters/Shaders

Update on 2014/01/04:
Many things changed since the original post was published. Now HaXe is 3.0 and HXSL reaches 2.0. So here is the updated source code of the example for HaXe 3 and HXSL 2:
https://flaswf.googlecode.com/svn/trunk/flaswfblog/Tutorials/HxSL2DShader/HaXe3HXSL2/
====================

Maybe you know how to use Pixel Bender in your Flash project to create some custom filters. Alternatively, with the new Stage3D API introduced in Flash 11, we can write 2D filters running with GPU. Here is the example:



The idea is simple: draw a plane using two triangles, upload the images you want to process as textures and do all the magic in your fragment shaders. I recommended you to try HxSL, an advanced shader language which has similar grammar to the Pixel Bender language. The above example - Poster Effect is ported from the Pixel Bender filter with only a few modifications of the original Pixel Bender filter code.

The full source code of the above example (HaXe/HxSL):
https://flaswf.googlecode.com/svn/trunk/flaswfblog/Tutorials/HxSL2DShader
The source code of the Poster Shader in Pixel Bender Language:
http://www.adobe.com/cfusion/exchange/index.cfm?event=extensionDetail&loc=en_us&extid=2400022

Links:
Announcing HxSL:
http://ncannasse.fr/blog/announcing_hxsl
Using Flash 3D API:
http://haxe.org/doc/advanced/flash3d
HxSL API:
http://haxe.org/manual/hxsl

Thursday, August 2, 2012

Haxenme Installation Notes

1. Download the standalone installation package NME-3.4.0-Windows.exe at
http://www.haxenme.org/download/
(Haxe [2.10], Neko [1.8.2], NME [3.4.0], HXCPP [2.10], Actuate [1.43], SWF [1.13])

2. Click and run to install.
(2013/3/15:
Tips: For updating NME from an older version, the simplest way is to download the new setup package, and reinstall. Uncheck the things that are already newest here, e.g., Haxe, Neko. Then select the same folder of the old installation.
http://www.nme.io/community/forums/feature-requests/eficient-way-to-upgrade-nme/)





3. Setup HaXe:
Go to D:\Motion-Twin\haxe, run haxesetup.exe


Done! Now let's test it.

4. Go to cmd:
haxe

nme


5. Now download the sample file at
http://www.joshuagranick.com/blog/2012/02/22/nme-game-example-pirate-pig/
to test.
Unzip the source code "jgranick-PiratePig-9deb597.zip" to D:\TEST_PROJECTS\jgranick-PiratePig-9deb597.
cmd commands to build the swf:
cd D:\TEST_PROJECTS\jgranick-PiratePig-9deb597
nme test "Pirate Pig.nmml" flash


and to build html:nme test project.nmml html5


6. Use Flashdevelop for nme projects. (You should install Flashdevelop at http://www.flashdevelop.org/ first)
Open Flashdevelop and configure haxe path:

Open "Pirate Pig.hxproj" and build the project:


7. To use haxecpp target windows, you need to install VC++ (nme setup windows) at
http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-cpp-express first.
After that
cd D:\TEST_PROJECTS\jgranick-PiratePig-9deb597
nme test "Pirate Pig.nmml" cpp

Friday, March 23, 2012

Simple Tutorial for using MochiAds with HaXeNME

HaXeNME (http://www.haxenme.org) is an open source, cross platform haxe lib for developing games using a Flash like api. Just try it if you don't know it. If you hope to write once and compile to flash/html5/cpp/ios..., HaXeNME should be your first choice. I never tried to use mochiads with haxenme, though I know it is totally possible. Since some one PMed me for this topic, I did a quick research and want to share it here as a reminder for future reference.

Note: this is not a detailed step-by-step tutorial for newbies, just a reminder. I assume you have some experience of developing with HaXeNME using FlashDevelop (http://www.flashdevelop.org). However, if you have problems, feel free to post it here below.

The general steps for using mochiads with HaXeNME:

1. Download mochi api source code and compile all the AS3 source files into a "mochi.swc", unzip the swc file, rename the "library.swf" to "mochi.swf".

2. Generate the haxe source files needed for compiling your NME project:

haxe.exe -swf mochi.swf --no-output -swf-lib mochi.swf --gen-hx-classes 
Copy the genetated "mochi" folder (in its "as3" subfolder you should find lots of haxe files, such as "MochiAd.hx", "MochiCoins.hx", ...) into your project's "src" folder.

3. Import the mochi apis in your haxe project's main class:
import mochi.as3.MochiAd;
import mochi.as3.MochiServices;
To show pregame ads, for example, using the following code, similar to AS3:
MochiServices.connect("60347b2977273733", root);
MochiAd.showPreGameAd( { id:"60347b2977273733", res:"640x580", clip: root} );

4. Edit your project's "application.nmml", add the following line to force the haxe compiler to link "mochi.swf":
<compilerflag name="-swf-lib yourpath/mochi.swf"/>
Make sure the path to "mochi.swf" is correct.

5. Compile your project, that's all.
(Besides, you can use other swf libs with haxenme similarly.)

Full source code of my test project:
https://flaswf.googlecode.com/svn/trunk/flaswfblog/Tutorials/HaXeNME MochiAds Test
And the demo swf proving it works:
https://flaswf.googlecode.com/svn/trunk/flaswfblog/Tutorials/HaXeNME MochiAds Test/bin/flash/bin/HaXeNMEMochiAdsTest.swf 

Links: 
1. NMML File Format: http://www.haxenme.org/developers/documentation/nmml-project-files/
2. http://haxe.org/doc/start/flash#using-the-library
http://www.alexjeffery.org/programming/how-to-embed-a-swf-file-in-haxe/
http://wootfu.com/2011/08/using-mochiads-with-haxe/
http://brianin3d.wordpress.com/2010/08/04/kit-kat-toe-mochiads-with-haxe/

Monday, March 28, 2011

Molehill with HaXe/HxSL

Last update: Nov. 10, 2011, Upgraded to Flash Player 11.
Finally I decide to use HaXe, because it grants me what I can't reject-HxSL, the haXe Shader Language, which can let you write your shaders more efficiently.
First, follow the instructions to install HaXe for Flash Player 11:
http://haxe.org/doc/advanced/flash3d

Now some HaXe codes to get started(forked from the cube example):

/*
  Forked from http://haxe.org/doc/advanced/flash3d: Example 0 - Cube
  Nov. 10, 2011; BY Bruce Jawn
  [http://bruce-lab.blogspot.com]
*/
import format.agal.Tools;

typedef K = flash.ui.Keyboard;

class Shader extends format.hxsl.Shader {

  static var SRC = {
    var input : {
      /*input vertex format: 
 pos.x:float; pos.y:float; pos.z:float; color.r:float; color.g:float; color.b:float;
 should be consistent with the input vertexbuffer*/
    pos : Float3,/*vertex position as input*/
    col : Float3,/*vertex color as input*/
    };
    var color : Float3;/*temp color variable for output*/
    function vertex( mpos : M44, mproj : M44 ) {
      out = pos.xyzw * mpos * mproj;/*set vertex transformation*/
      color = col;/*set temp color as input color*/
    }
    function fragment() {
      out = color.xyzw;/*set output color*/
    }
  };

}

class Test {

  var stage : flash.display.Stage;
  var s : flash.display.Stage3D;
  var c : flash.display3D.Context3D;
  var shader : Shader;
  var pol : Polygon;
  var t : Float;
  var keys : Array;

  var camera : Camera;
  var vertexbuffer : flash.display3D.VertexBuffer3D;
  var indexbuffer : flash.display3D.IndexBuffer3D;
  function new() {
    t = 0;
    keys = [];
    stage = flash.Lib.current.stage;
    s = stage.stage3Ds[0];
    s.addEventListener( flash.events.Event.CONTEXT3D_CREATE, onReady );
    stage.addEventListener( flash.events.KeyboardEvent.KEY_DOWN, callback(onKey,true) );
    stage.addEventListener( flash.events.KeyboardEvent.KEY_UP, callback(onKey,false) );
    flash.Lib.current.addEventListener(flash.events.Event.ENTER_FRAME, update);
    s.requestContext3D();

    trace("Click the screen to get Focus!");
    trace("Arrow Keys: Rotation"); 
    trace("Z/X: Zoom in/out");   
  }//end of function new

  function onKey( down, e : flash.events.KeyboardEvent ) {
    keys[e.keyCode] = down;
  }//end of function onKey

  function onReady( _ ) {
    c = s.context3D;
    c.enableErrorChecking = true;
    c.configureBackBuffer( stage.stageWidth, stage.stageHeight, 0, true );

    shader = new Shader(c);
    camera = new Camera();
    /*
      Let's draw a plane, which contains 12 triangles:

      0------1------2------3
      |     /|     /|     /|
      | t0 / | t2 / | t4 / |
      |   /  |   /  |   /  |
      |  /   |  /   |  /   |
      | / t1 | / t3 | / t5 |
      |/     |/     |/     |
      4------5------6------7
      |     /|     /|     /|
      | t6 / | t8 / | t10/ |
      |   /  |   /  |   /  |
      |  /   |  /   |  /   |
      | / t7 | / t9 | / t11|
      |/     |/     |/     |
      8------9-----10-----11
      0-11: vertex index
      t0-t11: triangle index
    */
    vertexbuffer = c.createVertexBuffer(12,6);

    var myVertexes:flash.Vector = new flash.Vector(0,false);
    for(j in 0...3)
      for(i in 0...4)
 {
   //set the vertex's position
   myVertexes.push(i);//vertex.x
   myVertexes.push(j);//vertex.y
   myVertexes.push(0.0);//vertex.z
   //set the vertex's color(random)
   myVertexes.push(Math.random());//color.r
   myVertexes.push(Math.random());//color.g
   myVertexes.push(Math.random());//color.b
 }
    vertexbuffer.uploadFromVector(myVertexes,0,12);
    indexbuffer = c.createIndexBuffer(36);

    var myIndexes:flash.Vector = new flash.Vector(0,false);
    for(i in 0...2)
      for(j in 0...3)
 {
   //up:t0
   myIndexes.push(i*4+j);//triangle.a:0
   myIndexes.push(i*4+(j+1));//triangle.b:1
   myIndexes.push((i+1)*4+j);//triangle.c:4
   //down:t1
   myIndexes.push((i+1)*4+j);//triangle.a:4
   myIndexes.push(i*4+(j+1));//triangle.b:1
   myIndexes.push((i+1)*4+(j+1));//triangle.c:5
 }
    indexbuffer.uploadFromVector(myIndexes,0,36);

  }//end of function onReady

  function update(_) {
    if( c == null ) return;

    t += 0.01;

    c.clear(0, 0, 0, 1);
    c.setDepthTest( true, flash.display3D.Context3DCompareMode.LESS_EQUAL );
    c.setCulling(flash.display3D.Context3DTriangleFace.BACK);

    if( keys[K.UP] )
      camera.moveAxis(0,-0.1);
    if( keys[K.DOWN] )
      camera.moveAxis(0,0.1);
    if( keys[K.LEFT] )
      camera.moveAxis(-0.1,0);
    if( keys[K.RIGHT] )
      camera.moveAxis(0.1, 0);
    if( keys[88] )
      camera.zoom /= 1.05;
    if( keys[90] )
      camera.zoom *= 1.05;
    camera.update();

    var project = camera.m.toMatrix();
    var mpos = new flash.geom.Matrix3D();
    mpos.appendRotation(t * 10, flash.geom.Vector3D.Z_AXIS);

    shader.init(
  { mpos : mpos, mproj : project },
  {}
  );
    //draw the triangles  
    shader.bind(vertexbuffer);
    c.drawTriangles(indexbuffer,0,-1);
    c.present();
  }//end of function update

  static function main() {
    haxe.Log.setColor(0xFF0000);
    var inst = new Test();
  }//end of function main

}//end of class

Result:(Flash Player 11 needed!)



Source Code:
https://flaswf.googlecode.com/svn/trunk/flaswfblog/Tutorials/HaXeMolehillTest/

Links:

Announcing HxSL:
http://ncannasse.fr/blog/announcing_hxsl

Using Flash 3D API(lighting/texture examples):
http://haxe.org/doc/advanced/flash3d

HxSL Documentation:
http://haxe.org/manual/hxsl

Flash 11 API Doc:
http://www.flash3v.com/doc/flash11/

Tuesday, January 4, 2011

Ken Silverman's GROUFST2 Terrain Raycaster Ported to AS3


Simple nice heightmap terrain raycaster, a good start for your own voxel engine.
Fork it here:
http://wonderfl.net/c/7d41
or
http://flaswf.googlecode.com/svn/trunk/GROUFST2/
==========
Update: April, 4,2011
GROUFST2 Ported to HaXe(Supporting targeting swf and cpp both):
Source Code: https://flaswf.googlecode.com/svn/trunk/GROUFST2/Groufst2HXNME
==========
Update: 11, 11,2011
Add HTML5 support:
Source Code: https://flaswf.googlecode.com/svn/trunk/GROUFST2/Groufst2HXNME/Groufst2NME_HTML5/
DEMO:  https://flaswf.googlecode.com/svn/trunk/GROUFST2/Groufst2HXNME/Groufst2NME_HTML5/Export/html5/bin/index.html (Very, very slow.)
==========

Original source code can be found at Ken's website:
Qbasic: http://www.advsys.net/ken/voxlap.htm (GROUFST2.BAS)
EVALDRAW: http://www.advsys.net/ken/download.htm (evaldraw.zip\demos\groufst2b.kc)

And

Happy Coding 2011!

Sponsors