Open two instances of Unity at once

Open two instances of Unity at once

onedayitwillmake No Comments

Sometimes you have a project that you’re using as reference, maybe you added some functionality in a previous project or you downloaded a sample project and you are trying to recreate that thing in your new project. It would be great if you could have them both open side by side so you can compare them right?

Unfortunately if you try to open Unity by clicking the icon, it will just bring your current instance into focus, so what can be done?

Here’s a simple trick that allows you to have two instances of Unity open at once, open the second instance from the command line and point it to a project.

$ /Applications/Unity/Unity.app/Contents/MacOS/Unity -projectPath ~/projects/coolgame

Note: You cannot open the same project twice, so if you have to do that create a temporary copy of the project.

Create iOS / Android icons from master icon

onedayitwillmake No Comments

This is just a simple script that will create your iOS icons from a masterfile.
I’m using it on a Unity project (Even though Unity will make the icons for you, the way it resizes the images leaves them appearing jaggy).

It works best with a 1024×768 icon as the source

#!/bin/bash
# Author: Mario Gonzalez
# Modified for iOS7 from: https://gist.github.com/jessedc/837916
f=$(pwd)
 
# App Icon - iPhone iOS7+
sips --resampleWidth 60 "${f}/${1}" --out "${f}/icon60.png"
sips --resampleWidth 120 "${f}/${1}" --out "${f}/icon120.png"
# App Icon - iPhone <= iOS6
sips --resampleWidth 57 "${f}/${1}" --out "${f}/icon57.png"
sips --resampleWidth 114 "${f}/${1}" --out "${f}/icon114.png"
# App Icon - iPad iOS7+
sips --resampleWidth 76 "${f}/${1}" --out "${f}/icon76.png"
sips --resampleWidth 152 "${f}/${1}" --out "${f}/icon152.png"
# App Icon - iPad <= iOS6
sips --resampleWidth 72 "${f}/${1}" --out "${f}/icon72.png"
sips --resampleWidth 144 "${f}/${1}" --out "${f}/icon144.png"
# Spotlight iOS7+
sips --resampleWidth 40 "${f}/${1}" --out "${f}/icon40.png"
sips --resampleWidth 80 "${f}/${1}" --out "${f}/icon80.png"
# Spotlight - Ipad <= iOS6
sips --resampleWidth 50 "${f}/${1}" --out "${f}/icon50.png"
sips --resampleWidth 100 "${f}/${1}" --out "${f}/icon100.png"
# Spotlight - iPhone <= iOS6
sips --resampleWidth 29 "${f}/${1}" --out "${f}/icon29.png"
sips --resampleWidth 58 "${f}/${1}" --out "${f}/icon58.png"
# iTunesArtwork
sips --resampleWidth 512 "${f}/${1}" --out "${f}/iTunesArtwork"
sips --resampleWidth 1024 "${f}/${1}" --out "${f}/iTunesArtwork@2x"
 
###### ANDROID ICONS
sips --resampleWidth 96 "${f}/${1}" --out "${f}/icon96.png"
sips --resampleWidth 48 "${f}/${1}" --out "${f}/icon48.png"
sips --resampleWidth 36 "${f}/${1}" --out "${f}/icon36.png"

Use it as such:

$ ./updateicon.sh  iconmaster.png

Note you made need to run chmod +x updateicon.sh on it before it will be recognized as executable

Using Greensock JS / TweenMax in a Dart application

onedayitwillmake No Comments

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 
            0.15,
            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
                                                         styleMask:NSBorderlessWindowMask
                                                           backing:NSBackingStoreBuffered
                                                             defer:NO];
    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

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 );
        return;
      }
 
    // 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:
https://vimeo.com/51533137

Thoughts on Dart

onedayitwillmake 3 comments

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() {
    Animal.call( 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 http://www.dartlang.org/docs/editor/