Archive for June, 2007

Wednesday, June 6th, 2007

When storing numbers in AS3 VM Andre Michelle and his collegue Bram de Jong at splicemusic found an interesting behavior of the internal uint storage.  When the numbers are stored they change from int to Number depending on range.  Why does this matter?  Because ints are faster than Numbers and during larger simulations with lots of math it could slow things down quite a bit at these types change. 

The disadvantage of this is that Numbers are slower in computation as well as reading, writing in an Array.

The internal findings when storing a uint 

From 0 to 27 it is int
From 28 to 31 it is Number
From 32 to 59 it is int (again)
From 60 to 63 it is Number (again) …

Found when reading another excellent polygonal labs post on benchmarks and performance (this one is great as well concerning faster operations using bitwise shifts or alternate ways to eek out more performance) where he wisely advises to use signed int for loops or iterations rather than uint where needed because the iterations with numbers will be slower.

Andre Michelle posted an Adobe response on the issue and it is a known and by design characteristic due to the metadata that is stored with the datatype in the AS3 virtual machine.          

The AS3 VM uses 32-bit Atom formats to store various types. 3-bits of the Atom describe the type data, leaving 29-bits for actual data. In some cases, like null/undefined/void/etc, we use 3-bits plus a few more bits to define the type.

For signed integers, we have 28-bits to work with plus a sign bit. For unsigned integers we have 29-bits (or maybe 28 with the upper bit always zero?). Once your number gets larger than 28/29 bits, we dynamically switch it to a Number Atom type, which contains a 3-bit type value with a 29-bit ptr. All ptrs are 8-BYTE aligned so we get away with using 29-bits there.

All three formats are basically interchangeable. When storing a number in an Atom, we see if it’s an integer and fits within the 28/29 bits. If so, we store it as a int/uint value – otherwise we store it as a Number value.

It essentially is an optimization for uint to make it faster at times but its good to know for large iterative loops or large storage where uints might be needed. This goes back to sometimes where optimizations are a mixed bag.  The switching/converting types adds delay to the iteration.

 
var num: uint;
for (var i: int = 0; i < 64; i++)
{
 num = 1 << i;
 trace( i, getQualifiedClassName( num ) );
}
0 int
1 int
2 int
3 int
4 int
5 int
6 int
7 int
8 int
9 int
10 int
11 int
12 int
13 int
14 int
15 int
16 int
17 int
18 int
19 int
20 int
21 int
22 int
23 int
24 int
25 int
26 int
27 int
28 Number
29 Number
30 Number
31 Number
32 int
33 int
34 int
35 int
36 int
37 int
38 int
39 int
40 int
41 int
42 int
43 int
44 int
45 int
46 int
47 int
48 int
49 int
50 int
51 int
52 int
53 int
54 int
55 int
56 int
57 int
58 int
59 int
60 Number
61 Number
62 Number
63 Number
Monday, June 4th, 2007

Photo Sharing and Video Hosting at PhotobucketIn case you haven’t heard the SWFObject creator Geoff Stearns and the UFO creator have teamed up to create a new Flash Embed kit for HTML/XHTML called SWFFix that is more DOM compliant yet works.  Its always been a battle on this front of DOM standards vs Javascript when it comes to Flash embedding.

This teamwork to make a common kit will help to consolidate all issues with this and hopefully provide a really solid platform for embedding flash that takes into account all browser and satisfies standards but also works all the time. Making it harder to vote against when it comes time to decide what technology to use.

Of course there have been libraries like SWFAddress (for deep linking in flash and back button support easily) that have been built on top of SWFObject that will have to be switched over that have large user bases and following.

Check out SWFfix (of course this project has been very quiet and is not public since Feb 6-7th) hrm.

Sunday, June 3rd, 2007

Flash is great for monitoring all actions by a user from what they type to what their mouse is doing and for how long. We have many tracking systems that rely on script in Flash and HTML when not using flash that can detect user interaction with our applications. Many tracking companies also use this info for hotspot or heat maps to see what your users are messing with.

To do all this interaction logging and tracking you need mouse events. Mouse events drive games, applications, cool user controlled interfaces, expected user direction and simplify your application. Understanding all the mouse events possible is important.

Here is a list of all the events that are clearly implemented in AS3:

CLICK : String = “click” MouseEvent
Used to detect mouse clicks.

DOUBLE_CLICK : String = “doubleClick” MouseEvent
Used to detect double clicks.

MOUSE_DOWN : String = “mouseDown” MouseEvent
Checks when mouse is pressed down.

MOUSE_LEAVE : String = “mouseLeave” Event
Monitors when the mouse leaves the stage.

MOUSE_MOVE : String = “mouseMove”
Monitors when the mouse moves.

MOUSE_OUT : String = “mouseOut”
Monitors when the mouse moves out of the attached to object of the event.

MOUSE_OVER : String = “mouseOver”
Monitors when the mouse moves over the attached to object of the event.

MOUSE_UP : String = “mouseUp”
Monitors when the mouse moves up the attached to object of the event from a click.

MOUSE_WHEEL : String = “mouseWheel”
Monitors when the mouse wheel moves, detect the positive or negative delta property for distance and direction moved.

Wiring up Events in AS3 is easier than its ever been.

// attach the event listener to this object, if you want a global event outside
// the current class attach to stage.addEventListener([event],[callback])
this.addEventListener(MouseEvent.CLICK, onMouseClickEvent);

// then make the callback
public function onMouseClickEvent(event:Event)
{
trace(event);
if(event.buttonDown) // if primary button down, left mouse button
trace("left button was down");
else
trace("left button was not down");
}

What about right clicks?

Well not all mouse equipment has right click so its not always best to implement but for the ones that have right click capabilities and other buttons there is both mouse wheel and right click support in Flash mouse events.

To detect right click:

In the MouseClick event there is a buttonDown property on the event that returns true if its a left click, false if its any other mouse button. So you could have a menu drop down on a mousewheel click, right mouse click or other mouse button clicks.

Detecting right clicks or other mouse clicks is impossible in Flash AS3. I got excited and error in testing and thought the buttonDown helped to determine the button pressed but it only listens to the left click.

What about drag over and drag out?

The buttonDown property is mainly used for drag over or drag out events (which are not an actual event) but you could do something like:

function onMouseOver(event:MouseEvent):void
{
if(event.buttonDown==true)
{
// mouse is down and dragged over.
trace('onDragOver');
}
}
function onMouseOut(event:MouseEvent):void
{
if(event.buttonDown==true)
{
// mouse is down and dragged over.
trace('onDragOut');
}
}

To detect when the mouse leaves the screen:

Use the MouseEvent.MOUSE_LEAVE event on your main document class or a class instantiated that assigns this event to the stage. This can be used for high intensity flash sites where performance is preserved when the user is not interacting with certain elements.

More on mouse events and timers shortly. Here’s a sample from the docs:
http://livedocs.adobe.com/flex/2/langref/flash/events/MouseEvent.html#constantSummary

package {
import flash.display.Sprite;

public class MouseEventExample extends Sprite {
private var size:uint = 100;
private var bgColor:uint = 0xFFCC00;

public function MouseEventExample() {
var child:ChildSprite = new ChildSprite();
addChild(child);
}
}
}

import flash.display.Sprite;
import flash.events.MouseEvent;

class ChildSprite extends Sprite {
private var size:uint = 50;
private var overSize:uint = 60;
private var backgroundColor:uint = 0xFFCC00;
private var overColor:uint = 0xCCFF00;
private var downColor:uint = 0x00CCFF;

public function ChildSprite() {
draw(size, size, backgroundColor);
addEventListener(MouseEvent.CLICK, clickHandler);
addEventListener(MouseEvent.DOUBLE_CLICK, doubleClickHandler);
addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler);
addEventListener(MouseEvent.MOUSE_OVER, mouseOverHandler);
addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
addEventListener(MouseEvent.MOUSE_WHEEL, mouseWheelHandler);
}

private function draw(w:uint, h:uint, bgColor:uint):void {
graphics.clear();
graphics.beginFill(bgColor);
graphics.drawRect(0, 0, w, h);
graphics.endFill();
}

private function clickHandler(event:MouseEvent):void {
trace("clickHandler");
}

private function doubleClickHandler(event:MouseEvent):void {
trace("doubleClickHandler");
}

private function mouseDownHandler(event:MouseEvent):void {
trace("mouseDownHandler");
draw(overSize, overSize, downColor);

var sprite:Sprite = Sprite(event.target);
sprite.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
sprite.startDrag();
}

private function mouseMoveHandler(event:MouseEvent):void {
trace("mouseMoveHandler");
event.updateAfterEvent();
}

private function mouseOutHandler(event:MouseEvent):void {
trace("mouseOutHandler");
draw(size, size, backgroundColor);
}

private function mouseOverHandler(event:MouseEvent):void {
trace("mouseOverHandler");
draw(overSize, overSize, overColor);
}

private function mouseWheelHandler(event:MouseEvent):void {
trace("mouseWheelHandler delta: " + event.delta);
}

private function mouseUpHandler(event:MouseEvent):void {
trace("mouseUpHandler");
var sprite:Sprite = Sprite(event.target);
sprite.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
sprite.stopDrag();
draw(overSize, overSize, overColor);
}
}
Sunday, June 3rd, 2007

Photo Sharing and Video Hosting at PhotobucketMichael Swanson has created a SWF2XAML converter that you should check out.  It has quite a few features and fixes that would seem like conversion from SWF to XAML might not be worth the time.  This might change that.  I think that it is important to stay up on all vector technologies as a RIA solution provider and we do not treat platforms like religions rather tools to use at our disposal.

The conversion at least for the vector art looks pretty on target.

Photo Sharing and Video Hosting at Photobucket

Features

The following table contains a list of features that are supported by the current version of the SWF2XAML tool or are planned for a future release. Where there are issues, I’ve tried to address them in the Comments column. If you’d like to see some visual illustrations, take a look at the Eye Candy.

Support Feature Comments
Yes  Frame by Frame Advance Use the horizontal scroll bar at the bottom of the window to navigate frames in the SWF file. Because frames in a SWF file must be processed sequentially, later frames will need to calculate intermediate frames, so jumping forward may take some time.

* The current version of the SWF2XAML tool does not cache prior frames (and that feature in Edit/Preferences is permanently disabled). So, when navigating backwards, the file will be re-calculated from the beginning. Depending on the file complexity, this may take some time.
Yes Explore Project Folder Choose File/Explore Project Folder to view the folder that contains any exported assets (like XAML files and bitmap images).
Yes XAML Export Choose File/Export… to export the current frame to a XAML file.
Yes Save Frame as Bitmap To save the current frame as a bitmap image (.PNG), choose File/Save Bitmap. The image will be named frame####.png where #### is replaced by the current frame number. The file will be saved to the subfolder identified in the application preferences.
Yes Launch XAML File Choose File/Launch XAML to automatically export the current frame to a XAML file and launch it in your default browser (normally Internet Explorer). 
Yes Launch Original SWF File Choose File/Launch Original to launch the current SWF file. If you have the Flash Player installed, this will open the player and begin the animation.
Yes Copy XAML to Clipboard Choose Edit/Copy XAML to copy the XAML for the current frame to the system clipboard.
Yes Copy ResourceDictionary Choose Edit/Copy ResourceDictionary to copy a XAML ResourceDictionary element that represents the shapes that have been defined up to the current frame. The XAML is copied to the system clipboard. Note that any shapes that are defined after the current frame will not be included (so, to include everything, first navigate to the last frame of the SWF file).
Yes Go To Specified Frame Choose Edit/Go To… and enter a frame number to jump to that frame. Because Flash files must be processed sequentially, all interim frames will also need to be calculated, so this may take some time.
Yes Preferences Choose Edit/Preferences… to configure various aspects of the tool:

  • The Display tab contains settings that determine the opacity of the Onion Skin mode and the stroke color and fill opacity for Wireframe Mode.
  • The XAML tab contains settings to export to WPF/E-compliant XAML and to control its formatting.
  • The Files tab controls where the various file types are saved on your system. By default, each SWF file will have its own subfolder created.
  • The Advanced tab contains settings that control how the tool caches various assets. Although caching of assets can improve performance, there may be a significant memory cost involved.
Yes Stage Clipping Choose View/Clip Stage to toggle clipping of the frame on and off. Often times, frames in a Flash file contain elements that can’t be seen with clipping turned on.
Yes File Information Choose View/File Information to enable the File Information pane. This pane displays information about the SWF file, including: file name, file signature, version, file length, frame width, frame height, frame rate (in fps), and the total frame count.
Yes Display List Choose View/Display List to enable the Display List pane. Think of the Display List as a stack of layers that make-up the current scene. You can use the checkboxes to selectively hide/unhide elements until the frame content looks the way you’d like. Note that not all checkboxes will change the visual display (only Shapes, MorphShapes, Sprites, Buttons, and Text).
Yes Advance Sprite Frames Many Flash files contains movie clips (or Sprites) that are sub-elements that have their own animation frames. Although these animations will automatically progress with each frame in the main scene, choosing View/Advance Sprites will manually advance each sprite in the scene by a single frame.

** If you run across a single frame Flash file and it doesn’t appear to animate properly, it may be because you need to manually advance the sprites in the scene.
Yes Wireframe Mode Choose View/Wireframe Mode to display the outlines of the elements in each frame. The wireframe stroke color and fill opacity can be configured under Edit/Preferences. Note that XAML exported or copied to the clipboard in this mode will represent the wireframe version of the frame (i.e. what you see).
Yes Onion Skin Mode Choose View/Onion Skin Mode to toggle opacity of the entire tool window. When Onion Skin Mode is enabled, the tool window becomes semi-transparent so that it can be moved over the top of a comparison window (like the Flash Player). This is useful to visually compare the converted geometry. The opacity of the window can be configured under Edit/Preferences.
Yes Tag Statistics Choose View/Tag Statistics to view a table of the Flash tags that have been encountered up until the current frame in the current file. To get statistics for the entire SWF file, choose Edit/Go To… to jump to the last frame of the file, then view the tag statistics.
Yes View Original Size Choose View/Original Size to size the frame to the height and width that is specified in the Flash file. When using Onion Skin Mode, this makes it easier to do a visual comparison with the Flash Player.
Yes Shape Morphs Shapes that were authored to morph over a specific number of frames are supported in the conversion. This includes geometry, fills, strokes, gradients, matrix transformations, etc.
Yes Clipping Layers Layers in the Display List that are set to clip lower layers are supported. Although these layers don’t have any visual strokes or fills, toggling these layers in the Display List pane will affect the display.
Yes Bitmaps All JPG, indexed color, and full color bitmap types are supported. Note that indexed color modes are simply converted to 32-bit RGBA PNG files (as are JPG files with an alpha layer, unique to Flash files).
Yes Color Transformations Simple color transformations (multiply and add) are supported per-layer in the Display List.
Yes/No Shape Fill Types  All fill types are supported to varying degrees:

  • Solid fills are fully supported
  • Both radial and linear gradient fills are supported. However, the new radial gradient settings in later Flash versions are not supported.
  • Bitmap fills are supported, but non-repeating clipped fills currently have some issues.
Yes/No  Buttons Only the button “up” state is currently converted and displayed. Also, there is no interactivity. 
No Frame Blend Modes No current support for various frame blend modes that were introduced in later versions of Flash.
No Dynamic Text Although static glyph text is supported, there is currently no support for text that uses locally-installed fonts.
No ActionScript All ActionScript code is currently ignored. As such, no interactivity is converted. 
No Sound No sounds are currently exported or played; they are simply skipped.
No Video All video is skipped. 

Installation

To get the SWF2XAML tool up-and-running on your system, follow these steps:

  • Make sure that you have the .NET Framework 3.0 installed on your machine. If you’re running Windows Vista, you can skip this step, because the Framework is automatically installed with the operating system.
  • Download SWF2XAML_0.2.zip (521KB).
  • Extract all of the files to a folder of your choice.
  • Double-click SWF2XAML.exe to run the tool.
Friday, June 1st, 2007

External CSS stylesheets can be used with flash AS3. This is possible with the StyleSheet class in AS3 and controls such as TextField have a property for the stylesheet.

AS2

var styles:TextField.StyleSheet = new TextField.StyleSheet();
styles.onLoad = function(success:Boolean):Void {
if (success) {
 // display style names.
 trace(this.getStyleNames());
} else {
 trace("Error loading CSS file.");
}
};
styles.load("styles.css");

OR apply to a StyleSheet object that can be used for many controls

AS3

package
{
 import flash.display.Sprite;
 import flash.events.Event;
 import flash.net.URLLoader;
 import flash.net.URLRequest;
 import flash.text.StyleSheet;
 import flash.text.TextField;
 import flash.text.TextFieldAutoSize;

 public class CSSFormattingExample extends Sprite
 {
  var loader:URLLoader;
  var field:TextField;
  var exampleText:String = "

This is a headline

" + "This is a line of text. " + "This line of text is colored blue."; public function CSSFormattingExample():void { field = new TextField(); field.width = 300; field.autoSize = TextFieldAutoSize.LEFT; field.wordWrap = true; addChild(field); var req:URLRequest = new URLRequest("example.css"); loader = new URLLoader(); loader.addEventListener(Event.COMPLETE, onCSSFileLoaded); loader.load(req); } public function onCSSFileLoaded(event:Event):void { var sheet:StyleSheet = new StyleSheet(); sheet.parseCSS(loader.data); field.styleSheet = sheet; field.htmlText = exampleText; } } }

[SOURCE]
Flash is limited in CSS support and only supports CSS1 properties and a minimal amount for formatting.

Supported CSS properties

Flash Player supports a subset of properties in the original CSS1 specification (www.w3.org/TR/REC-CSS1). The following table shows the supported CSS properties and values as well as their corresponding ActionScript property names. (Each ActionScript property name is derived from the corresponding CSS property name; the hyphen is omitted and the subsequent character is capitalized.)

CSS property ActionScript property Usage and supported values
text-align textAlign Recognized values are left, center, right, and justify.
text-decoration textDecoration Recognized values are none and underline.
margin-right marginRight Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.
kerning kerning Recognized values are true and false.
letter-spacing letterSpacing Only the numeric part of the value is used. Units (px, pt) are not parsed; pixels and points are equivalent.
font-family fontFamily A comma-separated list of fonts to use, in descending order of desirability. Any font family name can be used. If you specify a generic font name, it is converted to an appropriate device font. The following font conversions are available: mono is converted to _typewriter, sans-serif is converted to _sans, and serif is converted to _serif.
display display Supported values are inline, block, and none.

For an example of using styles on XML elements, see An example of using styles with XML.

[source]