Ph: 20010904

[image] About me

Java.net profile

View Andres Almiray's profile on LinkedIn

ohloh profile

View aalmiray's profile on slideshare

Twitter Feed FriendFeed

CodeCamp at FootHill College. Click Here for Details and Registration

Currently reading:

Programming Groovy - V.Subramaniam Beginning Java SE 6 Platform - J.Friesen The Story of the Irish Race - S.MacManus NFJS Anthology 2007 - N.Ford et al Groovy Recipes - S.Davis

[image] Recent Entries

[image] Tags

[image] Subscribe

Subscribe in Rojo

Add to Netvibes
Add to Google

[image] Projects

[image] I Recommend

GetJava Download Button

No Fluff Just Stuff

[image] Blogs I read

[image] Search

[image] Categories

[image] Monthly

« October 2008
Sun Mon Tue Wed Thu Fri Sat
     
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 
             

[image] Badges

[image]
[image]
[image]
[image]
[image]
Add to Technorati Favorites

 

Locations of visitors to this page
A couple of days ago there was an announcement on this blog about jSilhouette's 0.1 release, followed by a comparison between the geom, scene and jfx demos (regular Java, Project SceneGraph and JavaFx Script each).

Things have changed a bit. Jacek Furmankiewicz brought to my attention that Project SceneGraph is licensed under GPLv2 (no classpath extension) which means both jsilhouette-scene and jsilhouette-jfx must use the same licensing scheme. But jsilhouette-geom does not, in fact it has been re-licensed to ASL 2.0, this means that starting with the next release commercial use of jsilhouette-geom is no longer a problem. The commercial usefulness of the remaining modules lies in Sun's will to re-license Project SceneGraph to GPLv2 with classpath extension.

Some other updates
Donut shape has been added to all modules. Donuts may be circular or polygonal. Default values have been added to some attributes in the jfx module, alleviating the pain of setting each attribute. Groovy demo (GraphicsBuilder based) available!
Here is an screenshot on the latest demo app

[image]

Nice Nimbus look &feel, you may be thinking that this is the new version of the jfx demo, but it is not! this is the Groovy version (ShapesDemoGroovy.groovy) ;-) , the green color is darker in jfx, remember? let's revisit the stats, shall we?

  geom scene jfx groovy
LoC 369 505 619 369
Tokens 1486 1855 2644 2194
Source file size (bytes) 16412 21000 20626 15311
Compiled code size (bytes) 104K 60K 76K 92K


The Groovy version beats the JavaFx Script version in almost all categories (the source file is even shorter than the Java2D version) but these numbers do not reflect how small the code can be in each version. For example I discovered that the jfx version has some commas (,) between attribute declaration (which bump the char and file size), I was surprisewd to find out JavaFx Script was happy with them as not even a slight warning is given by the compiler, nice!; the Groovy version harnesses the power of native syntax for Lists and Maps to reduce variable declaration; defaults values are not really used that much in all versions.

I also mentioned previously that making the second and third demo was quicker once the first one was done, in this case it was no different. The jfx version was copied almost verbatim, added some Groovy sugar here and there (even had to add a MetaClass hack due to how SwingBuilder handles look&feel in the 1.5.6 version (the new one is slicker :-D thank @shemnon for that)). Quick comparison between how the jfx and groovy versions initialize the frame, first the jfx one

Where each draw* function is of the form

Here I'd like to take the opportunity to mention that the function signature must have Void as its return type otherwise a compilation error will be thrown. If the return type is not specified then it will be the same type of the last evaluated expression, in this case Node[], SwingButton expects its action function to return Void. I'm sure a tool (like NetBeans' jfx plugin) would have drawn a red underline/popped an error/whatever under the offending code before attempting a full compile on the code by myself, but I went with the "manual" way: Vim + command line compiler, so there, had to be more careful :-P

Here is the Groovy version

Where shapes is a Map initialized like

The Groovy version requires some 'plumbing'
Fix SwingBuilder.lookAndFeel to accept a List of L&F identifiers (available in Groovy 1.6.x). Set the preferred L&F. Tell the frame where it should be located by default (locationRelativeTo: null)
The native syntax for Lists and Maps comes in our aid here. Iterating each entry (String,GraphicsOperation) it is a matter of hooking up the proper values on the button's text and action. Notice that each time a button is clicked a new GraphicsOperation is created (a group) that has a 'global' property applied to all its children (borderColor: 'black') and antialias is turned on. GraphicsPanel is smart enough to know when it should repaint itself (similar to JSGPanel and Canvas). Of course some would say you may iterate over a sequence in the jfx version in order to build the buttons in a loop, sure you can. You could also create a java.util.Map that holds each label and related function, but the code is not as concise as the Groovy one. Assuming hypothetical classes javafx.util.LinkedHashMap and javafx.util.MapEntry
Yup, hypothetical is more like it (my code that is, still have to learn more about JavaFx Script) but you get the idea. Back to jSilhouette, I'd like to have proper javadocs/javafxdocs in place before releasing the next version, so it will take a couple of days more.

Feedback is always appreciated.

graphics graphicsbuilder groovy java java2d javafx jfx jsilhouette
jSilhouette includes a demo application for each one of its subprojects (geom, scene & jfx) showing the shapes in action. This post is a recollection of what happened during the time those applications were developed and what lessons I learned while doing so.

Let's start with some screenshots, both jsilhouette-geom and jsilhouette-scene use the default Swing settings (which means ugly Metal L&F), from an outsider's point of view there is no difference whatsoever on the finished app so the following screenshot is the same for both demo apps

[image]

The real difference strives in how the graphics are attached to the canvas panel. Regular Swing/Java2D applications that rely on custom painting usually create a subclass of JComponent or JPanel and plug-in the custom painting code. This is exactly what ShapesDemoJava.java does, it defines a CanvasPanel that requires and instance of PaintOperation to actually draw anything as its contents. Each button wires up a listener that creates an anonymous inner implementation of PaintOperation upon activation. In other words quite the regular plumbing we are used to in Swing/Java2D.

Now on the SceneGraph version (ShapesDemoSG.java) things look a bit brighter. SceneGraph relies on SGNode to do its work, happily for us it also includes a handy JSGPanel that knows how to render SGNodes, in other words, you do not need to create a CanvasPanel nor a PaintOperation, just make sure to build a proper graph of SGNodes and set it as the scene property of a JSGPanel instance. Notice that in both demo apps the main frame and the whole ui are built in the EDT (thanks to wrapping the building code with SwingUtilities.invokeLater), this is important to remark as the next demo relieves you of that burden: ShapesDemoFX.fx. The JavaFx Script libraries also provide a canvas, aptly named Canvas, where you can set a sequence of Node instances as its content, which will be used to draw anything into it. Declarative programming helps a bit in reducing the visual clutter (no setter/getters) but in no way reduces the amount of lines of code (more on that later). So how does it look?

[image]

If you run the demos with j6u10 installed you'll get a nicer L&F (Nimbus), the frame will be centered on the screen by default too. Notice that the green color differs form one screenshot to the other, I don't know why but java.awt.Color.GREEN is lighter that javafx.scene.paint.Color.GREEN.

Time for some stats. I have no recorded data on the time spent in each demo app, what it is true is that I started with the geom demo and finished with the jfx one. Once the first layout and behavior was set, the other two demo apps were quicker to implement (already had the recipe), it was just a matter of using the native facilities of each version. Lines of Code is also another metric people like to use, along with the size of the packaged product, here goes
  geom scene jfx
LoC 337 463 546
Tokens 1395 1713 2347
Size (compiled) 17854 (jdk4) 8659 (jdk5) 128553 (jdk5)
# source classes 10 9 9
# compiled classes 10 9 87


Looks like the geom version is the winner in terms of LoC & Tokens and the jfx is a considerable percentage behind, but there is some explaining involved. Even though the geom version creates its own 'rendering setup' it also relies on specialized constructors available in each shape, so creating a shape with a mix of default values and new ones is just a matter of invoking a one-liner. The scene version requires less plumbing on the 'rendering setup' (as explained before) but its shapes do not provide specialized constructors, which means that if those constructors were available this version should be the shortest one in terms of LoC), thus requiring helper methods to build each shape. Lastly the jfx version does not require any specialized 'rendering setup' (it is already there), so it is the declarative way of instantiating an object the one responsible for the amount of LoC and Tokens. Notice that many properties are clumped in the same line (contrary to many jfx demos out there) effectively rendering the LoC argument quite pointless, that is why I decided to also show the token count.

So is declarative programming bad for your productivity? certainly not. What we 'lost' in source file size we gained in comprehensibility and readability. The jfx version explicitly states which property has what value, in the geom/scene versions you will have to search the code to know the correct order and types of the parameters (this is where tool support kicks in, right?).

Regarding file size, the geom shapes provide accessors for each property and the actual implementation of each shape, the scene shapes provide only accessors for each property and rely on their correspondent shape (of the geom package) making them smaller. The jfx version is bigger given that
Each jfx class is compiled to a class and and interface Each trigger is compiled to its own class
The second rule should not be unknown to Groovy developers, after all triggers in jfx are functions, similar to Groovy's closures (I say similar but not identical, will explain that on another post); Groovy's closures are compiled to their own classes too. Some may say "what about compressing with pack2k? that will reduce the size of the jfx package", sure and that will reduce the size of the others too, so the size-ratio will be retained.

What about the Groovy version? I'm a bit embarrassed as it is not finished yet but here is a glimpse of how it may look
Other than requiring an explicit GraphicsBuilder instance (that will probably change in the future *wink*) this version as a bit shorter on the build code as the native Map syntax is really helpful here, but I believe the token count may be a bit bigger than the jfx version given that commas are required to separate each property when declaring the shapes.

graphics graphicsbuilder groovy java java2d javafx jfx jsilhouette
I'm pleased to announce the release of jSilhouette 0.1, a collection of Java2D shapes. Any of you that have followed this blog on the past knows that GraphicsBuilder bundles additional shapes to the set found in the java.awt.geom package, like Arrow and Cross, well jSilhouette provides those additional shapes sans Groovy, i.e, in a standalone distribution (GraphicsBuilder will be retrofitted to use the new package). This means the following shapes are now at your disposal: Arrow, Balloon, Cross, MultiRoundRectangle, Rays, RegularPolygon, RoundPin, Star and Triangle (some examples here, here and here). But wait, there is more! jSilhouette also includes SceneGraph and JavaFx Script friendly distributions.

jSilhouette is available under GPLv2 with classpath extension, the same license used by Java and JavaFx Script.

Feedback is always appreciated.

announcement graphics graphicsbuilder groovy java java2d javafx jfx jsilhouette
I'm pleased to announce that version 0.2 of the J2D plugin for Grails has been released. This version adds support for SVG output and image caching. It also solves a terrible problem that rendered the previous version quite unusable in reloading scenarios.

In order to cache an image you will have to specify two new parameters
name - the name of the file where the image will be saved (without file extension) ttl - (time-to-live) how long will the cached image will be valid (in milliseconds)
Feedback is always appreciated

Keep on Groovying!

grails graphics graphicsbuilder groovy j2d plugin
I'm pleased to announce that GraphicsBuilder 0.6 has been released. It has many updates and finally makes public both SVGRenderer and SWFRenderer. Here are a couple of posts that describe what's included in this release: The doc site has been updated with an alphabetical index of all available nodes and their properties.

Feedback is always appreciated.

Keep on Groovying!

graphics graphicsbuilder groovy java2d swing
Continuing with the Substance related additions, it is now possible to use Fractal Flames as texture filters. I was very impressed by Kirill's demo on Fractal Flames, even wanted to add them to GraphicsBuilder ASAP. Well it took a bit longer than that but now it is done. Check it out

[image]

Fractal Flames require SubstanceColorSchemes in order to work, you can reference a predefined one using smart builder variables, like limeGreenColorScheme (which is actually an instance of LimeGreenColorScheme); you may also use the colorScheme node, which will automagically translate its value into a predefined SubstanceColorScheme. The following are equivalent calls for obtaining a LimeGreenColorScheme
colorScheme( "limeGreen" ) colorScheme( "lime green" ) colorScheme( "lime_green" ) colorScheme( "LIME GREEN" )
As Kirill notes, generating a fractal flame is a costly operation, depending on the number of iterations and the type of function (IterativeFunctionSystem) that you use to generate them. This filter will try its best to keep a cached result of the generated fractal, calculating it again only when a visible property has changed value.

Keep on Groovying!

graphics graphicsbuilder groovy substance
Kirill has been busy lately updating Substance with new features, a recent post on his blog shows button shapers in action. Suddenly realized that supporting those shapes in GraphicsBuilder would be quite easy, and so graphicsbuilder-ext-substance was born. Here is a sample image

[image]

Once the shapers were wrapped with a ShapeGraphicsOperation (actually just one shaper was required) the rest of the work was just wiring property aliases. Here is the code that produced the image

You can find other goodies in the Substance Extras pack, like fractal flames. Imagine a filter based on those :-D

Keep on Groovying!

graphics graphicsbuilder groovy
GraphicsBuilder has had SVG support for some time ago, but it only supported transforming SVG documents into groovy code. Not anymore! it now is capable of writing SVG documents too, thanks to SVGRenderer. I must confess that Batik is the real workhorse here, as it provides a very handy SVGGraphics2D class (a subclass of Graphics2D), writing svg is just a matter of pluggin an instance of that class into a GraphicsContext, execute the code and write the result. To show you how easy it is here is the previous SWFRenderer example but with SVG this time

This code produces the following SVG output

Because SVGRenderer uses a Graphics2D subclass all other nodes are automatically supported, this means gradients, filters, images, ... neat!

Keep on Groovying!

graphics graphicsbuilder groovy svg
The initial announcement of SWF support in GraphicsBuilder was well received, I decided to follow João's advice and switch from Ming to Transform SWF, as Ming is quite behind in the feature department and Transform has been updated constantly and recently.

Here is a very basic example of SWFRenderer in action, as it only supports groups, shapes and outlines for the time being (basic fills, no fancy paints), the image on the right was produced by GraphicsRenderer, the one on the left by SWFRenderer (you can tell because it uses Flash's plugin ;-))
[image]


You may be wondering about the code, so here it is

No extra nodes required for SWF rendering so far, but I guess as the renderer gets fancier it may support SWF only nodes. SWFRenderer accepts optional settings like background color and frameRate, but I'll show how to use them in a later post. There is a "side-effect" from switching to TransformSWF, that library is able to read SWF files by creating an internal model, which although it is a bit tangled at first (the SWF model that is), may enable importing SWF drawings into GraphicsBuilder's drawings ... :-D

Keep on Groovying!

graphics graphicsbuilder groovy swf
It was bound to happen, once I rediscovered the Ming library through vnc2swf while making screencasts I knew I had the tools to output SWF files using GraphicsBuilder.

Ming offers various language bindings, fortunately one of them is Java, problem is that Ming is currently on 0.4beta but the java extension is on 0.3. Another problem that I found (which was quite annoying) is that the java extension declares all its classes in the default package, somehow making Eclipse & Maven complain while importing the classes. Lastly that extension is built using a Makefile, which may be understandable from the point of view that it is really old code and that it has some native code too.

So the first task was putting ming-java up to date, rolling an Ant based build, even enabling native compilation through the cpptasks from ant-contrib; also moved the classes to net.sf.ming package so no more import conflicts. The code seems to be tied to linux but I believe it may be possible to compile the native library for other OSes.

On the Groovy side, there is a new extension called graphicsbuilder-ext-swf which is responsible for converting from Groovy to SWF, the really good news? you can use the same syntax, the same nodes, nothing has changed :-) This extension has put into evidence some pain points in the API that may also help in making groovy2svg (might as well finish the other side too, right?). Right now it supports transforming basic shapes and color fills, more to come later.

Keep on Groovying!

graphics graphicsbuilder groovy swf
When I wrote Groodle #3 I mentioned that JavaFX had a better syntax to enable and handle dragging of a shape, GraphicsBuilder's version is definitely more verbose but allows you to drag shapes, images and groups. Well not anymore, now all displayable nodes have a new property autoDrag, that when set to true will allow dragging of said displayable. The actual code is exactly the same but it allows you to set additional behavior and react to a displayable being dragged. Groodle #3 can be updated as follows

I also updated the code to follow Joshy's version, now that dropShadow and reflection (from Swingx) are also available as filters, I can finally render a shadow whenever a piece of clothing is dragged. Instead of creating a new filter each time (as in the jfx version) the shadow filter's enabled state changes according to the situation.

Screencasts of all Groodles are available too (thanks to vnc2swf, I love being back to Linux)
Keep on Groovying!

graphics graphicsbuilder groovy
Back to Joshy's latest doodle, I managed to get something out after meddling with GraphicsBuilder's recent updates. So here goes

[image]

There were some minor problems along the way, like shadow filter not working as expected (this filter is not based on the one provided by Swingx), that is why I choose to use shapes instead of images, updating the border while dragging instead of applying a shadow filter.

Let's step into each element of this groodle, first we will look at each shape, starting with the frog face. If it looks familiar is because it is based on the multipaint sphere example
Well, that was easy, now for each draggable piece of clothing. They are simple shapes, some area operations, and the hat has a pair of filters to give it a little depth (these pieces of clothing are not as nice as Joshy's hand drawn ones)

One last touch before ending the build closure is attaching a Swing button (not shown in the image) that will reset the position of all pieces of clothing. Thanks to Groovy's closures and having ids associated with each piece the code is pretty straight forward.

We reuse the each/closure trick outside the building closure to assign the mouse event handlers to each piece

Alright, so now we must define 3 closures to handle each event and then we are done, right? well almost. It turns out it is not so easy to do drag&,drop with gfx, at least not in as many lines as its jfx counterpart, because as of today d&d support is not automatically included. If you look closely at the jfx example you will notice that it is just a matter of binding e.dragTransition.[x,y], hopefully it will be too in gfx during the next days. For now let me show you how it is done, there is definitely room for improvement so if anyone notices something please let me know! :-)

As you can see the code is a bit verbose right now but it gets the job done, looks similar to the revisited dragging example previously posted. I have posted the code for this and the other groodles here, you can take them for a spin as soon as GraphicsBuilder 0.5 is released.

Keep on Groovying!

graphics graphicsbuilder groovy javafx jfx
Joshy has posted Doodle #3, a basic yet interesting make-your-character demo using JavaFX. The interesting part being that the demo displays draggable images, I'm so happy I revamped event handling recently, but before getting to work with Groodle #3 I'd like to present a couple of new things you can do with GraphicsBuilder. Suppose you have the following Gfx demo running

[image]

there are 3 "shapes", actually the green square pair is a group, here is the relevant code

All "shapes" have the save event handler, you are probably wondering if it is the same as the one showed previously here, which looks like

But sadly it will only work for the rect node as the other two do not have a set of [x,y] properties (as a matter of fact an exception will be thrown), so what can we do to solve this? Luckily these operations support transformations so we may attach a translate transformation to them. Ok, but setting [x,y] is much simpler no? and surely it would be the same case if we could access the centre's coordinates of the star, right? Lastly, there is a gotcha using translate, how do we find out the correct offsets to set the relative [x,y] ?

Fear not because this is exactly what this post is about, all of these problems can be solved one at a time. All "displayable" operations (shapes, outlines, images and groups) share a common ancestor that provides a new set of methods useful in this situation
hasCenter() - returns true if the operation has [cx,cy] properties hasXY() - returns true if the operation has [x,y] properties bounds - returns the bounding rectangle, this value is calculated after the operation has been executed, so you can't access it with a beforeRender handler (it will be null).
Ok, those methods will help with the first two shapes (square and star), what about the group? let's look at the code and find out, shall we?

The trick is storing the [x,y] coordinates of the shape's bounds the first time the event is processed, as they will be updated during the next repaint, making a mess if you use them as is. In order to solve this problem operations (and filters) now have a built-in extra set of properties (the props property in shape) that work pretty much as client properties do for Swing components, they are even observable too thanks to ObservableMap, so don't forget to register a PropertyChangeListener with props if you want to receive notifications when a key is updated. Note how named nodes are also used to query for a translation node, either to create a new one or update its settings.

Keep on Groovying!

graphics graphicsbuilder groovy
It all started when my good friend Alex suggested that nodes built with GraphicsBuilder should have a name property as Swing components do (I wonder what he may have in mind ;-)) and it turned out to be a good idea, complementing the recent updates on event and render handlers.

As shown in a previous example, you may navigate a node's children using a ops property, which is actually a List, using array subscript notation, but with names now in place it is also possible to use a map-like notation to get a hold of a nested node. This feature has been extended to transformations, filters, paints and paths as well, so now you are able to get a reference to those nodes using either an index or a name.

Here is a list of the properties you may use in this way
ops - returns an OperationGroup representing the nested operations, available in all operations that support nesting. txs - returns a TransformationGroup representing any tranformations to be applied locally to the node, available in all operations that support transformations (clip, viewBox and gradientPaints too). filters - returns a FilterGroup representing any filters to be applied on the node, available in all operations that support filters paints - returns a List of PaintProviders, available in multiPaint only paint - returns a PaintProvider or a MultiPaintProvider if there is any paint defined for the current node, available in shape operations. borderPaint - returns a BorderPaintProvider if there is any defined for the current node, available in shape and outline operations. stroke- returns a StrokeProvider if there is any defined for the current node, available in shape and outline operations. paths - returns a List of PathOperations of a path node (or ExtPathOperations if it is a xpath node).
Assigning a name to a node doesn't create a variable reference, so it is not a replacement for the id attribute, it works in the same way as it does in SwingBuilder, where components may have a name (a regular property for JComponents) and a id property (a synthetic property used by the builder).

I expect to have the next release ready in the following days.

Keep on Groovying!

graphics graphicsbuilder groovy
If you have followed GraphicsBuilder's examples shown at this blog you have probably noticed that GraphicsBuilder has a lot of similarities with SwingBuilder, both create a hierarchical structure of nodes used to render artifacts to the screen, but GraphicsBuilder's operations are not rendered directly once built, it is the responsibility of a JComponent that understands these operations to call them in the context of a paint operation, as it is the case of GraphicsPanel. You can say that GraphicsBuilder has a design nature (the hierarchical structure of nodes) and the JComponent takes care of the runtime nature.

Because of these two natures you can't reach the graphics context while building (as it doesn't exist yet) and once you draw the artifacts on the screen is too late. This is the reason why every GraphicsOperation now has a pair of properties beforeRender/afterRender that take a closure as value, the runtime nature of the operations will assert that they are called at the proper time.

So now that we have access to the graphics context, what can we do with it? the following example shows a rectangle (presumably a background rectangle) that will always cover the full extent of the JComponent as it keeps in sync its width/height property with the JComponent's dimension

There is no ComponentListener registered to keep the sizes in sync (though you could register one inside beforeRender) so in order to see the effect, you can resize the painting panel and click on the rectangle, that will trigger a property change which in turn will trigger a repaint on the panel, drawing the rectangle with updated dimensions. It is worth noting that even though you can change an observable property that may affect the visuals of the operation using this new option, PropertyChangeEvents won't be triggered while the closures are executing, otherwise an infinite loop would happen.

Granted this is a cheesy way to have an operation react to its containing component, I'm looking at a better option to lazily bind this behavior in a simpler way and not using the existing bind() node (which is also an option but requires that the panel/component be created before the graphics operation).

Keep on Groovying!

graphics