Main | August 2006 »

July 31, 2006

Genetic Algorythm Part1

I will introduce the implementation of Genetic Algorythm with ActionScript 2.0. This sample shows a world that multiple bugs walk around in the stage, and it will be based on how its own bugs work on one another's behaviors under any conditions. It only have two classes; the World class and the Bug class. The World class is used to store a string of a linkage id of the bug and a reference to a movieclip for attaching movieclips dynamically, and to create bugs into the target. The bug class have two numbers; a speed and a bearing as a vector to move around using onEnterFrame event.

source code

import ai.*;
var world = new World(this);
world.initialize(Bug.LINKAGE_ID, 6);

July 29, 2006

Blog時代の用語集(JP)

いわゆるブログが大衆化した現在、様々な関連用語が当たり前のように至る所で使われているが理解しているだろうか。

RSS RSSとはウェブサイトの更新情報を配信用にまとめた文書フォーマットのこと。

Trackback 相手側から自分へのリンクを相手側に作成させる機能。通常htmlリンクは自分→相手側へ作成するものであり異なる。トラックバックにはRESTが使われる。自サイトがトラックバック送信機能を持ち、トラックバックping(通常トラックバックURLを含む)を送信すると、相手サイトからXMLが返信される。

REST RESTは主にhttpとxmlを用いたソフトウェアアーキテクチャー。

Podcasting ポッドキャスティングとは手段のことである。要するに、RSS又はAtomを使って音楽や映像などのマルチメディアファイルをインターネット経由で配信するための方法である。ビデオ配信はVodcastingやVlogと呼ばれる。

July 24, 2006

The Geometry Classes

Point class is used in
areInaccessibleObjectsUnderPoint(),getObjectsUnderPoint()
hitTest()
applyFilter(),copyChannel(),merge(),paletteMap(),pixelDissolve(),threshold()
deltaTransformPoint(),transformPoint()
bottomRight,size,topLeft

Rectangle class is used in
applyFilter(), colorTransform(),copyChannel(), copyPixels(),draw(), fillRect(),generateFilterRect(),getColorBoundsRect(), getPixels(),merge(), paletteMap(),pixelDissolve(), setPixels(),threshold()
getBounds(), getRect(),scrollRect, scale9Grid
addPage()
startDrag()
getCharBoundaries()
pixelBounds

E4X with XML namespaces

The Namespace class works with XML namespaces in ActionScript 3.0 and there are two way to define namespaces for working with XML.
var myXML:XML = 
<foo:order xmlns:foo = "http://www.example.com/foo"> 
<foo:book ISBN="0942407296" xmlns:bar = "http://www.example.com/bar"> 
<bar:title>The Book</bar:title> 
<foo:pageCount>238</foo:pageCount> 
</foo:book> 
</foo:order>;
var foo:Namespace = myXML.namespace("foo");
var bar:Namespace = myXML.foo::book.namespace("bar");
The namespaces can be defined with the constructor of Namespace class if you already know the URIs of them.
var foo:Namespace = new Namespace("foo", "http://www.example.com/foo");
var bar:Namespace = new Namespace("bar", "http://www.example.com/bar");

July 22, 2006

Working with Regular Expressions

In ActionScript 3.0, you can use regular expressions with the following methods od the String class, match(), search(), and replace(). The expression to match a valid e-mail address is shown below.

/([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}/

There are two way to create regular expression instance.

var p1:RegExp = /bob/i;
var p2:RegExp = new RegExp("bob", "i");

The following characters have special meaning in regular expressions.

^ $ \ . * + ? ( ) [ ] { } |

RegExp class
The RegExp class has two methods, exec() and test(). The test() simply returns true or false if it contains a match for the regular expressions. The exec() returns an array with the matching substring. The array includes an index property that indicates the index position of the start of the substring match.

Flags
The i flag means the search is not case-sensitive. The seach() method finds only one match and returns its starting index position even if the g flag is set in the regular expression, though the exec() method returns multiple substrings to be matched.

var pattern:RegExp = /the/i;
var str:String = "The";
trace(str.search(pattern)); // 0;

July 21, 2006

Security for Cross-script

By default, Flash Player dose not allow swfA.swf to script swfB.swf because of the diffrent domains. A SWF file gives permittion to SWF files from other domains by calling Security.allowDomain() method. For example shown below, swfA.swf can script swfB.swf, but swfB.swf cannot script swfA.swf. You can set up symmetrical permissions by having both SWFfiles call the Security.allowDomain() method.

swfA.swf

loader.load(new URLRequest("http://siteB.com/swfB.swf"));
loader.content.init();

swfB.swf

Security.allowDomain("siteA.com");
function init(){...};

July 20, 2006

Working with RFID

The Phidgets is a set of interfaces can be controlled through the PhighetWebService by ActionScript. I am especially interested in the RFID(Radio Frequency IDentification system) and I will build a simple application with Flash that let employees know what time they begin to work, what time they finish a work, and how long they work today. Its like a substitute timecard system. The RFID is one of the most simple user interface, it only expects a RFID tag to touch on itself. No tags has the same TagID, it is unique number in the world.

July 19, 2006

Core Display Classes Part3

MovieClip
You can set the frame rate for all movie clips in an application using the frameRate property of the Stage object. A loaded SWF file can be a MovieClip object, an AVM1Movie object, or a Sprite object.

BitmapData
A Bitmap object has a bitmapData property that is a BitmapData object. A BitmapData object represents a rectanglar array of pixels.

var bmpData:BitmapData = new BitmapData(10,10,10,10);
var bmp:Bitmap = new Bitmap(bmpData);
addChild(bmp);

SimpleButton
A SimpleButton has three states:upState, downState, and overState. These states are each DisplayObject objects. The hitTestState property of a SimpleButton object is also a DisplayObject instance that responds to the mouse events for the button.

Video

var conn:NetConnection = new NetConnection();
conn.connect(null);
var stream:NetStream = new NetStream(conn);
stream.publish(false);
var vid:Video = new Video(640, 480);
vid.attachNetStream(stream);
stream.play("ext.flv");
addChild(vid);

Core Display Classes Part2

The Loader class
You can load external SWFs or graphic files (JPG, PNG, and GIF) by using the Loader class. A Loader object can contain only one child display object in its display list and the display object represents the SWF or graphic file that it loads.
var l:Loader = new Loader();
l.load(new URLRequest("ext.jpg"));
this.addChild(l);

The LoaderInfo class
The LoaderInfo object is a property of both the Loader object and the loaded display object. The LoaderInfo class provides infomation such as load progress, the URLs of the loader and loadee, the number of bytes total for the media, and the nominal height and width of the media.

The LoaderContext class
Use checkPolicyFile only when loading an image file. If it is true, the Loader checks the origin server for a cross-domain policy file. Security.allowDomain() gives a permission that a SWF file be loaded from other domains. When you specify securityDomain, FlashPlayer checks for the existence of a cross-domain policy file. If one exists and SWF from the domain permitted in the cross-domain policy file, it can cross-script the loaded SWF content. By putting the loaded SWF file in the same application domain using applicationDomain parameter, you can access its classes directly.

var l:Loader = new Loader();
var context:LoaderContext = new LoaderContext();
context.securityDomain = SecurityDomain.currentDomain;
context.applicationDomain = ApplicationDomain.currentDomain;
l.load(new URLRequest("ext.swf"), context);

Core Display Classes Part1

Vector Graphics
Each Shape, Sprite, and MovieClip object has a graphic property. The graphics property is a Graphic object. The graphics layer for a Sprite or MovieClip does not appear in the child list of them.

import flash.display.*;
var circle:Shape = new Shape();
circle.graphics.drawCircle(x, y, r);
this.addChild(circle);

Text
The TextField class let you work with dynamic and input text fields. The StaticText class are only created in the Flash authoring tool. The TextFormat object can be used to set formatting for an entire TextField or for a range of text.

var tf:TextField = new TextField();
tf.text = "Hello";
var format:TextFormat = new TextFormat();
format.color = 0xff0000;
tf.setTextFormat(format);
addChild(tf);
var style:StyleSheet = new StyleSheet();
var styleObj:Object = new Object();
styleObj.fontSize = "bold";
style.setStyle(".bold", styleObj);
delete styleObj;

var tfHtml:TextField = new TextField();
tfHtml.styleSheet = style;
tfHtml.htmlText = "<span class='bold'></span>";
addChild(tfHtml);

The ... Parameter

The ... parameter is introduced in ActionScript 3.0. The parameter have the same functionality as the arguments array and arguments.length property but it does not provide functionality similar to that provided by arguments.callee. Although the ... parameter has the array of the parameters, the specified parameters in a function are no longer included in the array.

function traceArgs(x:int, ... args){}
// args does not have a value of a variable x

The Delete Operator

The delete operator only works on properties of objects.
dynamic class Test{}
var myTest:Test = new Test();
function myFunc(){};
delete myFunc; // no effect

Function expressions are not available before they are defined.

expression(); // run-time error
var expression:Function = function(){}

Untyped Variables

All classes derive from the Object class that is known to flash programmers.

AS 2.0
In ActionScript 2.0, the lack of a type annotation meant that a variable would be of type Object.

var someObj:Object;
var someObj;

AS 3.0
In ActionScript 3.0, however, an untyped varable is not the same as a variable of type Object. An untyped variable can hold undefined, while a variable of type Object cannot hold that value.

var someObj:*;
var someObj;

New APIs in AS3(JP)

ActionScrion 3 provides many new APIs. There is the summary of a part of 'Introduction to ActionScript 3.0' for Flex 2.


Network API
Loaderクラス
swfや画像の読込みとロードされたコンテンツの詳細な情報を提供。
URLLoaderクラス
テキスト、バイナリデータの読込み。
Socketクラス
あらゆるフォーマットでサーバソケットに対してバイナリデータの読み書き。
URLStreamクラス
URLLoaderクラスに実装され、ダウンロード中に生データへアクセスできる。
ByteArrayクラス
バイナリデータを効果的に扱う。


Sound API
SoundChannelクラス、SoundMixerクラス。


Text API
TextLineMetricsクラス
テキストフィールドの一行を扱う。
TextFieldクラス
getCharBoundaries()は文字を囲むバウンディングボックスを表す四角形を返す。
getCharIndexAtPoint()は特定の位置の文字のインデックスを返す。
getFirstCharInParagraph()は段落の最初の文字のインデックスを返す。
getLineLength()は特定の行の文字数を返す。
getLineText()は特定の行のテキストを返す。
Fontクラス
swf内の埋め込みフォントを管理する。

Concept of DisplayList

DisplayObjects must be registered for the list of a DisplayObjectContainer (often called 'DisplayList') to show themselves in it with actionscript 3.

DisplayList
The addChild() and the addChildAt() method is used to add a instance of a displayObject to its own displayList. The addChild() handles the depths automatically.

public addChild(child:DisplayObject) : DisplayObject
public removeChild(child:DisplayObject) : DisplayObject
public addChildAt(child:DisplayObject, index:int) : DisplayObject
public setChildIndex(child:DisplayObject, index:int) : Void

What's Sprite Object?
Movieclip class is a class extended from sprite class and there are no difference between them except movieclip class has a timeline and scenes.

var sprite:Sprite = new Sprite();

July 18, 2006

QRCode

QRCode generator was now released, it generates a code with javascript by calling ExternalInterface.call(). First input a string into the textfield right below and press enter key to generate your code, that shows it in the left pane. You can download the source below.

Download : source

Anatomy the script

<script type="text/javascript" src="QRCode.js"></script>
<script type="text/javascript">
var qr;
function generate(str){
	qr = new QRCode(4, QRErrorCorrectLevel.H);
	qr.addData(str);
	qr.make();
}
function count(){
	return qr.getModuleCount();
}
function isDark(r, c){
	return qr.isDark(r, c);
}
</script>

The isDark() method in a container can be invoked to make actionscript know the color of the dot for setting pixels with black and white in bimap to view.

ExternalInterface.call("generate", str);
var count:Number = Number(ExternalInterface.call("count"));
var bitmap:BitmapData = new BitmapData(width, height, true);
this.createEmptyMovieClip("c", 1).attachBitmap(bitmap, 1);
for(var r:Number = 0; r < count; r++){
   for(var c:Number = 0; c < count; c++){
      var col:Number = 
      Number(ExternalInterface.call("isDark", r, c)) ? 0x00000000 : 0x00ffffff;
      bitmap.setPixel((width - count) / 2 + c, (height - count) / 2 + r, col);
   }
}

Spry Review Part2(JP)

You can get all of the rows in the data set by calling getData().

var dsAlbum = new Spry.Data.XMLDataSet("album.xml", "/contents/album");
var rows = dsAlbum.getData();

By default, the current row is set to the first row in the data set. Note that the index of the first row is always zero. The current row can be changed by calling the setCurrentRowNumber() with the row number that you want to change to. The built-in id property in the data set named "ds_RowID" is not changed after the order of the rows in the data changed. It can be changed by calling the setCurrentRow() with the row ID.

dsAlbum.setCurrentRowNumber(2);
dsAlbum.setCurrentRow('{ds_RowID}');

Step1 : Import dataSet to comboBox
The Photolog f60k is a flash version of a image viewer and it will read a xml once when it loads. A php file will be used to create the xml. It extracts JPGs from the folder, and it writes them with xml tags into a blank document.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Photo Album</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="includes/xpath.js"></script>
<script type="text/javascript" src="includes/SpryData.js"></script>
<script type="text/javascript">
var dsAlbum = new Spry.Data.XMLDataSet("album.xml", "/contents/album");
</script>
</head>
<body>
<div spry:region="dsAlbum">
<select>
    <option value="{folder}" spry:repeat="dsAlbum">{name}</option>
</select>
</div>
</body>
</html>

album.xml

<?xml version="1.0" encoding="UTF-8" ?>
<contents>
<album>
<name>エミーズ</name>
<folder>amys</folder>
</album>
<album>
<name>ガブ</name>
<folder>gab</folder>
</album>
<album>
<name>鎌倉</name>
<folder>kamakura</folder>
</album>
<album>
<name>京都</name>
<folder>kyoto</folder>
</album>
<album>
<name>鳴子</name>
<folder>naruko</folder>
</album>
<album>
<name>ナイキ</name>
<folder>nike</folder>
</album>
<album>
<name>日光(夏)</name>
<folder>nikko8</folder>
</album>
<album>
<name>日光(寺)</name>
<folder>nikko_temples</folder>
</album>
<album>
<name>お台場</name>
<folder>odaiba</folder>
</album>
<album>
<name>大島</name>
<folder>ooshima</folder>
</album>
<album>
<name>フラメンコ</name>
<folder>party</folder>
</album>
<album>
<name>2003</name>
<folder>spr_sum2003</folder>
</album>
</contents>

July 17, 2006

First Flex Day

Flash 9 does not work on Intel mac because of bugs of the compiler with java, however I will try to study as3 with adobe flex. Terminal is required to compile mxml to swf with command line on mac, but its not familiar with most of mac users that have no knowledge of about unix. Use it in your terminal like this:

mxmlc --strict=true --file-specs MyFirst.mxml
In strict mode, the compiler has higher expectations of your code. --file-specs is used to specify mxml file to be compiled.

Embedding Images

<mx:Script>
        <![CDATA[
            [Embed(source="assets/logo.png")]
            [Bindable]

            public var Logo:Class;            
        ]]>
</mx:Script>
<mx:Image id="myLogo" source="{Logo}"/>

You can gild-line properties for tag to create scale-grid.

[Embed(
      source="assets/fancy_border.png", 
      scaleGridTop="55", scaleGridBottom="137", 
      scaleGridLeft="57", scaleGridRight="266"
)]

Embedding SWFs

[Embed(source="assets/hourglass.swf")]

The symbol property of tag is used to specify the Linkage ID of the symbol in the library.

[Embed(source="assets/library.swf", symbol="BadApple")]

Embedding MP3

[Embed(source="assets/pie-yan-knee.mp3")]
Embedding fonts
To specify characters to be embed using the unicode-range property of @font-face saves file size.
<mx:Style>
        @font-face 
        {
            font-family: Copacetix;

            src: url("assets/copacetix.ttf");
            unicode-range:
                U+0020-U+0040, /* Punctuation, Numbers */

                U+0041-U+005A, /* Upper-Case A-Z */
                U+005B-U+0060, /* Punctuation and Symbols */
                U+0061-U+007A, /* Lower-Case a-z */
                U+007B-U+007E; /* Punctuation and Symbols */

        }
        .MyTextStyle 
        { 
            font-family: Copacetix; 
            font-size: 24pt;    
        }
</mx:Style>

July 16, 2006

Spry Review Part1(JP)

Spry framework for Ajax prerelease ver1.2 was released from adobe lab. Not much knowledge of javascript are required to build ajax apps. It enables developers to create contents with minimal scripting. New features are shown in http://ray.camdenfamily.com/index.cfm/2006/7/14/New-features-in-Spry

Step1 : add references to page

<script type="text/javascript" src="includes/xpath.js"></script>
<script type="text/javascript" src="includes/SpryData.js"></script>

Step2 : construct DataSet objects

<script type="text/javascript">
var dsShops = 
new Spry.Data.XMLDataSet("shops.xml", "/shops/shop");
var dsDetail = 
new Spry.Data.XMLDataSet("{dsShops::detail_url}", "/detail");
</script>

Step3 : define master region

<div id="contents" spry:region="dsShops" >
  <table id="shop_list">
    <tr id="{ds_RowID}" spry:repeat="dsShops"><td>
    <p><b>
       <a href="javascript:;"