Processing with Jython and Nodebox/Shoebot libraries

Posted by stu at February 10th, 2010

Using Processing from Jython is a promising idea, so I took the base from this post on backspaces.net where they explained how to use Jython and built on it a little.

This is great as Shoebot/Nodebox have great libraries for data manipulation, while processing is more focused on graphics.

The result is the attached Netbeans project which demonstrates using the nodebox web library and  drawing with processing.

Slowcessing

The glue code is in slowcessing.py

Theres a special version of PApplet (PJApplet), and ‘pj_frame’ which can put this in a JFrame.

The other method is ’shoebot_imports’ adds the shoebot imports to the library path

In case anybody doesn’t want to download the whole project, heres the code:

imagestrip.py

from slowcessing import PJApplet, pj_frame, shoebot_imports
from processing.opengl import *

shoebot_imports()
import web
import thread

class ImageQueue(list):
    """
    Download images in the background and add them to a list
    """
    def __init__(self, search, size):
        list.__init__(self)
        self._search = search
        self._image_size = size
        thread.start_new_thread(self._get_images, ())

    def _image_downloaded(self, path):
        p = PJApplet()
        self.append(p.loadImage(path))

    def _get_images(self):
        for image in self._search:
            image.download(self._image_size, asynchronous=False)
            self._image_downloaded(image.path)

class WebTest (PJApplet):
  def setup(self):
    self.size(400, 400, self.P3D)
    self.images = ImageQueue(web.morguefile.search("sweets", max=1), size='small')

  def draw(self):
    self.background(0);
    y = (self.height * 0.2) - self.mouseY * (len(self.images) * 0.58)
    for image in self.images:
        self.image(image, 20, y)
        y += image.height

if __name__ == '__main__':
    pj_frame(WebTest)

slowcessing.py

from javax.swing import JFrame

from processing.core import PApplet

class PJApplet(PApplet):
  # rqd due to PApplet's using frameRate and frameRate(n) etc.
  def getField(self, name):
      return PApplet.getDeclaredField(name).get(self)

def pj_frame(pj_applet, **kwargs):
    from time import sleep

    frame = JFrame(kwargs.get('title', 'Slowcessing'))
    frame.defaultCloseOperation = kwargs.get('defaultCloseOperation', JFrame.EXIT_ON_CLOSE)
    frame.resizable = kwargs.get('resizable', False)

    panel = pj_applet()
    frame.add(panel)
    panel.init()

    while panel.defaultSize and not panel.finished:
        sleep(0.5)

    frame.pack()
    frame.visible = 1

    return frame

def shoebot_imports():
    """
    Allow import of the shoebot libraries
    """
    ##APP = 'shoebot'
    import sys
    DIR = sys.prefix + '/share/shoebot/locale'
    ##locale.setlocale(locale.LC_ALL, '')
    ##gettext.bindtextdomain(APP, DIR)
    ###gettext.bindtextdomain(APP)
    ##gettext.textdomain(APP)
    ##_ = gettext.gettext

    LIB_DIR = sys.prefix + '/share/shoebot/lib'
    sys.path.append(LIB_DIR)

Problems

There are some things I couldn’t work :

The callback to say that images have been downloaded happens before the whole file is available, for this reason there are grey parts on the images on the first run.

Nodebox web…

While I did manage to fix things to get this working in Jython and get Morguefile working, I had a lot of trouble understanding what was going on here.

Processing…

Some parts of PApplet to do with image loading seem to be static, which may also explain problems I was getting.

Download

If you want to have a go, you’ll need to:

Install Netbeans 6.8

Install Jython by installing the Netbeans python module

Add python to the path (if using Netbeans it’s copy is where Netbeans is installed).

Download my fork of shoebot-web and install it with:

jython setup.py install

In Netbeans, add all the jars in the processing\lib folder to the Jython classpath, and opengl\library\opengl.jar

Download the PythonOnProcessing (tested on Netbeans 6.8)

Posted in projects| 2 Comments | 

Using Cairo to generate SVG in Django

Posted by stu at February 3rd, 2010

Cairo is a 2D vector graphics api used by Firefox, Gtk and other desktop projects.

I’m going to show here that it can also be used to generate web content, using Django.

I’m going to port two examples from the Michael Urmans Cairo Tutorial for PyGTK Programmers.

To understand the cairo and it’s drawing model I’d recommend his his Cairo Tutorial for Python Programmers.

Note: In this example I’ll be generating SVGs…  as I.E. (as of 2010) does not support them, you might want to generate PNG or PDF – if you need to do this with cairo, look for one of the many cairo tutorials on the web.

The example django project can be downloaded at the end of the article.

(more…)

Posted in projects, web| 6 Comments | 

Using Java2Python to port a JavaCairo tutorial

Posted by stu at August 21st, 2009

I recently came across Java2Python.  As I’m interested in Cairo I thought it would be interesting to try porting one of the example tutorials from ZetCode.

I’ll run through the steps involved in porting then try and reach some conclusions at the end :) .

1. Get setup

This is easiest in Linux, I’m running Ubuntu (in vmware), and installed

antlr 2.x
python2.5.x
sun java6
pygtk
java-gnome

You can install them like this:

# sudo apt-get install antlr python2.5 sun-java6-bin libjava-gnome-java

Then install Python2Java with easy_install

# sudo easy_install-2.5 java2python

To test if it’s working run j2py -i.  It should complain there is no file:

# j2py -i
Usage: j2py [options]

j2py: error: -i option requires an argument

If you get any other errors your missing some packages.

2. Get the Java Code from the Simple Example.

Save the ’simple.java’ example as ‘GSimple.java’

If java-gnome is running ok, compiling and running it you should see a window:

# javac GSimple.java
# java GSimple

gsimple

Now we’ll run through the code, it’s important to understand what it does before we port it…

(more…)

Posted in Uncategorized, projects| 9 Comments | 

Flex for developers – Bootstrapping

Posted by stu at November 29th, 2008

A lot of information on the web is aimed at people who use flashdevelop and other guis to build flex apps, this article is aimed at developers.  I’ll give you the information to get started with flex development quickly, using the free sdk and building with ant from the commandline.

A passing knowledge of ant wouldn’t hurt either.

This tutorial uses the file blankapp.zip to help bootstrap you into the world of flex / actionscript development.

Prerequisites

Flex SDK

You will need the flex sdk available from the flex developer center

Apache ant

You will need apache ant, make sure that the bin folder is in your path.

Copy flexTasks.jar from the flex ant lib into your own ant lib folder.

Setup

Extract the blankapp.zip to a folder

Open build.xml and change the line <property name=”FLEX_HOME” value=”/usr/flex/sdk3″ /> to point to the flex sdk.

Build

You can build it by typing

ant build

You should see some output like this

Buildfile: build.xml

clean:
   [delete] Deleting directory C:\Documents and Settings\Stuart\Desktop\projects\flex\blankapp\build

init:
    [mkdir] Created dir: C:\Documents and Settings\Stuart\Desktop\projects\flex\blankapp\build

build:
    [mxmlc] Loading configuration file C:\usr\flex\sdk3\frameworks\flex-config.xml
    [mxmlc] Initial setup: 172ms
    [mxmlc] Loaded 8 SWCs: 391ms
    [mxmlc] C:\Documents and Settings\Stuart\Desktop\projects\flex\blankapp\src\blankapp_333027.cache (The system cannot
 find the file specified)
    [mxmlc] Files: 328 Time: 1562ms
    [mxmlc] Linking... 16ms
    [mxmlc] Optimizing... 125ms
    [mxmlc] SWF Encoding... 47ms
    [mxmlc] C:\Documents and Settings\Stuart\Desktop\projects\flex\blankapp\build\blankapp.swf (159158 bytes)
    [mxmlc] Persisting 33 compilation units... 15ms
    [mxmlc] Total time: 2328ms
    [mxmlc] Peak memory usage: 59 MB (Heap: 33, Non-Heap: 26)

BUILD SUCCESSFUL
Total time: 2 seconds

A new file, blankapp.swf should now be in the build folder

Type

ant deploy

To copy it to the deploy directory (later you can customise this later).

If you open the blankapp.swf in the browser you should see something like this

It’s fairly bare, but demonstrates some basic techniques and a couple of widgets.

Mxml and Actionscript, how they link together

There are two important parts, the blankapp.mxml and org/blankapp/BlankApp.as.

The mxml file defines the layout while the actionscript contains code to be executed.   In this case there is one mxml file, BlankApp.mxml which links to a single actionscript class, BlankApp (in the file src/org/blankapp/BlankApp.as).

The directory structure org/blankapp, defines the package, in much the same way as java packages.

The graphic below shows how the class is linked to the mxml and where the instance of the class is:

The app is very basic, but should provide a jumping off point.

Adding libraries

If you need to add any libraries, just place the swc files in the lib folder and they will be included, the build.xml can be changed if this isn’t satisfactory.

Afterword

I only wanted to get started with papervision, but found it a bit of hassle to get started, hopefully this post will help people get started quickly.

Acknowledgements

The ant build file is by no means my own, owes inspiration to previous ant files I’ve known, including the pyAMF one and information available on the web.

This blog entry: http://talsma.tv/post.cfm/ant-mxmlc-and-swc-files for the info on how to include swc files.

Posted in projects| 3 Comments | 

Aggregated angst

Posted by stu at October 5th, 2008

A little python, a lot of angst…  for just 3 hours of work this was definitely worth it :)

Click the image to view it in wordle where you can mess with it.

I love the way that Im is the biggest word, you can really see how egotistical they are on grouphug.

(Cheers to Andy for turning me onto wordle and helping with ideas).

Posted in projects| No Comments | 

5 Minute python

Posted by stu at February 26th, 2008

I’ve recently been learning python and decided to note down the *very basics* that took longer to find out than I would’ve liked.

Without furtherado, heres my 5-minute-python.

Posted in projects| 5 Comments | 

Playing a sound in pygame

Posted by stu at February 24th, 2008

It can be useful to test sounds in your current engine (esp for testing MOD support), so I’ve made a tiny sound player for pygame. The code is just this:

import sys, pygame
from pygame.locals import *

import pygame.mixer

if __name__=="__main__":
    pygame.display.set_mode((120, 120), DOUBLEBUF | HWSURFACE)

    pygame.init()

    try:
        filename = sys.argv[1]
        pygame.mixer.init()
        sound = pygame.mixer.Sound(filename)
        print 'Press ESC to quit, any other key retriggers sound'
        sound.play()

        running = True
        while running:
            for event in pygame.event.get():
                if event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        running = False
                    else:
                        sound.play()

    except IndexError:
        print 'Usage tplay.py filename'

The file is attached here: Tiny pygame audio player.

Posted in projects| No Comments | 

Ball breaker update

Posted by stu at November 19th, 2007

Reached a small milestone in my bat and ball game (BallBreaker), the fonts are implemented as bitmap fonts, meaning that everything on the rendered on the game screen is original material.

The current font system is based on tiles, so it should be easy to implement animation and cool stuff next, it definately feels like the project is about 1/2 way to releasable.

Switching to Cairo is starting to seem attractive, especially when making bitmapped versions of the fonts.

For the moment I won’t switch to Cairo as I’m very curious to see what happens to performance when pygame 1.8 comes out.

Another reason I haven’t switched yet is a bit of lazyness – the pycairo msi doesn’t install the cairo dll… and of course the learning that goes with the new API :)

Posted in projects| No Comments | 

Retro font

Posted by stu at October 8th, 2007

I’ve just finished the initial version of the font that’ll go into my game ball breaker (“Ball Breaker Caps”)… Some of the characters need more work, but it has the retro-future look I’m going for.

This means that I can feel happy about putting in the high score table and scrolling messages and they’ll have the look I’m going for.

Posted in projects| 3 Comments | 

Ball Breaker!

Posted by admin at October 5th, 2007

I’ve recently started learning python in earnest, to this end I’ve been writing a bat and ball game. I’m quite suprised at how much you get for your LOC in python… so far it’s about 1,000 LOC and has multiple powerups and bats, plus sound fx by ne7.

Title screen of ball breaker,

Graphics are made in inkscape and the GIMP – ingame screenshot after the cut.  (more…)

Posted in projects| No Comments |