With respect for Kathy

Go Kathy!Kathy Seirra, one of the top three bloggers that I know of has been under attack. The short story is some people thought it would be comical, daring, or cool to slander the woman over the internet for whatever reason. The entire situation is foolish but you can’t easily stop something as powerful as the internet once it turns against you. I only have a small set of readers that frequent my pages, and I’m thankful for each one of you. I’m going to follow Scoble’s lead and refrain from posting or commenting at all during the following week in respect for Kathy. (I do realize that I may loose most of my loyal readers since I’m not as powerful or as cool as Joel or Rory but it’s something that I feel is necessary. It’s all good though because I got John Blaze stuff here, y’all just ain’t reckognizin’!!!) That’ll give me more time to actually work on GSpec as well as some other things. You can continue to post comments, hollaback, and drop it like it’s hot (unless of course it is really not all that hot and rather easy and comfortable to hold onto), I’ll respond to everyone and everything in a week. Support Kathy!If ya’ got a blog and ya’ wit’ me then take a moment of silence in support. If you don’t have a blog but yer’ still with me then join in the moment of silence by meditating on my man Cuba Gooding. (Show your further support for Kathy and Cuba by checking out one of his DLLs.) In parting I’d like to remind everyone that reads me, be careful of what you post on the net because once it’s out there, it’s impossible to take it back.

Groovy Invaders II

Yesterday I began a trail on my development of the classic Space Invaders using Groovy. So far I only shared my Maven “pom.xml” which I will use to build my final project. I’d eventually like to execute the project with Maven if possible/practical but since I’m still a newbie I’ll stay content with a basic Maven build. Let’s move onto the code for the game. I explained yesterday that if you wanted to follow along you should create a folder named groovy-invaders somewhere on your hard drive to hold all of our hard work. It doesn’t need to be called groovy-invaders at all; you can call it whatever you wish. (Name the folder “crap-that-occupies-my-time-when-i-should-be-working” if your operating system supports really long folder names.) The code in my little series is all based on code found in a tutorial here.

The Game Logic
The majority of my trail will be a shameless copy from the original tutorial with some minor modifications here and there as I attempt to put my personal touch on it. If you are familiar with Groovy and see a better way of writing a particular line of code, drop a line and I’ll incorporate it in the tutorial. I’ll start with the core “Game” object which is defined in “Game.groovy”, and explain what it is and how it works as I understand it. (Hint: Now would be a really nice time to right click inside of your folder you created earlier and click the “add new text file” feature of your file system browser. Or do the same with your IDE if you’re using one. Name the file “Game.groovy”) I’ll explain things at a high level then supply code to illustrate what I’m doing. I encourage you to vary your logic from mine because I’m varying mine from the tutorial as I follow it. As I follow the tutorial I try to code from the explanation rather than reading and copying the example and using the explanation to decipher afterwards.

The Game object extends java.awt.Canvas. Why java.awt? Well from what I’ve learned in various Open GL writings and Java Gaming articles, java.awt plays much better with accelerated graphics than Swing. Probably because it’s all heavyweight, close to the native and stuff. The idea is the accelerated drawing can happen in a java.awt component which you can mix in with your Swing application. (There are some issues with mixing AWT and Swing you should be aware of.) Our main Program Entry Point (or PEP as some call it) will merely instantiate Game and throw it into a game loop. You can include the PEP logic right in Game or create a separate file. Whatever you see fit. The game is responsible for creating a window or a frame and embedding itself into it. The game loop will be defined in Game and is responsible for all of the high level logic running the game.

Are you following along? If so then you may have guessed or imagined the following in Game.groovy:

   public Game()
   { //Here we create a frame and draw ourselves to the screen   }

   public Game gameLoop() { //core logic goes here }

   public static void main(String[] args)
       def g = new Game()

Drawing the Game
The most important piece of our project concerns creating the frame and drawing to the screen. I’ll explain a little about the technology we’re using. Because we want accelerated graphics we take advantage of the Java 2D API. Eventually our trail will take us to a refactoring where we’ll pull Java 2D out and do the rendering with the JOGL API over Open GL. (I’m not sure if that last sentence makes sense, I’m just throwing tech terms at you so you’ll think I’m smart.) In our Game constructor we’ll create a frame and get a reference to it’s content panel, set the panel to 800×600 dimension, and set the panel layout to null. Then we’ll disable window resizing (cause this is a game and we don’t want to have to truncate the action or deal with resizing graphics on the screen), add ourselves to the content panel, pack the frame and set visibility to true. There’s two things in our Canvas sub-class to pay attention to at this time. We have to tell AWT not to repaint the screen because we’re doing low level accelerated drawing. We also need to define our buffering strategy and get a reference to it. My code looks like this:
    public Game()
        def container = swing.frame(title:"Groovy Space Invaders",
        def panel = container.getContentPane()
        panel.setPreferredSize new Dimension(800, 600)
        panel.setLayout null
        setBounds 0, 0, 800, 600

        setIgnoreRepaint true
        container.setResizable false
        container.setVisible true

        createBufferStrategy 2
        strategy = getBufferStrategy()

(Yours can look better or worse. The idea is to get a feel for the API by using it rather than watch how I use it and copy text.) Note how the strategy variable is not defined in the constructor. I am caching it in an instance member for later use.

Game Loop Logic
Here is where the bulk of my innovation begins. As I read the tutorial it explains the loop works as follows:

# Work out how long its been since we last looped
# Process any input from the user/player
# Move everything based on the time since last loop
# Draw everything on screen
# Swap the buffers over to make the new image visible
# Wait for a set period

To me, that evaluates to this here Groovy code:
           elapsedTime = calculateElapsedTime()

I initially used something similar to the above code with an additional method call to a moveSprites() method but as I followed the tutorial certain things didn’t line up correctly, forcing me to tuck the movement logic into the draw method. Pay close attention to that code because it may refactor some more as we move along. I’m calling it quits for now. (“Hey, we only wrote two or three methods? C’mon! Let’s keep it movin’!”) I have work to do so you can dream about the remaining programming or you can read ahead on the other tutorial and get ideas. Show me some love in the comment section and I’ll hit’cha back…

(Showing love is a brotherly way of expressing ones ideas and innermost thoughts. In no way does it referr to an intimate relationship of any sort. As the author promises to “hit’cha back” the only desire is to respond to any “love” or comments included in the trailer of the post. Punches are not implied and violence is not tolerated.)

Previous Part Next Part

Groovy Invaders

Update!! I’m adding more info about setting up the project at the tail end of this post. Please read after the Maven2 pom.xml to see the updated information.

What’s up party people??!! I’m off and running with a series devoted to creating the classic SpaceInvaders game using Groovy as my programming language of choice. Those of you who have been following me posts will recall that I’ve been wanting to post something on Open GL and Groovy. Here’s a short history on that idea. I found a simple JOGL Java tutorial that I re-coded with Groovy and tried to run. This is what was supposed to happen afterwards. I would run the code which would result in a screen with a really exciting triangle drawn on it. I would then post the code here and tell you all how cool I am because I can draw a triangle and you can’t. I would then spend another day or two reading and recoding and have Doom 3 implemented completely in Groovy while bragging some more on this here blog wagging my finger at nay sayers that don’t believe Groovy is worth a dime. Here’s what actually happened. I finished writing the code and hit run. I cussed because I got an error explaining something about a native library couldn’t be locted. I cussed some more after fixing that minor problem and a couple of other dumb issues. I finally got all jars and native libraries installed for JOGL, ran the code and found out that the example must have been using an earlier implementation of JOGL than what I was using. I browsed the net some looking for more up to date examples and cussed some more. I then resolved to do the one thing that would benefit neither me nor my employer in any way, write a video game using Java 2D. (Learn to walk before you run!) And now, here we are.

Groovy Invaders
I’ll begin my series with the link to the finished product (created by someone else in Java for the purpose of this tutorial) demonstrating what my hard work should look like at the end. I’ll also include a snippet of my Maven2 project descriptor because, well, I’m using Maven2 for everything nowadays.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <name>Groovy Space Invaders</name>
                                <taskdef name="groovyc"
                                    <classpath refid="maven.compile.classpath"/>
                                <groovyc destdir="${project.build.outputDirectory}"
                                    srcdir="${basedir}/src/main/groovy/" listfiles="true">
                                    <classpath refid="maven.compile.classpath"/>
                                <taskdef name="groovyc"
                                    <classpath refid="maven.compile.classpath"/>
                                <mkdir dir="${project.build.testOutputDirectory}"/>
                                <groovyc destdir="${project.build.testOutputDirectory}"
                                    srcdir="${basedir}/src/test/groovy/" listfiles="true">
                                    <classpath refid="maven.test.classpath"/>

That code is tucked in a little file named “pom.xml” that I nested in a folder called “groovy-invaders”. If you want to follow along I suggest you right click somewhere in Windows Explorer or Konqueror or what ever you use to browse your file system and create those same two artifacts. I’ve tested the Maven2 pom against my groovy invaders project and verified that it can compile all Groovy source and run all Groovy test cases. That is an important item to note because a few people have asked how to get Groovy source and Groovy tests integrated with Maven.

Updated setup information
To setup for development you may use Maven, Maven2, Ant, Eclipse, Idea or whatever you’re comfortable with. I will be following Maven2 conventions for the layout of the project and that should work just fine in most build tools and IDEs. I will assume you are following a similar structure which would indicate the Groovy source will be compiled before running it. It is not necessary to compile Groovy I will be compiling throughout the tutorial. The structure by convention will include everything under a project folder labeled groovy-invaders. In the project we will use “src/main/groovy” as the home for all of our Groovy source code. The package name I use is com/craig/groovyinvaders so most of our Groovy source will live unders “src/main/groovy/com/craig/groovyinvaders”. We will also use “src/resources” as the home for anything else that needs to be on the classpath for our application. (Our graphics will live in a folder called sprites in this directory.) In the root of the project folder we will keep our Maven2 project descriptor (the pom.xml file).

That’s all for today. I’ll start filling in the blanks with code later. Until then, holla at me…

Next entry in the series

Groovy and Open GL

I’ve been occasionally folling with Groovy and Open GL on the side but I have had any radical success. So far I managed to find a quick start tutorial on JOGL and rewrite the code using Groovy. (The rewrite consisted of a copy and paste and the removal of one anonymous inner class.) While I’m not thrilled at my success I am thrilled at what I found on the net… a tutorial for Space Invaders 2d/3d! Now let me explain. My days of being a video game addict are long gone and I haven’t played any games in over a year. The last time I played anything I didn’t feel the same addiction that would keep me up for hours through the night. I think I’ve out grown video games a little. I said a little. I still love them and I’m still partially interested in creating my own game as I was so many years ago in my youth. More important I believe the aformentioned tutorial is an excellent starting point for someone like me who has little if any knowledge on UI or Open GL. I feel like I really need to sit in front of some text and read up on it as much as possible and the tutorials are inspiring.

Why Open GL? Well I saw a video stream of one of Romain Guys presentations of his Aerith project and I heard him mention that he used Open GL in some Swing components to acheive some of the effects. Let me tell you. I’ve been loosely following this guy’s work and I’d be proud to recreated a small percent of what he has done in Swing. Ever since then I’ve been on a quest to design a spectacular UI using Groovy and Swing. Romain Guy shows us what you can do in Swing so I see what’s possible. I also know how much fun it is to work with Groovy so that’s what has been flaming my passion.

Getting to the point. Let me share a little of what I’ve done so far. (It ain’t much.) I downloaded the JOGL API and it’s native binaries for Linux. I set my library path in the startGroovy script (so I could work from Groovy console) to include my $HOME folder. I placed the JOGL jar in $GROOVY_HOME/lib and expanded the native jar in my $HOME folder. I started Groovy console, copied and tweaked the code from the first Open GL tutorial I found and ended up with this:

import javax.media.opengl.*
import com.sun.opengl.util.*

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestRenderer implements GLEventListener
   private GL              gl;
   private GLDrawable      glDrawable;

   public void init(GLDrawable drawable)
       this.gl = drawable.getGL();
       this.glDrawable = drawable;

       drawable.setGL( new DebugGL(drawable.getGL() ));

       System.out.println("Init GL is " + gl.getClass().getName());

   public void display(GLDrawable drawable)

       gl.glColor3f(1.0f, 0.0f, 0.0f );

       gl.glBegin( GL.GL_TRIANGLES );
           gl.glVertex3f( 0.0f, 0.0f, 0.0f );
           gl.glVertex3f( 1.0f, 0.0f, 0.0f );
           gl.glVertex3f( 1.0f, 1.0f, 0.0f );

   public void reshape(GLDrawable drawable, int x, int y, int width, int height)

   public void displayChanged(GLDrawable drawable, boolean modeChanged, boolean deviceChanged)


public class InnerWindowListener extends WindowAdapter {
      def animator
      public InnerWindowListener(def animator) { this.animator = animator }
                public void windowClosing(WindowEvent e) {

           Frame testFrame = new Frame("TestFrame");
           testFrame.setSize( 512, 384 );

           GLCapabilities glCaps = new GLCapabilities();

           GLCanvas canvas = new GLCanvas(glCaps);

           testFrame.add( canvas );

           canvas.addGLEventListener(new TestRenderer());

           final Animator animator = new Animator( canvas);
           testFrame.addWindowListener(new InnerWindowListener(animator));


All I get is a grey screen when I run it. Failed attempt If anyone can decipher what I’ve done wrong then please holla back…

Open GL

I’ve not had much time to work with Open GL under groovy as I planned but that will change today. I made a commitment to do two things:

  • Figure out what the heck Open GL is
  • Write my first hello world Open GL app with Groovy

Now some people would wonder why write Open GL from a scripting language? Aren’t scripting languages inherently slow and isn’t Open GL all about performance? (Isn’t it? I don’t know I’m guessing here.) Groovy is more than a scripting language. It has been defined as a dynamic language for the JVM. As I see it Groovy is an alternative syntax to Java since it too can be compiled to bytecode. What that amounts to is the ability to do anything Java can do but with a looser syntax. So it makes perfect sense, given these parameters, to write Open GL or anything else you would write in Java using Groovy.

Since we’re talking about Open GL I thought I’d mention my experimenting with the notorious Korrora Linux distribution. It’s notorious for being one of the only Linux Live CD distros to bundle proprietary video drivers and as such violates the licenses of the Linux kernel itself. (My personal opinion on the license to the kernel is that such restrictions become senseless barriers when you wish to roll your own distro. Maybe they should be rethought a little?) Korrora is a very visually appealing distro at first glance when booting from the live disk. It includes not only the official NVidia driver but the XGL and Compiz combination that allows for all the really slick visual effects like 3D desktop switching, true transparency, and window distortion. (I like the distortion feature where dragging a window results in a inertia effect causing the window to strecth and wobble.) All of this is made possible by the XGL graphics system which uses Open GL for rendering. I wouldn’t consider installing Korrora though, because it’s Gentoo based and from my understanding Gentoo is one of the more complicated distros better suited for Linux pros and gurus. Also KDE, my choice desktop environment, is not well integrated with the newer XGL and Compiz stuff. Until that issue gets fleshed out I’m staying away from both Kororra and XGL.

Back to the point. I’m heading into Open GL today. Look out for the blow by blow as I move along. So far I’ve managed to download the stuff, run some example code and get an exception. Not very interesting but the fun is yet to come. Hollaback…