Archive for July, 2007

Using JavaDB and db4o in Processing

Tuesday, July 31st, 2007
Kind of as reply to Tom’s mini howto for using SQLite with Processing, but also since I’ve been dabbling with it myself recently, here’s an alternative take on using an embedded database from within Processing (or more generally in Java)…

Mainly due to Java’s strong focus on server side development, over the past few years there have been several large scale community efforts to create Java native database engines, which don’t rely on underlying C code, are high performant and portable: the essence of the Java way. The other benefit is that such DB engines can be embedded and distributed with your application without requiring any further installation. One such development effort is Apache Derby, a project which started in 1996, swapped owners several times (amongst them IBM) and then became an incubator project at Apache in 2004. Sun also joined the project and has been bundling it as library (under the name JavaDB) as part of the JDK (v6+) since December 2006. So in other words if you have Java6 installed you also should have Derby. But even if you don’t (for example Mac users), you can download Derby from here and unzip it to any folder on your hard drive.

The following deals with setting up Processing to work with Derby:

  1. Create a new folder structure /derby/library within Processing’s /libraries folder
  2. Copy the file derby.jar from Derby’s /lib folder into the newly created folder

Before we can start using the database now we first need to create a new database. Derby comes with its own commandline client “ij” which is located in the /bin directory of the main Derby install dir (If you’re going to use this tool more often it would make sense to add this /bin directory to your system path).

Launch ij from the commandline and then create a new database with this command:

ij> connect 'jdbc:derby:/path/to/database;create=true';

Databases are just folders and can be stored anywhere. For example on Windows the path /dev/derby/mydb would refer to C:\dev\derby\mydb

Next create some a simple table in the new database and add some data:

ij> create table cities (cityID integer not null primary key,name varchar(32) not null);insert into cities values(1,'london');insert into cities values(2,'berlin');insert into cities values(3,'san francisco');

Given that all worked fine so far we can finally move on to a small Processing demo to query our exciting dataset:

import org.apache.derby.*;import java.sql.*;

String driver = "org.apache.derby.jdbc.EmbeddedDriver";String connectID = "jdbc:derby:/derby/testdb";Connection conn;

void setup() {  size(100,100);  try {    query();  }  catch(SQLException e) {    e.printStackTrace();  }}

void query() throws SQLException {  try{    Class.forName(driver);   }   catch(java.lang.ClassNotFoundException e) {    e.printStackTrace();  }

  try {    conn = DriverManager.getConnection(connectID);    Statement st=conn.createStatement();    ResultSet results=st.executeQuery("SELECT * FROM cities");    while (results.next()){      println("City: "+results.getString("name"));    }    results.close();  }  catch (Exception e)  {    e.printStackTrace();  }  finally {    // always make sure we close the connection    if (conn!=null) conn.close();  }}

Now, this is obviously an absolute bare bones demo, however Florian Jennet wrote a little database library last year to hide all these excessive try/catch clauses. Unfortunately he’s also hardcoded the database connection string to only work with MySQL and there’s no source supplied with the library so one could change it and easily add support for other JDBC drivers… (nudge! :)

Speaking of databases, here’s another food for thought. SQLite, MySQL, Apache Derby et al are all based on the relational database model. Java on the other hand is object oriented and as you can see it takes a relative large effort to exchange data between both worlds without any further help. To ease these tasks there’re various powerful object relationship mappers available acting as translators between the worlds of objects and that of SQL. Last but not least, native object oriented databases are yet another alternative approach here which is far more aligned with the language. db4o is such an object database and allows you to store and query complex object hierarchies in a most natural (in a Java context) way. For example with db4o you can store and restore the entire state of an application – with just a single line of code. This in turn not just saves you a lot of time and headaches, but also enables building more complex, data intensive applications. If you’re interested, the db4o site has a very easy to follow tutorial

New software from Protohaus added to the exhibition.

Tuesday, July 31st, 2007

New software from Protohaus added to the exhibition.

A Quick Note on using SQLite in Processing

Monday, July 30th, 2007

SQLite is a great standalone SQL database engine – not ideal for every situation (particularly large websites), but more than good enough to have already made its way into desktop projects from Apple, and more recently Adobe and Google.

My colleague Mike recently used it as a way to distribute data from a 511.org transit website scraping project he’s been doing. I wanted to see if I could download his data (gathered and processed using python) and access it using Processing.

Web searches for SQLite and Java (java wrapper sqlite, etc.) turn up lots of matches, including this promising tutorial from Tim Anderson, but sadly the most prominent matches didn’t work for me. It’s a real pain to get up and running and installed in a reliable way, mainly due to the need to compile SQLite natively for each platform and then talk to the native code using Java.

Enter this amazing project, a JDBC library for SQLite written in pure java that uses NestedVM to compile the C code for SQLite into something any Java VM can use. It’s frightening to think about the amount of misdirection, abstraction and interpretation going on here, but it worked first time and plenty fast enough for my purposes.

Take a look after the jump for the code I ended up with. I hope people find it useful:

(more…)

memories

Monday, July 30th, 2007


memories

Cast: ghedo

String based designs

Sunday, July 29th, 2007
As we delve deeper into the realms of applied generative design and deal with a whole population of possible design outcomes, we often find ourselves preferring certain outcomes more than others and want to narrow down our explorations. So the identity of each such design plays an important role. Identity in this context can be defined by the set of input parameters used, but we also need to ensure the processing of these parameters is deterministic, meaning that even though we often use (pseudo)randomness as part of the algorithm, the outcome should be replicable for each set of parameters.

Most (if not all) pseudo-random generators use the concept of a random seed which subsequently produces a unique (and deterministic) sequence of “random” numbers. In Processing you can use both randomSeed() and noiseSeed() to achieve this. Now while using numbers is all fine, and technically speaking, all digital media is just numbers – there’re use cases where it’d be nicer to use e.g. text as seed directly. For example, the 20,000 designs of the Lovebytes fluffies are all based on their generated character name only. There’re about 10 other parameters, but these too are chosen based on the random sequence seeded by the name.

One way of turning a string into a number is by using message digests, like the popular MD5 or SHA1 algorithms. A message digest takes any number of bytes as input and calculates a fixed length hash. MD5 results in a number 128 bits long and SHA1 160 bits. This is more data than we can cope with since most common random number generators only accept up to 64 bits as input. In Java/Processing this is equivalent to the long type.

The following function takes a string as input, computes the hash and then returns the first 8 bytes as long integer to be used as random seed. Because it doesn’t use the full hash it’s possible in theory to end up with the same result for different inputs. However, I’ve not yet managed to come across a collision with the relative short strings (names, sentences, phrases) used in my work.

import java.security.*;

/** * Calculates the message digest of the given string and * returns the first 8 bytes packed into a long * * @param msg string to form hash from * @param digest message digest ID (e.g. "MD5" or "SHA1") * @return zero if failed, else partial digest as type long  */long getLongHash(String msg, String digest) {  long result=0;  try {    MessageDigest md = MessageDigest.getInstance(digest);    md.update(msg.getBytes());    byte[] buffer=md.digest();    for(int i=0,bits=56; i<8; i++) {      long val=(buffer[i]<0 ? 0x100+buffer[i] : buffer[i]);      result|=val< 

And again, use it like that:

long seed=getLongHash("Hello world!","MD5"); // "SHA1" as alternative
noiseSeed(seed);

Btw. The default Java Random generator does not guarantee to produce a deterministic sequence across all platforms. This means as long you’re using Processing’s default random() or noise() functions you’re only guaranteed the same sequence as long as you stay on either Windows or OSX or Linux. Last year Marius wrote a Processing wrapper for the famous Mersenne Twister generator, however this one can only be used as alternative and in isolation. Processing’s noise() function is hardcoded to use the default Java generator…

Ribbons in space

Saturday, July 28th, 2007

I’ve started working on a new code-driven graphics project in processing using toxi’s vector library which has turned out quite fitting so far. It’s basically a series of pull/push points in space which direct a number of ribbons.

ribbons in space (in progress)

more soon…

COS – July sale projection

Saturday, July 28th, 2007

This month I completed a custom-software installation for COS. It’s all built with processing and is running until the sale ends (mid-August) in the stores in London, Berlin and Stuttgart. This screenshot is from the close-to-finished graphics.

cos - projection 01

…and here is a shot of the final graphics running in-store at the Regent Street store in London. The projection has two main render-modes: 1) a dotted grid cycling through press-photos from the launch of the brand and 2) a typewriter style renderer showing text being typed (with spelling mistakes – which are corrected) and hessitating pauses to simulate a person writing it.

cos - july sale dot-renderer

cos - july sale text-renderer

classwar

Saturday, July 28th, 2007

Another try with the surfaceLib. Now different textures.

Author: eskimoblood
Keywords: processing.org 3d surface visual
Added: July 28, 2007

Processing: Random spheres 01

Friday, July 27th, 2007


Processing: Random spheres 01

Created in Processing. More info at http://www.nofi.org/2007/04/10/processing-random-spheres-01/

Cast: nofi

Processing: Random circles greyscale

Friday, July 27th, 2007


Processing: Random circles greyscale

Created in Processing. More info at http://www.nofi.org/2007/03/29/processing-random-circles-greyscale/

Cast: nofi

Processing: Random bezier curve 02 color

Friday, July 27th, 2007


 Processing: Random bezier curve 02 color

Created in Processing. More info at http://www.nofi.org/2007/03/26/processing-random-bezier-curve-02-color/

Cast: nofi

Processing: Random bezier blur & posterize

Friday, July 27th, 2007


 Processing: Random bezier blur & posterize

Created in Processing. More info at http://www.nofi.org/2007/04/09/random-bezier-blur-posterize/

Cast: nofi

Processing: Random lines vertical sequence RGB 02

Friday, July 27th, 2007


 Processing: Random lines vertical sequence RGB 02

Created in Processing. More info at http://www.nofi.org/2007/03/15/processing-random-lines-vertical-sequence-rgb-02/

Cast: nofi

John Whitney and Digital Harmony

Thursday, July 26th, 2007
    Considering arts techniques from the broad perspective of the present, I observed that the best “computer art” did not compare
    well with lacework from Belgium made a century ago. But the computer possessed a unique capability of making very complex pattern flow. One could plan exacting and explicit patterns of action and distinctive motions as intricate as lace, but in a way no Belgian lace maker would ever imagine. – John Whitney, 1980.

This 1975 film is reportedly John Whitney’s first foray into computer graphics. Until ‘Arabesque’, Whitney used a converted mechanism of a World War II M-5 Antiaircraft Gun. Essentially a twelve-foot-high analog computer of amazing complexity; where design templates were placed on three different layers of rotating tables and photographed by multiple-axis rotating cameras.

In Digital Harmony (1980), the book that describes his life’s work, his hypothesis –

    …assumes the existence of a new foundation for a new art. It assumes a broader context in which Pythagorean laws of harmony operate. These laws operate in a graphic context parallel to the established context of music. In other words, the hypothesis assumes that the attractive and repulsive forces of harmony’s consonant/dissonant patterns function outside the dominion of music.

Whitney acknowledges that, ‘Music does not need images any more than paintings need sound’ but saw in computing, ‘a visual medium which is more malleable and swifter than musical airwaves. That medium is light itself.’

The book often communicates personal opinion rather than rigorous argument but Whitney makes some original and interesting points. It seems Whitney is not really pursuing visualisation or a tightly fused AV form. Whitney’s search is instead for abstract graphics with the fluidity, expressiveness and structural qualities of music. Whitney begins the book by highlighting the inherent spatial and visual qualities of music and damning early ‘visual music’ inventions:

    Most people visualize music as two-dimensional, with time represented by the horizontal lines and pitch by vertically arrayed symbols, as is the convention on paper. But the perception of music is not two dimensional. The ears reside at the center of a spherical domain. We hear from all around. We hear music as patterns of ups and downs, to and fro in a distinctly three-dimensional space – a space within.

    The eye, more outwardly oriented, perceives objects and events outside at the point where our eyes focus. Yet the eye enjoys design equally as well as the ear. The mind’s eye shares with the ear any inward experience of architectonic spatial constructions and would perceive them with the same pleasure, were they to exist.

    The fact is, however, that these interior fluid visual edifices hardly exist. Anyone can visualize an architectural fantasy of music dancing in the head, but manifesting in reality is another matter! Each century since Leonardo, a vision, grand and obscure as its myth, compelled one or two inventors to struggle with the pathetic inadequacies of the color organ. Twentieth-century abstract art has been a training ground for visual response to musical experience, but in the mind’s eye, architecture in motion lies at the root of our enjoyment of music. Many people, with closed eyes at a concert, are “watching” the music, but after all these centuries, there still exists no universally acceptable visual equivalent to music! It should exist and it will soon.

Whitney also documents his and others failed attempts at experimental film based endeavours:

    Pointing their cameras at the world, all those “symphonists” inadvertently recorded the stasis of the world, even as they filmed its busiest moments – its winds and storms and birds and water and city traffic. Those films are not symphonies, I thought, poetry perhaps, but not liquid architecture, not music.

    …wherever I pointed my camera, I failed to discover that special quality of any material possessing the controllable visual fluidity that I desired … pointing my camera anywhere resulted in recording images of somewhere. If the camera’s record is unclear, blurred by the smear of too fast panning or being out of focus, the sense of somewhere as place is simply flattened. The spatial content of an image is flattened. The eye resists the attempt to domesticate abstraction. This sort of deception hardly satisfies the eye, because the sense of being (or seeing) somewhere is so strong. The eye is the natural master of pattern recognition. The eye demands satisfaction by invoking in us strong feelings of puzzlement.

And makes the important point that, “No abstraction in my camera had the generative potential, the capability to propagate fluid patterns or especially, the liquid variability of the intervallic families of music tones.”

This is where the computer comes into play and Whitney’s argument gets interesting. Whitney sees a parallel between musical tones and generative animation. Whitney sees music as an abstract and generative form in itself:

    There is no such thing as the harmonic organization of musical tone in nature. Occasionally a stone may ring like a bell, birds pattern “song,” but there are few natural bells, fewer natural flues where the winds sound organ tones. Even the whistle of the wind is eerie and non-musical. Patterning of musical tones is a man-made reality of the aural world, universally accepted as such, but nowhere looked upon as an abstraction that has been extracted (or abstracted) out of the natural environment, nowhere regarded as a manifestation of the environment.

Whitney in deciding that music is not an abstracted picture of anything, allows for his second level of pure abstraction and generation. He focuses on three qualities applicable to both forms:

    A benchmark was reached when I began to apprehend the relationship of the three terms: differential, resonance and harmony. First, motion becomes pattern if objects move differentially. Second, a resolution to order in patterns of motion occurs at points of resonance. And third, this resolution at resonant events, especially at the whole number ratios, characterizes the differential resonant phenomena of visual harmony.

    What I knew about music confirmed for me that emotion derives from the force-fields of musical structuring in tension and motion. Structured motion begets emotion. This, now, is true in a visual world, as it is a truism of music.

Digital Harmony, the documentation of a life’s work is the most comprehensive study of generative animation and its musical potential that I have found yet. It provides some useful counterpoints when compared to Chion’s deconstruction of audio visual relations. A simple reading of Chion would state that audio is predominately temporal while vision is predominately spatial but Whitney’s musical ‘liquid architecture’ metaphor is a wonderful one. Regardless, I’m starting to side with Chion’s idea of ‘audiovisual illusion’ and perhaps through a lifetime of work and focus, Whitney has merely become a better magician.

This is not to say Whitney is wasting his time. Magic is an art form. This also doesn’t devalue his ideas of visual consonance, dissonance, harmony and disharmony. A work where consonance and dissonance is linked between audio and visual, temporally and structurally without doubt creates moments of audio-visual resonance. These ideas are particularly interesting in regards to my choice of song and visual aesthetic.