Can’t edit properties in the visual editor in Android Development Tool (ADT) – solution

I was using the visual editor when developing an Android, and suddenly I couldn’t update any properties. I realized that it was because of the latest update to Android 19 (KitKat 4.4). The workaround is simply to pop it back a version when using the editor.

The simplest way to do that is to click on the little green Android in the top-right corner of the visual editor and select version 18 instead of 19.

The little Android icon let's you switch the editor between versions. Version 19 has a bug, when it comes to editing properties

The little Android icon let’s you switch the editor between versions. Version 19 has a bug, when it comes to editing properties.

I guess it’s just a matter of time before this is solved, but until then – here is how to make the editor useful again :-)

 

 


Pick a color outside Photoshop (small tip)

I have used this from time to time, but often tend to do it wrong in the first place. Therefore, this little post about picking colors outside Photoshop for use in eg. web development.

The case

I need to adjust color settings on a menu item in WordPress, and uses the inline editor for the job. I wan’t to have a variation of a color used in the header image.

The solution

I open up Photoshop and have the choice of using the Eyedropper Tool (Shortcut I), or open the Color picker dialog. My main problem is that, because I just opened Photoshop for the problem, I have no document open. Both Eyedropper and color picker wont sample outside, if you don’t have an image open.

When using the Eyedropper, you start by making sure that you can see both Photoshop and the color you want to pick on the screen. Move Photoshop a bit to the side if needed. Then simply click inside the Photoshop document, hold down the mouse and drag it over the color you will like to sample. Release the mouse over the color, and it gets sucked up as a foreground color.

You use the same technique inside the color picker.

Other solutions colors

I know that there is plenty of other ways to achieve this. Wrappers for the OS X color picker and plug-ins for Chrome to do the task, but I tend not to fill my machine with too many of these small single tools, when I have the possibility relatively close at hand (inside Photoshop). My machine is slow enough, as it is :-)

 


What’s up with the browser render engine future?!

I just realized that both Google and Mozilla has new render engines in the melt pot - what is that all about. If you look at the Chromium Blog the are introducing “Blink” as a fork of WebKit. As the say in the blog:

However, Chromium uses a different multi-process architecture than other WebKit-based browsers, and supporting multiple architectures over the years has led to increasing complexity for both the WebKit and Chromium projects. This has slowed down the collective pace of innovation – so today, we are introducing Blink, a new open source rendering engine based on WebKit.

For me it sounds like they a sacrificing the common effort of bringing WebKit forward in the attempt to strengthen it’s own browser and operating system. Chrome is a popular browser, so features implemented in that browser is likely to be experimented with on a lot of pages.

What bothers me here, is that it shows me a history repeating – “the lung of web tech” as I call it – inhaling and exhaling. WebKit and WebGL is both promising pointers towards a general way to handle the web pages of tomorrow. IE11 seems to support WebGL - that is an exhale. As for now, a lot of browsers is supporting WebKit, and more is coming.

This latest move from Google is symptomatic for companies reaching a certain level of market dominance – it happened to Apple, and it happened to Microsoft. But my previous experience tells me that this isn’t bringing anything good with it, in the long run. Internet Explorer is moving towards standards now, after years of vbscript and IE-specific features. Apple is also fighting a loosing battle with its “iWay or the Highway” mentality.

I believe Google’s initial theory is: “If most people use my technology, I could alter the rules of the game, and people will start to follow me because they feel left out with competing technologies … we are leading the people.”

This move takes the browser (and the web designers) as hostages again. As Google states

This was not an easy decision. We know that the introduction of a new rendering engine can have significant implications for the web. Nevertheless, we believe that having multiple rendering engines—similar to having multiple browsers—will spur innovation and over time improve the health of the entire open web ecosystem.

Yeah, right – bullocks. They think they are going to win this one (and maybe they will). Here they say that the browser’s rendering engine is inhaling again, spreading the possible combinations. Google sees a lot of momentum with their Chrome Experiments, and commercial adoptions in experiments like Find Your Way To OZ where there was a solid focus on using Chrome to be sure of the full experience, is possibly motivating them to push forward.

-prefixes is for everyone else

Another odd move is to deal with the tradition of vendor prefixes meaning that they will use the default naming instead even though the property isn’t final. I don’t like prefixes, but see them sort of necessary for the final CSS-property to be left untouched until ratified. There is a best practice already among designers when writing CSS, that lists all the vendor specific prefixes and ends with the standard definition. That way, the browser can use the prefix and eventually overwrite the property with the standard if supported. Now Google is breaking with the other browsers and make their own rules. I believe, they hope to achieve people seeing them as the” renderer of the real open standard”, and other browsers (including WebKit browsers) to be sort of patching their way with prefixes.

This will try to trick developers to think: “Hey Chrome is everywhere, and we don’t need prefixes anymore. If it works here, it’s OK with me.” sort of like a Chrome Experiment out of the lab. Other browsers may see prefixes disappear in code, and is forced to render the unprefixed version. And they have to do it like Google does or it will break the layout – this is the box model all over again, arrrrgh!

Mozilla is also on the loose

To add to the pain, Mozilla is also making an engine called Servo. Teaming up with Samsung, they are making what they call a “Next Generation Browser Engine” … what the hell is that? In a blog post, they talk about a C-like programming language called Rust, probably to compete with JavaScript on mobile devices. I believe that partnering with Samsung is going to give it some sort of impact on mobile devices in the future, if you believe that Samsung at some point will soften up on their attitude towards Firefox OS or alter future Tizen devices.

We may be in for a deep breath

When Flash left the webdesign desk, HTML5 (and the browsers) promised that they where up for the task. Now, leaving them alone for a few month, everyone seems to go in each direction. This is not a step forward – this is each browser taking a step in the direction that serves them best … hello “Browser War 2″.


Optimization tips for using && (AND) and || (OR) in evaluations

Reading an old blogpost from grauw.nl made me learn some small new, but very important, details when it comes to evaluating conditions or retrieving propery values in JavaScript or ActionScript. This optimization struck me so hard, that I am confident that I will never forget it again – when you have experimented with it, you probably won’t either :-)

The issue is that the operators && and || not evaluate both side, if the left side is false.

Take for example this code:

var testArr:Array = new Array();
var i:uint;
var max:uint = 10000;
var begin:uint;
var end:uint;

testArr = new Array();
begin = new Date().time;

for (i = 0; i < max; i++)
{
testArr.push(Math.random());
}
i = 0;

while (testArr.indexOf(32) || i < max)
{
if (i > max)
{
trace("BAIL OUT!");
break;
}
i++;
}

end = new Date().time;
trace("Begin: " + (begin));
trace("End: " + (end));
trace("Difference: " + (end-begin));
I have made a random array of 10000 numbers to look in – I do that in the while-loop. I look for a number that I know doesn’t exist (32) and check whether that, or the other condition evaluates positive. Inside the loop I test if i is greater than 10000 and increment it. When it finally reach max, it breaks out of the loop and write the difference in milliseconds.
When you run that, you will get a number that can vary – every time you do it on your own machine, and of course if you try on different machines. On my – relatively old MacBook Pro – it was around 980 milliseconds. Now to the fun part. Try to switch the two evaluations around, so it states:
while (i < max || testArr.indexOf(32))
Now, when you run it again you get something quite lower. I got 2!! (two) – this means that the first solution was around 500 times slower. “So, this is 500 times slower,” you may add, but this is a variable factor. I tried to alter the number in the while-loop to 100.000 and kept the array at 10.000. That results in around 9600 milliseconds but the other way around it was still 2 milli seconds.
This happens because the OR operator skips the right side if the left is enough to answer the evaluation, and that makes a difference if there is a difference in the complexity of the two evaluations. How many times haven’t you checked a boolean value to se if a flag is set, and if not set, traversed the display list to see if the object is there … well, maybe you haven’t but this info would be crucial if you did. If it is done once, no harm, but in a game loop it will be a show stopper.
Now, that you know the trick you can apply the same – or rather opposite with &&. Here, you will stop if the first one is false, because the condition never can be true if one of them is false.

Are we ready or what?

Another trick I saw at the site was the abillity to initialize a variable, if it wasn’t set. I have often these undefined array’s and this trick deals with that. This shouldn’t be a hack in order to work around good coding practise, but I think that there are plenty situation where this is a sleek solution. Tak this code for example:
var array:Array;
trace(array);
This of course gives you a null in your face, but you could do something like this:
var array:Array ;
trace(array ||= (array = [123]));
Here I use the “logical OR assignment” (||=) to evaluate both expressions and assigns it to the left side. Here, it is important to get rid of a widespread mistake – that the result of the logical operation is a boolean value. In the code above it will trace “123″ because the first is false, but will be assigned the expression to the right. I have placed parentheses around the right expression so it is the result of the statement that is evaluated.
The fine part here is, that if the left part evaluates positive, you will never get to the right part of the statement – that is what I realized in the first tip :-) You can try to assign a value to the array before the trace to test it. You can use it in conditions and you can use it to move on with a default property. Something like this:
var myname:String;
trace((myname || "ockley").length);
This will trace “6″ because the string isn’t defined. If you define it, that will be used.
I am sure that this will go straight to the tool belt, so get out and optimize your game loops :-)

Twitter Bootstrap for beginners

When producing web designs, you are often set for a specific grid to get some structure on the content. Sometimes it is because of restrictions in the brief and a relation to an underlying CMS. Other times it is just because it helps to get some rules to obey.

The nature of HTML has previously been table based. Beside, all the bad things said about tables  in design they was somehow well suited for a grid based thought.  Thinking in tables (and nested tables) made a natural hierarchy in the way to organize content.

Twitter Bootstrap is a way to get into the grid thoughts again. It is a system based on a number of columns that you can span over. You start by creating a row (just like a table row) and inside them you define a set of elements with a span (just like table cells and col-span).

The system is very flexible, and you get a vast amount of styling for free when using it, so whether it’s for prototyping or layout purpose: If you develop websites, you ow yourself to at least try making a site or two with Bootstrap or similar grid based framework.

I have written a starter tutorial to get you going. It covers the basics of presenting the framework. How to set it up, and how to convert a relative simple layout into a fully working HTML document.

Go to http://www.hjaelpmignu.dk/content/getting-twitter-bootstrap-and-running and give it your best shot :-)

Remember to ask questions in the forum under HTML and CSS (http://www.hjaelpmignu.dk/forum/16), in case of problems.


“RAM Preview needs 2 or more frames to playback” in After Effects

A lot of people have seen this message from time to time when using After Effects CS6. This was primarily because of a more strict way of deciding whether or not to swap memory to the hard drive during RAM Previews. Mac OS where holding back on previously used memory, so when After Effects CS6 asked for more, it wen’t something like: “Nah, I don’t have anything totally unused RAM for you. I have this, previously used and I don’t know if I’m gonna use it later down the road, so i rather not give it to you!” After Effects CS6 then said “OK,” and tried to manage without.

That ended up in situations, where you only had a few 100 mega bytes, and the program continually popped up an alert saying something like “RAM Preview needs 2 or more frames to playback” – a fair request actually.

Today, Adobe has released an update to version 11.0.2, that addresses most of these problems. You have a new preference, enabling you to tweak this setting. It is located under Memory & Multiprocessing and is called “Reduce Cache size, when system is low on memory (this will shorten RAM preview)“. By default the “strict mode” is disabled, so After Effects CS6, should behave more like it did in CS5.5 when it comes to accessing the system memory, and cache it to disc more often instead of just accepting the OS answer.

Memory setting

The setting is disabled by default, so you actually don’t have to do anything in order to make it work

Anyway, fire up the updater and get the latest version. You can read more about the release at http://blogs.adobe.com/toddkopriva/2012/10/after-effects-cs6-11-0-2-update-bug-fixes-and-added-gpus-for-ray-traced-3d-renderer.html

 


Using Adobe Web Fonts with Adobe Edge Animate

I am personally very excited about the new Adobe Edge Animate, because of the easy learning curve, ans vast possibilities of making animation based on CSS and JavaScript. In a way, it’s like jQuery on wheels – but don’t stop there. It can do a lot more.

A great feature is the possibility to add Web Fonts. Some time, in a near future, you will be able to just select them inside Adobe Animate, but until then it is actually quite easy to implement them in your layout. I will talk about two repositories for fonts called Google Web Fonts and Adobe Web Fonts. As it is now, I found that Google’s version is actually working better with Edge Animate, than Adobes, but I’ll get to that and how to overcome it in a minute. First try this:

1. Get the document ready.

Open Adobe Edge Animate. You you don’t have it. It’s is freely available in the free tier of Creative Cloud. So go there and sign in to get access to the tools. Click on Create New in the left side of the document.

 2. Get the link to the Web Font.

If you use Google you can get the link by going to http://www.google.com/webfonts and select among the listed fonts. When you find the font you like – click on the Quick-use link in the bottom of the preview window. Under section 3 called “Add this code to your website” you copy the link-tag. It should look something like:

<link href='http://fonts.googleapis.com/css?family=Molle:400italic' rel='stylesheet' type='text/css'>

If you use Adobe Web Fonts you can get the link by going to http://html.adobe.com/edge/webfonts/ and select among the fonts in the list under “Preview Edge Web Fonts”. Copy the script tag below – it should look something like this:

<script src="http://use.edgefonts.net/marck-script.js"></script>

This will link to the font and it’s default subset (bold, italic etc.) You you want to fine grain your selection to optimize download speed, you can read more about how to tweak the link at http://www.edgefonts.com/.

 3. Add the Web Font to the Font List

In the Library panel, click the plus icon in the top-right part of the Fonts-subsection. You will see a dialog box, that asks you for information about the font. Here you can paste in the copied tag in the Embed Code area, and the name of your font in the Font Fallback List field. You can (and should) also enter some fallback fonts, if the web font couldn’t be accessed. Enter manually (comma separated) or choose from a list, by clicking on the plus icon to the right. Remember to add single quotes around fonts that have blank space in their name.

Now, you have access to the font in your font list, and can select it in the font list, when entering text. There is a little catch, though with the Adobe version. Somehow it doesn’t work right out of the box. I guess it has something to do with the fact that it is based on a script tag, and Googles approach is based on a link tag. The script tag isn’t executed inside the program “live”, while a link to a resources is called when needed, but I’m not sure. When Edge Web Fonts is integrated into the program, this will not be an issue anymore, but until then you should manually open the HTML document and paste in the link just below the title-tag.

 


Is Edge Tools & Services the long awaited stepping stone for interactive designers?

Since it was clear that the Flash Platform has taken on new challenges in the gaming area, interactive designers have looked around with flickering eyes after visual tools that support the need to comply with web standards and deliver to desktop as well as devices.

It has been technically possible to use JavaScript to animate DOM element for years, and with frameworks like jQuery there is a lot of effort spend on making it “designer friendly”. However, designers don’t want to code what they are trying to express. They are seeing the canvas as their viewport for communication – add information about how elements are introduced, laid out and moved around on the stage. If a page have a button, that only can be clicked if a criteria is met, the designer will like to be able to show how the button looks in different stages and how a tooltip should animate over it, if the criteria isn’t met – they don’t want to dwell on the criteria itself. Something like: “I want it to look like this, and when the user clicks the computer goes bum-tji-bum-tji-bum, and then it show up like this, or goes to this page depending on the result”. Frankly, that’s why a lot of designers love Flash.

Now, most traditional webpages is (and should) be done in HTML. The new capabilities in the language, makes it possible to do transitions and animations directly in the HTML document. Flash is placed on earth partly to help HTML with the stuff it can’t do, so its time with banners an regular to semi-advanced webpages are over. A lot of designers, that relied on Adobe Flash Professional to create websites, where quite anxious about that development – they have seen the Flash Platform as a solid rock to stand on, but different advances in the technology was pushing them closer and closer to the edge. HTML can do a lot more know that it could a few years back, and Adobe Flash can do a lot more now that it could a few years back, too. Doing animated, highly interactive websites has become simpler with present tools at hand.

Talking about tools

I was recently to a one-day event in London called “Create The Web”. Here, Adobe demonstrated how they will help designers express themselves in the world of web standards … how “standard” web standards may turn out to be. The sessions primarily revolved around the information presented at http://html.adobe.com And after that day I must say that I am pretty confident that their will be a new stepping stone to stand on for new designers as well as previous designers using Flash that feels they are balancing on the edge of the cliff. Speaking of “edge”, that is actually what the set of tools and services is called. (pun intended)

Edge Tools & Services

This initiative is Adobe’s serious effort to communicate that they believe in web standards. Frankly, the always have but here they take serious steps to provide tools for designers and developers, so they can take advantage of the modern browsers. The Edge Tools & Services are based on the following dogmas:

  • Optimized for creating mobile-ready web content and apps
  • Focused on a specific task
  • Improve productivity without hiding the underlying web technologies

The tools in this “suite” is currently (as seen on http://html.adobe.com)

  • Edge Animate
  • Edge Reflow
  • Edge Code
  • Edge Inspect
  • Edge Web Fonts
  • TypeKit
  • PhoneGap Build

A lot of the tools have been available as public previews, and some of them are based on open source projects. As a cadeau to that, and the great user feedback that have improved the tools, they are actually being given away for free in Creative Cloud. When logging into http://creative.adobe.com, there is a paid tier and a free tier. These tools are available in the free tier, so there is no excuse not to try them out.

I will dive into details on some of the products in separate posts, but a quick introduction to them would sound something like this:

Edge Animate

The most feature rich of the tools (for now, at least) is Edge Animate. It was previously known by the codename “Edge” and that name was then adapted by the suite as a whole. Some of us, need to readapt, and I still tend to call it “Edge” instead of “Edge Animate” or simply “Adobe Animate” … but I will get it – eventually :-)

This tool is used when designing animations, transitions and interactivity. You can open up HTML pages and interact directly with the DOM elements or draw new ones from scratch. There is a timeline as you know it from Adobe After Effects or Adobe Flash Professional, but where After Effects are rendering a video and Flash is compiling a flash movie, you will here be given a standard compliant animation based on JavaScript or CSS with some help from jQuery. Everything you do in Edge Animate will directly be translated into HTML and JavaScript, and the tool makes sure that differences in browsers are taken into account (as much as possible).

Edge Reflow

This tool isn’t available yet, but is sort of a teaser of what to expect in the near future. They are saying “public preview before Christmas, but rather sooner than later”, so we’ll just have to wait. This is a visual tool trying to overcome some of the obstacles when making responsive web design. Adobe Dreamweaver has plenty of help on that front, but a lot of them are based on the designers ability to code CSS, and remember – some rather won’t. In Edge Reflow you are drawing div-tags or other elements, scale the viewport, and then relocate the elements accordingly. All the CSS-code and media Queries are then generated in the back, leaving you with a final layout that scales and repositioning itself when the browser width changes. The tool itself is made with HTML and JavaScript, so if the layout can make it there, it’ll make it anywhere. (Sing with me) It’s up to you [designers name, desiiiiigners name]

Edge Code

This tool isn’t yet feature complete, and probably not something you would use for your everyday coding yet. Nevertheless, it is released in a public preview and under heavy development, with regular updates on a 2-3 weeks basis. It is based on the open source project called “Brackets” initially started by Adobe, in order to make an open, effective and lightweight editor for JavaScript, HTML and CSS. The editor itself is also developed in HTML, CSS and JavaScript (how meta is that!) and witness the underlying power there actually is in the scripting language when done properly. One of the greatest features is it’s ability to quick edit CSS or color properties. Standing on a tag, you are unfolding an area, with the tags CSS right beneath it. Over a color, you unfold a color-picker. It still needs some fundamental functionality, but the tool looks really promising.

Edge Inspect

Previously lived under the codename “Adobe Shadow”. While I think there is a bit more “double O” in the old code name, I think that Adobe Inspect represents the tool very well. With Inspect, you can connect a range of devices to your computer if they are in the same wireless network, and remotely control them. You can take pictures, refresh all of them and remotely inspect the HTML elements on the device. The free version allows you to connect one device at a time, but that is probably enough for a lot of designers in the beginning. Just seeing your webpage on a real device instantly, while designing it on the computer is a massive production improvement compared to previous workflows.

Edge Web Fonts

Great typography is not difficult to implement on web pages anymore – no need to insert images or use complex Flash substitutions. A joined effort from Adobe and Google has made over 500 free fonts available to web designers, and with Edge Web Fonts, it seems pretty easy to implement. You are now given a unique URL for each font family, and when including that in your HTML document the font will be available for use in the document. Adobe Web Fonts is also build into the other tools, so all the font’s are available as WYSIWYG there. The whole system is served by Typekit that Adobe also uses to serve all their non-free typefaces. That makes the whole ecosystem pretty robust and reliable.

PhoneGap Build

This service is sort of sneaking in (along with Typekit) because it actually lives pretty well on its own as the PhoneGap framework. The service is relevant in the “Edge-suite” though, because it also adhere to the fundamental dogma. Here you can take a HTML project – or PhoneGap enhanced project, and compile it into a native application. This is taking your HTML-skills in making WebApps into the world of App stores and markets on the different devices. The free version allows you to make unlimited open projects and a single private project. The paid version makes 25 private projects available. A lot of Apps on the device is actually done well by HTML, CSS and JavaScript alone, so you don’t necessarily have to learn a “native language” to make an App.

Final thoughts

As a Flash developer myself, I actually think that this grouped effort from Adobe, is a solid comeback from their clumsy way of communicating what they have planned for the Flash Platform. If the “Create The Web” tour has been on the road before or in conjunction with a “Flash and the New Frontiers” tour, I am sure it would have made a massive impression on the users. We can’t undo that but here we have a set of tools, that I am sure the designers pretty quickly will be comfortable with and, as they mature, is going to be a natural extension to an interactive designers tool belt. Now, go to http://html.adobe.com/edge/ to learn more about the tools.

 


Gradient mesh with a hole in Adobe Illustrator (tutorial)

Just a quick note, that I posted a new short tutorial on how to make a gradient mesh with a hole in.

Nothing fancy, but nice to know. See http://www.hjaelpmignu.dk/content/punching-holes-gradient-mesh for more info


Tile based games using the Starling framework

In my quest for making my sons game, I managed to get Starling up and running, and create a performance test, that showed me some pretty intense performance – that bode well for my continuous success in the making of a game.

I have started to dive into tiles, and how to make tile based games. Some of the most relevant info on that topic was found in an old book called “Flash MX 2004 game design demystified”. As the title implies, it is not quite current, but the theories behind tiles still works a long way.

Continuing on the seas of The Web, I stumbled onto Tonypa and his section about Tile Based Games (via Terry Paton - thanks). The problem with that info was, that it was just as old as my book reference. Therefor I decided to send him a mail, and ask for permission to update his tutorials to a more current ActionScript 3.0/Flash Builder/Starling version.

I will have to do a lot of learning, while porting this to AS3, and there may be introduced several errors and rewrites along the way, but I take that as a part of the proces. I will hopefully end up with a solid foundation of tutorial to use in my own game, and the continuing work on that project.

Feel free to comment, ask questions about unclear parts, and come with suggestions to improvements – I’m almost guaranteed not to get this right at the first shot :-)

Take a look at Tile Based Games in the top menu.


Testing Starling performance

Get the work files and final example here

This post is just a quick solution to test the performance of Starling. It build upon the previous one called Getting hooked up with Starling, and just adds a lot of the mice and make them react to the mouse.

The process here is simply:

  1. Initialize Starling
  2. Wait for the stage to be ready
  3. Insert a whole lot of images
  4. Make each image react to their position in relation to the mouse.
  5. See, how it goes

Initializing starling and waiting for the stage, was explained in the other tutorial, so I will discuss the other topics here. This is an example of what you will be doing.

Insert more than one image

When dealing with images, it is generally a good idea to define a custom class for them. This way it is easier to manipulate and retain individual information in the individual images. In this example you should go ahead and add a custom class. You can use the Start project to follow along or even better, complete the previous tutorial and use those files :-)

Right click on the default package and select New > ActionScript Class

 

Call the Class CustomImage and make the Image class (starling.display.Image). Declare two public variables called destX and destY as numbers, so the code should look like this:

package
{
  import starling.display.Image;
  import starling.textures.Texture;

  public class CustomImage extends Image
  {
 public var destX:Number;
 public var destY:Number;
    public function CustomImage(texture:Texture)
    {
      super(texture);
    }
  }
}

These variables are used to store the destination coordinates for each image. They are supposed to move to a random new location from time to time, and these variables are taking care of the values.

Open the StarlStage.as file and declare the following variables:

[Embed(source="assets/mouse.png")]
private var mouseBMP:Class;

private const NUM_MICE:uint = 500;
private var miceVector:Vector.<Image> = new Vector.<Image>(NUM_MICE, true);

private var mouseCoord:Point = new Point(); 
private var maxDist:Number;

First, you create a constant that holds the number of mice you want in the test. Change that to suit your need. Then a vector object is created. The first argument is the number of elements in the vector, and the second argument (set to true) is creating a fixed vector, so it isn’t allowed to change size during runtime. These arguments are optional, and only set for performance reasons.

After that a Point object is created to hold the position of the mouse, and a value to hold the maximum distance there can be between two points on the stage (a diagonal line).

Change the onAdded() method, so it looks like this:

private function onAdded(event:Event):void
  {
    q = new Quad(800, 600, 0x880000);
    addChild(q);
    maxDist = Math.sqrt((stage.stageWidth * stage.stageWidth) + (stage.stageHeight * stage.stageHeight));

    var texture:Texture = Texture.fromBitmap(new mouseBMP());

    for(var i:int = 0; i < NUM_MICE; i++)
    {
      var image:CustomImage = new CustomImage(texture);
      image.pivotX = image.width >> 1;
      image.pivotY = image.height >> 1;
      image.alpha = Math.random();
      image.destX = Math.random()*stage.stageWidth;
      image.destY = Math.random()*stage.stageHeight;
      image.x = Math.random()*stage.stageWidth;
      image.y = Math.random()*stage.stageHeight;
      image.rotation = deg2rad(Math.random()*360);

      addChild(image);
      miceVector[i] = image;
    }
}

The first two lines is the colored background, made from the Quad. Next line uses the Pythagorean Theorem to calculate the diagonal based on the width and height of the stage. The value is stored in maxDist for later use.

Then the texture is created, exactly like in the previous tutorial, and a loop is set up to generate the amount of mice, that is declared in NUM_MICE.

Fir you declare a variable called image as the type CustomImage, which is the class you made earlier. pivotX and pivotY is a nice set of properties that Starlings display objects have. They move the origin point inside the object to a new position. In Flash, you are normally moving the object in a negative direction in order to be able to rotate or scale around the middle of the object; With Starling you can just set the pivot point to be any coordinate in the image. The bit shift to the right (>>) is just a fancy way of divide by 2. I could have entered something like image.height/2 but I am told that the performance of this bit shift is a bit faster, so I-ll stick with that :-)

The rest sets a lot of random numbers in the objects properties (alpha, x, y and rotation). It also sets the public variables inside the CustomImage class, with new random coordinates.

degrees to radian conversion

Pay attention to the rotation property. Starling uses radians, when working with rotation. Fortunately, you can use the little helper deg2rad() in Starling. Just remember to import starling.utils.deg2rad 

Finally the image is added to the stage, and places inside the vector, so it can be referenced later on.

Test the project to see a lot of mice with different position, rotation and transparency on a dark red background.

Getting the coordinates from the mouse

The Starling framework do not work with mouse events, but it has (like Flash) an event called TouchEvent, that takes care of most of your needs. Add a listener called onTouch() and update the constructor so it looks like this:

public function StarlStage()
{
  addEventListener(Event.ADDED_TO_STAGE, onAdded);
  addEventListener(TouchEvent.TOUCH, onTouch);
}

private function onTouch(event:TouchEvent):void
{
  var touch:Touch = event.getTouch(stage);
  mouseCoord = touch.getLocation(stage);
}

In the constructor you listen for the TouchEvent (remember to import the Starling version), and set it to call the onTouch method. A touch event can contain multiple touch, so there is a method called getTouch() and one called getTouches(). Here we just take one single touch from stage, and keep it in the object called called touch. These Touch objects holds all relevant information regarding the specific place it points to. Here you use the method getLocation to retrieve a Point objects, that is store in your own mouseCoord variable for later use.

Make the mice move

Not it’s time to move the mice. Start by registering a listener last in the onAdded() method, so the last line should look like this:

private function onAdded(event:Event):void
{
  ...
  //previous code here
  ...
  stage.addEventListener(Event.ENTER_FRAME, draw);
}

Again, remeber to import Starlings own Event class (starling.events.event), instead of the one you are used to in Flash. Create a method called draw, and enter the following:

private function draw(event:Event):void
{
  var distance:Number;
  var tmpImg:CustomImage;
  var ratio:Number;

  for (var i:int = 0; i < NUM_MICE; i++)
  {
    tmpImg = miceVector[i] as CustomImage;
    tmpImg.x -= (tmpImg.x - tmpImg.destX) * .01;
    tmpImg.y -= (tmpImg.y - tmpImg.destY) * .01;
    if(Math.abs(tmpImg.x - tmpImg.destX) < 1 && Math.abs(tmpImg.y - tmpImg.destY) < 1)
    {
      tmpImg.destX = Math.random()*stage.stageWidth;
      tmpImg.destY = Math.random()*stage.stageHeight;
    }

    distance = Point.distance(mouseCoord, new Point(tmpImg.x, tmpImg.y));

    ratio = distance/maxDist
    tmpImg.rotation += 0.2 * ratio;
    tmpImg.scaleX = tmpImg.scaleY = 1 - ratio;
  }
}

That’s a lot, so let’s take it in small chunks. First you create two variables, one to hold the distance between the mouse and the current image. The other is just a temporary instance of the image made outside the loop, so you don’t fill up the memory with hundreds of local instances. This way, you are using the same object over and over again.

Then a loop is set up, that iterates through your pool of images, contained in the vector called miceVector. Inside the loop you first transfer a reference to the current objects to tmpImg. From now on, you can avoid the time consuming process it is for Flash to look up an object in arrays and vectors – it is also a bit easier to read.

tmpImg.x -= (tmpImg.x - tmpImg.destX) * .01;
tmpImg.y -= (tmpImg.y - tmpImg.destY) * .01;

Then each image is moved a bit closer to it’s destination. This is done, by taking the distance between the two points (current and destination) and multiply it with a low number – in this case .01. If you enter a higher value, they will travel faster, but since it is redrawn 60 times per second (if it can), you are working with very low numbers here. In more complex solutions, I would introduce dedicated tween classes, but this should do it, for a quick test.

if(Math.abs(tmpImg.x - tmpImg.destX) < 1 && Math.abs(tmpImg.y - tmpImg.destY) < 1)
{
  tmpImg.destX = Math.random()*stage.stageWidth;
  tmpImg.destY = Math.random()*stage.stageHeight;
}

Then you test if the distance between current position and destination is below 1. If it is, a new destination point is set in the images destX and destY. This is done, because, you would never reach the exact same values when multiplying with .01.

distance = Point.distance(mouseCoord, new Point(tmpImg.x, tmpImg.y));

This one can be a bit tricky. It uses a stetic method in the Point class called distance, to get the distance between two point objects. it actually just does the same as the calculation of maxDist earlier on. Since tmpImage doesn’t have a Point as a property, you create one. I am not sure, that this is very performance effective, but I included it here, so you can see both methods in practice.

ratio = distance/maxDist
tmpImg.rotation += 0.5 * ratio;
tmpImg.scaleX = tmpImg.scaleY = 1 - ratio;

the last lines takes care of scaling and rotation of the objects. First a ratio between the distance variable and the maximum distance is found. This results in a value between 0 and 1. This value is the multiplied with 0.5 to get a number between 0 and 0.5 for the rotation. Remember, that rotation in Starling is in radians, so 0.5 is actually quite a lot :-)

The it scales both x and y on the image based on the same ratio and the value 1 (which mean 100%). The ratio is subtracted from 1. This makes the images smaller the further away from the mouse it is.

Take it for a spin

Try running the application. Fiddle with the values, to achieve other effect. Try to adjust NUM_MICE, to test the performance. There is certainly room for improvements, but I am pretty impressed with the performance. My machine is taking 1000 objects without blinking – I can’t recall doing that earlier, while using square root, and having semi-transparent images rotating and moving on top of each other- Starling is fun :-)


Getting hooked up with Starling

Files with a working solution is available here

One of the more promising aspects of the new Flash Player and AIR runtime is the Stage3D object. The obvious and breathtaking improvements is seen in experiments like http://www.unrealengine.com/flash/ where you are moving around in a 3D landscape in realtime, with reflections, light and all the Unreal Engine can throw at you. Another great example is Unity, that exports to the Flash Player. Take a look at the video on http://blogs.unity3d.com/2011/09/01/unity-and-flash-a-sneak-peek/ to see how it raises the bar for what is possible in a browser.

My project with Mouse Wood calls for a simpler solution, though. Fortunately Stage3D is not only for 3D content. There are several initiatives like ND2D, M2D and Citrus Engine, that I find very interesting because of it’s buit-in level editor and side scrolling ability (and I am in desperate need of inside knowledge on how to make side scrolling games). My love falls on the Starling Framework. First of all, it looks simple and straight forward – and have a lot of similarities to the traditional display list approach. Secondly, I hear it mentioned quite a few places, performing some nice results on both desktop as well as mobile. I may look into the other as well, but this article dives into Starling.

Get the packages

Starling originates from the gaming framework called Sparrow, that targets iOS game development. Both frameworks resides at the site http://gamua.com/ and provides easy access to packages and tutorials. You get access to the framework by doing the following:

  1. Go to http://gamua.com/starling/download/ and hit the Download Starling button (currently 1.0)
  2. Unzip the package

Inside you will find a few folders and a read me-, change log- and license file.

Folders in Starling

There is a folder with some samples, and a folder to Flex Unit Tests. I will not discuss these files, but solely focus on the starling folder. Inside the Starling folder you will see a few folders. You are interested in the bin folder and the src folder – actually, you are only interested in the bin folder. Looking into the source folder, you will find all the ActionScript classes, that makes up the framework. The same files, are the one compiled into one handy swc-file (ShockWave Component, Small Web Component – or something like that. Nobody seems to know .. or care) located in the bin folder for you to keep.

Copy the starling.swc from the bin folder to where you keep you class-files. I have made a folder in my dropbox folder, so everytime I update a package on one of my machines, i automatically gets updated on the other machines.

Link to the framework

In my experiments I will primarily use Flash Builder for the development. So fire up Flash Builder and:

1. Create a new ActionScript project (File > New > ActionScript Project)
2. Call it StarlingTest (or similar) as the project name.
3. Click Next to go to the Build Paths.


4. In the dialog, click on the Add SWC button. Navigate to the startling.swc and add that to the list.
5. Click on finish, to create the project.

NB: If you are following along in Flash Professional, you can add the swc’s so they are always available in the programs preferences (under ActionScript settings) or per project (in it’s publish settings)

Making a stage3D object

With the project in place. You will now make a Stage3D object. The Stage3D object i placed in the Display List just like any other display object. In fact it is placed behind the stage. You can have many stage3D object on top of each other, but they all have to be behind the normal stage and it’s contained objects – so no stage3D floating around a traditional animation in Flash, only the other way around.

With StarlingTest.as open – enter the following code. The highlighted areas is where you should enter text, if you follow along:

package
{
  import flash.display.Sprite;
  import starling.core.Starling;

  [SWF(frameRate="60", width="800", height="600", backgroundColor="0xFFFFFF")]
  public class StarlingTest extends Sprite
  {
    private var starl:Starling;

    public function StarlingTest()
    {
      starl = new Starling(StarlStage, stage);
 starl.start();
    }
  }
}

First is the SWF-meta tag, that allows you to set specific parameters that is used at compile time. This one simply sets the frame rate to 60fps, width and hight and finally a white background.

Then you declare an object of the type Starling. This object is the main motor. It translates everything that goes into it into the native Stage3D framework underneath. Inside the constructor, it is initialized. The signature has a lot of parameters, but in general i believe you will use the first two in most cases. The first one, is the name of the Class that is supposed to be inserted on stage and the other one is just a reference to the stage object. This example references the StarlStage class that isn’t defined yet, so you will get an error – don’t worry. You will create it in a moment.

The Starling object itself has a few methods and properties, that can be used to control the behaviour of the object. The one you will use everytime is the start() method, that starts up the engines.

Create the Starling sprite class

Right click in the default package and choose New > ActionScript Class. In the dialog box enter “StarlStage” in the name field (the same name you refered to in the main class). In the input field called Superclass, begin typing the word “sprite” to see the code completion kick in. Select the option called Sprite – starling.display to make sure that the sprite inherits from the right superclass.

Showing a background with the Quad class

One of the more interesting classes I found in the Starling framework is the Quad. Maybe I just haven’t looked around, but I haven’t seen other objects, that made it so easy to manipulate rectangles, and their colors. The Quad is basically a rectangle that is able to present a uniform color or a gradient. Not a normal gradient, but a gradient that radiates from every vertex in the rectangle.

Quad Vertices

The individual vertex is stores in an array, going from top-left, over top-right and down to bottom-left and finally bottom-right

The signature of the class is:

Quad(width:Number, height:Number, color:uint = 0xffffff, premultipliedAlpha:Boolean = true)

You simply set width and height. If you leave all other parameters, you will get a white box. You can set the third and fourth parameter to change the color or the default alpha method, premultiplied alpha. (read more about it here)

With the StarlStage.as active enter the following code. The text in bold is the one you should add:

package
{
  import starling.display.Quad;
  import starling.display.Sprite;
  import starling.events.Event;
 
  public class StarlStage extends Sprite
  {
    <strong>private var q:Quad; </strong>
    public function StarlStage()
    {
     <strong> addEventListener(Event.ADDED_TO_STAGE, onAdded); </strong>    }
 
<strong> private function onAdded(e:Event):void { q = new Quad(800, 600, 0x880000); addChild(q); } </strong>  }
}

First it declares the Quad as the variable q. Then the class listens for the event that is triggered, when the object is added to the stage. It is a good habit to make sure the stage is available before adding content to it. In this case, you could do it all in the constructor, but you may end up in a situation later on, where you need to be sure that the stage is reachable – this way, you are on the safe side.

Finally in the onAdded() listener, you instatiate it with a width, a height and a dark red color. Because the similarity between traditional display objects and Starlings display objects, it’s just a matter of calling addChild() to place it in the display list.

Test it

Now, would be a great time to see if everything is working as expected. If you try to run the code, you will see that it shows an error on the screen that says: “This application is not correctly embedded (wrong wmode value)”

This is a default message, that Starling displays if you haven’t enabled the the players the right access to the GPU. To do that, open the file called StarlingTest-app.xml that is located in the root of your source folder. This file contains all relevant information about the project, and this is where you will find the node called RenderMode (around line 104). Uncomment that node and correct it to:

<renderMode>direct</renderMode>

This way you tell the application, that although you will render vectors through the software renderer they will blit through the GPU. It is also possible to enter “gpu” and make all the calculations in the GPU, but for the most part, I believe that direct gives the best performance … but you can fiddle with that.

Save all the documents and try again. You should see a dark, red colored window. If not, review your code, and look for errors. You might download and look at the accompanying files to look for things that might have gone wrong.

Placing an image

OK, with a Quad in place, it is time to step up a level – let’s introduce images. You can’t go around showing colored rectangles all day, at a point you have to bring in some detailed pixels. Update your code, so it looks like this:

package
{
  import flash.display.Bitmap;

  import starling.display.Image;
  import starling.display.Quad;
  import starling.display.Sprite;
  import starling.events.Event;
  import starling.textures.Texture;

  public class StarlStage extends Sprite
  {
    private var q:Quad;

 [Embed(source="assets/mouse.png")]
 private var mouseBMP:Class; 
    public function StarlStage()
    {
      addEventListener(Event.ADDED_TO_STAGE, onAdded);
    }

    private function onAdded(e:Event):void
    {
      q = new Quad(800, 600, 0x880000);
      addChild(q);
 var mouseBMP:Bitmap = new mouseBMP();
 var mouseTEX:Texture = Texture.fromBitmap(mouseBMP);
 var mouse:Image = new Image(mouseTEX);
 addChild(mouse);
    }
  }
}

That was a lot for a little result, you may think. Well, some of it is the way Flash Builder is used to embed images, and some of it is because of Starlings way to treat content inside images as textures – actually Image works like Flash’s own Bitmap class. In the references it is told like this:

An Image is a quad with a texture mapped onto it.

The Image class is the Starling equivalent of Flash’s Bitmap class. Instead of BitmapData, Starling uses textures to represent the pixels of an image. To display a texture, you have to map it onto a quad – and that’s what the Image class is for.

Let’s take the code in chunks

 [Embed(source="assets/mouse.png")]
 private var mouseBMP:Class;

This is the normal way to embed images in Flash Builder. By using the Embed meta tag you are making the image available from the beginning, instead of loading it in at runtime. You can read more about the embed meta tag at http://www.adobe.com/devnet/flash/articles/embed_metadata.html

You are capturing the path to the source and immediately assign it to a class object. This is because you have to assign the image info to an object in order to reference it later on in the code. The second part of the code is executed when the stage is ready, and looks like this:

var mouseTEX:Texture = Texture.fromBitmap(new mouseBMP());
var mouse:Image = new Image(mouseTEX);
addChild(mouse);

First you make a texture, to place on your image. You are using the static methods in the Texture class to tell, what will be the foundation for the texture. This example use Texture.fromBitmap() to indicate that a bitmap info is used for the texture. As argument, you just enter “new mouseBMP()” so a new instance of the image is passed on to the texture.

The next line declares Starlings Image object, that is similar to the Flash Bitmap class. Instead of passing bitmap data to a bitmap object, you are passing the texture data to an image object in Starling – similar proces, different names. Finally it is added to the stage with addChild()

Now what?

This is the absolute fundamentals of presenting images and Quads. In the next tutorial, I will add some movement, but use this tutorial as a reference to get things out on the stage in Starling – Other articles I do will take it for granted and refer to this one for explanation.

Feel free to comment and ask quations in the forum