close

Вход

Забыли?

вход по аккаунту

?

Flash & Flex. 2012.03

код для вставкиСкачать
FFDM 2012.03
4
03/2012 (33)
Dear Readers,
Springtime is coming. So I hope that the March Flash and Flex Developer’s Magazine issue brings you a little bit of freshness. This time, I would like to welcome new authors – Christopher Caleb, Emerson Maningo and Jeffry Houser. Christopher Caleb’s article will provide you with how to setup a basic Starling application and how to use Starling’s particle system extension. Christopher Caleb is a professional Flash developer and author of Flash iOS Apps Cookbook. He currently leads Flash developer at WeeWorld – an avatar-based social network and virtual world for teens. Specially, I recommend you to read an article from Jeffry Houser who is the Brains behind Flextras, a set of user interface Flex Components that save you time and help you create better Flex applications. He has a Computer Science degree from the days before business met the Internet and has solved a problem or two in his programming career. From his article, you will know what the Flex Component Lifecycle is and you will learn how the Lifecycle works when a component is created. Third author, Emerson Maningo, starts you into new audio solutions with Introducing jPlayer: jQuery Audio Solutions for your Website. Emerson is an independent record producer and music publisher. He runs a music production and publishing blog where he shares tips and techniques on audio recording, mixing and mastering. There is also News In Brief from Gabor Csomak – read and find out what’s up in Flash and Flex World!
Enjoy your reading
Adela Kuźniarska and FFD Team
Editor: Adela Kuźniarska adela.kuzniarska@software.com.pl
Proofreaders: Garry Schafer, Michael Jovel,Alberto Jose Argon Alvarez, Nick Middleweek, Ranjan Rajendran, Ed Werzyn DTP Team: Ireneusz Pogroszewski ireneusz.pogroszewski@software.com.pl
Art Director: Ireneusz Pogroszewski ireneusz.pogroszewski@software.com.pl
Senior Consultant/Publisher: Paweł Marciniak
Flex/ActionScript 101 Section Editor: Marc Pires marcpiresrj@gmail.com
iPhone Development Section Editor: Ryan D’Agostino
Games Section Editor: Chris Hughes
Contributing Editors: Pedro de La Rocque, Ali Raza, Csomák Gábor
Publisher: Software Press Sp. z o.o. SK
ul. Bokserska 1 02-682 Warszawa Poland Worldwide Publishing If you are interested in cooperating with us, please contact us by e-mail: cooperation@software.com.pl
Whilst every effort has been made to ensure the high quality of the magazine, the editors make no warranty, express or implied, concerning the results of content usage.
All trade marks presented in the magazine were used only for informative purposes.
All rights to trade marks presented in the magazine are reserved by the companies which own them.
Thanks to the most active and helping beta testers:
Russell TangChoon, Lee Graham, Jassa Amir Lang, Ed Werzyn, Yann Smith-
Kielland, Justus, Csomák Gábor, Kevin Martin, Charles Wong, Ali Raza, Almog Koren, Izcoatl Armando Estanol Fuentes, Lionel Low, Michael J. Iriarte, Paula R. Mould, Rosarin Adulseranee, Sidney de Koning To create graphs and diagrams we used program by company.
Mathematical formulas created by Design Science MathType™
ATTENTION!
Distributing current or past issues of this magazine – without permission of the publisher – is harmful activity and will result in judicial liability.
DISCLAIMER!
The techniques described in our articles may only be used in private, local networks. The edi-
tors hold no responsibility for misuse of the presented techniques or consequent data loss.
Editor’s Note
5
03/2011 (33)
CONTENTS
InBrief
6 Flash Roadmap Posted to ADC. News BY GABOR CSOMAK
The Flash white paper provides an overview of the Flash runtimes and a roadmap for their development. This will give you some insight into our current thinking and plans around Flash functionality in the Flash Player and AIR over the next one to two years.
Starling Framework
8 Creating Particle Effects with Starling
BY CHRISTOPHER CALEB
Learn how to create particle effects using the Starling Framework and its particle system extension. From this article you will know How to setup a basic Starling application, The fundamentals of particle systems and how to use Starling’s particle system extension.
Photonstorm.com
16 The Reality of HTML5 Game Development and making money from it
BY RICHARD DAVEY
If you work for a company that has a pointy haired boss running up all excited about this new fangledHTML5 thing, at least now you have some appreciation of the vast scope of technology and platforms that simple request can span. Of course when people say that what they usually mean is “I want it to work on my iPhone” (i.e. “Don’t use Flash”) but now you can see it isn’t as simple as that. Serious thought has to be put in to targetting the right platform, deciding how many versions to create and what trade-offs you’re willing to make along the way.
Flex and MongoMD
26 Using MongoDB
BY MARCO PIRES
In this first article we’ll see the basing concepts related to MongoDB, how to install and configure it. In upcoming articles we’ll be creating a small but functional file store application.You will learn how to use MongoDB with your Flex Application, Key concepts of NoSQL and Administer MongoDB server. Marc Pires is a Developer located in Brazil, during his career, he has worked in various roles such as Network Administrator, Instructor. He has a strong passion for working with and researching new technologies. Specialized on RIA, Iphone Development, Restful web services and other interesting things, he’s one of the main developers of the Esus System and is beginning his startup specialized on mobile development.
Interview
28 Interview with Adrian Simonovich
BY ALI NEKOU POUR
Adrian Simonovich is CEO of Flare3D, he borns in Argentina, studied at ORT Argentina and worked at Top Toys (Mattel) before foundingSIA Interactive at the age of 21.Since then, Adrian leaded an amazing team that founded several High-tech companies that connect creativity with technology and made them grow into multinational companies.In he’s free time he like to run (runned Adidas 42K Marathon) and travelling with his wife Viryna. From this interview you will know what types of Flare3D Licences are available and what is the Flare3D Desktop Tool for.
Adobe Flash and jQuery
30 Introducing jPlayer: jQuery Audio Solutions for your Website BY EMERSON MANINGO
Emerson is an independent record producer and music publisher. He runs a music production and publishing blog: http://www.audiorecording.me/ where he shares tips and techniques on audio recording, mixing and mastering.This article is written for the beginner in web development particularly artists and singer/songwriters that manage their own websites. LifeCycle
38 Understanding the Flex Component LifeCycle
BY JEFFRY HOUSER
Jeffry is an Adobe Community Professional and produces The Flex Show, a podcast with expert interviews and screencast tutorials. He hosts the Flextras Friday Lunch Podcast, a weekly live Q&A session where you can get your programming questions answered and also runs AskTheFlexpert.com where you can get your questions answered privately. Jeffry is one of the initial contributors to Apache Flex and has spoken at user groups and conferences all over the US. He is manager of the Online Flex Meetup Group, author of three technical books, over 30 articles, and hundreds of podcasts. Adobe is creating tools, such as the touch apps for the Creative Cloud, using Adobe AIR. This is a significant investment in the Flash Platform. Flex has been donated to The Apache Foundation. 6
IN BRIEF
03/2012 (33)
Flash Roadmap Posted to ADC
Following quickly on the heels of the Flex White Paper, you can now find on the ADC the Adobe Roadmap for the Flash Runtimes: http://www.adobe.com/go/
flashplayer_roadmap. The Flash white paper provides an overview of the Flash runtimes and a roadmap for their development. This will give you some insight into our current thinking and plans around Flash functionality in the Flash Player and AIR over the next one to two years.
Between these two white papers you should have a much clearer understanding of Adobe’s current plans and intentions for Flex and Flash.
Summary of Flash Roadmap:
• For the past decade, Flash Player and, more recently, Adobe AIR have played a vital role on the web by providing consistent platforms for deploying rich, expressive content across browsers, desktops, and devices. Beginning as a platform for enabling animation, the Flash runtimes have evolved into a complete multimedia platform, enabling experiences that were otherwise not possible or feasible on the web.
• Looking forward, Adobe believes that Flash is particularly suited for addressing the gaming and premium video markets, and will focus its development efforts in those areas. At the same time, Adobe will make architectural and language changes to the runtimes in order to ensure that the Flash runtimes are well placed to enable the richest experiences on the web and across mobile devices for another decade.
source: The Official Flex Team Blog
Rovio Chooses Flash Player 11 with Support for 3D Graphics
On february 13, Rovio launched Angry Birds for Facebook using Flash Player 11 with support for 3D graphics. The most social version of Angry Birds yet takes advantage of hardware accelerated graphics in Flash Player to bring a silky smooth gaming experience to a wider audience than ever before. More than 130 million people play Angry Birds every day – now with Flash Player, hundreds of millions of Facebook users can do the same. New, enhanced special effects like lighting, smoke and explosions running smoothly at 60 frames per second bring the game to a whole new level and allow players to have a more connected and engaging experience. Angry Birds on Facebook game makes it even more exciting to play with friends, offering amazing new power-ups like Sling Scope, Birdquake, King Sling and Super Seed to extend players’ gratifying arsenals. And with new accelerated graphics, the feathery antics have never been more fun to more people. For more information about how to power-up your games using Flash and AIR, please visit the Adobe Gaming Solutions site.
source: Adobe Flash Platform Blog
AIR 3.2 RC SDK available on Adobe Labs!
Adobe announced the availability of AIR 3.2 (Release Candidate) with Stage3D support for mobile.
You will be able to develop fully GPU accelerated mobile content with AIR 3.2 for iOS and Android using the same Stage3D APIs you are using today on the desktop.
It allows you to distribute AIR captive runtime versions of apps, enabling you to publish apps immediately to marketplaces such as the iOS App Store, Android Market, and Amazon Appstore. Adobe recommends that you update your applications with the GM build when it is available.
source: http://www.bytearray.org
Compuware Presents Live Webcast: „Early-Lifecycle Performance
Testing & Optimization Without the Grief”
Webcast to Detail Best Approaches to Making Web Load Testing a Standard Part of the Application Delivery Lifecycle and How the Right Solution Makes it Easier.
DETROIT, Feb. 16, 2012 (GLOBE NEWSWIRE) – Compuware Corporation (Nasdaq:CPWR), the technology performance company, today announced a live webcast that will highlight the best approaches organizations canemploy to make web load testing a standard part of their application delivery lifecycle and will show how using the right web load testing solution makes it easier to do so.
source: http://www.compuware.com/ News by Gábor Csomák (@csomak)
03/2012 (33)
8
STARLING FRAMEWORK
T
he introduction of Flash Player 11 and the Stage3D APIs allows Flash developers to leverage the incredible graphics rendering capabilities of modern GPUs. While powerful, the APIs provided by Stage3D are intended for those with an understanding of low-level 3D graphics programming.
Fortunately many high-level frameworks and libraries built on top of Stage3D are now available, relieving much of the burden. One such framework is Starling – an extensible ActionScript 3 library that provides hardware-accelerated rendering of 2D graphics via an API that closely follows Flash’s conventional display list architecture.
In addition, Starling provides features that weren’t previously possible in Flash such as advanced particle systems. With minimum effort, it’s possible to create a stunning array of visual effects including explosions, smoke, fire, dust clouds, and even spiralling galaxies. This tutorial will introduce you to the Starling Framework and its particle system extension. You’ll learn how to quickly create and include particle effects within your ActionScript projects.
Getting Started
In order to work through this tutorial, you’ll need a suitable integrated development environment. I’ll be using Adobe Flash Builder 4.6, a trial version of which can be downloaded from www.adobe.com/
downloads.
You’ll also need Flash Player 11.1 installed in your browser. You can update to the latest version by visiting http://get.adobe.com/flashplayer.
Finally, both the Starling API and its Particle System extension API will need to be installed on your development computer via GitHub. Download and extract a zip file of the Starling Framework from https://
github.com/PrimaryFeather/Starling-Framework. Do the Creating Particle Effects with Starling
Learn how to create particle effects using the Starling Framework and its particle system extension.
What you will learn…
• How to setup a basic Starling application
• The fundamentals of particle systems
• How to use Starling’s particle system extension
What you should know…
• How to use Flash Builder or a similar IDE such as FlashDevelop or FDT
• You should be comfortable developing with ActionScript 3.0
Figure 1. Creating a new ActionScript project
Creating Particle Effects with Starling
03/2012 (33)
9
same for the Particle System extension, which can be found at https://github.com/PrimaryFeather/Starling-
Extension-Particle-System. Extensive documentation and support for both libraries is available from the official Starling Framework website at http://starling-
framework.org.
With Starling downloaded, launch Flash Builder and create a new ActionScript 3 project by selecting File | New | ActionScript Project. Name your project Particles and opt for a Web application type (Figure 1).
Starling and the Particle System extension are provided as pure ActionScript 3 libraries and will need to be added to your project’s build paths. From the New ActionScript Project panel, click Next then select the Source path tab. Use the Add Folder button to add each library’s source path. The Starling API’s source folder can be located within its package at: PrimaryFeather-Starling-Framework\starling\src\
(Figure 2), while the Particle System’s can be found at: PrimaryFeather-Starling-Extension-Particle-System\src\
.
Before moving on, also add your project’s src folder to the list of build paths. We’ll need this when embedding various resources into one of your ActionScript classes a little later on. When you’re done, click Finish and your project will be created.
We’re almost ready to start coding. Stage3D introduces a new direct-to-path rendering mode, which enables hardware accelerated presentation of your SWF. All content written with Starling must use this window mode.
Direct rendering can be enabled by editing your project’s HTML template file. To do this, open the Package Explorer panel by selecting Window | Show View | Package Explorer. Within your project, expand the html-template folder and right-click on index.template.html
. From the context menu, select Open With | Text Editor to open the file within Flash Builder. Within the template file, set the window mode to direct by adding the following highlighted line of code and saving:
attributes.name = „${application}”;
attributes.wmode = „direct”;
attributes.align = „middle”;
If you’re using Flash Builder 4.6 then you’re ready to go. If however you’re using an older version of Flash Builder or another IDE then you may need to perform the following additional steps:
Figure 2. Adding Starling’s source folder to our project
Figure 3. The default view of the Starling particle editor
03/2012 (33)
10
STARLING FRAMEWORK
• Download the latest Flex SDK from http://
opensource.adobe.com/wi ki/di spl ay/f l exsdk/
Downloads and configure your project to use it
• Download playerglobal.swc for Flash Player 11.1 from http://www.adobe.com/support/flashplayer/down
loads.html and add it to your project’s library path
• Configure your project to target SWF version 13 by adding the -swf-version=13
compiler argument
Okay, now we’re ready to start experimenting with particle effects using Starling. Using a Particle Editor
Let’s move away from Flash Builder for the time being and concentrate on creating a particle effect that will be used within our project. We’ll use a browser-based particle editor (Figure 3) by onebyonedesign, which is itself built using Starling. This will allow us to see exactly what our particle effects will look like when run within our own projects.
Launch your web browser and point it to the particle editor at http://onebyonedesign.com/flash/particleeditor. A default particle effect of a flame will appear along with a series of settings that represent it. These settings can be adjusted to create new effects. Let’s go ahead and make the relevant changes to create an exhaust plume for a missile that’s travelling vertically upwards.
The particle system uses a single texture for each individual particle. We’ll begin by selecting a different texture. From the GENERAL column, click the Edit Texture button and select Blob. Clicking DONE will use that texture and the changes will be reflected immediately in the editor’s current particle effect.
Now move to the PARTICLES column and make the following adjustments to the PARTICLE CONFIGURATION section:
• Reduce Max Particles to 100
• Increase Lifespan to 2.8
• Change Start Size Variance to 17
• Reduce Finish Size to 0
• Change Emitter Angle to 90
As before, the particle effect will change in real-time with each change. Let’s also make some alterations to the settings within the GRAVITY EMITTER section, which can be found in the PARTICLE BEHAVIOR column:
• Increase Speed to 230
• Increase Speed Variance to 46
Finally, change the BLEND FUNCTION by selecting One from its Source dropdown box. The blend function settings can be found near the editor’s bottom-right corner.
Before saving, preview your particle effect in motion by dragging it around the screen with the mouse (Figure 4). Feel free to experiment with the settings until you’re happy with the effect.
Once done, click the Export Particle button to save your work. Two files will be produced and bundled within a .zip file. The first file will be named texture.png and is the texture used by your particle effect. The second is an XML file named particle.pex that holds the settings you configured. Both these files will be used by Starling’s Particle System extension.
Save the .zip file and extract its contents to your project’s src folder. Close your web browser.
You may have found the slider bars used by the particle editor to be inaccurate, making it difficult to match this tutorials settings exactly. If this was the case then you can edit your particle.pex
file directly within a text editor. Being XML, the file is easy to read. Alternatively, if you’re using a Mac then you really should consider using Particle Designer by SeventyOne Squared instead. In fact, onebyonedesign’s particle editor is based upon Particle Designer and even exports XML in the same format. Particle Designer can be downloaded from http://
particledesigner.71squared.com.
Setting Up Starling
With your particle effect designed we can move back to Flash Builder and write the ActionScript required Figure 4. Your �nal particle efect
03/2012 (33)
12
STARLING FRAMEWORK
to import and display it. We’ll begin by setting up the Starling framework. From the Package Explorer panel, open your Particles.as
class and enter the ActionScript shown in Listing 1.
The Starling class belongs to the starling.core package
and is trivial to set up. In fact, the following three lines of code were all that was required:
starling = new Starling(ParticlesExample, stage);
starling.antiAliasing = 1;
starling.start();
The constructor expects two mandatory arguments. The first is the name of a class that extends starling.display.Sprite
and will represent the root of Starling’s display list. The second is a reference to the stage. In our code example, we passed a class name of ParticlesExample as the first argument. This class doesn’t exist yet but we’ll address that shortly.
With Starling instantiated, all that remains to be done is to select an anti-aliasing level and then commence rendering of your scene’s display list by calling start()
. A value between 0 and 16 can be used for anti-aliasing, with 16 being the maximum level and 0 being none at all. When working with 2D content there’s generally no need to use a value higher than 2, and for most cases 1 will suffice.
Creating your Root Class
Let’s now write the root class for Starling’s display list. It’s within this class where we’ll eventually setup and display our particle effect, but first we’ll concentrate on the creation of a skeleton version.
Within Flash Builder, add a new ActionScript class to your project’s src folder. Name the class ParticlesExample
and ensure that it extends starling.display.Sprite (Figure 5). Don’t confuse Starling’s Sprite class with flash.display.Sprite. Starling mimics many of the display classes used by Flash’s traditional display list, which can catch-out those new to the framework.
Add the ActionScript shown in Listing 2 to your class and save it.
The structure of your ParticlesExample class should look fairly conventional. Within the constructor, a listener is added for the ADDED_TO_STAGE event. When your Starling display list has been added to the stage you will be free to add content to it via the addedToStage() handler. As was the case with Sprite
, notice that ADDED_
TO_STAGE
belongs to starling.events
rather than the flash.events package.
You should now be able to successfully build and run your project. If all goes according to plan, a browser window will launch and you’ll be greeted by an empty dark-blue screen. This is expected as we haven’t yet added any visual content. If you haven’t correctly set the Listing 1. Source code for the Particles class
package
{
import
lash.display.Sprite;
import
lash.display.StageAlign;
import
lash.display.StageScaleMode;
import
starling.core.Starling;
[SWF(width="640",height="640",frameRate="60",backg
roundColor="#000033")]
public
class
Particles extends
Sprite
{
private
var
starling:Starling;
public
function
Particles()
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
starling = new
Starling(ParticlesExample, stage);
starling.antiAliasing = 1;
starling.start
();
}
}
}
Figure 5. Adding the ParticlesExample class to your project
Creating Particle Effects with Starling
03/2012 (33)
13
window mode then you’ll see an error message (Figure 6) within your browser window instead. To correct this, either alter your project’s template HTML file by setting the wmode to direct, or manually edit the .html file that’s generated within your project’s bin or bin-debug folder.
Adding Your Particle Effect
If satisfied that you’ve successfully set-up Starling and added a root class for its display list, then we can go ahead and add your particle effect.
Start by embedding both your particle’s XML file and its texture by including the following lines within your ParticleExample class:
[Embed(source=”/particle/particle.pex”,mimeType=”applica
tion/octet-stream”)]
private var ParticleXML:Class;
[Embed(source=”/particle/texture.png”)]
private var ParticleTexture:Class;
Starling provides a ParticleDesignerPS class that can display particle systems created using tools such as onebyonedesign’s particle editor. Let’s import it and a few other classes required to get the job done:
import starling.core.Starling;
import starling.extensions.ParticleDesignerPS;
import starling.textures.Texture;
Now declare a member variable that will be used to hold an instance of the ParticleDesignerPS class:
private var particles:ParticleDesignerPS;
Within our ADDED _ TO _ STAGE event handler, instantiate ParticleDesignerPS and add it to Starling’s display list:
particles = new ParticleDesignerPS(
XML(new ParticleXML()),
Texture.fromBitmap(new ParticleTexture())
);
particles.emitterX = stage.stageWidth / 2;
particles.emitterY = 170;
particles.start();
addChild(particles);
Its constructor expects an XML object representing your particle system’s settings, and the Texture that will be used to render each particle. We simply used the particle.pex
and texture.png
files that were exported from the particle editor. Before using texture.png
, it needs to be converted from a bitmap to a Starling texture. This is achieved by calling the static Texture.fromBitmap()
method.
Once instantiated, the particle system is positioned by setting its emitterX and emitterY properties. Although an x and y property are available, for realistic movement, it’s important that emitterX and emitterY are used instead. The x and y properties will move the container that each particle is a child of, while emitterX and emitterY will change the position within that container where the next Figure 6. The expected error when using the wrong window mode
Listing 2. Our skeleton class representing the root of Starling's display list
package
{
import
starling.display.Sprite;
import
starling.events.Event;
public
class
ParticlesExample extends
Sprite
{
public
function
ParticlesExample()
{
addEventListener(Event.ADDED_TO_STAGE, addedToStage);
}
private
function
addedToStage(e:Event):void
{
}
}
}
03/2012 (33)
14
STARLING FRAMEWORK
Listing 3. Source code for the ParticleExample class
package
{
import
starling.core.Starling;
import
starling.events.Event;
import
starling.extensions.ParticleDesignerPS;
import
starling.textures.Texture;
import
starling.utils.deg2rad;
public
class
ParticlesExample extends
Sprite
{
[Embed(source="/particle/particle.pex",mimeType="application/octet-stream")]
private
var
ParticleXML:Class;
[Embed(source="/particle/texture.png")]
private
var
ParticleTexture:Class;
private
var
particles:ParticleDesignerPS;
private
var
angle:Number;
public
function
ParticlesExample()
{
angle
= 0;
addEventListener(Event.ADDED_TO_STAGE, addedToStage);
}
private
function
addedToStage(e:Event):void
{
particles = new
ParticleDesignerPS(
XML(
new
ParticleXML()),
Texture.fromBitmap(
new
ParticleTexture())
);
particles.emitterX = stage.stageWidth / 2;
particles.emitterY = 170;
particles.start();
addChild(particles);
Starling.juggler.add(particles);
addEventListener(Event.ENTER_FRAME, update);
}
private
function
update(e:Event):void
{
var
x:Number = Math.
sin(deg2rad(angle)) * 40;
particles.emitterX = stage.stageWidth / 2 + x;
angle += 3;
}
}
}
Creating Particle Effects with Starling
03/2012 (33)
15
particle is to be generated from. Finally, start()
is called to commence emission of the particles, and the particle system is added to Starling’s root display list with a call to addChild()
.
There’s one last step to perform. Although we’ve called start()
, we won’t see any of the particles being emitted until our particle system is added to Starling’s default Juggler object. The Juggler is responsible for updating any objects that are to animate, including the particles within a particle system. Add the following line of code to the end of your event handler:
Starling.juggler.add(particles);
Now build and run your project. You should see your exhaust plume particle effect running within a browser window.
Adding Motion
Now that your particle effect is up and running, let’s add some finishing touches by applying some motion to it.
Staying within your ParticlesExample class, declare a member variable of type Number
:
private var angle:Number;
Initialise it within the constructor:
angle = 0;
Now within your addedToStage()
handler, add a listener for the ENTER _ FRAME event:
addEventListener(Event.ENTER_FRAME, update);
Again, as with ADDED _ TO _ STAGE
, the ENTER _ FRAME
event that we’re using belongs to the starling.events
package rather than lash.events
.
Now write the ENTER_FRAME
handler, providing a few lines of code to animate the particle effect across its x-
axis
:
private function update(e:Event):void
{
var x:Number = Math.sin(deg2rad(angle)) * 40;
particles.emitterX = stage.stageWidth / 2 + x;
angle += 3;
}
The motion follows a sine wave and the emitter’s current x-value is calculated using the Math.sin()
static method, which expects, as its only argument, an angle measured in radians. To convert the angle member variable to radians, we use Starling’s deg2rad() support function, which must be imported. Add the following to your class’ list of import statements:
import starling.utils.deg2rad;
Save your class and test the final version of your code. The exhaust plume should now move back and forth across its x-axis. Listing 3 shows the code for your ParticlesExample class in its entirety.
Final Statement
Working with the Starling Framework and its Particle System extension is fairly straightforward. With the help of a suitable particle editing tool and a minimal amount of ActionScript, you’ll be able to create results that match the visual effects seen in popular console and handheld video games.
CHRISTOPHER CALEB
Christopher Caleb is a professional Flash developer and author of Flash iOS Apps Cookbook. He is currently lead Flash developer at WeeWorld – an avatar-based social network and virtual world for teens. Christopher blogs at www.yeahbutisit�ash.com and tweets as @chriscaleb. If you �nd anything he says vaguely interesting then feel free to send him an email at info@christophercaleb.com.
03/2012 (33)
16
PHOTONSTORM.COM
H
igh profile and high quality game releases such as the Microsoft sponsored Cut the Rope are making headlines across the world, and engaging the public more than ever before. But what is the reality of developing an HTML5 game today? Especially for those coming from a different platform. And more importantly is it possible to actually make any money doing it?
HTML5 is just a mark-up standard!
Relax When I talk about HTML5 I’m doing so from the popular media use of the word, rather than the technical one. On a technical level HTML5 is of course just a specification for a mark-up language. But the media has chosen to use the term as an umbrella, spanning lots of browser related technologies including WebGL, JavaScript, Web Sockets, GLSL, Web Audio, NaCl, Canvas, DOM, CSS3 and more. As a whole these things do not comprise HTML5, indeed they have their own standards, but I guess to preserve the sanity of the layman (and journalists?) that isn’t really what HTML5 means any more.
What is an HTML5 game?
This seemingly innocuous question actually has a myriad of answers, and can get complex pretty fast. The Reality HTML5 game development and indeed the abilities of web browsers are in state of rapid evolution right now. On the HTML5 Game Devs site that I run I’ve been noticing an increasing pace of new content, game releases, tutorials, business news and technology.
of HTML5 Game Development and making money from it
Note
This was written near the end of January 2012 and as such re�ects the state of the technology and markets at the time. Everything is moving so fast a lot of the information below is subject to change, so bear that in mind.
03/2012 (33)
18
PHOTONSTORM.COM
While I could say that on a basic level an HTML5 game is made using JavaScript paired with a browser based technology, that isn’t strictly true as it’s actually possible to make complete (albeit simple) games using purely CSS3. So let’s approach it by listing the technologies available to HTML5 game developers and what they offer:
CSS3
Most developers know CSS as the stuff that styles web sites. CSS3 is an evolution of this that includes support for built-in transformations and animation. So no longer do you need to use JavaScript to make something move around a web page. CSS3 is so powerful there are even games made entirely using it. Some modern browsers support hardware accelerated CSS. Yes, you read that correctly – CSS rendered via the GPU, and because of this there’s even CSS based Shaders. But as a serious game developer would you code a game using just CSS? Not really. It’s more the domain of pro web developers and you’re likely to hit the limitations of what it can do rapidly. Still, don’t rule it out as an option if the project fits.
DOM (Document Object Model)
The DOM is familiar territory for web developers but much less so for everyone else. It’s a way of defining how elements within HTML should interact with each other and provides JavaScript with a means to inspect the browser and the HTML loaded into it. In terms of game development DOM based games are the way in which developers talk about HTML5 games that are constructed using HTML elements and CSS3 rather than rendered to a Canvas (see below). There are advantages to this approach. Due to the hardware acceleration available it’s possible to write extremely fast and responsive DOM games. The game Sumon is a good example of this. In fact in some browsers, and depending a lot on the type of game, this is often a better option than Canvas.
Canvas
Canvas is probably the most well known approach to creating HTML5 games. A canvas is an HTML element defined using the <canvas>
tags. Think of it as a large dumb block of graphics data, that once added to a web page you can manipulate through JavaScript at will. Those coming from Flash can relate it to a Bitmap object. You can read and write pixel level data, paste images into it, set compositing modes, alpha, transforms, scales and draw basic shapes like lines, curves and rects. As it has been around for quite a while it’s well supported in browsers, both desktop and mobile, although rendering speeds vary dramatically.
WebGL (Web Graphics Library)
WebGL is a means to have GPU accelerated 3D in browser. Based on OpenGL ES 2.0 (the same as Adobe Flash Stage3D) it offers a direct route to the 3D The Reality of HTML5 Game Development and making money from it
03/2012 (33)
19
graphics API, including shader support via GLSL. As it runs on GPU performance is hardware dependant, but typically significantly higher than Canvas. From a game development perspective you can of course create 3D games with it, and some notable examples like SKiD Racer and GT Racing have done just that. All the issues inherent with 3D development on other platforms are manifest in WebGL as well such as memory / bandwidth required for texture and model data, the variety and respective speeds of GPUs and the evolving nature of the technology. The other massive gotcha about WebGL is that Microsoft have no public plans to support it yet. So you won’t find it in Internet Explorer or the new Windows 8 Metro. That doesn’t rule it out entirely, but it makes adoption of it a harder sell to clients. On the flip side it’s gaining traction in mobile. iOS5 has it built-
in although currently disabled and Firefox on Android supports it.
SVG (Scalable Vector Graphics)
SVG is a means to display vector graphics and animations natively on the web. It’s an XML based format that has been around for over a decade but has only recently seen more wide-spread browser adoption. But that support is now comprehensive and includes modern mobile browsers. Performance varies dramatically from device to device. On the Desktop it’s perfectly possible to use it to handle the graphics rendering for games, but mobile mileage varies tremendously. Development support is good and there are a number of comprehensive SVG libraries available. Google provide a tool called Swiffy that converts Flash vector animations to SVG animations, as was recently demonstrated so well on the One hour per second site. I would also put good money on a future version of Adobe Flash exporting to SVG or a similar product from them. On its own you cannot make a game with SVG as it needs to be paired with JavaScript but it’s definitely a viable rendering solution.
Native Client (NaCl)
Native Client (NaCl for short) is a Chrome specific technology that allows developers to code in C/C++ and produce a .nexe file, a compiled native module. These run inside the NaCl sandbox in Chrome. Why might you want to do this? The main reason is speed. It runs at near native OS speeds, which is crucial for intensive games. You have access to multi-core / threading, 3D, low latency audio, shaders and soon networking. Being able to port C/C++ code makes it an interesting option for game developers working in that area already. A good example is Super Giant’s game Bastion. NaCl is Chrome only but cross-platform and could be a useful option if you already develop C/C++ games and want to have a web browser ready demo (or full game) without recoding it from scratch in another language.
WebSockets
If you have a need to support multiplayer in your game or perform any sort of intensive network based activity then WebSockets is a new technology that falls under the HTML5 umbrella. WebSockets are a protocol for two-way communication with a remote host. To crib the official site they provide an enormous reduction in unnecessary network traffic and latency and account for network hazards such as proxies and firewalls, making streaming possible over any connection. With the ability to support upstream and downstream communications over a single connection HTML5 Web Sockets-based applications reportedly place less burden on servers, allowing existing machines to support more concurrent connections. The real-time nature of them make them perfect for games requiring low latency, such as the multiplayer asteroids game Rawkets.
Node.js
Node.js on the other hand is a server-side technology. Although you could argue it has nothing to do with HTML5 as it’s JavaScript based and allows good use of WebSockets it is often categorised as such. Designed specifically for highly scalable network applications you can run JavaScript on the server in an asynchronous 03/2012 (33)
20
PHOTONSTORM.COM
event driven model. Node.js can create HTTP and WebSocket servers as needed, which is almost the reverse of the traditional web stack where a server (such as Apache) sits on the bottom with a language like PHP or Ruby parsing the scripts and outputting HTML. Neither of these technologies are a requirement for HTML5 games but with WebSockets support now native in all major browsers including Mobile Safari (but not on Android!) it’s a sensible option to explore. And with Node.js you can create server-side modules without learning a new language as it’s all JavaScript based.
JavaScript (JS)
JavaScript is the de-facto standard language for interacting with all of the above technology and is the glue pulling everything together. When JavaScript code is executed in browser it’s parsed by a JavaScript Engine. Different browsers have different engines: Chrome uses an engine called V8, Mozilla Firefox uses SpiderMonkey, Safari uses Nitro, Internet Explorer 9+ uses Chakra and Opera uses Carakan. Although the browsers are relatively matched in terms of JavaScript performance, the SunSpider Tests being the easiest way to check this, always keep in the back of your mind that each engine is executing the same code slightly differently. What may be an optimisation in one may not be for another.
As for the language itself Wikipedia sum it up well: JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-
oriented, imperative, and functional programming styles. Depending on your programming experience this may or may not scare the hell out of you. I know a good few developers who struggle with moving from a strict language such as AS3 to something so fluid, but the reality is that if you want to create HTML5 games you really need to learn it. Personally I’ve had very few issues with it and in fact am finding the dynamic nature extremely fast to develop in and powerful. But everyone works in different ways. I feel the misconceptions around JavaScript (it’s messy!, no IDEs!) are largely unfounded, but should be addressed in different article. My one single piece of advice is simply this: Don’t fight it. Don’t try to make JavaScript into something it isn’t by forcing strictly typed conventions and structures onto it. Embrace it for what it is and allow that to influence the way you code.
If you really don’t want to touch JavaScript I’d argue it’s best you don’t entertain the thought of making an HTML5 game. There are languages that will compile into JavaScript, such as Google’s Dart. Karel Crombecq has also left a detailed comment to this article about the benefits of GWT if Java is more your thing. Also worth considering are WYSIWYG game creation software like Game Maker and Construct2 which export their final builds to JavaScript for you. But you absolutely need to get close to the metal, especially when working on mobile, so be prepared to get your hands dirty.
That was just the tech, let’s add the platforms into the mix …
Now we know what technologies are available for HTML5 game development we need to look at the different platforms available. You’re probably thinking that surely the web is the platform? But of course it’s more complex than that.
Desktop Browser
By Desktop Browser we mean the browser you are likely using to read this article, one of the big 5: Chrome, Firefox, Safari, Internet Explorer and Opera. As it stands desktop is the single biggest market at the moment with the most eyeballs. The benefits of targeting the Desktop browser is that you may have a GPU available (essential for WebGL), they are generally faster at processing, have more memory and have larger resolutions. Bandwidth and network speed is less of an issue and you can expect to find a keyboard and mouse combination available. Potentially there may even a gamepad connected which you could access via the new GamePad APIs.
The problem with the Desktop Browser, specifically in relation to game development, is that you also have Flash installed into 99% of them. And right now if you are targeting the desktop browser exclusively then it’s �������������������������������
�
�����������������
�������������������������
�
��������������������������
��������������������������
���������������������
����������������������������������������������
���������������������������������������������
����������������������
�����������������������������������������������
�����������������������������������������������
�������������������������������������������������
������������������
����������������������������
������������������������������������������������
����������������������������������������������
�������������������������
����������������������������������������������������
������
��������� ����
����������������������
���� ����� ������
��������������������������������
��������
�
���������������������������������������
�
�������������������������������������������������������������������������������������������������������������������������
��������������
�����
����
�����������������������
���������������������������
03/2012 (33)
22
PHOTONSTORM.COM
a real struggle to find a compelling reason to pick any of the web technologies listed above over Flash. So be pragmatic in your choice, at the end of the day it should come down to does it make good business sense?.
Facebook
Technically this is only really an extension of the Desktop Browser platform above, but I’m listing it here as it’s increasingly easy to create Facebook HTML5 games. They have a complete build, test and distribution system and are extremely HTML pro-active. And of course all of their APIs and Facebook credits are available.
Mobile Web Browser
Not to be mistaken with mobile apps, which you download and install onto your phone, the Mobile Web Browser is an increasingly important platform to target. Mobile browsing is catching up to Desktop fast with some predictions putting the overlap period to be as early as 2014. Take that figure with a pinch of salt of course, but no-one denies the rapid growth here. This is in part supported by the recent advances in mobile technology. It assumes the player is online and browses to your game via the browser installed on their phone or tablet. There is a rapidly growing market in mobile web games, with a number of high profile games portals already on board buying them and many more will follow. In terms of development you need to approach it from either the DOM or Canvas angle. Most smart phones contain dedicated GPUs and Mobile Safari will now use it to render DOM elements and under iOS5 Canvas as well. WebGL is also on its way. Enabled in Firefox on Android and a hidden option in Mobile Safari expect to see more of this soon.
The biggest issue mobile web has is speed and device disparity. For example the difference in rendering performance between an iPhone running iOS4 to one running iOS5 is dramatic. And the performance between that an a cheap Android phone is even more startling. Add the varying resolutions and memory constraints of the devices in to the pot and you’ve got a whole world of QA pain awaiting you. Especially when you factor in that Android devices tend to favour DOM in terms of speed.
Mobile Apps
A mobile app is the sort you most likely have installed onto your phone right now. Downloaded from Apples App Store or Android Marketplace and often paid for. HTML5 is certainly capable of creating mobile games but you’ll need a 3rd party technology like PhoneGap, App Mobi’s DirectCanvas or Game Closure to package it up. They will also accelerate your games to near native rendering speeds and address missing or broken issues like low latency audio. The advantages are obvious: you can sell the game in mobile vendor stores which is a proven (if somewhat extremely hit and miss!) business model, and you can use the same source code in the process. The downside is that you’re now competing against the likes of Angry Birds, Jetpack Joyride and Infinity Blade as you’ll be sharing the same marketplace, often referred to as the smallest shop window in the world.
Tablet Speci�c (BlackBerry PlayBook, Nook, Kindle Fire)
The largest tablet manufacturers are also providing a means to develop HTML5 games for their devices. BlackBerry have a well established Web Works SDK. You can publish to the Nook using a framework like Titanium or PhoneGap. And while the Kindle Fire is reported as being lacklustre in terms of HTML5 performance Canvas support was OK, so it could probably handle a simple or low-intensity game.
Windows 8 Metro / Mac App Store
Windows 8 will ship in 2012 and features Metro. Metro is actually a design guideline rather than an actual technology, but what it effectively means is a new styled user interface for Windows 8 that features panels and typography based content. And it’s created using HTML5 technologies. It’s entirely possible to create games to run as apps in Windows 8 and Microsoft will encourage this via its Windows 8 Marketplace. Windows 8 will also ship with Internet Explorer 10. Although most tech savvy people used to know IE as the browser to avoid, with IE9 the reasons for doing so are far less defined now. It has incredible Canvas support with GPU accelerated rendering and a very fast JavaScript Engine. Things have certainly changed a lot since IE6. Also worth mentioning is the ability to sell HTML5 games in the Mac App Store, like these guys did.
Intel AppUp
Intel AppUp is an Intel run store-front in which you can buy apps and games. It comes pre-installed on lots of laptops, netbooks and ultrabooks. Of course you can create AppUp games using HTML5 technology and the Intel Developer Program provides all the tools you need to do this. As you would expect you’re dealing with a variety of hardware configurations and resolutions, but on the whole the performance is easily high enough to carry a fun game without having to cut too many corners.
The Reality of HTML5 Game Development and making money from it
03/2012 (33)
23
Connected TV (Opera TV Store)
The Opera TV Store is a complete HTML5 based store solution for Connected TVs. Much like you install apps onto your smart phone, a Connected TV allows you to do the same onto it. Opera have released an SDK and TV emulator to develop with, and it’s probably only a matter of time before similar SDKs come out from other vendors. A story in mid 2011 flew around the web showing a dev who hacked into his Apple TV and found it could run HTML5, so made a Blackjack game for it. It’s just a matter of time before App Store comes to Apple TV.
This sounds like cross-platform hell!
To a degree, it is. I guess the hell part of that is quantified by how far down each platform you wish to travel. On the plus side it’s at least comforting to know that with one set of technology it’s possible to hit such a wide variety of platforms and potential sources of income. But on the other the thought of supporting that many devices should rightly send a cold chill down your spine.
The first decision to make should be which platform is essential for you and work from there. If you know you need to get onto mobile web then rule out playing with WebGL for example. If you are only worried about the Desktop market and need to make a game that “goes viral” and spreads then you should probably question the use of HTML5 in the first place and still consider Flash.
I’m not one to believe there is any such thing as a true cross-platform technology when it comes to games. While it’s true that you can take the same code written for Desktop and deploy it to Mobile you’ll almost certainly hit performance issues. Assets will need to be created with the mass of varying resolutions in mind and you’ll almost certainly need to generate multiple versions of game UIs. Depending on the type of game it’s entirely possible you will end up with a Desktop version that provides for a detrimental experience because of limitations placed on it by the Mobile Web build. Start with the Desktop version and you could find you’ve created a game that’s simply impossible to port to Mobile Web at all.
I don’t mean to demoralise anyone reading. I just want to inject some sanity into the “cross platform” dream. The more platforms you want to support, the more variations of everything you’ll need. On the plus side the code base is identical and for some games the resolution issue won’t be an issue at all.
How on earth do you monetise all of this?!
That’s a bloody good question. And I wish I had the answer. What I can do is point you to the know stores / markets as they exist right now. If you know of any more please leave details in the comments.
Google Ads
You can run Google Ads in your HTML5 games. Google offer a range of mobile sized banners and if you’ve got the traffic this can be a nice consistent earner.
In-app and Mobile Billing Payments
There are several systems out there offering in-app payment solutions for HTML5 developers. Of course do your research before picking one and this list is by no means exhaustive, so search around. Fortumo recently announced it was providing mobile billing solutions via an HTML5 API which means your players can be charged directly to their phone bill. Google have an in-
app payments system which provides a simple API to take payments for virtual and digital goods. LevelUp provides an API to allow players to buy via their own personal QR codes.
Facebook Credits
You can’t really ignore Facebook and the ability to take payments via Facebook Credits. This is a whole subject in its own right and only really suitable for very specific types of game.
Mobile Gaming Portals
There are a growing number of game portals who are embracing mobile browsers and setting up portals specifically for them. Spil and MindJolt are probably the two biggest but there are plenty of smaller players with money to spend. They are buying games in the same way portals buy Flash games – exclusive and non-exclusive licenses. It’s 03/2012 (33)
24
PHOTONSTORM.COM
important to understand these are Mobile Web Browser games, not Apps, although there are plenty who will buy apps too.
Mobile Apps
Apple App Store and Android Marketplace are the two largest, but not the only stores you can get your app wrapped HTML5 game in to. The process is painless and relatively trouble free. The resulting income? Well, hopefully you know the reality by now. I would just add that it’s worth releasing your games into these markets because if you don’t someone else will. Time and time again I’ve seen games ripped and released onto App Store – and with HTML5 games it’s even easier. They literally just download the code, wrap it and publish it. So if you care – make sure you get in there first.
Browser Vendor Stores
This is a new and evolving marketplace. Google run the Chrome Web Store and Mozilla are beta testing their new HTML5 App Store right now.
Mobile Vendor and Tablet Stores
This is another emerging marketplace. At CES last year AT&T announced a new HTML5 API for its In-App billing system FierceWireless. In their presentation they displayed a graph showing an expected total market of 1.5 billion smartphones by 2016. Microsoft already have their Windows Phone Marketplace open to app submissions and of course are embracing HTML5 with open IE shaped arms. Motorola also announced Webtop – the ability to run HTML5 applications on their latest mobile and tablet devices. You can find presentations and docs on the subject in their developer portal Motodev. You can also get your HTML5 game in to the BlackBerry App World PlayBook store, the Intel AppUp Center, the NOOK Apps and onto the Kindle Fire via Amazon. Do your research first though, a lot of these places will give you a pittance re: income if not marketed correctly. Although surprise hits are totally possible.
Windows 8 Marketplace for Metro Apps
I’ve already mentioned this in the article but Microsoft will have an apps Marketplace built directly in to Windows 8. They also have great development tools to go with it, so don’t rule this one out even if you’re an Apple fan boi.
In Summary …
If you’re an indie game developer this may seem like an overwhelming range of platforms and technologies to contend with, and it is. Unity, Corona and Flash/AIR can hit a lot of the platforms listed above with substantially less effort. But the platform growing the fastest and of most importance right now is the Mobile Web and that is now firmly in the domain of HTML5 technology only.
So why list all of the other platforms? It’s because I believe that to be a successful indie developer today you almost need to take a shotgun approach to your game. Getting it on to as many places as possible while compromising its integrity as little as possible. Thus creating lots of small income streams all flowing back to you. More games, on more platforms, hopefully over time builds those streams in to a proper torrent of income. That’s my hope for you at least If you work for a company that has a pointy haired boss running up all excited about this new fangled HTML5 thing, at least now you have some appreciation of the vast scope of technology and platforms that simple request can span. Of course when people say that what they usually mean is I want it to work on my iPhone (i.e. Don’t use Flash) but now you can see it isn’t as simple as that. Serious thought has to be put in to targetting the right platform, deciding how many versions to create and what trade-offs you’re willing to make along the way.
But one thing is for certain: despite the technology stack involved HTML5 games are no longer just for web developers. Proper game devs should be paying attention and starting to dip their toes in, because the routes to market and associated technology are exploding.
RICHARD DAVEY AND PHOTONSTORM.COM
Photon Storm are Richard Davey and Ilija Melentijevic. This is our place on the web where we publish our HTML5 and Flash games, artwork and tutorials. We like writing about all facets of game development and sharing cool links now and again.
For my day job I’m the Technical Director of Aardman Digital, the online department within Aardman Animations – most famously known for Wallace and Gromit, Shaun the Sheep and Creature Comforts. Part of the work our department does is to create games and online experiences based around our key brands.
Prior to joining Aardman I spent years working in the games industry for a �ne company called The Game Creators. They produce software that allows anyone to create decent games on the PC with relative ease. I’m still in close contact with the guys there and will be blogging about anything exciting I see on their horizon.
I consider myself a hardcore gamer, and have always loved gaming since I saw my �rst ever Atari 2600. I’m also an Atari otaku. The Atari ST holding a special place in my heart, which is why I built this site dedicated to it. So if my code experiments have a seriously “retro” �avour to them, that is why!
03/2012 (33)
26
FLEX AND MONGOMD
I
n this first article we’ll see the basing concepts related to MongoDB, how to install and configure it. In upcoming articles we’ll be creating a small but functional file store application.
MongoDB
In the NoSQL world MongoDB is referenced as a document-based database. It provides a lot of interesting features, such as easy scaling, a rich data model and so on. MongDB is also schema-free this gives us a great flexibility on how we work with a constant evolving data model.
Installing MongoDB
Installing MongoDB is a dead easy approach, just go to http://www.mongodb.org, download a package suitable for you operating system. In this article I downloaded the tgz package and unpacked it in the Applications folder of MacOSX. After that just create a data/db folder where our databases will be stored. For simplicity I created it in the mongodb folder. See Figure 1.
That’s it, MongoDB is installed and ready to run. Documents Documents, Documents
Let’s now see the building blocks for working with MongoDB, understanding this simple but useful concepts will help a lot, specially novices in the NoSQL world.
• A document is the basic unit of data for MongoDB, it’s equivalent a row in a relational databas
• collections can be compared to tables.
• Every Document has a special key called _id that’s unique across collections (Listing 1)
Running MongoDB
Now that we installed Mongo, let’s begin using it. To run the Mongo daemon for now, let’s open a console window and issue the mongod command. See Figure 2.
Flex and MongoDB
This month i’ll begin a writing about using MongoDB along out Flex applications, it will be divided in 3 parts where we’ll from configuring MongoDB to connect to it and other interesting things.
What you will learn…
• Use MongoDB with your Flex Application
• Key concepts of NoSQL
• Administer MongoDB server
What you should know…
• Database basics
• Strong passing for new topics
• Be curious
Figure 1. The data/db folder, where our databases will reside
Listing 1. A document example in MongoDB
{"book_title" : "Beginning Python"}
Flex and MongoDB
03/2012 (33)
27
Note
MongoDB searches for the database folder from the root folder of your system. On *nix like system it’s /data/
db
(on Windows it’s C:\data\db
). If you create this folder on other location as I did here, we must specify the –
dbpath parameter along with the location for this folder. See Figure 2.
The Mongo shell
To test if everything went ok, connect to the MongoDB instance running on your machine with the mongo command. Upon connecting to the MongoDB instance, the test database will be selected. See Figure 3.
Playing with collections
Before we starting developing our application, let’s begin creating a collection with the console. To create a new database within MongoDB, use the use <dbname>
, for our app I’ll call it storage. See Figure 4.
After we created our database a db variable is available – that refers to our storage database.
Now let’s create a users collection where. To do that let’s create a users variable and assign to it our user representation. See Listing 2 and Figure 5.
Inserting data to the collection
Now that created the document representation for a user, to insert it in the collection is just a matter of using the insert function passing the user variable. After that we find all data in this collection. See Figure 6.
Final Statement
And that’s it for now. In this article, we saw the basic piece of information for working with MongoDB, despite it show no ActionScript, understanding this concepts will help greatly as we move forward with more advanced topics, in part 2 where we’ll begin to design our little application. See you there. Any question regard MongoDB will be appreciated.
Figure 2. Running MongoDB daemon with speci�ed –dbpath parameter
Figure 3. Connecting to the MongoDB instance
Figure 4. Creating a new database
Figure 5. Data to be inserted in the users collection
Figure 6. Inserting data and querying the users collection
MARC PIRES
Marc Pires is a Developer located in Brazil, during his career, he has worked in various roles such as Network Administrator, Instructor. He has a strong passion for working with and researching new technologies. Specialized on RIA, Iphone Development, Restful web services and other interesting things, he’s one of the main developers of the Esus System and is heads a startup specialized on mobile development.
Contact information: @MarcPires (Twitter) | marcpiresrj@
gmail.com | IChat: marcpiresrj@aim.com
Listing 2. Data to be inserted in the users collection
users = {"name" : "marcpires", "email" : "marcpiresrj@gmail.com",
"password" : "change_me_later"}
28
INTERVIEW
03/2012 (33)
What’s your role @ Flare3D Team. How and when did it all start?
Im Flare3D CEO. I work on business development, specially in technology adoption from biggest studios.
Flare3D started as a internal production tool in SIA Interactive, until we realize it has a tremendous potential and we made a spin-off and founded Flare3D with
Ariel Nehmad, one of the brightest minds on the 3D industry and Flare3D’s CTO.
How long did it take to put the Library together?
Our team started developing Flare3D 6 years ago. It was a software rendering enging used on internal projects.
We started working with Adobe Labs since the inception of Stage3D (codename Molehill), since then, our product has evolved month after month.
How many Developers are working on the Engine?
Flare3D has a small team of 4 core developers, but we have research centers in Israel and Argentinian universities.
When needed we use the resources of SIA Interactive that employs around 50 developers.
What types of Flare3D Licences are available?
Flare3D has 3 kind of licenses.
A. Free for non commercial applications.
B.
Annual suscriptions at 496 U$S per year per seat.
It includes Flare3D Studio. Published content doesn’t pays any kind of runtime or royalty.
C.
Source code licensing annual subscription. This license is made only to selected studios prior the sign of a NDA.
In comparison to other 3D Engines and Libraries, what you think is the most unique selling proposition of Flare3D Lib?
Our customers are professionals who needs best performance, good documentation and a professional tech support.
We provide a great workflow for developing on AS3: Flare3D includes a deeply integrated plugin for 3DS Max, Flare Studio and a AS3 based engine optimized for Flash.
Biggest studios are choosing to develop Flash 3D content coding on AS3.
Do you have any tips for developers who are looking to work with Flare3D?
We suggest developers evaluate the different available 3D technologies for Flash 3D. I recommend to download Flare3D free trial and read documentation and tutorials that includes source code and 3D assets.
Any plans for a conference in the european area?
We are in contact with many Adobe Users group and our users are very active presenting Flare3D and giving training.
However we expect to be very active and have a strong presence in events in Europe.
Interview with Adrian Simonovich
Adrian Simonovich
Adrian Simonovich is CEO of Flare3D, born in Argentina, studied at ORT Argentina and worked at Top Toys (Mattel) before founding SIA Interactive at the age of 21. Since then, Adrian leaded an amazing team that founded several High-Tech companies that connect creativity with technology and made them grow into multinational companies. In his free time he likes to run (ran the Adidas 42K Marathon) and travelling with his wife Viryna.
03/2012 (33)
This year we will be sponsoring Flash Game Summit, Adobe Max and participating at GDC 2012.
What you think about the Future of Flash in 3D?
Stage3D team at Adobe Labs has done an amazing work. 3D in Flash is a reality.
We expect Flash 3D gets better and better.
Adobe is working to made Stage3D compatible with older graphic card drivers in order to reach more users.
3D in Flash means 3D has reach the mass market for first time ever.
Studios will to increase adoption of 3D to communicate and play.
Do you think we can see some Stage3D stuff on Adobe Air (for Mobile), soon?
3D for Adobe Air is already released with AIR 3.2!!
http://www.bytearray.org/?p=3970
What is the Flare3D Desktop Tool for?
Flare3D Studio is an integrated IDE. It is really helpful for creating materials on real time.
Visualize animations, place lights, save 3D assets in highly efficient F3D format.
Many studios are using Flare Studio extensibility to made their own plugins for batch processing tasks.
What are the next goals for Flare3D?
Our intention is to keep Flare3D as an independent company. We are very profitable. Since the launch of Flare 2.0 (a year ago) biggest studios in USA, China, Germany and France adopted Flare3D.
Our goal for 2012 is to move our operation to San Francisco and make Flare3D the natural choice for Flash 3D and WebGL content creation.
What u do in your free time?
I do running. I ran the Adidas 42K Marathon and several 21K’s. I love travelling with my wife Viryna (Venezuela) to the caribean beaches.
In short: iOS or Android?
The End-User must admit that nothing is closer to Apple products in terms of hardware and user experience.
And Windows or Mac? :)
I got Windows 7 running on a Macbook Pro.
ALI NEKOU POUR
Ali Nekou Pour is a senior application developer in Germany specialized in the Adobe Flash Platform, producing interactive applications for web, desktop and mobile environments. He worked many years in famous advertising agencies and now, for an internaltional publisher in the science sector. He is an active member of the Adobe Flash & Flex Community.
03/2012 (33)
30
ADOBE FLASH AND JQUERY
T
his article is written for the beginner in web development particularly artists and singer/
songwriters that manage their own websites.
Getting Started
Step 1
Download the jPlayer core files here: http://jplayer.org/
download/. Click the button Download jPlayer. This tutorial would be using version 2.1.0. You need to download the plugin (which is zip file) to your local computer.
Step 2
Download test skins that will be used with jPlayer: http://
jplayer.org/latest/jPlayer.Blue.Monday.2.1.0.zip. Step 3
Extract the contents of both zip files. Step 4
You need a local host server in your computer to run jPlayer in a development setting. You can use a portable version of XAMPP which simulates an Apache server in your own computer: http://www.apachefriends.org/en/
xampp-windows.html. Look under XAMPP portable and download the .exe file. You will then install it to your computer. Since this is a portable version, you can install this to your USB drive or any other local drives.
Step 5
Go to XAMPP htdocs folder and create a test website where you will run the jPlayer application. For example, you need to create a website called: mytestwebsite.
Step 6
Go inside the mytestwebsite folder and create two folders named js and skin. The js folder is where you will place your JavaScript files that are needed with jQuery while the skin folder is for customizing the look and feel of your audio player (see Figure 1 for these two folders).
Step 7
Place these two files inside the js folder. You can find these files from the extracted jQuery.jPlayer
folder.
Introducing jPlayer: Audio players are indispensable features in a music or art website. This article examines jPlayer (http://jplayer.org/) which is an open source (free) jQuery plug-in for your website audio needs. It combines Adobe Flash and jQuery to create modern, highly customizable players for your website. What you will learn…
• Install jPlayer in your website.
• Associate your audio �les with jPlayer.
• Customize jPlayer to blend with your website.
What you should know…
• This article is written for the beginner in web development
jQuery Audio Solutions for your Website
Figure 1. Inside the “mytestwebsite” Introducing jPlayer: jQuery Audio Solutions for your Website
03/2012 (33)
31
• jquery.jplayer.min.js
• Jplayer.swf
Step 8
Copy the extracted blue.Monday
folder to skin. Figure 2 shows the content of blue.Monday skin.
The steps on the previous section teach you how to upload jPlayer files to your own website server. For example, in the above section, this is path to your website in the local server XAMPP: http://localhost/
mytestwebsite/. The path to the js and skin folder are shown below accordingly:
• http://localhost/mytestwebsite/js/
• http://localhost/mytestwebsite/skin/
In a relative URL path, it would be:
/mytestwebsite/js/
/mytestwebsite/skin/
But in a real website server (the one in your hosting company), this is an example path of your domain name: http://www.example.com/.
And js and skin are created in the root directory so that gives the path:
• http://www.example.com/js/
• http://www.example.com/skin/
The relative URL path (relative to the root) would now be:
/js/
/skin/
Using the above concepts and comparing the local host path to the real website path, it gives you a pretty good idea how you to include and access core files of jPlayer in your website. Let’s now learn how to create an example web page using jPlayer.
Creating the jPlayer <head> Section of your Web Page
Step 1
First, launch notepad and let’s create a sample webpage application. Copy the code below to the blank text file and save it as index.htm to this test website folder in your local server: /mytestwebsite/
<html>
<head>
<!—This is the head section -->
</head>
<body>
<!—This is the body section -->
</body>
</html>
Step 2
The next thing is to add the skin CSS of the jPlayer:
<link type=”text/css” href=”/mytestwebsite/skin/blue.Monday/
jplayer.blue.monday.css” rel=”stylesheet” />
The skin used is blue.Monday
. CSS should be added first before any JavaScripts to have a quick web page rendering at the web browser. Step 3
Before you can implement any jQuery application (such as jPlayer), it requires the jQuery framework. The most Figure 2. Inside the blue.Monday skin
Listing 1. JavaScript added for Jplayer
<script type="text/javascript">
$jQueryvariable = jQuery.noConlict();
$jQueryvariable(document).ready(
function
(){
$jQueryvariable("#jquery_jplayer_test1").jPlayer({
ready: function
() {
$jQueryvariable(
this
).jPlayer("setMedia", {
mp3: "http://localhost/mytestwebsite/audio/test.mp3"});},
swfPath: "/mytestwebsite/js/",
supplied: "mp3"
});
});
</script>
03/2012 (33)
32
ADOBE FLASH AND JQUERY
recommended is to use Google libraries because this is faster, lighter and compressed:
<script type=’text/javascript’ src=’http://ajax.googleapis.com/
ajax/libs/jquery/1.7.1/jquery.min.js’></script>
Step 4
The next step is to include the jPlayer JavaScript file which is:
<script type=”text/javascript” src=”/mytestwebsite/
js/jquery.jplayer.min.js”></script>
Step 5
Finally you need to add the JavaScript for your audio player: Listing 1.
Code Discussion
• First, define a jQuery variable named as $jQueryvariable
.
Then set that variable to no conflict mode to avoid problems with other JavaScript libraries and framework in your website.
• In your actual HTML code for the jPlayer in the <body>
section (to be discussed later), it is referenced using jquery _ jplayer _ test1
and the jPlayer constructor.
• The player is programmed to play an mp3 file as defined by setMedia
jQuery method. It also shows the path to the mp3 file is given by: http://localhost/
mytestwebsite/audio/test.mp3.
So try creating a folder named audio and put in any mp3 file named as test.mp3
. This is the final <head>
code: Listing 2.
Creating the jPlayer <body> Section of your Web Page
You are now ready to add jPlayer on your web page. This will be placed in the <body>
tag. Start by copying and pasting the code below to the index.htm body tag. This is the standard code of jPlayer HTML audio interface provided by the developers here: http://jplayer.org/
latest/quick-start-guide/step-6-audio/. Since it is HTML, the design and feel of the audio player is highly customizable (Listing 3).
To play the media you will need to either update your browser to a recent version or update your <a href=”http://
get.adobe.com/flashplayer/” target=”_blank”>Flash plugin
</a>
.
</div>
</div>
</div>
</body>
Try to run the web page in the browser. Enter the following URL in your browser address bar: http://
localhost/mytestwebsite/. It should look like what is shown in Figure 3.
How the jPlayer Audio Interface Works
• <div id=”jquery _ jplayer _ test1” class=”jp-jplayer”></
div>
This would activate the jPlayer jQuery JavaScript associated with the id jquery _ jplayer _ test1
and then load the flash player.
• <div id=”jp _ container _ 1” class=”jp-audio”> </div>
This is the main container of the audio player; you can visualize this easily by installing the Listing 2. Final Head section source code
<head>
<link type="text/css" href="/mytestwebsite/
skin/blue.Monday/
jplayer.blue.monday.css" rel="stylesheet" />
<script type='text/javascript' src='http://
ajax.googleapis.com/ajax/libs/
jquery/1.7.1/jquery.min.js'></
script>
<script type="text/javascript" src="/mytestwebsite/
js/jquery.jplayer.min.js"></
script>
<script type="text/javascript">
$jQueryvariable = jQuery.noConlict();
$jQueryvariable(document).ready(
function
(){
$jQueryvariable("#jquery_jplayer_test1").jPlayer({
ready: function
() {
$jQueryvariable(
this
).jPlayer("setMedia", {
mp3: "http://localhost/mytestwebsite/audio/
test.mp3"});},
swfPath: "/mytestwebsite/js/",
supplied: "mp3"
});
});
</script>
</head> 03/2012 (33)
34
ADOBE FLASH AND JQUERY
Firebug plug-in within the Firefox browser: http://
getfirebug.com/ (Figure 4).
As you can see, the entire audio player has been highlighted (in blue shade) when you select <div id=”jp _ container _ 1” class=”jp-audio”>
in Firebug.
The rest of the HTML components of the jPlayer audio interface can be analyzed using the Firebug technique. Suppose you would like to examine the affected area of <ul class=”jp-controls”>
. It is shown in Figure 5 (enclosed in the red rectangle box). At this stage, if you click on the MP3 player play button, it should be able to play the audio file.
Customizing the jPlayer Style and Design
Another important aspect of learning jPlayer is to know how to edit the style and design to fit your site. The Listing 3. HTML code in the Body section
<div id="jquery_jplayer_test1" class
="jp-jplayer"></div>
<div id="jp_container_1" class
="jp-audio">
<div class
="jp-type-single">
<div class
="jp-gui jp-interface">
<ul class
="jp-controls">
<li><a href="javascript:;" class
="jp-play" tabindex="1">play</a></li>
<li><a href="javascript:;" class
="jp-pause" tabindex="1">pause</a></li>
<li><a href="javascript:;" class
="jp-stop" tabindex="1">stop</a></li>
<li><a href="javascript:;" class
="jp-mute" tabindex=
"1" title="mute">mute</a></li>
<li><a href="javascript:;" class
="jp-unmute" tabindex="1" title="unmute">unmute</a></li>
<li><a href="javascript:;" class
="jp-volume-max" tabindex="1" title="max volume">max volume</a></li>
</ul>
<div class
="jp-progress">
<div class
="jp-seek-bar">
<div class
="jp-play-bar"></div>
</div>
</div>
<div class
="jp-volume-bar">
<div class
="jp-volume-bar-value"></div>
</div>
<div class
="jp-time-holder">
<div class
="jp-current-time"></
div>
<div class
="jp-duration"></div>
<ul class
="jp-toggles">
<li><a href="javascript:;" class
="jp-repeat" tabindex="1" title="repeat">repeat</a></li>
<li><a href="javascript:;" class
="jp-repeat-off" tabindex="1" title="repeat off">repeat off</a></li>
</ul>
</div>
</div>
<div class
="jp-title">
<ul>
<li>Test audio</li>
</ul>
</div>
<div class
="jp-no-solution">
<span>Update Required</span>
Introducing jPlayer: jQuery Audio Solutions for your Website
03/2012 (33)
35
basic requirement is to install Firebug in Firefox browser and some knowledge in CSS (Cascading style sheets). It would be easier by following the steps illustrated in the previous section. Changing the design of the player as shown in Figure 6. Below are the steps to change the current design of jPlayer by editing the CSS.
Step 1
Locate the affected style. Using Firebug; changing the background to white needs to be accomplished by editing the jp-interface class background color as shown in Figure 7. The current background color is #EEEEEE
, which should be changed to #FFFFFF
.
Step 2
Open the CSS file jplayer.blue.Monday.css
under blue.Monday
skin. Don’t forget to make a backup of this CSS file before saving any new changes.
Step 3
Find div.jp-interface
class and then change the background color to white (
#FFFFFF
); this is the revised CSS code:
div.jp-interface {
position: relative;
background-color:#ffffff;
width:100%;
}
Step 4
To change the title background color to black and the font color to white, find the affected style using Firebug that is:
div.jp-title, div.jp-playlist {
background-color: #CCCCCC;
border-top: 1px solid #009BE3;
width: 100%;
}
Changing the background color to black and declaring a new CSS property that is a font color set to white:
div.jp-title, div.jp-playlist {
background-color: #000000;
color:#ffffff;
border-top: 1px solid #009BE3;
width: 100%;
}
Step 5
To change the font to Courier New for all elements in the jPlayer; this is the affected style:
Figure 3. Jplayer on the web page
Figure 4. Analyzing jPlayer audio interface using Firebug
Figure 5. Another example of analyzing HTML components
Figure 6. Changing the style of jPlayer
Figure 7. jp-interface class
03/2012 (33)
36
ADOBE FLASH AND JQUERY
div.jp-audio, div.jp-video {
background-color: #EEEEEE;
border: 1px solid #009BE3;
color: #666666;
font-family: Verdana,Arial,sans-serif;
font-size: 1.25em;
line-height: 1.6;
position: relative;
}
Simply change the font-family from Verdana,Arial,sans-
serif
to Courier New
.
Implementing jPlayer in Production Environment
So far the examples above restrict only to the local server (XAMPP localhost). However, once you have a fully working example, you can deploy it to your actual website production server. Below are some performance related tips:
• Put JavaScript at the bottom section of your website template including jQuery (before </body>
) and retain CSS on the <head>
. This is for faster website loading (example HTML code structure): Listing 4.
• Combine your existing CSS with the jPlayer skin CSS, simply copy and skin the entire contents of the skin CSS to your old CSS.
• Make sure all relative paths are correct and updated to work with your website.
• For multiple audio tracks in a single page, you might want to use this variant: http://jplayer.org/latest/
demo-03/. Same concept but using a different skin/
theme.
Listing 4. Suggested HTML code layout for faster website loading
<html>
<head>
<link type="text/css" href="/newtestwebsite/skin/style.css" rel="stylesheet" />
</head>
<body>
<!—jPlayer HTML audio interface
code here -->
<!—Start of jPlayer JavaScripts and jQuery -->
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type="text/javascript" src="/newtestwebsite/js/jquery.jplayer.min.js"></script>
<script type="text/javascript">
$jQueryvariable = jQuery.noConlict();
$jQueryvariable(document).ready(
function
(){
$jQueryvariable("#jquery_jplayer_test1").jPlayer({
ready: function
() {
$jQueryvariable(
this
).jPlayer("setMedia", {
mp3: "http://localhost/newtestwebsite/audio/test.mp3"});},
swfPath: "/newtestwebsite/js/",
supplied
: "mp3"
});
});
</script>
</body>
</html>
EMERSON MANINGO
Emerson is an independent record producer and music publisher. He runs a music production and publishing blog: http://www.audiorecording.me/ where he shares tips and techniques on audio recording, mixing and mastering.
03/2012 (33)
38
LIFECYCLE
H
owever, Flex is currently tied to Adobe proprietary runtimes, namely the Flash Player and Adobe AIR. With the surge of mobile devices, the browser Flash Player appears to be dying a slow death, as it no longer provides the ubiquitous, consistent support that once it once provided as king of the desktop plugins.
However, not all is lost. Adobe is creating tools, such as the touch apps for the Creative Cloud, using Adobe AIR. This is a significant investment in the Flash Platform. Flex has been donated to The Apache Foundation. This allows the community to progress the Flex SDK in a way they have never been able to do so before. Even if nothing changes with Flex, there is going to be a profitable niche for Flex Developers over the next 3-5 years. However, the community has rallied around the Apache Foundation and the initial developers on the Apache project are energetic and inspired. There is talk of creating a new, optimized, Flex compiler. There is talk of decoupling the framework from the proprietary Adobe runtimes to allow people to compile direct to Java, or HTML5, or other languages. There is talk of fixing all those fringe bugs that didn’t affect enough customers for Adobe to be affected. Flex is not dead, yet, and the community is determined to make sure that Flex stays relevant in Enterprise development in the long term. There is still a need, today, for Flex Developers. The key to doing any serious Flex Development is to understand the Flex Component Lifecycle. This article will teach you about the Flex Component Lifecycle.
What is the Flex Component Lifecycle?
The Flex Component Lifecycle is a set of methods and events that Flex uses to create and update UI elements on the Flash display list. When you write your own code, especially custom components, it is beneficial to override the lifecycle methods, or listen to lifecycle events, in order to customize your components. There are two versions of the Flex Component Lifecycle that are relevant to current development. The first is the Halo – or MX – component lifecycle that was introduced in Flex 2. The second is the Spark component lifecycle which was introduced in Flex 4. The two are closely related so understanding one will help you understand the other. First this article will examine the Halo lifecycle, and then it will explain the Spark Lifecycle. I defined the lifecycle as a set of methods and events, so I’m first going to explain those methods and events, and what they are. Then I’ll talk about the creation process of the lifecycle, which occurs during the first initialization of the component. Finally this article will talk about the render process, which is the process used to update a component.
The Halo Lifecycle Methods and Events
There are five methods the Halo Lifecycle. These are methods that are called automatically as part of the component creation or update process.
Understanding
The future of Flex currently remains uncertain. For years Flex has been a fantastic choice for Enterprise Application Development. It provides a mature UI Framework, an interactive debugger, and an ecosystem of community and tools that help you get the job done. What you will learn…
• This article will teach you the intricacies of the Flex Com-
ponent LifeCycle and how you can leverage that information when building your own Flex Components
What you should know…
• Flash Player and Adobe AIR
the Flex Component LifeCycle
Understanding the Flex Component LifeCycle
03/2012 (33)
39
•
createChildren()
: This is a method used to create a component’s children. For example, a ComboBox is created with a TextInput
, a button, and the list that displays in the drop down. • commitProperties()
: This is a method used for coordinating property changes into a single place. This is a catch all method, and its’ use will depend primarily on what properties are changing.
• measure()
: This method is used to determine the ideal height and width of the component. It sets the measuredHeight and measuredWidth properties. A component never sets its own size; it is always the responsibility of a parent to set the size of its children. These are suggestions that the component offers to a parent’s container.
• updateDisplayList()
: This method is used to handle any visual changes to the component. It is primarily used for positioning and sizing a component’s children. Other uses could include handling style changes or dealing with other graphical elements.
All these methods are defined in the UIComponent class; which is the parent for all Flex Components. There are five main events related to the Halo lifecycle:
• preinitialize
: Dispatched after the constructor is run and default properties are set.
• initiliaze
: Dispatched after createChildren()
is run, thus creating all children.
• childAdd
: Dispatched after a child is added to its parent.
• updateComplete
: dispatched every time a component is rendered.
• creationComplete
: Dispatched the first time the component is rendered. When building your own components, it is important to tie into these methods and events. Events are primarily used when dealing with MXML components where you cannot have constructors and have limited control in how the Flex compiler generates the underlying ActionScript. When writing in all ActionScript, I generally stick to overriding methods. The next section will step you through the full creation process and explain how these events and methods work together.
The Halo Lifecycle Creation Process
This section will tell you about how the lifecycle works when a component is created. It will also define your responsibilities as the person writing code, and the responsibilities that the framework will take care of. • First, you must create a new instance of the component:
var myInput :TextInput = new TextInput(); • Then set the default properties on the component:
myInput.text = “Default Text Here”;
This can also be a good place to add event listeners or set styles. • Call the addChild()
method of the parent container with this component as an instance:
this.addChild(myInput);
The first three steps are all things that you must perform manually. If you are writing components and defining children in MXML, then the compiler generates code to do this for you during the translation of MXML into ActionScript. After these three steps, the Flex Framework starts to take over.
• Next the parent property is set on the component
• Then the style settings are computed. • Then the preinitialize event is dispatched. If you want to set properties on an MXML component, this event is probably the best one to listen for.
• Then the createChildren()
method is called. • Everything is invalidated. I’ll talk more about invalidation in the next section on the render process.
• The initialize event is dispatched. At this time, we can safely assume that all the component’s children have been initialized. If you want to access a component’s children when creating an MXML component, then this is probably the best event to listen to.
• The parent container dispatches the childAdd
event, because at this point the child is all set up and ready to progress through the lifecycle process. • The parent container dispatches the initialize event. It is important to remember that the parent container is going through the same lifecycle process as all of its children. It may be doing other things – such as setting up other children – before this component continues on through its’ own lifecycle.
• Flex performs a render cycle on the component. The next section on the render process will discuss this in more details.
• If invalidation occurred during the render process, then the component will be queued up for another render event by the Flex framework. The next section will explain invalidation and rendering.
• After the component if finished rendering, Flex then makes the component visible by setting the visible property to true. • Next the component dispatches the creationComplete event. When creating a lot of MXML components, 03/2012 (33)
40
LIFECYCLE
I’ve seen many people use creationComplete almost as a constructor. In reality a lot happens between the constructor call and the creationComplete event. You should take care with the actions you need to perform and it may be entirely possible that the initialize or preiniitalize are much better choices for your code. This is especially true if your code needs to change something that will cause the component to run through a new render cycle. • Finally, the component dispatches the updateComplete
event.
The Halo Lifecycle Render Process
One important piece of the component lifecycle that I did not cover in the previous section about the creation process is the render process of a component. The render process consists of running the lifecycle methods if needed. There are two elements to this. First, you must tell the Flex Framework that you need to run the methods. The next step is that the methods get queued up to execute during the next render event. How often render event happens relate to the frame rate of the application you’re building. In Flex the default is 24 frames per second, so a render event will occur 24 times each second.
To tell the Flex Framework that one of the lifecycle methods needs to be executed during the next render event, you must use an invalidation method on the component. There are three invalidation methods:
• invalidateProperties()
: This will cause the commit
Properties()
method to execute during the next render event.
• invalidatesize()
: This will cause the measure() method to execute during the next render event.
• invalidateDisplayList()
: This will cause update
DisplayList()
to execute during the next render event.
It is important to remember that you must call the invalidate method to force the lifecycle method to execute during the next render event. Only the methods that need to be executed again will be run. The render event works like this:
• commitProperties()
is called
• measure()
is called. It is worth nothing that measure() is not called if the component has an explicit height and width set. There is no need to spend time calculating the ideal size of a component; when we already have an explicit height and width regardless of what we ask for.
• updateDisplayList()
is called. updateDisplayList()
will size and position the children of the component.
• Finally, updateComplete
is dispatched. updateComplete
is very similar to creationComplete
except it is dispatched every time the component is rendered, whereas creationComplet
e is only dispatched after the first creation process is complete.
Most of the code you write when creating custom components is going to be to make use of the render cycle to change the components based on property changes. Halo Sample
This is a sample to show you how this all works together. This code will create a single component that contains a label and a TextInput
. This is a common task if you have to build out a form. This component will have a property named labelPlacement which will be used to determine whether the label should be to the right of the textInput or to the left. For the sake of this sample, I’ll use a full ActionScript component. The first step is to get the component up on screen. Create a variable for each component: public var label : Label;
public var textInput : TextInput;
If you were creating an MXML Component, the variable name would be the id of the MXML Component. Next, I’ll implement createChildren()
, which will create each component and add it to the stage (Listing 1).
This represents the first three, manual, steps of the Flex Component lifecycle creation process. I create the component, set a property on it, and add it as a child.
Next, we can implement the measure method. The measure method will determine the ideal height and width of the component and set those values to the measuredHeight and measuredWidth of this component. It is up to the parent’s container to determine whether or not to accept these size values, but when creating a component for reuse, you’ll want to implement the measure()
method: Listing 2.
The measuredHeight
will just be the larger height of the label, or the textInput. The measuredWidth will be the sum Listing 1. MX createChildren() method
override
protected
function
createChildren() : void{
super
.createChildren();
label = new
Label();
label.text = 'Enter your Value';
this
.addChild(label);
textInput = new
TextInput();
this
.addChild(textInput);
}
Understanding the Flex Component LifeCycle
03/2012 (33)
41
of the label and the textInput. The component calculates its ideal size based on the ideal sizes of its children. This can get more complicated and take into account styles, such as padding; however I kept it simple for this sample.
The next step is to implement the property for the labelPlacement option. A property on a component could be implemented as a public variable, however in this case I decided to use the get/set implementation of a property. The reason for this is so that the display list can be invalidated when the property is set (Listing 3). The set method also changes a flag to announce that the property has changed. This flag will be used in updateDisplayList()
to determine whether or not to move reposition the label and input.
It is the updateDisplayList()
method’s responsibility to size and position the children: Listing 4.
Listing 2. MX measure() method
override
protected
function
measure() : void{
super
.measure();
this
.measuredHeight = Math.max(
this
.label.getExplicitOrMeasuredHeight(), this
.textInput.getExplicitOrMeasur
edHeight());
this
.measuredWidth = this
.label.getExplicitOrMeasuredWidth() + this
.textInput.getExplicitOrMeasuredWidth();
}
Listing 3. MX labelPlacement property
private
var
_labelPlacement:String = "left";
protected
var
labelPlacementChanged :Boolean = true
;
[Bindable]
public
function
get
labelPlacement():String {
return
this
._labelPlacement;
}
public
function
set
labelPlacement(value:String):void {
this
._labelPlacement = value;
labelPlacementChanged = true
;
this
.invalidateDisplayList();
} Listing 4. MX updateDisplayList() method
override
protected
function
updateDisplayList(unscaledWidth:Number, unscaledHeight:Number) : void{
super
.updateDisplayList(unscaledWidth, unscaledHeight);
this
.label.setActualSize(
this
.label.getExplicitOrMeasuredWidth(), this
.label.getExplicitOrMeasuredHeight());
this
.textInput.setActualSize(
this
.textInput.getExplicitOrMeasuredWidth(), this
.textInput.getExplicitOrMeasu
redHeight());
if
(labelPlacementChanged == true
){
if
(
this
.labelPlacement == 'right'){
this
.label.move(
this
.textInput.width,0);
this
.textInput.move(0, 0);
} else
{
this
.label.move(0
,0);
this
.textInput.move(
this
.label.width, 0);
}
labelPlacementChanged = false
;
}
}
03/2012 (33)
42
LIFECYCLE
This method first sets the size of the label and textInput using the setActualSize
method. It uses the helper function to determine the measuredWidth
and measuredHeight
of the children. Then it checks to see if the labelPlacement
has changed. You’ll notice from above, this value was defaulted to true. If labelPlacement
has changed, then it repositions the children based on the value. One component is moved to position 0,0 and the second is placed right after it.
Create a new component that extends UIComponent
and copy the code, above, into it. Then you can use this simple application to test it out: Listing 5.
The application contains an instance of our component and a button that will toggle the labelPlacement
value. When the button is clicked the labelPlacement property changes its value. This in turn will invalidate the display list which will cause updateDisplayList()
to run on the next render event. When updateDisplayList()
is run, it will check to see if the labelPlacement
value changed and if so reposition the children using their respective move properties. The Spark Lifecycle Methods and Events
The Spark lifecycle was introduced in Flex 4, and it was primarily a response to problems people had with the MX lifecycle. The intent is to make it easier to skin and extend components. Spark is based heavily on the MX Lifecycle; however it provides different hooks into the architecture which make the approach we use for building components very different.
Spark uses a two class model, with one class being used for component classes which would contain business logic, events, component data, and the skin parts, and different view states that make up the component. The second class is the skin class used for defining the look and feel and placement of the class. It defines the positioning of the skin parts. It also determines how view states will be implemented.
Using the standard approach recommended by Adobe, a component class is implemented using ActionScript and it extends SkinnableComponent
. SkinnableComponent
extends UIComponent
, which is the parent of all Halo components. A skin class should extend the SparkSkin component, which extends UIComponent
. Because both the skin and the SkinnableComponent extend UIComponent
, all the methods and events previously discussed apply to building Spark components. In a Skin class, there are no new or special methods to make note of. You’d still use updateDisplayList()
, measure()
, and commitProperties()
as needed. If building MXML Skins with MXML children, there is no need to implement your own createChildren()
. There are a few changes implemented on the Component class side of the equation, though:
Listing 5. MX Sample Application
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:haloSample="com.lextr
as.haloSample.*">
<mx:Script>
<![CDATA[
import
lash.events.MouseEvent;
protected
function
swapLabelPlacement(event:MouseEvent):void
{
if
(sampleComp.labelPlacement == 'right'){
sampleComp.labelPlacement = 'left';
} else
{
sampleComp.labelPlacement = 'right';
}
}
]]>
</mx:Script>
<haloSample:HaloSample id="sampleComp" x="10" y="10"/>
<mx:Button label
="Change Label Placement" click="swapLabelPlacement(event)" x="10" y="50" />
</mx:WindowedApplication>
Understanding the Flex Component LifeCycle
03/2012 (33)
43
•
partAdded()
: The partAdded()
method is called whenever a skin part is created in the skin. It is called from the attachSkin()
method, which in turn called from the createChildren()
method. You’ll use this method for setting default properties or styles on the component, or adding event listeners. • partRemoved()
: The partRemoved()
method is called whenever a skin part is removed from the skin. It is called from the detachSkin()
method, which in turn is called from the createChildren()
method. You’ll use this method primarily for removing event listeners from skin parts.
• getCurrentSkinState()
: The getCurrentSkinState()
method is used to determine which view state the skin will be displaying. It is called from the commitProperties()
method, and is used primarily. The result of this new structure is that you will not normally write code for updateDisplayList()
, measure()
, or createChildren()
inside the component class. That processing is offloaded to the skin class. Instead you’ll use the three methods above in the component class to interact with skin parts, or the skin class.
The methods dispatched all still exist without changed, however a brand new one is added, named elementAdd
. This is dispatched whenever an element is added. Elements are, basically, no children under a different name; and all the children methods, such as addChild() have element counterparts, such as addElement()
. The Spark Lifecycle Creation Process
This section will tell you about how the Spark lifecycle works when a component is created. It will also define your responsibilities as the person writing code, and the responsibilities that the framework will take care of. • First, you must create a new instance of the component:
var myInput :TextInput = new TextInput(); Presumably when dealing with spark components, you’ll be using Spark Components. It is possible to make Halo and Spark components work together, but it is beyond the scope of this presentation.
• Then set the default properties on the component:
myInput.text = “Default Text Here”;
As with the Halo architecture, this can also be a good place to add event listeners or set styles. • Call the addElement()
method of the parent container with this component as an instance:
this.addElement(myInput);
The spark architecture uses elements instead of children, but the two are analogous to each other. I believe this was implemented so that the framework could do special code when adding a element to help sync up things between the component and skin classes. The first three steps are normally things you’d perform manually, however that is not always the case. If you are writing components and defining elements in MXML, then the compiler generates code to do this for you during the translation of MXML into ActionScript. If you are writing a Spark component with both a skin and component class, then the skin class will handle creating the component instance and adding the element, but the component class would set the default properties inside of partAdded()
. After these three steps, the Flex Framework starts to take over.
• Next the parent property is set on the component
• Then the style settings are computed. • Then the preinitialize event is dispatched. If you want to set properties on an MXML component, this event is probably the best one to listen for.
• Then the createChildren()
method is called, which in turn will call attachSkin()
. attachSkin()
will call partAdded()
for each skin part. • Everything is invalidated. The spark invalidation process is almost identical to the halo invalidation process, and I’ll discuss more about this in the next section.
• The initialize event is dispatched. At this time, we can safely assume that all the component’s children have been initialized. If you want to access a component’s children when creating an MXML component, then this is probably the best event to listen to.
• The parent container dispatches the elementAdd
event, because at this point the child is all set up and ready to progress through the lifecycle process. • The parent container dispatches the initialize event. It is important to remember that the parent container is going through the same lifecycle process as all of its children. It may be doing other things – such as setting up other children – before this component continues on through its own lifecycle.
• Flex performs a render cycle on the component. The next section on the render process will discuss this in more details.
• If invalidation occurred during the render process, then the component will be queued up for another render event by the Flex framework. The next section will explain invalidation and rendering.
• After the component if finished rendering, Flex then makes the component visible by setting the visible property to true. 03/2012 (33)
44
LIFECYCLE
Understanding the Flex Component LifeCycle
03/2012 (33)
45
• Next the component dispatches the creationComplete
event. • Finally, the component dispatches the updateComplete
event.
As you can see the approach used by the Spark components lifecycle is very similar to the approach used by the Halo component lifecycle. It is important to understand what is going on under the hood, and will help you understand how to best modify your own components as needed.
The Spark Lifecycle Render Process
The Spark render process is an extension of the Halo render process. The concept is the same. If you want to re-run any of the lifecycle methods on the component, you tell the Framework to do so with an invalidate method. During the next render event, the framework will know to execute the methods.
A Spark component inherits support for invalidateProperties()
, invalidateSize()
, and invalidate
DisplayList()
from the UIComponent
. It also adds a brand new method, invalidateSkinState()
. You can call invalidateSkinState()
whenever you want the skin state to change. Behind the scenes, invalidateSkinState()
will call invalidateProperties()
and set a flag to true. The commitProperties()
method will check the flag, and if it is true it will call getCurrentSkinState()
. The results of the getCurrentSkinState()
are used to change the view state in the skin. The render event works like this:
• commitProperties()
is called, if needed. • If the skin state has been invalidated, then getCurrentSkinState()
is called from within the commitProperties method. It will be used to change the state in the skin.
• measure()
is called. • updateDisplayList()
is called, and that will size and position the children of the component.
• Finally, updateComplete
is dispatched.
Remember that both the skin class and the component class are both UIComponents
and will be going through the lifecycle together. Spark Sample
To demonstrate how you may use the Spark lifecycle, we are going to recreate our MX component as a Spark component. It will be a single component with two children, a textInput and a label. We’ll need to create two classes; a skin class and a component class. The component class will be implemented in ActionScript, and the skin class will be implemented in MXML. Traditionally, it is considered bad practice to implement Listing 6. Spark partAdded() method
override
protected
function
partAdded(partName:String, instance:Object):void { super
.partAdded(partName, instance); if
(instance == textInput) { // do nothing
} if
(instance == label) { label.text = 'Enter your Value';
} } Listing 7. Spark labelPlacement property
private
var
_labelPlacement:String = "left";
[Bindable]
public
function
get
labelPlacement():String {
return
this
._labelPlacement;
}
public
function
set
labelPlacement(value:String):void {
this
._labelPlacement = value;
this
.invalidateSkinState();
}
03/2012 (33)
44
LIFECYCLE
Understanding the Flex Component LifeCycle
03/2012 (33)
45
skin classes in ActionScript, although it is possible and is the recommended approach in mobile development. MXML does make things easier, though.
When you create the new ActionScript class, be sure to extend SkinnableComponent. To handle the label placement, the spark implementation is going to use skin states. To define skin states in the component class, metadata is used:
[SkinState(„textLeft”)]
[SkinState(„textRight”)]
This metadata is placed right before the class definition in the component. Next, the code needs variables for the label and the text input:
[SkinPart(required=”true”)]
public var label : Label;
[SkinPart(required=”true”)]
public var textInput : TextInput;
This is slightly different than our Halo approach because we added metadata that defines these as skin parts. This tells the compiler that these two classes must be implemented inside the skin class.
The component class will not override createChildren()
, so we set the default values in the partAdded()
method: Listing 6.
The partAdded method lets you set default properties, and add event listeners onto the component’s children. In this case the code only needs to set the default Listing 8. Spark getCurrentSkinState() method
override
protected
function
getCurrentSkinState():String {
var
returnState:String = "textLeft";
if
(
this
.labelPlacement == 'right'){
returnState = 'textRight';
}
return
returnState;
}
Listing 9. Spark Sample Application
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/lex/spark" xmlns:mx="library://ns.adobe.com/lex/halo" xmlns:sparkSample="com.lextras.spark
Sample.*">
<fx:Script>
<![CDATA[
import
lash.events.MouseEvent;
protected
function
swapLabelPlacement(event:MouseEvent):void
{
if
(sampleComp.labelPlacement == 'left'){
sampleComp.labelPlacement = 'right';
} else
{
sampleComp.labelPlacement = 'left';
}
}
]]>
</fx:Script>
<sparkSample:SparkSample id="sampleComp" x="10" y="10" skinClass="com.lextras.sparkSample.SparkSampleSkin"/>
<s:Button label="Change Label Placement" click="swapLabelPlacement(event)" x="10" y="50" />
</s:WindowedApplication>
03/2012 (33)
46
LIFECYCLE
property for feature parity with the Halo implementation. Here is the labelPlacement property: Listing 7.
labelPlacement
is implemented in a similar manner. Instead of the set method invalidating the display list, it invalidates the skin state. This will cause the component to rerun commitProperties()
, and getCurrentSkinState() during the next render event. We don’t have to implement anything in commitProperties()
, but the code will need a getCurrentSkinState()
: Listing 8.
The getCurrentSkinState()
method just checks the value of the labelPlacement and returns the relevant state. The two options – textLeft
and textRight
– refer to the skin states defined in metadata.
For the component class, that is all there is to it. It does not handle measurement or placement of the components; as those tasks are offloaded to the skin class. The skin class will extend the SparkSkin class. The first step is to add some HostComponent metadata:
<fx:Metadata>
<![CDATA[ [HostComponent(„com.lextras.sparkSample.SparkSample”)]
]]>
</fx:Metadata> The HostComponent metadata tells the compiler that this class is a skin for this component. Next up, the states need to be defined:
<s:states>
<s:State name=”textLeft” />
<s:State name=”textRight” />
</s:states>
Finally in the skin, you need to place the two skin parts:
<s:Label id=”label” x.textLeft=”0” y=”0” x.textRight=”{textInput.width}”/>
<s:TextInput id=”textInput” x.textLeft=”{label.width}” y=”0”
x.textRight=”0” />
Instead of using updateDisplayList()
to position and size the children they are positioned and sized using the MXML state syntax. The x position is changed depending which state the component is in. Finally, you’ll need a sample application to test this: Listing 9.
This application works very similar to the previous one. It loads the new component we just created, and provides a button to change the label placement property. The component class and skin class are associated using the skin class property.
When the button is clicked, the property will change, which will invalidate the skin state, which will force commitProperties()
to run during the next render event, which will in turn force getCurrentSkinState()
to run. The value returned from getCurrentSkinState()
will be used to change the state on the skin and that will in turn toggle the placement values of the label and textInput. Final Thoughts
This article should give you a strong understanding of both the Spark and Halo Flex Component Lifecycle, and how you can leverage the lifecycle when building your own Flex applications. For more information you should read the formal documentation on creating Advanced Flex Components (http://
livedocs.adobe.com/flex/3/html/help.html?content=asc
omponents_advanced_2.html) and creating Advanced Spark Components (http://help.adobe.com/en_US/flex/
using/WS460ee381960520ad-2811830c121e9107ecb-
7fff.html). Things can get much more complicated than the examples I provided, very quickly, and it is best to make use of the lifecycle methods and events to build and optimize your applications. JEFFRY HOUSER
Jefry Houser is a technical entrepreneur that likes to share cool stuf with other people. Jefry is the Brains behind Flextras, a set of user interface Flex Components that save you time and help you create better Flex applications. He has a Computer Science degree from the days before business met the Internet and has solved a problem or two in his programming career. In 1999, Jefry started DotComIt, a company specializing in Rich Internet Applications with Flex and ColdFusion.
Jefry is an Adobe Community Professional and produces The Flex Show, a podcast with expert interviews and screencast tutorials. He hosts the Flextras Friday Lunch Podcast, a weekly live Q&A session where you can get your programming questions answered and also runs AskTheFlexpert.com where you can get your questions answered privately. Jefry is one of the initial contributors to Apache Flex and has spoken at user groups and conferences all over the US. He is manager of the Online Flex Meetup Group, author of three technical books, over 30 articles, and hundreds of podcasts.
In his spare time Jefry is a musician, old school adventure game a�cionado, recording engineer, and he owns a Wii. Find more about Flextras at http://www.�extras.com, ask Jefry Questions at www.askthe�expert.com, or check out his podcast at http://www.the�exshow.com, or you can read his personal blog at http://www.jefryhouser.com
Документ
Категория
Информатика
Просмотров
572
Размер файла
5 669 Кб
Теги
flash, flex, adobe
1/--страниц
Пожаловаться на содержимое документа