Using Greensock JS / TweenMax in a Dart application

Using Greensock JS / TweenMax in a Dart application

onedayitwillmake No Comments
  Dart Howto Uncategorized

Once you use Greensock / TweenMax / TweenLite, you don’t really want to use anything else.
It’s fast, it’s feature rich, and it works on more browsers than dart itself.
This is a quick post on how to use the animation library, it’s surprisingly easy.

  • First import the dart:js library
    import 'dart:js';

  • Next, add dart.interop.js to your HTML after your own apps script tags.
    Mine looks like this:

    <script type="application/dart" src="dart/mandala.dart"></script>
    <script src="packages/browser/dart.js"></script>
    <script src="packages/browser/interop.js"></script>

Now to call JS from dart you must follow the js-interop syntax, which I agree is a bit annoying – but one approach is to create a wrapper class / function for it.

  • With that out of the way, here is an example of a Tweenmax call to modify the Y / Alpha values of a div:
      // You can also just pass the element's ID instead to greensock
      // but assuming we already retrieved it or may not have an id we would use this method
      HTMLElement divToAnimate = querySelectorAll("#myDiv");
      // Context refers to the JSContext, and retrieves global window objects
      context['TweenMax'].callMethod("to", [divToAnimate 
            new JsObject.jsify({
                  "delay" : 0.5,
                  "y": "40"
                  "autoAlpha": 0
      // A simpler one for reference
      context['TweenMax'].callMethod("to",["#myDiv", 0.15, new JsObject.jsify({x:100})]);

We can think of Context as referring to the Window object in the javascript context. So we retrieve it, and then call a method on it. Passing the method name to and then an array of parameters. For the last parameters, we create a new javascript object using the JsObject.jsify method which takes a map of primitive types with strings as keys.

In the next post / or an update to this one, I will show you how to create a simple wrapper class to make using Greensock more like calling it from JS

Placing an AppKit controls over a NSOpenGLView / CinderView

onedayitwillmake No Comments

Currently working on an OSX application that requires UI controls to live above a CinderView (Which is a type of NSOpenGLView).

Obviously first I tried to simply place the objects above one another in InterfaceBuilder, but that had no effect. The NSOpenGLView always draws above all other content.

Next I tried some information someone suggested, with switching to layer-backed views.
That crashed my application on startup.

Instead what I found that worked, was to create a separate NSWindow, and style it to be transparent and place it inside of your NSWindow that contains the CinderView / NSOpenGLView.

Create a window to house your AppKit UI controls, and place your NSView inside

    // Transparent UI window
    CGRect wRect = self.window.frame;
    NSView *contentView = self.window.contentView;
    CGRect cRect = contentView.frame;
    CGRect rect = CGRectMake(wRect.origin.x, wRect.origin.y, cRect.size.width, cRect.size.height);
    self.overlayWindow = [[NSWindow alloc]initWithContentRect:rect
    self.overlayWindow.backgroundColor = [NSColor clearColor];
    [self.overlayWindow setOpaque:NO];
  // Add it to the window which contains our NSOpenGLView
    [self.window addChildWindow:self.overlayWindow ordered:NSWindowAbove];
    // Place UI in overlay window
    self.settingsController = [[SettingsViewController alloc] init];
    [self.overlayWindow.contentView addSubview:self.settingsController.view];

[iOS] Creating reusable UIViews with Storyboard

onedayitwillmake 6 comments
  iOS sourcecode

I’m a big fan of using Storyboards to act as the glue for your application.
It just makes everything much easier, and makes your program feel like a cohesive application instead of a random assortment of UIViewControllers

However one problem is that, Storyboards don’t lend themselves to having reusable views.
Which I find kind of odd, because it seems common that you would have a view that needs to exist in multiple screens for myriad reasons in a lot of applications.

Wellp, it’s actually not that difficult to do – although definitely falls in the ‘tricky’ category.

Compiling LESS from a node.js script

onedayitwillmake 2 comments

LESS is a tool that allows you to write CSS in a programmer friendly way (with variables, and some simple functions), it then converts it to regular CSS for browser friendly consumption.

It’s amazingly easy to use, during development you don’t have to change a thing.
You simply import your .less file, then under you import ‘less.js’ and it does it’s magic.

Eventually you need to preprocess it as part of your build operation.

For some reason I could not find a simple response for how to do this.
I found many articles / answers for how to run LESS from the command line, or using it with Express to pre-compile it for you when serving then cache it.

Here’s what I ended up using, much of it referenced from the lessc command line tool.

var less = require( 'less' );
var fs = require( 'fs' );
var path = require('path');
// Load the file, convert to string
fs.readFile( '../less/gaf.less', function ( error, data ) {
  var dataString = data.toString();
  var options = {
    paths         : ["../less"],      // .less file search paths
    outputDir     : "../css",   // output directory, note the '/'
    optimization  : 1,                // optimization level, higher is better but more volatile - 1 is a good value
    filename      : "gaf.less",       // root .less file
    compress      : true,             // compress?
    yuicompress   : true              // use YUI compressor?
  // Create a file name such that
  //  if options.filename == gaf.js and options.compress = true
  //    outputfile = gaf.min.css
  options.outputfile = options.filename.split(".less")[0] + (options.compress ? ".min" : "") + ".css";
  // Resolves the relative output.dir to an absolute one and ensure the directory exist
  options.outputDir = path.resolve( process.cwd(), options.outputDir) + "/";
  ensureDirectory( options.outputDir );
  // Create a parser with options, filename is passed even though its loaded
  // to allow less to give us better errors
  var parser = new less.Parser(options);
  parser.parse( dataString, function ( error, cssTree ) {
      if ( error ) {
        less.writeError( error, options );
    // Create the CSS from the cssTree
    var cssString = cssTree.toCSS( {
      compress   : options.compress,
      yuicompress: options.yuicompress
    } );
    // Write output
    fs.writeFileSync( options.outputDir + options.outputfile, cssString, 'utf8' );
    console.log("Converted Less: '" + options.filename + "', to CSS: " + options.outputDir + options.outputfile);
var ensureDirectory = function (filepath) {
  var dir = path.dirname(filepath);
  var existsSync = fs.existsSync || path.existsSync;
  if (!existsSync(dir)) { fs.mkdirSync(dir); }

A Little About Digital Audio and Linear PCM

onedayitwillmake No Comments

This is from Apple’s documentation on CoreAudio.

Since I find wikipedia to be only marginally helpful these days (it actually suffers from TOO much information)
I found it explained these concepts so well, I had to quote it for future reference.

A Little About Digital Audio and Linear PCM
Most Core Audio services use and manipulate audio in linear pulse-code-modulated (linear PCM) format, the most common uncompressed digital audio data format. Digital audio recording creates PCM data by measuring an analog (real world) audio signal’s magnitude at regular intervals (the sampling rate) and converting each sample to a numerical value. Standard compact disc (CD) audio uses a sampling rate of 44.1 kHz, with a 16-bit integer describing each sample—constituting the resolution or bit depth.

A sample is single numerical value for a single channel.
A frame is a collection of time-coincident samples. For instance, a stereo sound file has two samples per frame, one for the left channel and one for the right channel.
A packet is a collection of one or more contiguous frames. In linear PCM audio, a packet is always a single frame. In compressed formats, it is typically more. A packet defines the smallest meaningful set of frames for a given audio data format.

In linear PCM audio, a sample value varies linearly with the amplitude of the original signal that it represents. For example, the 16-bit integer samples in standard CD audio allow 65,536 possible values between silence and maximum level. The difference in amplitude from one digital value to the next is always the same.

Excellent open-course, from NAND to Tetris

onedayitwillmake No Comments

Came across this while I was reading an entry on #ALTDEVBLOGADAY. The entry was part 2 of 9, C / C++ Low Level Curriculum part 2 which is interesting in it’s own right.

There was a link to this interesting MIT open course called:
From NAND to Tetris, which discussing building an entire computer from first principals. The idea is to work backward, instead of starting at high-level abstraction beginning at the lowest interesting level in computer science (logic gates)

Although not required, it’s meant to be consumed with it’s own accompanying book, which i’ve already ordered and should get here by Tuesday – i’m very excited to start reading it and going through the course.

The Elements of Computing Systems: Building a Modern Computer from First Principles

List of programmer shiny things

onedayitwillmake No Comments

This is from Andrew Bell’s talk at the EyeO festival. I’m taking it out of context, and in fact he was talking about focusing in on your craft, not being distracted, and finishing projects that you start. “Which of these will you avoid this year, in order to finish your projects?”

I think it’s also a good list of interesting technologies to jump into… blasphemy i know.

The talk is awesome and worth watching in full:

Thoughts on Dart

onedayitwillmake 3 comments
  Dart Opinion

Lately I’ve started playing around with the Dart programming language by Google. The idea behind Dart, is that writing applications in javascript is really a painful act. Sure overtime many of us have gotten used to the various pain points, and there are conventional workarounds that have essentially become part of the ‘hidden standard’ of Javascript language. But why should we have to live with them? Just because it is, doesn’t mean we should be forced to deal with it!

Let me give you an example, in Javascript how would you go about creating a class (Note: Please don’t bother me with the semantics of class vs prototypical inheritance, just go with it for the sake of argument)?
Well here’s one way:

Animal = function () {
    this.isAlive = true;
Animal.prototype = {
    eat: funciton(){},
    pray: function(){},
    love: function(){}

So far so good, no big deal here, now we can create many new Animal’s all we want.
However what if we want to subclass Animal, to a more specific type of say Dog?

Well here’s where javascript’s faults come into play, there is no one way to do this so what you have is many people reinventing the wheel and confusion for new comers especially from other languages when they attempt to implement something as simple as creating a Dog that inherrits from Animal.

Here’s one way of doing it in Javascript:

Dog = function() { this ); // Call super's constructor
Dog.prototype = Object.create( Animal.prototype );

Here’s a different way of tackling the problem:

function extend( subclass, superclass ) {
    var originalSubclassPrototype = subclass.prototype;
    // Store the superclass prototype in a surrogate function
    var F = function(){};
    F.prototype = superclass.prototype;
    subclass.prototype = new F();
    subclass.superclass = superclass.prototype;
    subclass.prototype.constructor = superclass;
    for(var method in originalSubclassPrototype) {
        if( originalSubclassPrototype.hasOwnProperty(method) )
            subclass.prototype[method] = originalSubclassPrototype[method];

Which is correct? Well the answer is both, there’s plenty of ways to skin a classy cat in Javascript, and these are just two of them, there’s plenty more out there as well. To me having too many ways to do something as simple as creating a subclass is a A Bad Thing.

In Dart there is only one way to create a Class, and only one way to create a subclass:

    class Vec2 {
        num x;
        num y;
        Vec2( this.x, this.y );

That’s it, and in case you’re wondering about that sleek looking constructor, as you should be, well that is a special type of syntatic sugar shorthand in Dart that is the equivalent of:

    class Vec2 {
        num x;
        num y;
        Vec2( num pX, num pY ) {
            x = pX;
            y = pY;

How many times have you had to create a constructor where the first 10 lines were just simply setting the variables of the local instance? A lot i’m sure. Instead Dart allows you to simply state that the arguments passed in should be set to the respective local variables. Also notice that I did not type the word this. In Dart the scoping is already correct, so there is no need to explicitely type ‘this’ (although you can if you like).

Creating a subclass is equally as straight forward:

/// A circle is similar to a [Vec2] except it contains an area.
class Circle extends Vec2 {
  /// Radius of the [Circle]
  num radius;
  /// Creates a new [Circle] with [radius]
  Circle( num pX, num pY, this.radius) : super(pX, pY);
  /// Returns whether a point is contained within [this] [Circle]
  bool containsPoint( Vec2 p ) => ( distanceSquared(p) <= radius*radius );

That’s all there is to it, no confusion about which is the correct way, the “fastest” way, etc.

A couple of other things to notice here as well.
Firstly are the comments. In Dart a comment that contains three slashes, ///, is considered a Documentation comment. It will be parsed by the built-in (!!) Dart-Doc generator. It even uses Markdown so you don’t have to write annoying HTML in your Documentation comments. Again notice the brackets around [Vec2], because Dart has full knowledge of your application, it knows to go and find the class Vec2 and link to it in the documentation.

So back to subclassing, notice our constructor:

Circle( num pX, num pY, this.radius) : super(pX, pY) {
    print("My radius is ${radius}");

Here we are using another two special constructs Dart provides for constructors.
The first is the ‘initializer list’, which come from C++. They allow you to set properties separated by comma’s after the constructor, but outside of the function’s body. Notice the call to super, very straightforward.

Finally the last thing to notice is the string interpolation occuring in the ‘print’ function (essentially console.log). Here we have a single string, and inside we have a special syntax ‘${}’, where inside we can place an expression ( or value ), that dart will evaluate for us. No more having to concact strings with plus signs and making typos that are hard to spot.

Overall I’m very much liking the things that Dart is bringing to the table, best of all it compiles to Javascript so it will work on any modern browser. Currently Dart’s compiled javascript, runs at 80% speed of something written in vanilla javascript, and getting it’s not even at version 1.0 yet! Also worth mentioning that DartVM is already outperforming V8 in nearly all javascript benchmarks.

In the next post I’ll dissect a few more interesting things that I like about Dart, and a few who I dislike.
In the meantime, don’t waste any time, go watch the screencast that sold me

Calculating the gravity of the gravitational force or 0.00000000000667

onedayitwillmake No Comments
  math snippet sourcecode

Gravity is by far the best force in the universe. Despite being the weakest of the “main” four (strong nuclear force, weak nuclear force, electromagnetism, gravity). It is the one that dominates given enough time and distances. All this even though it falls of inversely to the square of the distance, meaning, if you double the separation between the two objects you quarter the force, or if you cut the separation in half you quadruple the force of attraction.

It’s also one of my favorite things when creating visualizations, because things move so beautifully when you simply let gravity take over.

So I thought I would give it it’s own tiny blog post, in honor of its value 0.00000000000667

    // Compute the net force acting between the invoking body a and b, and
    // add to the net force acting on the invoking Body
    public void addForce(Body b) {
        Body a = this;
        double G = 0.00000000000667;
        double EPS = 0.0001;      // softening parameter
        double dx = b.rx - a.rx;
        double dy = b.ry - a.ry;
        double dist = Math.sqrt(dx*dx + dy*dy);
        double F = (G * a.mass * b.mass) / (dist*dist + EPS*EPS);
        a.fx += F * dx / dist;
        a.fy += F * dy / dist;

Eclipse template project with cocos2dx

onedayitwillmake No Comments
  C++ eclipse gamedev Howto

I have created an eclipse project template, which contains an SDK project, with a NDK C++ bindings ( done via ‘javah’ build step ), combined with Cocos2dx helloworld project.
I have used it as the base for 2 projects, and figured I would share.