Stroep

Just a collection of random works – Mark Knol

Tag Archives: experiment

Recently I found an interesting question on FlashFocus.nl, about creating light and shadows in a 2D environment. I started experimenting with this to see how far I could take it. I love to share the results and some insides about this fun project.

How to get started

The initial code that the topic starter used a loop through all objects, and used hitTestPoint-function to detect if the light hits a wall. Therefore he used a loop with 360 steps, used for all directions. In the innerloop it tries if it hits the wall, otherwise goes away from the light (using the direction of the outerloop), tries if it hits the wall. That loop goes on till it does hit a wall. It is a bit of trial and error, but I think it is very clever. At the end of each loop a lineTo is used to draw the light, so in the end it will be a shape with 360 vector points.

Speed of light

Now, that screams for optimization and speed. It’s a fun project to mix some things you have seen and want to try out for a long time. The first thing that I tried to make it faster, draw all objects into an BitmapData, and use the getPixel function instead of hitTestPoint, which is notable faster if you don’t move objects. I used that BitmapData object only too check if the light hits the objects; no one actually sees it. To use hitTestPoint, you must loop through all objects and detect if they hit. With a lot of objects, it would be slower. With BitmapData, you don’t need that loop, and you are free to use unlimited objects with even custom shapes. Less looping == faster, unlimited objects == awesome :)

More realism

I also wanted to make it look more realistic. Having light only is not close enough to realism. It needs shadows. I created an inverted shape of the light-shape and filled it with black (a). This creates a nice shadow, however has very hard bounds, which is ugly. So then I took the shape again and drawed with a nice transparent to black gradient (b). Those 2 layers have the BlendMode ALPHA. The holder of those has a solid shape fill (as big as the stage) with BlendMode LAYER. This creates a nice ‘hole’ which I think works very well as shadow if you make it half-transparent. Oh, the colored light-layer (c) is a gradient too, with the same shape as b, only with BlendMode ADD.

Re-using shape data

Another optimization I used was to use graphics data API. In this case I have 1 shape which could be reused 3 times. So before even drawing, I collect all points and commands in an Vector. When I have all data collected, it draws the light-layer and shadow-layer at first, then it pushes some extra points to the Array to make the outer shadow-layer. So with 1 Array of (manipulated) data I could draw multiple shapes. That’s a good case of using the graphics data, I guess.

Optimized trig functions

I also used the TrigLUT-class (Trigonometry LookUp Table) from jacksondunstan.com, since the loop heavily uses Math.sin and Math.cos. I could use the valNormalizedPositive() function from that class in this case. It’s very fast and for me it was fun to use that class. :D

But it is still too slow..

The most intense about this thing isn’t the calculation, but the rendering itself. The whole ‘canvas’ needs to be updated and redrawed every frame with lots of layers and blendmodes, which is very intense for the CPU. I don’t know if this would be possible with Stage3D, but that would be the last step to render really fast. And when that is possible, I’ll guess I could move the object real-time too, which makes it very interesting for games.

Check out the experiment:
» Lights and shadows

Let me know what you think about it and how does it perform on your computer?

Tagged with , , , .

FindClosest (7)

March 14th, 2010, under actionscript.

findClosestWho follows me on twitter already noticed I’ve created a little app inspired by scribbler from zefrank. I also found another cool version of Mario Klingemann aka Quasimondo called scribblerToo. But the one where it all started is the javascript version of Mr.Doob. I wanted to try this in flash, and called it findClosest. It’s not as great as the other versions, but I really think there are some interesting things in here.

See it in action
» FindClosest

The trick in this little application is to store each mouse position, locate the mouse position and find the closest points around it (from the stored data) and draw some lines between those points. Well that code isn’t very exiting, because most people know how to find the distance between 2 points, and basically there are 2 ways find this:

// option 1: Using the build-in function
var distance:Number = Point.distance( point1, point2 );

// option 2: Using Math
var distance:Number = Math.sqrt( point1.x * point2.x + point1.y * point2.y );

The results are amazing and I love the fact that even if you can’t draw, it looks really cool :)

Store lines as small as you can

I was already trying to find a way to store lines in a format I can reuse for my artworks. Most artworks are random but I am looking for a way to have more control. The first step would be the ability to control the (what I call) movements. So in this little experiment I’ve tried to find a way to store the lines into a compact file, which can be redrawed by the app. I’m really exited about this. So I’ve started to save as a plain-text file writing something like this:

{x:100,y:300},{x:110,y:340},{x:125,y:350},{x:125,y:350}

It’s readable code, and easy to These are 56 chars for 4 points. So I tried to make it more smaller using this:

{100,300},{110,340},{125,350},{125,350}

I’ve removed the x and y from the file, because I know that it’s always a pair of x and y values. Alright.. now I have 40 chars which represents 4 points, so that saves me 16 chars. Can this be done more smaller?

100,300,110,340,125,350,125,350

Yes, sometimes basic is the best. I removed the brackets. I know the odds are the x values, and the evens are the y values. It’s always x,y,x,y,x,y,x,y etc. So now I have 32 chars to store 4 points.

The application doesn’t know where I start pressing and releasing the mousebuttons. I have to know this, otherwise all my lines are just 1 big line instead of multiple lines. When pressing the mouse, I want to start with an graphics.moveTo function.

So what I did is this:

100,300,110,340,125,350,125,350&m=0,2

&m=0,2 means I have released the mouse on point 0 and point 2. A point referrers to the x and y position.

I think this is almost the smallest I can get. It’s easily to revert these values back to usable values using String.split().

But.. In real life there aren’t ints, but Numbers. The values mostly looks like 452.12070158. I stripped the value, and only use decimals. You don’t actually see the difference when redrawing between 10.04 and 10.042. This saves me a lot of chars too.

Compress it!
When saving the file, I push the data into a ByteArray using the bytes.writeUTFBytes() function. I realized ByteArrays can be compressed, so I also use the bytes.compress(); to make the file smaller again. This saves me about 50%! When importing the lines, I used bytes.uncompress(); to make it a normal string again.

This flower is 14kb :) Import this file in the app to see how I haved drawed it. You can also load it from an url: http://projects.stroep.nl/findClosest/flower2.stroep
flower
flower on Flickr

Well this is a next step and I hope to create one day an editor for simple lines and merge this into my artwork process. I think it needs to be more complex but for now this will work. I hope you like it.

Tagged with , , .

After writing this post of using perlin noise, I’ll did some more experiments making cool things. I draw lines using Perlin noise as input. Check this out:

I was also experimenting/figuring out how to convert a actionscript generated movie to video. I never knew it was possible (or that easy) with the Flash CS3 (maybe because I never tried). Just choose file > export movie > and choose .mov extension. The video isn’t smooth, because (when I save it) it is not really rendering, it’s just like an invisible screencapture, I guess. So I can’t use more heavy CPU things. Thats a pity.

But maybe I could use my ImageSaver Class to create a movie-sequence by saving frame by frame as PNG.

Tagged with , , , , , , .

Looking for class to save images? Check out ImageSaver.as

I’m experimenting with AIR, because I heard saving a ByteArray ( for example encoded PNG or JPG ) should be quite simple. You don’t need PHP or another serverside script for this, just write directly on you disk. Well, just check it out.

See this example of how to get it work. The image will be save on the same directory as your AIR application.

// use adobe’s encoder to create a byteArray
var jpgEncoder:JPGEncoder = new JPGEncoder( 60 );
var byteArray:ByteArray = jpgEncoder.encode( bitmapData );

// set an filename
var filename:String = "cool-image.jpg";

// get current path
var file:File = File.applicationDirectory.resolvePath( filename );

// get the native path
var wr:File = new File( file.nativePath );

// create filestream
var stream:FileStream = new FileStream();

//  open/create the file, set the filemode to write in order to save.
stream.open( wr , FileMode.WRITE);

// write your byteArray into the file.
stream.writeBytes ( byteArray, 0, byteArray.length );

// close the file.
stream.close();

// That’s it.
 

Is that it? This would be a boring post if I stopped right now ;)
I experimented to create a colorful cool wallpaper using AS3 only and save it using AIR. If you don’t got AIR or just don’t want to use it, I recommend using my ImageSave class.

Cool wallpaper created with AS3

This is my code to create this wallpaper:
Feel free to play with the code, but post a link to your experiment / wallpaper here.

package
{
    import com.adobe.images.*;
    import flash.display.*;
    import flash.events.*;
    import flash.filesystem.*;
    import flash.filters.*;
    import flash.geom.*;
    import flash.text.*;
    import flash.utils.*;
    import nl.stroep.utils.*;
   
    public class Main extends Sprite
    {
        public function Main():void
        {          
            var bitmapData:BitmapData = new BitmapData (1280, 1024, false, 0×000000 );
           
            // create colorful radial lines
            var shape:Shape = new Shape();
            shape.graphics.moveTo ((bitmapData.width/2), (bitmapData.height/2))
            for (var i:Number = 0; i < 1900; i++)
            {
                // create some weird colors using sinus
                shape.graphics.lineStyle( 30, (Math.sin( i * 9 ) * i / 200) * 0xffffff, 0.4 );
                // do some weird sin/cos moves
                shape.graphics.lineTo ((bitmapData.width/2) + (Math.sin( i/3 )*i/2),  (bitmapData.height/2) + (Math.cos( i/3 )*i/2) );
            }                  
            // add it multiple times using other blendmodes, isn’t that what we do all the time in PhotoShop?
            bitmapData.draw ( shape, null, null, BlendMode.NORMAL );
            bitmapData.draw ( shape, null, null, BlendMode.ADD );
            bitmapData.draw ( shape, null, null, BlendMode.MULTIPLY );
            bitmapData.draw ( shape, null, null, BlendMode.OVERLAY );
            // cool! filters! Add some blur to our lines to make a nice blurry background
            bitmapData.applyFilter( bitmapData, bitmapData.rect, new Point() , new BlurFilter( 40, 40, 5 ) );
           
            // create colorful radial lines
            var anotherShape:Shape = new Shape();
            anotherShape.graphics.moveTo ((bitmapData.width/2), (bitmapData.height/2) );       
            for (var j:Number = 0; j < 1900; j++)
            {              
                // create some weird lines with weird sizes
                var lineWidth:Number = 50((j / 50) >> 0);
                var color:Number = (Math.sin( j ) * j / 200) * 0xFFFFFF
                anotherShape.graphics.lineStyle( lineWidth, color, 0.2, false, LineScaleMode.NORMAL, CapsStyle.SQUARE, JointStyle.MITER );
                anotherShape.graphics.lineTo ((bitmapData.width/2) + (Math.sin( j/3 )*j/2),  (bitmapData.height/2) + (Math.cos( j/4 )*j/2) );
            }   
            // cool! filters! Add some blur to our lines to make a little blurry
            bitmapData.applyFilter( bitmapData, bitmapData.rect, new Point() , new BlurFilter( 5, 5, 5 ) );
            // blendmode ADD is awesome
            bitmapData.draw ( anotherShape, null, null, BlendMode.OVERLAY );
           
            // create some text
            var textfield:TextField = new TextField ();
            textfield.antiAliasType = AntiAliasType.NORMAL;
            textfield.htmlText = "<font face=’Arial’ color=’#FFFFFF’ size=’60′>FUN WITH BITMAPDATA</font> <br/> <font face=’verdana’ color=’#FFFFFF’ size=’20′><B>CREATE YOUR OWN WALLPAPER WITH FLASH</b></font>";
            textfield.autoSize = TextFieldAutoSize.LEFT;           
           
            // cool! filters! Add blur to your text
            textfield.filters = [ new BlurFilter(20,20,3) ]
           
            // draw textfield into bitmapdata, and use a matrix to set its position to center screen
            bitmapData.draw ( textfield, new Matrix( 1, 0, 0, 1, (bitmapData.width/2)(textfield.textWidth/2) ,(bitmapData.height/2)(textfield.textHeight/2)), null, BlendMode.ADD);          
                   
            // reset the filters, just add DropShadow
            textfield.filters = [ new DropShadowFilter( 0, 45, 0, 0.3, 5, 5, 2, 5 ) ]
           
            // draw textfield again
            bitmapData.draw ( textfield, new Matrix( 1, 0, 0, 1, (bitmapData.width/2)(textfield.textWidth/2) ,(bitmapData.height/2)(textfield.textHeight/2) ) );         
           
            // show the bitmapData, just add it to the stage, using the Bitmap Class
            this.addChild ( new Bitmap ( bitmapData ) )

            // use adobe’s encoder to create a byteArray
            var jpgEncoder:JPGEncoder = new JPGEncoder( 60 );
            var byteArray:ByteArray = jpgEncoder.encode( bitmapData );

            // set an filename
            var filename:String = "cool-wallpaper.jpg";

            // get current path
            var file:File = File.applicationDirectory.resolvePath( filename );

            // get the native path
            var wr:File = new File( file.nativePath );

            // create filestream
            var stream:FileStream = new FileStream();

            //  open/create the file, set the filemode to write; because we are going to save
            stream.open( wr , FileMode.WRITE);

            // write your byteArray into the file.
            stream.writeBytes ( byteArray, 0, byteArray.length );

            // close the file. That’s it.
            stream.close();
                   
        }      
    }
}

Tagged with , , , , .