Posted by: Dennis | March 30, 2010

PixelBender and arrays

Greetings all!

It’s been a while…

This post is dedicated to those who seek a solution for passing arrays to a pixel bender shader and use it in Flash Player.

Since you are here, I suppose you know that, and I quote – ” When Pixel Bender is used in Flash Player, arrays are not available”. This made me very sad when I faced the problem for the first time.  I found a quick solution which worked like a charm for me and may be it will save the day for you too.

The idea is to convert the array to a grayscale M px * 1 px  image (M px  * N px for 2 dimensional arrays). For that you’ll need to map the array to [0, 255] interval, by finding the max and then dividing all elements by that value. Generate a BitmapData object out of that and use it as a secondary input for your pixelbender shader.

The intensity of the color at position (x, 1) is your array element at position x. Obviously it will be in interval [0.0 , 1.0] so you will need to multiply by something (like the already known max; or ‘255’ if you are working with color).

I successfully used this method to create several image processing operations like levels, curves, tone mapping and other LUT-based stuff.

I hope it makes sense to some of you. If I’m not too lazy I’ll post a sample project later.

Dennis

Advertisements
Posted by: Dennis | July 29, 2008

My first struggle with Red5 server

Have you ever seen the following errors while developing your first red5 application:
No scope “something” on this server
NetConnection.Connect.InvalidApp
NetConnection.Connect.Failed

If yes than may be you’ll find this post somewhat helpful…

As any flex developer I had eventaly come across a project that needed server side support. Since Red5 is free, this is what everyone uses, right?
Ok, great – a quick google search brought me to osflash.org.
Latest version – 0.7, took 1 minunte to download.
Installed, tried runninng the demos – nothing worked. It appeares, the apache and coldfusion servers where conflicting with red5.
Stopped the apache and coldfucion services – the demos worked, played around with the ball demo.
Trying to follow a tutorial from flashextensions.net confused me a little. The guy was talking about several ways of deploying your applications on the server and none of them worked for me. Why?
First of all, trying to start the server by running the ant server command in a prompt just gave me a list of unresolved dependencies. That was very sad.
After some more google searching I found that this distribution of red5 was missing some config files. The one particularly important was ivysettings.xml. I found it in the project’s repository: http://svn1.cvsdude.com/osflash/red5/java/server/trunk/. Dowloaded all the ivy*.xml files, just to be sure.
Managed to start the server, but unfortunately saw the following flash output:
“No scope “demo” on this server”
NetConnection.Connect.InvalidApp
Again, very sad.
Tripple checked everything – seemed to be ok.
Sniffed around the existing demos, to find a valid scope. The bandwidth test application provided me with one – bwcheck. Connecting to rtmp://localhost/bwcheck instead of rtmp://localhost/demo showed:
description : Connection succeeded.
code : NetConnection.Connect.Success

This was sort of a good start.

Time for intensive google search.
I found that a LOT of people where screaming for help, having the same issues with this distribution.
The most obvious thing to do was to try an older server version.
Tried version 0.6.3, windows instalation.
Very happy to see that everything works just fine! I mean, just copy the new files in webapps directory, restart the server (the red5 service, in my case) and TA-DAAA.

Great! But what about red5 0.7? Why doesn’t it work as it should? Did anyone manage to create an application without encountering tons of errors?

I decided to test the version that resides in the repository.
SVN checkout, ant build – worked fine.
Tried to run red5.bat, it threw a lot of exceptions but eventualy started up. (I have no knowledge of creating new windows services)
Copied the necessary files in webapps directory, started the server again, tested the flash movie – SUCCESS ! 😐

Conclusion:
Even though 0.7 has some new features and bugfixes, use 0.6.3, at least I will. Or, use the SVN version of 0.7 (but I won’t).
And yes, write to osflash.org asking for better releases!

Red5 is fun 🙂

Posted by: Dennis | June 26, 2008

Flash Player 10 content

Lee Brimelow posted some nice tutorials about creating flash player 10 content.

The features taken into consideration are 3D, dynamic sound generation, and local file access.

Enjoy!

Posted by: Dennis | May 9, 2008

Restore deleted file in Flex Builder

I don’t know how many of you have experienced this issue but it’s a reeeeeally nasty one.

I have been working for the whole day on a class just to find it deleted at the end of the day after I hit CTRL+Z+something else (still a mistery).

I found the solution here:

http://thesaj.wordpress.com/2008/04/23/how-to-restore-lost-files/

The thing is to restore it from editor’s local history – right click the directory you know the file was and select “Restore from local history”.

What a relief!

Funny thing is that the deleted file couldn’t be found even by recovery tools.

Posted by: Dennis | August 21, 2007

External Interface Tip

This article will treat solutions to “swfObject.callback() is not a function” problem when using ExternalInterface in Flash/Flex.

Ok, not so long ago I had to test some interaction between JavaScript and ActionScript. It wasn’t the first time I was using EI, and since it’s always good to start from a working examle, I set up the one provided by Adobe, test it – works fine.

(An important note – you have to run it from a web server and add it to flash player’s security domain. I’ll show you how later). Now in this example the flash function is called the onClick event of form button is fired:

<input type="button" value="Send" onclick="callAsFunction();" >

while what I needed was to call the AS function as soon as the document loads. I decided to put it in body’s onLoad event:

<body onload="callAsFunction();">

and SURPRIIIIIIIISSEEEEEEEE !!!! – not working!
I double check everything again and nothing. WHAT THE … ?! [picture of me scratching the head]. It is there, why isn’t it working?? The error message thrown by JavaScript was “blabla.blabla() is not a function”
I am a person who thinks that if smth isn’t working right in a computer program, it’s most certainly your fault, not computer’s, so I start thinking of a solution. I searched the net and all the examples/tutorials/forums out there were variations of the one provided by Adobe, which is calling AS function after the button is pushed. GREAT!
I made another test, called the function from within a <script> tag after the embed code – didn’t work either. So I thought, perhaps in both cases the flash object simply isn’t ready yet.
Another test – add a timeout:

setTimeout('callAsFunction();', 100)

TADAAA, it worked, BUT, only in 9 out of 10 page refreshes. If I set timeout to smth like 500 it solves the issue, but it’s not a good solution. Who wants to wait half a second? It can screw many things up. So what do we do? We make flash tell JavaScript when it’s loaded and ready, and only after that, call AS functions. Piece of cake!
Here is the JS code:

    function onFlashReady() {
		sendToAS("another test message");
    }

    function callJS(value) {
        onFlashReady();
        return "Hi Flash.";
    }

    function thisMovie(movieName) {
         if (navigator.appName.indexOf("Microsoft") != -1) {
             return window[movieName];
         } else {
             return document[movieName];
         }
     }
     function sendToAS(value) {
         thisMovie("test").callAS(value);
     }

and AS code:

import flash.external.*;

System.security.allowDomain("http://localhost");

tf.text = "Flash loaded and ready!";
tf.text += "nEI available: " + ExternalInterface.available;

var wasSuccessful:Boolean = ExternalInterface.addCallback("callAS", this, func);
tf.text += "nAdd callback success: " + wasSuccessful;

greeting = String(ExternalInterface.call("callJS", "Hello JS!"));
tf.text += "nI called Javascript and it said: " + greeting;

function func(value:String) {
	tf.text += "nJavascript called me, saying: " + value;
}

Note that you need a TextField on the stage with the name “tf”. Give the swf object the name “test” when embedding.
You can also download the source files here: http://www.box.net/shared/ocq972d435
IMPORTANT!!! – the html file needs to be run on a web server. Simply douleclicking it won’t work!!!
This should appear in the textfield:
“Flash loaded and ready!
EI available: true
Add callback success: true
Javascript called me, saying: another test message
I called Javascript and it said: Hi Flash.”

Have fun coding!

Posted by: Dennis | August 7, 2007

Editing Flex application settings

Perhaps not many of you know how to change the default settings of a flex application. You might be very comfortable with what you have right now you even haven’t wondered whether there is such a possibility. Those of you who have, must have googled it already and found the answer, but here is a quick tip for those who haven’t:

  • Right-Click on you project folder > Properties or go to Project menu > Properties
  • Click ActionScript Compiler
  • Fill in, for example “-default-background-color #FFFFFF” in the field labeled: “Additional Compiler Arguments”, this will set the background color to white

Here are some other settings (followed by allowed arguments, and by the way, flex will tell you how many arguments it expects once you type in a setting):
-default-frame-rate 31
-default-size 800 600
-default-script-limits 5000 10

It took me a while to find the complete list, here is the link : About the mxmlc application compiler options

From what I’ve found there some important features are – changing the default output folder and file name/path, some font manipulation, external libs, as3 encoding, etc.

I hope it’s helpfull in any way!

Have fun coding!

Posted by: Dennis | August 3, 2007

Flash content in Flex

Ok, this is not an innovation, I’m pretty sure there are a lot of tutorials out there, and ofcourse mine is not the best, if you find a better one, let me know, I just found that it is suitable for most situations. Flex Builder 3 Beta and Flash CS3 where used in this example.

Now, when do we need Flash content in Flex? – when it is too difficult (or even impossible, or we are just too lazy) to draw smth programmatically, using ActionScript.

The project and all its files can be found here: http://www.box.net/shared/xg4ce2p1z3 , I’ll just walk you through it and give you a description.

There are two main options when we are talking about using Flash content in Flex (and by Flash content I mean a swf)
1. embed it into the pubilshed (by FLex) SWF
2. load the Flash content dynamically, which is not quite appropriate for most cases, but really necessary in other ones. It means that before you can use that content you must load it first (pause the application, add event listeners, load, un-pause), and it’s not a pleasant situation if you were looking for something extremely simple.
So I’ll just stick to the first case. In the application directory you will see an FLA file named library.fla, this will be our so-called library for the application. Just like the library in the Flash IDE, any symbol can be added to the display list at any time (as long as it is exported in the first frame). Now check out the library panel in Flash (by the way Flash 8 won’t work). We’ll be using these two symbols: buttonsSymbol and scrollbarSymbol. These two cover the situations I have dealt with so far – one is using a symbol as an asset for a single class, and the other one is using a symbol as assets for multiple classes. More about this later.

Right now it’s not important what is on the stage. I’ve just put the symbols there so that they are visible the minute you open the FLA file. The most important thing is two export the symbols in the first frame. Let’s take scrollbarSymbol as example. In the linkage properties window it sais that it’s class is Scrollbar (which can be found in the same directory – Scrollbar.as) and base class is flash.display.Sprite. Now, if your class resides in a directory within a direcotry .. within a directory you have to give the full path to it in the “Class” field (in linkage properties), smth like “com.yourcomany.flash.as3.myproject.Scrollbar” if the directory structure is “com/yourcomany/flash/as3/yourproject/”.

If you look inside scrollbarSymbol, you will notice that it has only one object – a dimond-like shape, which I found difficult to draw only by using actionscript when developing a scrollbar once. It has an instance name of “arrows”, and it is also important, since we will be accessing it from flex using this name. Now switch to Flex builder, and open Scrollbar.as file. The functionality of the scrollbar isn’t implemented here, one of my favourite lines: “it’s outside of the scope of the project”. What you have to look at is the Embed meta-tag. It specifies a source (library.swf) and a symbol (Scrollbar) for the class. We know that Scrollbar symbol in flash had a movieclip inside, instance-named “arrows”, so now we can access it by this name, store it in a local variable, rotate, scale, or whatever. Initially it will appear at 0,0 cooridnates.
So what do you have by now – a scrollbar class (with all the functionality , in case you decided to implement it) with a symbol inside, drawn in Flash which can be easily used here, in Flex. Hooray!!!

Second example is about using a symbol to add assets to multiple classes. Here is the scenario: you have to develop a navigation bar, with buttons like next, previous, first, last and so on. If you were to use the first example, you would need a class for each button, which is already bad OOP, since you could have a single class but multiple instaces of it with different assets, instead. So what do you do? You export all these buttons as a single symbol and use them separately when instanciating you gereric button class (mine is called NavigationButton). So, check out the buttonsSymbol in library.fla, it has some buttons, each with unique name. The class Buttons.as is the one in which you embed that symbol, and then in flash_content_in_flex.as you instanciate both Buttons.as and NavigationButton.as. The latter gets an extra parameter which actually links to an object from within the buttonsSymbol symbol. In NavigationButton.as you can see that this symbol is added immediately to the display list and becomes visible right away.

Good luck coding!

Posted by: Dennis | July 25, 2007

Reflections on FLA-based components

Every day brings me more and more proof that Adobe released such an unfinished piece of software as Flash CS3. I think it’s because of the whole “suite” idea. A dozen of programs means a dozen of development teams and a dozen of deadlines which had to be pushed to the actual release date. Kinda difficult to achieve. I wouldn’t be surprised if some users of DW and PS are as disapointed as I am. I know what it means to “speed up the process” because the management wants a pre-Christmass release. You can’t blame the programmer, the manager is the problem here.

It’s not a secret that I don’t like the new component architecture. A couple of days ago I decided to sit down and try to make some use of it. Today I cant tell you that I HATE it! No offence to Grant Skinner but I think that he and the flash development team could have come up with extremely usefull, not something so annoying that you won’t try to use it ever again.

First of all, you have to work with 4 .fla files to get the component ready – 1 for the component (components), 1 for component shim, 1 for live preview and 1 for testing, but it would have been ok if you hadn’t had to restart flash every time you wanted to see the effect of a modified line of code. Really now, restarting FLash CS3 is a painful procedure, especialy if you have an antivirus which starts to scan the files being used (by Flash IDE, when it’s loading) >:).

Another thing is the live preview. I was LMAO when I saw how many steps you need to make to add this absolutely necessary feature to your component. And you know which is the best part? The best part is that this live preview only affects the dimensions and the inspectable params. If you have ever tried to change the border color or remove the border completely on a Button component (and see NO EFFECT in live preview), you’ll know what I mean.

And lastly, the what-we-are-trying-to-get-used-to lack of documentation on how to develop custom comonents.Considering that the new architecture is already not so easy to use, there had to be at least something!

Hopefully our screams for help will be heard and we’ll see some changes in an update or something.

Cheers!

Posted by: Dennis | July 20, 2007

Liquid Layout for Flash Components

Recently I had to develop a photo gallery in flash. I have had many challenges since I decided to use a combination of 2 design patterns, the “road” was overall quite bumpy but I managed to find solutions to all the problems and I decided to share some of them.

Now, according to wikipedia the term of liquid layout actually refers to controlling the appearance of the elements on screen, mostly in web browsers. What I want to show you is controlling the layout of your component whether it is used as a Flash CS3 component or a standalone Flex ActionScript Application.

Google showed me only a few good results and most of them where AS2 solutions:
http://www.jamesor.com/2006/10/12/creating-liquid-guis-with-flash-part-3/
http://www.tutorio.com/tutorial/liquid-flash-layout

My solution isn’t the best nor the worst, it’s just something I found easy to understand and use. The main idea is to break down the appearance of your components in several elements, each defined by it’s own class. So, consider the simplest example of a photo gallery with 3 elements – a thumbnail bar, a navigation panel and an area for the big image (detail from now on). For that we’ll need 4 classes – 1 for each element (Detail, Navigation and ThumbnailBar) and another one to wrap them all together (PhotoGallery). In terms of Model View Controller design pattern, the 3 visual elements will act as views and the PhotoGallery class will act as the controller.

The end result will look like this: (note that it’s not an actual photo gallery, implementation of this kind of functionality is beyond the scope of the project)

Liquid Layout Test

Here is the complete source of the project. I have used Flex Builder 3 Beta to build it.

I have described the steps to create a simple CS3 components here so I’ll just go on with the description of the classes. All the classes have a similar structure – a couple of properties and some methods:
– init() – handles some initialization
– createChildren() – creates instances of visual objects and adds them to the display list
– draw() – draws and arranges the visual objects

Now, if you are interested only in using it as a Flash CS3 component, you should check out lltest.fla and notice the 2 symbols in the library. The linkage properties for lltest symbol (lltest stands for liquid layout test) show that it’s base class is PhotoGallery.as, so this is your main class. If you are to use it as an ActionScript project in Flex, you need to open LiquidLayouts.as file. This is the class that creates the photo gallery (PG). Use the setSize method to set the PG’s size. As I have mentioned in the post about building flash cs3 components, your main class needs to define a public setSize method in order to see live preview happen, which means that both, the Flash IDE and your the LiquidLayouts class use the same method to resize and redraw the photo gallery.

Among the properties of the PhotoGallery class there are 2 public variables: _navigationSize and _thumbBarSize – these come with some meta tags which will make those 2 properties show up in the property inspector of the component in the Flash IDE (only if used as a component). The properties specify the size (well, the height actually) of the navigation and thumbnail bars. The height of the detail area will becalculated from total height minus the sum the other two:

_detail.setSize(_width, _height - (_navigationSize + _thumbBarSize));

As mentioned earlier, ThumbnailBar, Navigation and Detail classes have pretty much the same structure. It would have been easier to create a generic class having the common behavior and make our view classes extend it. But for the sake of an easier understanding of the project I decided not to shorten it. So each view class has a background and a textfield that shows the class’ name and dimensions. Whenever you resize the component it will show you the new width and height of each element.Finally, if you are using flex, you can set the desired size for the photo gallery and see the end result, or if you want to use it as a Flash CS3 component, export the lltest symbol to a SWC file, open a new AS3 file in Flash, reload the components panel and drag and drop the newly created component

I hope this is a good starting point for those who were searching for some information related to this matter.

Posted by: Dennis | June 27, 2007

Building Flash CS3 components

Issue: Develop an ActionScript 3 component for Flash CS3 that resizes correctly and has a live preview.

To find the solution, first, I searched the documentation, and I got almost nothing. Just references to how to customize a component or how to export a SWC file, things I already knew. Then I googled it, only to find out that the new component architecture is now FLA-based. There were only a few pages about it and even less pages explaining how to actually build a FLA-based component (one of them was in japanese, so it was useless). This guy spender has a very good step-by-step tutorial of how to build a simple FLA-based component. But those steps are so annoying: edit-save-reopen flash-copy-edit-close-reopen… and so on. And this guy’s component extends UIComponent which adds another 10K to your published SWF. Where is the old-style export to SWC solution? If it exists (and yes, it’s still there), why is it so poorly documented? To me, the documentation seems a little misleading, it gives you the impression that the FLA-based components are the only components supported by Flash CS3. But this is not true!. The new features brought by the new FLA architecture are cool, but you don’t need them every time you build a simple component. If you are, for example, building your ActionScript application in Flex and want to use it as a Flash CS3 component (again, without the styling features), follow the old steps:

– write your actionscript class which will be the base component class in your favourite editor
– create a new fla file
– add a MovieClip symbol to the library, check Export for ActionScript and Export in first frame, in the Class textfield write the path to your component’s .as file, set the Base Class to the class extended by the previously mentioned .as file (actually flash.display.MovieClip will do in most cases).
– make sure your component class defines a public “setSize” method as it is the method used for live previewing. Add all resize handling there. (for more information check out the fl.livepreview.LivePreviewParent class)
– right click the symbol in the library, select component defenition, type in the name of the .as file again in the Class textfield, check “Display in Components panel”, click OK
– right click again > Export to SWC file > save to (for windows) Documents and Settings/$user/Local Settings/Application Data/Adobe/Flash CS3/Configuration/Components/MyComponent.swc
– create another FLA file, reload the components panel (a small button with an arrow pointing down below the x button)
– search (in the Components panel) for the name of the directory created in the previous step, drag and drop your new component

Here is the code I used to create a trivial component that has a rounded rectangle as the background and a textfield which tells the width and height of the component:

package { 

	import flash.display.Sprite;
	import flash.text.TextField;
	public class MyComponent extends Sprite	{ 

		private var _tf:TextField;
		private var _width:Number = 0;
		private var _height:Number = 0; 

		private var _background:Sprite; 

		public function MyComponent() {
			init();
			createChildren();
			draw();
		} 

		private function init():void { 

			_width = width;
			_height = height;
			scaleX = 1;
			scaleY = 1; 

			// remove the avatar
			removeChildAt(0);
		} 

		private function createChildren():void { 

			_background = new Sprite();
			_tf = new TextField();
			_tf.autoSize = "left"; 

			addChild(_background);
			addChild(_tf);
		} 

		protected function draw():void { 

			_background.graphics.clear();
			_background.graphics.beginFill(0xFF0000, 1);
			_background.graphics.drawRoundRect(0, 0, _width, _height, 10, 10);
			_background.graphics.endFill(); 

			_tf.text = "w: " + _width + ", h: " + _height;
			_tf.x = Math.floor((_width - _tf.width)/2);
			_tf.y = Math.floor((_height - _tf.height)/2); 

		} 

		public function setSize(w:Number, h:Number):void {
			_width = w;
			_height = h;
			draw();
		} 

	}
}

simple AS 3 component

Older Posts »

Categories