Tag:

The following Processing example shows how to set up a separate thread for loading images into a sketch. I wrote it up in response to this post on the Processing forums, figuring it will be useful to some of my students too.

Code: ThreadImageLoader.pde

Read the rest of this entry »

5 Comments »

Turns out Java has no mechanism for discovering the names of disk volumes. You can use java.io.File.listRoots() to get the root paths for multiple disks, but you can’t auto-discover their names.

Here’s a quick hack that will work on Windows. It uses Runtime.getRuntime().exec() to run “cmd /c dir “, the output of which is parsed to get the volume name.

import java.io.*; 

void setup() {
  println("Testing getVolName");

  String path="D:";
  println("Volume name for "+path+" is: "+
    "'"+getDiskVolumeName(path)+"'");
}

public static String getDiskVolumeName(String path) {
  String volname="Unknown";
  String check="Volume in drive "+path.charAt(0)+" is ";
  try  {
    Process p=Runtime.getRuntime().exec("cmd /c dir "+path);
    //p.waitFor(); 

    BufferedReader reader=new BufferedReader(
      new InputStreamReader(p.getInputStream()));
    String line=reader.readLine();
    while(line!=null) {
      if(line.indexOf(check)!=-1)
        volname=line.substring(line.indexOf(check)+check.length());

//      System.out.println(line);
      line=reader.readLine();
    }
  }
  catch(Exception e1) {
    println("Failure: "+e1.toString());
  }
  return volname;
}

No Comments »

Sample code to use mouse wheel events in Processing.

Read the rest of this entry »

1 Comment »

Marcus Wendt has published a new Processing library called libCollada, providing 3D export in the Collada 3D format. Collada is XML-based, and is intended to provide support both for basic 3D geometry and more advanced 3D authoring features like shaders and physics.

The obvious question is why another 3D format? Well, I guess the ones out there still aren’t good enough. Collada looks very complete, but most importantly is not tied to a single software vendor. It comes with a range of Open Source libraries for importing and exporting for various languages, and so could easily become a good choice for Open Source developers.

I recommed subscribing to Marcus’ Infostuka blog for technology- and design-related news. His own projects like Gestures on Sound show a great eye for computational work.

No Comments »

2D line intersection

Code for 2D line intersection

I’ve been struggling with finding the intersection between two lines so that the resulting point actually lies on the specified line segments. Most line intersection formulas use an infinite line model, so the point will tend to lie on an infinite extension of the segments. Which is not what I wanted at all.

First I implemented Paul Bourke’s excellent breakdown of the math. Then after much experimentation I realized I could calculate the distances from the intersection point to the end points of the two lines, and then check their combined length against the length of the lines. If the lenghts are the same then the intersection point is actually on the line segment. Quod erat demonstrandum.

The code also checks to see if the two lines are parallel using the dot product of the two vectors. Considering that I’m actually fairly inept at math I feel like I’ve scored a minor victory.

Code - lineIntersect.pde

Read the rest of this entry »

7 Comments »

When writing realtime applications optimal code is always the goal. But it’s hard to always know exactly what is going to be “expensive” in terms of CPU time.

Java Performance Tuning is a very comprehensive optimization resource, but a bit too dense for less experienced programmers. JavaWorld has an article called Make Java fast: Optimize!, which is more accessibly and explains some basics quite well. More importantly, it provides a benchmark applet that gives an overview of the relative CPU cost of basic Java instructions.

For instance, the assignment “int x = 0″ would take 987 picoseconds to execute a certain number of times, while “x[0]=x[10]” would take 1304 picoseconds. See below for benchmark examples.

There is also the classic Jonathan Hardwick optimization tutorial, which is a bit more technical. It’s old (1998), but the basic concepts are still valid. One thing he warns against is the cost of object instantiation. Creating a new object instance can be expensive, particularly if it’s a complex object with lots of data. Try recycling complex objects rather than creating new ones.

Keep in mind that spending tons of time optimizing single lines of code is usually not worth it. Small differences in the benchmarks below would only matter if you’re doing some calculation a huge amount of times. Try using a profiler if you have the time and the need to figure out which parts of your program suck CPU cycles.

Otherwise, some basic rules of thumb should get you a long way:

  • Don’t calculate values more than once. Instead, store them in a local variable for reuse.
  • Avoid creating new complex objects when you could recycle old instances instead.
  • If possible, use simple data structures. A one-dimensional array is faster to access than a two-dimensional one.
  • If you’re doing work with Strings, consider using StringBuffer to avoid instantiating temporary String objects.
Benchmarks

Read the rest of this entry »

No Comments »

JDIC embedded browser engine

Screenshot of IE running integrated with Processing and other AWT components.

For a while I’ve been wondering if it couldn’t be useful to be able to render proper HTML from inside Processing. While Processing is excellent for realtime graphics, the typographic support is a little basic when faced with the task of designing a more complex layout. Rather than write a new library, why not just use a fast HTML engine?

While there are quite a few HTML rendering engines out there, not all are very complete or indeed very fast. This might be one of the cases where using native code makes sense. Both Internet Explorer and Mozilla offer ways of embedding their rendering engines through native bindings, and after a little googling I was able to find JDIC - the JDesktop Integration Components project.

JDIC aims to bring Java applications closer to feeling like “real” desktop apps. I’m not sure if that’s a battle I would have taken on myself, but in any case they have exactly what I needed: A simplified web browser ready for embedding, able to use either IE or Mozilla as engines. A little coding later and I had a hybrid Processing / AWT application running a web browser. It will even support Flash and Java content, provided that you’ve installed the proper plugins.

The WebBrowser.setContent() function is perfect for loading your own machine-generated content, and events can be captured and processed appropriately. It would even be possible to have a hybrid application, with part of the interface being straight Processing and the rest AWT. I’m keen to try using this to create more complex on-screen layouts. HTML and CSS will always look much better than anything one could create using Swing.

See Flickr for some screenshots.

Code - JDICsample.pde

Read the rest of this entry »

2 Comments »

As mentioned previously, I’ve been working on developing a visual piece for a Nokia phone. After trying Mobile Processing, I came to the conclusion I’d be better off going the old school way: Pure J2ME development in Eclipse. It makes me appreciate just how easy developing in Processing really is compared to going back to the bare bones.

Seeing as my target is a Nokia phone, I figured using Nokia’s own Carbide.j tool for J2ME development. Now it looks like that was a mistake. Nokia has just announced that they’re discontinuing development of Carbide.j. Instead, they suggest two Open Source alternatives, Eclipse with the EclipseME plugin or NetBeans IDE with the NetBeans Mobility Pack.

I found out about the announcement while trying to repair my apparently broken install of Carbide.j, so I’ve now made the jump to EclipseME and dumped Carbide.j altogether. EclipseME feels much better integrated with the IDE, running a MIDLet in a given emulator is as easy as running a regular app. Carbide.j forced you to use a series of clumsy steps just to get the emulator up and running.

Right now everything’s running flawlessly except when I try to use Nokia’s S60 3rd Edition (FP 1) emulator. It barfs at the step of creating the JAR file for some reason. I guess I’ll just stick to Sun's WT5 2.5 emulator and forget about using any fancy Nokia-specific stuff like transparency. The upside is that my final app will theoretically run on any MIDP 2.0 phone.

Update: When trying to install my MIDP application generated with EclipseME on the Nokia phone I kept getting “Invalid JAR” errors. According to a post on eclipseme-users, this is due to EclipseME not including a vital piece of information in the JAD file. To fix it, simply open the generated JAD file with a text editor and add the following:

MIDlet-1: Classname,,packagename.Classname

“Classname” should be the name of your MIDlet class, “packagename” should be the name of the package it’s in. After I added this line to the JAD it installed just fine.

No Comments »

For two joined bezier curves to be continuous (i.e. no corners or abrupt slope changes), the control points on each side of the joining point must be colinear. This behavior is default in vector editing programs like Adobe Illustrator.

An example in Processing:

// BezierJoins.pde
// Marius Watz - http://workshop.evolutionzone.com

void setup() {
  size(400,400);
}

void draw() {
  background(200);
  noFill();

  float xD=width/2-mouseX;
  float yD=height/2-mouseY;  

  bezier(0,0,
    300,100,
    width/2-xD,height/2-yD,
    width/2,height/2);

  bezier(width/2,height/2,
    width/2+xD,height/2+yD,
    400,300,
    400,400);
}

1 Comment »

I’ve just learned some handy tricks about packaging Processing-based applications with OpenGL for deployment on Mac OS X. As it turns out, it’s remarkably easy to do on a PC if you use Processing’s own application export as a template. My thanks to Ben Fry for the tip (and also for all the other hard work he’s put into Processing…)

Create a sketch called “Dummy” in the Processing GUI. If your final application will use OpenGL, make sure that “Dummy” does as well. Export using “Export as application”. This produces several folders, of which only “application.macosx” is of interest. This has a “Dummy.app” subfolder which is the actual MacOS application. It’s not a single file, but rather a folder structure that on a Mac shows up as a clickable application. Change the name of “Dummy.app” to whatever name you want, keeping the magic “.app” extension.

In “Contents” you will find a file called “Info.plist”. This contains various parameters controlling your Java application, bundled as pairs of <key> and <string>. Make sure that “MainClass” string is the full name of your main class (including package name if any). Change all instances of “Dummy” to the name of your application. You can also tweak a bunch of other options at will.

If you have JAR files that you need to add, place them in the subfolder “Contents\Resources\Java”. It should already contain core.jar as well as the OpenGL-related JARs and jnilib libraries if you exported Dummy with OpenGL imported. You will need to include the new JARs in the “ClassPath” string found in “Info.plist”.

If all changes have been done correctly, you should now have a runnable application. Copy it to a Mac for testing.

For some icing on the cake (and as an alternative to present mode), you can hide the dock and menu bar on application start. Add the following lines to the <dict> section of “Info.plist”:

LSUIPresentationMode
4

Thanks to Vitaflo for his post on the Processing Forums for this tip.

If you compile your code including the Processing source in an IDE like Eclipse, you can simply replace core.jar with your own as long as it contains all the usual Processing class files. I’ve made a few small changes to the PApplet class, so I prefer this option to the standard JAR file.

This is particularly pertinent if you want your OpenGL apps to be anti-aliased on Mac OS, since smooth() does not always turn it on. The solution is to make an alteration to PGraphicsOpenGL using the GLCapabilities class. Read Mike Creighton's post on the Processing forums for the details.

1 Comment »