Solar Flexus

Posted on January 1st, 2010

I’ve wanted to write a physics engine for years and messing with Squeak made me want to try it in Flex. It wasn’t quite as easy as Squeak but it wasn’t too hard.

(It probably needs flash 10 to work)

So far I have gravity and collisions for circular objects. Up next: drag.

Here’s the main loop:

    public function tick() :void {
      for each(var body :Body in bodies) {
        var force :Point = calculateForceOn(body);
        body.apply(force);
        body.move(1);

        checkForCollision(body);
      }
    }

Inverse Square Law to calculate gravity:

    public function calculateForceOn(body :Body) :Point {
      var force :Point= new Point(0, 0);

      for each(var other :Body in bodies) {
        if(body != other) {
          var distance :Number = Point.distance(body.position,other.position);

          var magnitude :Number = (body.mass+other.mass) /(distance*distance);

          var direction :Point = other.position.subtract(body.position);

          var additionalForce :Point = new Point(direction.x*magnitude/distance, direction.y*magnitude/distance);

          force = force.add(additionalForce);
        }
      }

      return force;
    }

Look for collisions and calculate the impulsive forces:

    public function checkForCollision(body :Body) :void {
      for each(var other :Body in bodies) {
        if(body != other && body.intersects(other)) {
          var normal :Point = body.findCollisionNormalTo(other);

          var relativeVelocity :Point= body.findVelocityRelativeTo(other);

          var relativeNormalVelocity :Number = dotProduct(relativeVelocity, normal);

          if(relativeNormalVelocity < 0) {
            var impulse :Number = -dotProduct(normal,relativeVelocity) *(coefficientOfRestitution+1) /(1/body.mass+1/other.mass); 

            body.applyImpulse(impulse, normal);
            other.applyImpulse(-impulse, normal);
          }
        }
      }
    }

And some heavenly bodies:

      var sun :Body = new Body("Sun", World.Origin);
      sun.radius = 60;
      sun.mass = 50000;
      sun.color = 0x26393D;

      var earth :Body = new Body("Earth", new Point(0,500));
      earth.radius = 40;
      earth.mass = 4;
      earth.velocity = new Point(5,0);
      earth.color = 0xE8E595;

      world.add(sun);
      world.add(earth);
      world.add(moon);
      world.add(mars);

I am still not sure whether I like Flex. The libraries are fantastic but the language - ActionScript - is super-annoying. It makes me wish for C#. It’s allegedly a dynamic language but the compiler makes you declare every type anyway in that wacky syntax that I can never quite remember. Simulating solar systems is fun though.

My Drawing Table Squeaks

Posted on December 30th, 2009

Took the kids to the Exploratorium today. It’s currently my favourite museum. Better even than OMSI (although they don’t serve beer at The Exploratorium. How come that hasn’t caught on outside Portland?)  I wish San Jose had a decent museum. The Tech sucks worse than possibly any museum in the world except Morwelham Quay.

I couldn’t find my favourite exhibit - Ladle Rat Rotten Hut. There are so many great exhibits that I have never actually seen them all.

Wan moaning, Rat Rotten Hut’s murder colder inset, “Ladle Rat Rotten Hut, heresy ladle basking winsome burden barter an shirker cockles. Tick disk ladle basking tutor cordage offer groin-murder hoe lifts honor udder site offer florist. Shaker lake! Dun stopper laundry wrote! An yonder nor sorghum-stenches, dun stopper torque wet strainers!”

Jazz fell in love with the drawing board and watched it for about 90 minutes. It’s basically a table hung from four ropes like a pendulum and a pen that draws patterns on a piece of paper as the table swings and twists.  There is a weight that makes it swing eccentrically to make the patterns more interesting.

I promised to make her a real one but I wanted to see if I could do it in Alan Kay’s excellent Squeak first. It was pretty easy and quite effective.

Here’s the program. I messed around with the constants to get different effects.

squeak program

and here’s a picture I made with it:

drawingtable

Today: simulation. Tomorrow: the real thing.

Wish us luck!

UPDATE:

I just downloaded the latest version of Squeak (now called etoys). It’s MUCH better than it used to be. All the bugs are gone and it doesn’t look like it was made in 1983 any more. Go get it from http://www.squeakland.org/ then you can play with my project - Squeak: Drawing Table

etoys

Maybe you could add damping for me.

Heaven Knows I’m Miserable Now

Posted on September 10th, 2009

I have been a Rhapsody subscriber for several years. The service they provide is fantastic:

Think of a song. Any song. Play it.

I suspect that people who suggest “try Pandora” (and there are many of you) probably don’t get what Rhapsody is about. It’s like owning all the songs in the world and you can play any one at any time.

But their software absolutely sucks.

RhapsodySo when Rhapsody suspended my account (I got a new credit card and forgot to tell them), I took it as an excuse to go see what else is happening in music software in the years that I have been gone.

I tried something like twenty different players this week and they pretty much fall into two basic categories:

  1. Music discovery (like Last.fm and Pandora)
  2. Playlist management

Within category 2, there are two business models (purchase tracks or monthly subscription) but the software all has the same primary use case:

User wants to manage their playlists.

They are playlist managers with the ability to actually play the music seemingly tacked on as an afterthought.

I don’t want to edit playlists.

I hate playlists.

Playlists are very seductive at first. You think Oh yes. I’ll build me a playlist with all my favourite songs. But then, after the third time you play it. You start thinking Oh man! This again!? I’m gonna build me another playlist. Then I’ll have two.

Before you know it, you have hundreds of playlists called things like Early English Folk (I) and Early English Folk (II) and you are spending all your time managing your playlists which, by the way, is exactly what the people who make the playlist managers want you to be doing.

No. Playlists are not a good solution for anything.

Here’s what I want:

I want to listen to music that I like.

I’ll clarify that a little:

chetOne day, I might have a hankering to play 7 different versions of My Funny Valentine (Chet Baker’s is best) or every single recording of John Barleycorn Must Die (Traffic’s).

piratesAnother day I’ll have an urgent need to listen to Rogue’s Gallery: Pirate Ballads, Sea Songs, and Chanteys - because there is a piratefest coming up - or to hear the latest Lily Allen album.

I might have just read that there have only ever been two songs sung in latin to make the UK Top Twenty and I’ll want to hear them both.

gogolI might be on my way to a Gogol Bordello concert and I want to hear their albums over and over to get myself in the mood.

But most of the time,

I just want the thing to play me stuff that it thinks I’ll like.

Pandora excels at that last one but is a non-starter for the rest. iTunes will do the job if you don’t mind shelling out 99c every time you have a hankering to listen to some early Abba. If you listen to a lot of music, those 99cs will soon rack up.

So given that

a) music subscriptions rock and

b) the software for music subscription services sucks

oh, and by the way,

c) I have been meaning to learn Flex for a while now

there is only one thing for it…

..I’ll have to write my own damn software.

So that’s what I have doing the last few evenings. It’s fun. I don’t get to program much at work any more so it’s a nice change of pace. I have a prototype that will play Rhapsody or Napster tracks on my wonderful Squeezebox. I have a design all sketched out and I even have a color scheme and icons (step 3 - profit!)

clown music

So, meanwhile, in my ongoing quest to find some existing software that doesn’t suck (and to steal ideas) I keep trying out new players and services. So far, they are all - every single one of them - playlist managers until…

…this morning I discovered GrooveShark.

GrooveShark is uncannily like my sketched design (they even copied my color scheme and icons) and I have been playing it all day.

They have a passably good search screen (mine is better of course but, since it is only sketched on paper, doesn’t work as well as theirs) and it is easy to find a song and stick it in your queue. But, what makes them different from everyone else is that tantalyzing autoplay button.

autoplay

If you stop adding tracks to your queue, AutoPlay will start playing stuff that it thinks you will enjoy. That was gonna be my killer feature!

I have figured out their algorithm though.

It is:

Play The Smiths.

Did the user veto it?

No - Play The Smiths all day. Over and over (and over). Throw in the occasional REM track.

Yes - Play REM all day (throw in some Smiths though in case they have changed their mind).

Try playing some rap every now and again to make sure they are paying attention and not just listening to any old crap.

Play some more Smiths.

That’s it.

If I had known it was this easy, I would’ve done it years ago.

Technology Crisis

Posted on August 17th, 2009

I feel a Technology Crisis coming on. Here were my clues:

Exhibit A: I’ve been meaning to learn Flex for a while. I have got as far as “Hello World” four times now.

Exhibit B: The Rhapsody client sucks. I love having access to all the music in the world but the client really, really sucks. The web client doesn’t completely suck but it’s a web client so it sucks a fair amount.

Put those two together and you have yourself a challenge. Build a new client for Rhapsody in Flex. How hard could it be?

rhapsody1Pretty hard it turns out, because Rhapsody does every thing in its power to make it hard for developers to use their APIs for anything useful. They have an amazing RESTful API that was years ahead of its time. They have a fantastic affiliates program. But - to make sure that no one does anything useful with the API, they force you to use their crappy player.

Go read their forums and you’ll find four years of posts like this:

Dear Rhapsody,

I luuurrve your service but your client is crappy and I would like to write a better one. Hey! You know what? I have a great idea that would send new subscribers your way by the thousand! Just give me an api to play songs. I could even use your player if you’ll give me a method to play a song and let me know when it is done.

Love,

Your Biggest Fan

PS. Let’s make some $$$$ !!111!

And there are four years of replies saying,

Dear Biggest Fan,

We don’t have that API right now but I’ll mention it to product management and they’ll get right on it. Meanwhile we have this asinine JavaScript API. It doesn’t really do anything, but it’s what we have.

Respectfully,

Rhapsody

There was even one VC funded company that figured out a backdoor. The upside for Rhapsody was that they sent scads of new subscribers their way. The downside was that…no …wait…there was no downside. Anyway, someone at Rhapsody decided that they didn’t want all these new subscribers and set the lawyers on them.

yottamusic_shot

I still check the forums for old times sake and there are still hopeful posts like this one:

Dear Rhapsody,

I love the new Flash Player. I see there is a sendMessage() method but I can’t figure out how to work it.

Hugs,

Another Huge Fan

and the reply pretty much says “Don’t be using the sendMessage() method or we’ll set the lawyers on you like those other people who wanted to help us make money.”

Makes you wonder.

Anyway. Fast forward to yesterday and I decided to make a start on my little project. I got stuck (as you do) and googled.

Instead of finding my answer, I found:

The Rhapsody subscription service, which is 51-percent owned by RealNetworks, lost approximately 50,000 of its 800,000 subscribers over the past three months

I went to the forums and found that they have just had big layoffs at Rhapsody. They are going to focus on their web services instead of client software. Oh. And they cancelled the affiliates program.

I wonder if they laid off the dude who decided that they didn’t want third party developers writing clients for their still excellent service?

Anyhoo.

napsterExhibit C: Napster just reduced their subscription service for all-you-can-eat music to $5 a month. They’ll even throw in 5 free mp3s of your choice. I was happy paying $15 a month to Rhapsody but if Napster’s client is even a tiny bit better, I am switching.

Exhibit D: I use my Sansa to play Rhapsody in the car. It’s pretty crap, but there aren’t too many choices. I’d soooo get an ipod if Apple had a subscription service (or let me use rhapsody).

g1Exhibit E: Napster works on the G1.

Exhibit F: I have been wishing I had a camera.

I don’t need too many exhibits to know that the times are a-changin’ and I might be finally ready to get a phone that costs more that $12, that has a camera and that plays music from a subscription service.

But you can’t rush into these things. I need to mull over the idea for a while. Maybe the interwebs will help me make up my mind.

I’ll finish my Flex app but instead of having it drive Rhapsody, I’ll make it drive the Most Excellent Squeezebox because the nice people at SlimDevices know that, if you have a great product, you don’t need to write all the software for it. Expose some useful APIs and The People will do the rest.

squeezebox

Humane Software

Posted on August 10th, 2008

I have had my Squeezebox for a good while now but I just discovered that I have been missing its best feature.

Squeezebox comes with SqueezeCenter - a piece of software that lets you remote control your Squeezebox from a PC.You can stream music from your hard drives or iTunes or any number of internet radio stations or subscription services. But the best bit is that SqueezeCenter is hackable.

SqueezeCenter is open source and has a plugin model and there are tons of plugins for it. Here’s my favourite:

Do you ever find you’re in the middle of listening to your favourite track when your other half suddenly announces that the volume is far too loud and turns it down for you? If so, this may be the plugin for you! VolumeGuard detects “unauthorised” changes in volume and stealthily restores the volume to its original level. Changes are made in small increments over a period of time, so with any luck they won’t notice!

I have wished for that since forever! Well done, writer of VolumeGuard!

Problem 12

Posted on June 22nd, 2008

To save you going all the way to Project Euler to read it, I have copied problem 12 here for your puzzle solving convenience…

The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.

The first ten terms would be:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, …

Let us list the factors of the first seven triangle numbers:

1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28

We can see that 28 is the first triangle number to have over five divisors.

What is the value of the first triangle number to have over five hundred divisors?

In case you were wondering, the answer to problem 10 is


primes = Primes.new
puts primes.find_primes_less_than(2000000).inject{|s,n| s+n}

How come inject and collect haven’t caught on in other languages? They are awesome.

Forgetful me

Posted on June 21st, 2008

According to Kurzweil, the singularity (the moment when we will start to invent things instantaneously) will occur in 2045. According to me the singularity (the moment when I forget things fast than I can learn things) occurs in 2009.

Every time I start over with Ruby (or XSLT or …) I find that I have forgotten the most basic things (like how to construct an object).

Anyway, thanks to Project Euler (according to which, I am 4% genius), I had an excuse to go go back and learn Ruby all over again.

Here’s my prime number generator (which is about a third of the size of my Java version):


class Primes
  def initialize
    @primes = []
    @next_candidate = 2
  end

  def prime? number
    root = Math.sqrt number
    find_primes_less_than root

    @primes.each do |prime|
      return true if prime > root
      return false if number % prime == 0
    end
  end

  def find_primes_less_than limit
    until @next_candidate > limit
      @primes << @next_candidate if prime? @next_candidate
      @next_candidate += 1
    end
  end

  def [] index
    until @primes.size > index
      find_primes_less_than @next_candidate + 100
    end
    return @primes[index]
  end
end

The answer to problem #7 is @primes[10000], in case you were wondering.

Wasting Time

Posted on June 15th, 2008

Project Euler. Wasting time with Maths.

My attempt at #3 is running now (which probably means it is wrong).

Monty Hall in Squeak

Posted on May 4th, 2006

Over at www.developertesting.com, I wrote about the Monty Hall problem and how I was convinced of the answer by an unused variable in my Java simulation.

Markus wrote a nice simulation in Squeak (dunno what it will do if you don’t have squeak installed but it makes a good excuse for you to go get it).

click for bigger image

I am always on the lookout for ideas for a science project for Dylan. For me, the ideal kid’s science project has a hypothesis that

  1. will almost certainly be wrong
  2. can be tested empirically
  3. can be proven mathematically

with extra credit if you can write a computer simulation of it. Dylan’s project last year was “What should you do if draw three cards to an inside straight in poker?”. He said you should raise. I usually beat him at poker :-)