Began implementing player controls.  Part of #10.

# game

This module contains your game logic.  Its methods are called by the "index"
module to update the game state.

    gamepad = require "./input/gamepad.litcoffee"
    keyboard = require "./input/keyboard.litcoffee"

    context = require "./rendering/context.litcoffee"
    cloud = require "./rendering/cloud.litcoffee"
    matrix = require "./matrix.litcoffee"
    plane = require "./plane.litcoffee"
    misc = require "./misc.litcoffee"
    navmesh = require "./navmesh.litcoffee"
    vector = require "./vector.litcoffee"

    triangle = undefined

    testEntity = testMap = testNavmesh = undefined

# load
Called before the first "tick"/"draw" to load any resources needed by the game.
Execute the argument when you have finished successfully.

    load = (callback) ->
        keyboard()
        context.load()
        cloud.load (require "./testEntity.msc"), (testEntity_) ->
            testEntity = testEntity_
            cloud.load (require "./tracks/test/geometry.msc"), (testMap_) ->
                testMap = testMap_
                navmesh.load (require "./tracks/test/navmesh.msn"), (testNavmesh_) ->
                    testNavmesh = testNavmesh_
                    triangle = testNavmesh[0]
                    callback()
                    return
                return
            return
        return

# tick
Called at 20Hz to update game state.  Guaranteed to be called once between
"load" and "draw".  May be called more or than once per call to "draw" or not at
all.

    firstTick = true
    firstDraw = true

    entityTransform = []
    entityTransformToDraw = []
    entityTransformPreviousTick = []
    entityTransformPreviousDraw = []
    matrix.identity entityTransform

    torsoTransform = []
    torsoTransformToDraw = []
    torsoTransformPreviousTick = []
    torsoTransformPreviousDraw = []

    surfaceCorrectedEntityTransform = []
    matrix.identity surfaceCorrectedEntityTransform

    cameraTransform = []
    cameraTransformPreviousDraw = []
    matrix.identity cameraTransform

    velocity = [0, 0, 0]
    xAxis = []
    yAxis = []
    zAxis = []
    torsoXAxis = []
    torsoZAxis = []
    translation = []
    targetForwardVelocity = []
    targetSidewardVelocity = []
    targetVelocity = []
    torsoTranslation = []

    yaw = 0
    pitch = 0

    stick = [0, 0, 0]
    stickAngle = 0

    edgeCallback = (edge) -> vector.flatten velocity, edge.plane.normal, velocity

    tick = ->
        if not firstTick
            matrix.copy entityTransform, entityTransformPreviousTick
            matrix.copy torsoTransform, torsoTransformPreviousTick

        matrix.translate velocity, entityTransform

        stick[0] = gamepad.right - gamepad.left
        stick[1] = gamepad.forward - gamepad.backward
        stickLength = vector.magnitude stick

        inDeadzone = stickLength < 0.1

        if inDeadzone
            stick[0] = stick[1] = 0
        else
            stickAngle = Math.atan2 -stick[0], stick[1]
            if stickLength > 1
                vector.divide.byScalar stick, stickLength, stick
                stickLength = 1

        # Left/right rotation.
        matrix.rotateY (stick[0] * -0.1), entityTransform, true

        # Apply navmesh triangle collision.
        matrix.getTranslation entityTransform, translation
        triangle = navmesh.constrain translation, triangle, edgeCallback

        # Gravity.
        velocity[1] -= 0.2

        # Forwards/backwards movement.
        matrix.getZ entityTransform, zAxis

        # Determine if we're underground.
        altitude = plane.distance triangle.plane, translation

        if altitude < 0
            velocity = velocity
            plane.project triangle.plane, translation, translation

            # Reflecting the velocity against the hit surface but then
            # flattening it has the effect that hitting a ramp bounces you up it
            # but you don't bounce when falling onto the floor.
            vector.reflect velocity, triangle.plane.normal, velocity
            vector.flatten velocity, triangle.plane.normal, velocity

            if not inDeadzone
                matrix.getX entityTransform, xAxis
                vector.multiply.byScalar zAxis, (stick[1] * 10), targetForwardVelocity
                vector.multiply.byScalar xAxis, (stick[0] * 10), targetSidewardVelocity
                vector.add.vector targetForwardVelocity, targetSidewardVelocity, targetVelocity
            else
                targetVelocity[0] = targetVelocity[1] = targetVelocity[2] = 0
            vector.interpolate velocity, targetVelocity, 0.05, velocity

        # Apply air resistance.
        vector.multiply.byScalar velocity, 0.98, velocity

        # This section attempts to align the entity with the triangle surface.

        # We take the triangle's normal as the Y/up axis.

        # First, flatten the Z/forward axis onto the surface.
        vector.flatten zAxis, triangle.plane.normal, zAxis
        vector.normalize zAxis, zAxis

        # Then, find the X/right axis which is perpendicular to the Z/forward
        # and Y/up axes.
        vector.cross triangle.plane.normal, zAxis, xAxis
        matrix.setX xAxis, surfaceCorrectedEntityTransform
        matrix.setY triangle.plane.normal, surfaceCorrectedEntityTransform
        matrix.setZ zAxis, surfaceCorrectedEntityTransform

        # Blend between our current transform and the aligned one.
        matrix.interpolate entityTransform, surfaceCorrectedEntityTransform, 0.1, entityTransform

        matrix.setTranslation translation, entityTransform

        matrix.copy entityTransform, torsoTransform

        matrix.getY entityTransform, yAxis
        vector.multiply.byScalar yAxis, 10, torsoTranslation
        vector.add.vector torsoTranslation, translation, torsoTranslation

        yaw = misc.interpolateAngle yaw, stickAngle, 0.2, yaw
        matrix.rotateY yaw, torsoTransform, true

        matrix.getZ torsoTransform, torsoZAxis # TODO: If the entity transform is ever non-identity at startup we'll need to initialize torsoTransform for this to be right in the first ticks.
        matrix.getX torsoTransform, torsoXAxis # TODO: If the entity transform is ever non-identity at startup we'll need to initialize torsoTransform for this to be right in the first ticks.
        pitch = misc.interpolate pitch, (0.5 * stickLength - 0.1 * vector.dot torsoZAxis, velocity), 0.2
        matrix.rotateX pitch, torsoTransform, true
        matrix.rotateZ (0.1 * vector.dot torsoXAxis, velocity), torsoTransform, true

        matrix.setTranslation torsoTranslation, torsoTransform

        if firstTick
            matrix.copy entityTransform, entityTransformPreviousTick
            matrix.copy torsoTransform, torsoTransformPreviousTick
            firstTick = false
        return

# draw
Called with the progress through the current frame (a number between 0 and 1) to
redraw the scene.

    draw = (progress) ->

        if not firstDraw
            matrix.copy entityTransformToDraw, entityTransformPreviousDraw
            matrix.copy cameraTransform, cameraTransformPreviousDraw
            matrix.copy torsoTransformToDraw, torsoTransformPreviousDraw

        matrix.interpolate entityTransformPreviousTick, entityTransform, progress, entityTransformToDraw
        matrix.interpolate torsoTransformPreviousTick, torsoTransform, progress, torsoTransformToDraw

        matrix.invert entityTransformToDraw, cameraTransform
        matrix.translate [0,-10, 10], cameraTransform

        if firstDraw
            matrix.copy entityTransformToDraw, entityTransformPreviousDraw
            matrix.copy cameraTransform, cameraTransformPreviousDraw
            firstDraw = false

        context.begin 0, 0, context.width, context.height, 1, cameraTransformPreviousDraw, cameraTransform, 0.1, 0.5, 0.9
        cloud.draw testMap
        cloud.draw testEntity, torsoTransformPreviousDraw, torsoTransformToDraw

        return

    module.exports = { load, tick, draw }

# game

This module contains your game logic.  Its methods are called by the "index"
module to update the game state.

    gamepad = require "./input/gamepad.litcoffee"
    keyboard = require "./input/keyboard.litcoffee"

    context = require "./rendering/context.litcoffee"
    cloud = require "./rendering/cloud.litcoffee"
    matrix = require "./matrix.litcoffee"
    plane = require "./plane.litcoffee"
    misc = require "./misc.litcoffee"
    navmesh = require "./navmesh.litcoffee"
    vector = require "./vector.litcoffee"

    triangle = undefined

    testEntity = testMap = testNavmesh = undefined

# load
Called before the first "tick"/"draw" to load any resources needed by the game.
Execute the argument when you have finished successfully.

    load = (callback) ->
        keyboard()
        context.load()
        cloud.load (require "./testEntity.msc"), (testEntity_) ->
            testEntity = testEntity_
            cloud.load (require "./tracks/test/geometry.msc"), (testMap_) ->
                testMap = testMap_
                navmesh.load (require "./tracks/test/navmesh.msn"), (testNavmesh_) ->
                    testNavmesh = testNavmesh_
                    triangle = testNavmesh[0]
                    callback()
                    return
                return
            return
        return

# tick
Called at 20Hz to update game state.  Guaranteed to be called once between
"load" and "draw".  May be called more or than once per call to "draw" or not at
all.

    firstTick = true
    firstDraw = true

    entityTransform = []
    entityTransformToDraw = []
    entityTransformPreviousTick = []
    entityTransformPreviousDraw = []
    matrix.identity entityTransform

    surfaceCorrectedEntityTransform = []
    matrix.identity surfaceCorrectedEntityTransform

    cameraTransform = []
    cameraTransformPreviousDraw = []
    matrix.identity cameraTransform

    velocity = [0, 0, 0]
    xAxis = []
    yAxis = []
    zAxis = []
    translation = []
    acceleration = []
    forwardVelocity = []
    sidewardVelocity = []

    edgeCallback = (edge) -> vector.flatten velocity, edge.plane.normal, velocity

    tick = ->
        if not firstTick
            matrix.copy entityTransform, entityTransformPreviousTick

        matrix.translate velocity, entityTransform

        # Left/right rotation.
        matrix.rotateY ((gamepad.left - gamepad.right) * 0.1), entityTransform, true

        # Apply navmesh triangle collision.
        matrix.getTranslation entityTransform, translation
        triangle = navmesh.constrain translation, triangle, edgeCallback

        # Gravity.
        velocity[1] -= 0.2

        # Forwards/backwards movement.
        matrix.getZ entityTransform, zAxis

        # Determine if we're underground.
        altitude = plane.distance triangle.plane, translation

        if altitude < 0
            velocity = velocity
            plane.project triangle.plane, translation, translation

            # Reflecting the velocity against the hit surface but then
            # flattening it has the effect that hitting a ramp bounces you up it
            # but you don't bounce when falling onto the floor.
            vector.reflect velocity, triangle.plane.normal, velocity
            vector.flatten velocity, triangle.plane.normal, velocity

            vector.multiply.byScalar zAxis, ((gamepad.forward - gamepad.backward) * 0.2), acceleration
            vector.add.vector velocity, acceleration, velocity

            # Apply friction.  There is more sidewards than backwards/forwards.
            vector.flatten velocity, zAxis, sidewardVelocity
            vector.straighten velocity, zAxis, forwardVelocity
            vector.multiply.byScalar sidewardVelocity, 0.9, sidewardVelocity
            vector.multiply.byScalar forwardVelocity, 0.99, forwardVelocity
            vector.add.vector sidewardVelocity, forwardVelocity, velocity

        # Apply air resistance.
        vector.multiply.byScalar velocity, 0.98, velocity

        # This section attempts to align the entity with the triangle surface.

        # We take the triangle's normal as the Y/up axis.

        # First, flatten the Z/forward axis onto the surface.
        vector.flatten zAxis, triangle.plane.normal, zAxis
        vector.normalize zAxis, zAxis

        # Then, find the X/right axis which is perpendicular to the Z/forward
        # and Y/up axes.
        vector.cross triangle.plane.normal, zAxis, xAxis
        matrix.setX xAxis, surfaceCorrectedEntityTransform
        matrix.setY triangle.plane.normal, surfaceCorrectedEntityTransform
        matrix.setZ zAxis, surfaceCorrectedEntityTransform

        # Blend between our current transform and the aligned one.
        matrix.interpolate entityTransform, surfaceCorrectedEntityTransform, 0.1, entityTransform

        matrix.setTranslation translation, entityTransform

        if firstTick
            matrix.copy entityTransform, entityTransformPreviousTick
            firstTick = false
        return

# draw
Called with the progress through the current frame (a number between 0 and 1) to
redraw the scene.

    draw = (progress) ->
        if not firstDraw
            matrix.copy entityTransformToDraw, entityTransformPreviousDraw
            matrix.copy cameraTransform, cameraTransformPreviousDraw

        matrix.interpolate entityTransformPreviousTick, entityTransform, progress, entityTransformToDraw

        matrix.invert entityTransformToDraw, cameraTransform
        matrix.translate [0,-10, 10], cameraTransform

        if firstDraw
            matrix.copy entityTransformToDraw, entityTransformPreviousDraw
            matrix.copy cameraTransform, cameraTransformPreviousDraw
            firstDraw = false

        context.begin 0, 0, context.width, context.height, 1, cameraTransformPreviousDraw, cameraTransform, 0.1, 0.5, 0.9
        cloud.draw testMap
        cloud.draw testEntity, entityTransformPreviousDraw, entityTransformToDraw

        return

    module.exports = { load, tick, draw }


Fixed plane.fromTriangle generating a backwards normal.

A plane is an object containing:

- normal: A vector specifying the facing direction of the plane.
- distance: A number specifying how far from 0, 0, 0 along the normal the plane
            is.

Exports an object.

    vector = require "./vector.litcoffee"
    tempA = []
    tempB = []

Call the "fromTriangle" property with three input vectors forming a clockwise
triangle and an output object to create a plane on which those three vectors
lie.  If the output object is undefined, an empty one is created.  The output
object is returned.

    fromTriangle = (a, b, c, output) ->
        output = output or {}
        output.normal = output.normal or []
        vector.subtract.vector a, b, tempA
        vector.subtract.vector a, c, tempB
        vector.cross tempB, tempA, output.normal
        vector.normalize output.normal, output.normal
        output.distance = vector.dot output.normal, a
        output

Call the "distance" property with a plane and a vector.  The distance between
the plane and vector is returned.  If the vector is behind the plane, the
distance is negative.

    distance = (plane, input) -> (vector.dot plane.normal, input) - plane.distance

Call the "project" property with a plane, input vector and output vector to
write the nearest point to the input vector on the plane to the output vector.

    project = (plane, input, output) ->
        dist = distance plane, input
        vector.multiply.scalarBy dist, plane.normal, tempA
        vector.subtract.vector input, tempA, output
        return

    module.exports = {
        fromTriangle
        distance
        project
    }

A plane is an object containing:

- normal: A vector specifying the facing direction of the plane.
- distance: A number specifying how far from 0, 0, 0 along the normal the plane
            is.

Exports an object.

    vector = require "./vector.litcoffee"
    tempA = []
    tempB = []

Call the "fromTriangle" property with three input vectors forming a clockwise
triangle and an output object to create a plane on which those three vectors
lie.  If the output object is undefined, an empty one is created.  The output
object is returned.

    fromTriangle = (a, b, c, output) ->
        output = output or {}
        output.normal = output.normal or []
        vector.subtract.vector a, b, tempA
        vector.subtract.vector a, c, tempB
        vector.cross tempA, tempB, output.normal
        vector.normalize output.normal, output.normal
        output.distance = vector.dot output.normal, a
        output

Call the "distance" property with a plane and a vector.  The distance between
the plane and vector is returned.  If the vector is behind the plane, the
distance is negative.

    distance = (plane, input) -> (vector.dot plane.normal, input) - plane.distance

Call the "project" property with a plane, input vector and output vector to
write the nearest point to the input vector on the plane to the output vector.

    project = (plane, input, output) ->
        dist = distance plane, input
        vector.multiply.scalarBy dist, plane.normal, tempA
        vector.subtract.vector input, tempA, output
        return

    module.exports = {
        fromTriangle
        distance
        project
    }


Work on Batman.View docs

Work on Batman.View docs

# /api/App Components/Batman.View

`Batman.View`s connect a batman.js app to the DOM. This includes rendering HTML, handling DOM events, and maintaining view bindings. `Batman.View` extends `Batman.Object`. When subclassing `Batman.View`, you can create reusable UI components by defining attributes of the new view:

- [`::source`](/docs/api/batman.view.html#prototype_accessor_source) or [`::html`](/docs/api/batman.view.html#prototype_accessor_html) define the view's HTML.
- [`@option`](/docs/api/batman.view.html#class_function_option) adds context-based initialization options.
- [`@filter`](/docs/api/batman.view.html#class_function_filter) adds custom view filters.
- [Lifecycle hooks](/docs/views.html) fire when the view is loaded, rendered, or destroyed.

For more information about views, see [the guide](/docs/views.html).

## Accessors and Event Handlers

[View bindings](/docs/api/batman.view_bindings.html) have access to the views they're rendered by, so custom views are a great place to define view-specific accessors and event handlers. Then, you can connect them to your HTML with view bindings. For example, define a view:

```coffeescript
class CoffeeView extends Batman.View
  @accessor 'coffeeOfTheDay', -> "Guatemalan"
  drinkCoffee: -> alert("Yum!!")
```

then apply it to some HTML:

```html
<div data-view='CoffeeView'>
  <span data-bind='coffeeOfTheDay'></span>
  <button data-event-click='drinkCoffee'> Take a sip! </button>
<div>
```

Data bindings look for keys on their closest views first, so these bindings will be handled by `CoffeeView`. If the HTML inside a custom view will always be the same, you can use [`::source`](/docs/api/batman.view.html#prototype_accessor_source) or [`::html`](/docs/api/batman.view.html#prototype_accessor_html) to define it.

## ::constructor(options = {}) : Batman.View

Returns a new `Batman.View`. Since `Batman.View` extends `Batman.Object`, all `options` are mixed in to the new instance. Use this to override `html`, `node`, `superview`, `parentNode`, and/or your custom data.

## ::lookupKeypath(keypath : String)

Traverses up the view tree searching for `keypath` and returns the first
result or `undefined` if no match is found. The path it takes is:

current view → chain of superviews → layout view → active controller → app →
window

    test 'lookupKeypath returns the value if defined on the view or on an ancestor', ->
      superview = new Batman.View(cat: 'Meowie')
      subview = new Batman.View(superview: superview, dog: 'Fido')
      equal 'Fido', subview.lookupKeypath('dog'), "finds an accessor on itself"
      equal 'Meowie', subview.lookupKeypath('cat'), "finds an accessor on its superview"
      equal undefined, subview.lookupKeypath('bogusKeypath'), "returns undefined if the keypath isn't defined"

If used in an accessor, `keypath` is registered as source and will be correctly bound. `lookupKeypath` is used by [view bindings](/docs/api/batman.view_bindings.html) to get data.

## ::setKeypath(keypath, value)

Traverses the view tree searching for the specified keypath and sets the value
on the nearest ancestor which defines it. If no ancestor view defines the given
keypath, it will be set on the nearest ancestor which is not a
backing view.

`setKeypath` is used by [view bindings](/docs/api/batman.view_bindings.html) to set data.

    test 'setKeypath sets the value if defined on the view or on an ancestor', ->
      superview = new Batman.View(cat: 'Meowie')
      subview = new Batman.View(superview: superview, dog: 'Fido')
      subview.setKeypath('cat', 'Mittens')
      equal 'Mittens', superview.get('cat'), "updates an accessor on its superview"
      subview.setKeypath('dog', 'Lassie')
      equal 'Lassie', subview.get('dog'), "updates an accessor on itself"

    test 'setKeypath sets the value on the nearest non-backing view when not defined anywhere', ->
      superview = new Batman.View()
      view = new Batman.View(superview: superview)
      backingView = new Batman.BackingView(superview: view)

      backingView.setKeypath('animal', 'cat')
      equal 'cat', view.get('animal')

## ::%node : Node

Returns the DOM node that this view encapsulates.

Accessing `node` will load and parse the template if it isn't already
loaded.

    test 'node parses the template', ->
      view = new Batman.View(html: '
cat
')

      node = view.get('node')
      equal 'cat', node.firstChild.innerHTML

You can also access a view's `node` in its methods, for example, activating jQuery plugins:

```
class App.SearchBarView extends Batman.View
  viewDidAppear: ->
    $node = $(@get('node'))
    $node.typeahead() # <= whatever jQuery plugin you want!
```
## ::%source : String

This string will be used to fetch a view's HTML, relative to [`Batman.config.pathToHTML`](/docs/configuration.html).
You don't need to add `.html` to this string -- it will be added automatically.

Inside a controller action, batman.js provides a default source based on the
contoller's [`routingKey`](/docs/api/batman.controller.html#routingkey_and_minification) and the [controller action](/docs/api/batman.controller.html#actions).

You can set `source` in the class definition:

```
class App.HeaderNavigationView extends Batman.View
  source: 'layout/_header'
```

Or when calling `@render()` inside a controller action:

```
class App.PostsController extends Batman.Controller
  show: ->
    @set('post', new App.Post)
    if @get('post.isAlternative')
      @render(source: "posts/alternative_new")
    else
      @render() # defaults to 'posts/new'
```

## ::%html : String

The HTML source for the view's template. Setting this will parse the template
and build bindings automatically, but it will not be inserted into the DOM
until the view is added to a superview. You can specify a view's HTML when you define the class:

```
class App.SearchBarView extends Batman.View
  html: "<input type='text' placeholder='Enter a search term' />"
```

If you don't explicitly set `html` but you do set `source`, then getting `html`
will automatically fetch the template source from the local template store.

    test 'setting a source loads the correct template', ->
      Batman.View.store.set('/animals', '
cat
')
      view = new Batman.View(source: '/animals')

      node = view.get('node')
      equal 'cat', node.firstChild.innerHTML

## @filter(label : string, filter : function)

Defines a custom [view filter](/docs/api/batman.view_filters.html) for use within the `View`.

`filter` will be invoked with the pre-filter `value` and any arguments passed to the view filter. For example:

```coffeescript
class App.MultiplierView extends Batman.View
  @filter 'multiplyBy', (value, multiplier) -> value * multiplier
```

would handle:

```html
<div data-view='MultiplierView' data-context-amount='100'>
  <span data-bind='amount | multiplyBy 6'>
    <!-- would render to "600" -->
  </span>
</div>
```

_Note_: If the `View`'s HTML is loaded before the view is instantiated, this filter won't have been defined yet and batman.js will throw an error. Avoid this by defining your custom filter at app-level or by defining the `View`'s HTML with [`::source`](/docs/api/batman.view.html#prototype_accessor_source) or [`::html`](/docs/api/batman.view.html#prototype_accessor_html).

## @option(keys...)

Defines a custom option for the `View`. `@option` allows you to initialize your view with data from its context. For example:

```coffeescript
class App.MultiplierView extends Batman.View
  @option 'amount', 'multiplier'
  @accessor 'finalAmount', -> @get('amount') * @get('multiplier')
```

```html
<div data-view='MultiplierView' data-view-amount='10' data-view-multiplier='8'>
  <span data-bind='finalAmount'>
    <!-- would render to "80" !-->
  </span>
</div>
```

Options passed with `data-view-#{option}` may also be keypaths. Keypath changes will be tracked by the view.

## ::.superview : Batman.View

Returns the view's superview. Every view except an app's `LayoutView` has a superview.

## ::.subviews : Batman.Set

The set of direct children of this `View`. Since it's a [`Batman.Set`](/docs/api/batman.set.html), you can operate directly on this set and batman.js will automatically keep the DOM in sync.

Adding to a view's subviews will automatically update the tree and parse
the template and bindings. If the superview is in the DOM, this will
insert the current view's node into the DOM.

    test 'adding to a superview parses bindings', ->
      superview = new Batman.View()
      view = new Batman.View(html: '

', animal: 'cat')

      superview.subviews.add(view)
      equal 'cat', view.get('node').firstChild.innerHTML

Removing from a view's subviews will automatically remove the subview from
the DOM.

    test 'removing from the current superview removes the node from the DOM', ->
      superview = new Batman.View(html: '', parentNode: document.body)
      superview.get('node')
      view = new Batman.View(html: '', superview: superview)

      ok Batman.DOM.containsNode(superview.get('node'), view.get('node'))

      superview.subviews.remove(view)
      ok not Batman.DOM.containsNode(superview.get('node'), view.get('node'))

## ::removeFromSuperview()

Removes this view from its parent (and from the DOM), without killing it.

    test 'removing from the current superview removes the node from the DOM', ->
      superview = new Batman.View()
      view = new Batman.View(superview: superview)

      view.removeFromSuperview()
      ok not superview.subviews.has(view)

## ::die()

Kills this view, which renders it to forever unusable. This has the
following implications:

- The view is removed from its superview
- The view's node is removed from the DOM
- The view's bindings are destroyed
- The view's current subviews are killed

      test 'die kills the view', ->
        superview = new Batman.View()
        view = new Batman.View(superview: superview)

        view.die()
        equal true, view.isDead
        equal 0, superview.subviews.length

## ::.isDead : boolean

True if the view has been killed, false otherwise.

## ::destroySubviews()

Kills every subview of this view.

    test 'destroySubviews kills all subviews', ->
      superview = new Batman.View()
      one = new Batman.View(superview: superview)
      two = new Batman.View(superview: superview)

      superview.destroySubviews()
      ok one.isDead
      ok two.isDead

## ::propagateToSubviews(eventOrKey : string, value : Object)

If `value` is defined, set `eventOrKey` to `value` on the entire subtree.
Otherwise, fire `eventOrKey` on the entire subtree.

    test 'propagateToSubviews propagates events', ->
      superview = new Batman.View()
      one = new Batman.View(superview: superview)
      two = new Batman.View(superview: one)

      superview.on 'eventName', superSpy = createSpy()
      one.on 'eventName', oneSpy = createSpy()
      two.on 'eventName', twoSpy = createSpy()

      superview.propagateToSubviews('eventName')

      equal 1, superSpy.callCount
      equal 1, oneSpy.callCount
      equal 1, twoSpy.callCount

    test 'propagateToSubviews propagates keys', ->
      superview = new Batman.View()
      one = new Batman.View(superview: superview)
      two = new Batman.View(superview: one)

      superview.propagateToSubviews('key', 'value')

      equal superview.get('key'), 'value'
      equal one.get('key'), 'value'
      equal two.get('key'), 'value'

## @viewForNode(node, climbTree = true) : Batman.View

Finds the view acting as the current context for a node — i.e. perform the
reverse mapping of the view tree to the DOM. If you pass `false` for
`climbTree`, it won't traverse up the DOM, and will return `undefined` unless
the node is the view's root.

# /api/App Components/Batman.View

For a general explanation of `Batman.View` and how it works, see [the guide](/docs/views.html).

## ::constructor(options = {})

A `View` is a `Batman.Object`, so any options you pass are mixed in. Use this
to set `html`, `node`, `superview`, `parentNode` and/or your custom data.

    test 'constructor mixes in options', ->
      view = new Batman.View(animal: 'cat')
      equal 'cat', view.get('animal')

    test 'constructor automatically adds to the superview if supplied', ->
      superview = new Batman.View()
      view = new Batman.View(superview: superview)
      equal 1, superview.subviews.length

## ::lookupKeypath(keypath) : Object

Traverses up the view tree searching for the specified keypath, and returns the
result. This is equivalent to performing a `Batman.get` for each view above
`this` in the tree, until a defined result is returned. The path it takes is as
follows:

current view → chain of superviews → layout view → active controller → app →
window

If there is no match, `undefined` is returned. However, if used in an accessor
or binding, the entire path to the root will be registered as a potential
source of data. Consequently, if the keypath is later set on any part of the
chain, the data will be correctly bound.

`lookupKeypath` is the function invoked to locate data when evaluating a
binding.

    test 'lookupKeypath returns the value if defined on the view', ->
      view = new Batman.View(animal: 'cat')
      equal 'cat', view.lookupKeypath('animal')

    test 'lookupKeypath returns the value if defined on an ancestor', ->
      superview = new Batman.View(animal: 'cat')
      subview = new Batman.View(superview: superview)
      equal 'cat', subview.lookupKeypath('animal')

## ::setKeypath(keypath, value) : Object

Traverses the View tree searching for the specified keypath, and sets the value
on the nearest ancestor which defines it. If no ancestor view defines the given
keypath, it will be set on the nearest ancestor which is not a
backing view.

`setKeypath` is the function invoked to set data when using an input binding.

    test 'setKeypath sets the value if defined on the view', ->
      view = new Batman.View(animal: 'dog')

      view.setKeypath('animal', 'cat')
      equal 'cat', view.get('animal')

    test 'setKeypath sets the value if defined on an ancestor', ->
      superview = new Batman.View(animal: 'dog')
      subview = new Batman.View(superview: superview)

      subview.setKeypath('animal', 'cat')
      equal 'cat', superview.get('animal')

    test 'setKeypath sets the value on the nearest non-backing view when not defined anywhere', ->
      superview = new Batman.View()
      view = new Batman.View(superview: superview)
      backingView = new Batman.BackingView(superview: view)

      backingView.setKeypath('animal', 'cat')
      equal 'cat', view.get('animal')

## ::%node : Node

A reference to the DOM node that this view encapsulates. The entire tree
beneath this node is also the responsibility of this view and/or its subviews.

Accessing `node` will load and parse the template on demand if it isn't already
loaded.

    test 'node parses the template', ->
      view = new Batman.View(html: '
cat
')

      node = view.get('node')
      equal 'cat', node.firstChild.innerHTML

You can also access a view's `node` in its methods, for example, activating jQuery plugins:

```
class App.SearchBarView extends Batman.View
  viewDidAppear: ->
    $node = $(@get('node'))
    $node.typeahead() # <= whatever jQuery plugin you want!
```
## ::%source : String

This string will be used to fetch a view's HTML, relative to [`Batman.config.pathToHTML`](/docs/configuration.html).
You don't need to add `.html` to this string -- it will be added automatically.

Inside a controller action, batman.js provides a default source based on the
contoller's [`routingKey`](/docs/api/batman.controller.html#routingkey_and_minification) and the [controller action](/docs/api/batman.controller.html#actions).

You can set `source` in the class definition:

```
class App.HeaderNavigationView extends Batman.View
  source: 'layout/_header'
```

Or when calling `@render()` inside a controller action:

```
class App.PostsController extends Batman.Controller
  show: ->
    @set('post', new App.Post)
    if @get('post.isAlternative')
      @render(source: "posts/alternative_new")
    else
      @render() # defaults to 'posts/new'
```

## ::%html : String

The HTML source for the view's template. Setting this will parse the template
and build bindings automatically, but it will not be inserted into the DOM
until the view is added to a superview. You can specify a view's HTML when you define the class:

```
class App.SearchBarView extends Batman.View
  html: "<input type='text' placeholder='Enter a search term' />"
```

If you don't explicitly set `html` but you do set `source`, then getting `html`
will automatically fetch the template source from the local template store.

    test 'setting a source loads the correct template', ->
      Batman.View.store.set('/animals', '
cat
')
      view = new Batman.View(source: '/animals')

      node = view.get('node')
      equal 'cat', node.firstChild.innerHTML

## ::.superview : Batman.View

A reference to the current superview (the direct ancestor in the tree). This is
used for traversing the tree when searching for data, as in
`View::lookupKeypath`.

## ::.subviews : Batman.Set

The set of direct children of a `View`. To manipulate the view tree, you should
operate directly on this set — batman.js will automatically keep the DOM in
sync with the logical tree.

## ::subviews.add(view)

Adding to a view's subview set will automatically update the tree, and parse
the template and bindings. If the superview is already in the DOM, this will
insert the current view's node into the DOM.

    test 'adding to a superview parses bindings', ->
      superview = new Batman.View()
      view = new Batman.View(html: '

', animal: 'cat')

      superview.subviews.add(view)
      equal 'cat', view.get('node').firstChild.innerHTML

## ::subviews.remove(view)

Removing from a view's subview set will automatically remove the subview from
the DOM.

    test 'removing from the current superview removes the node from the DOM', ->
      superview = new Batman.View(html: '', parentNode: document.body)
      superview.get('node')
      view = new Batman.View(html: '', superview: superview)

      ok Batman.DOM.containsNode(superview.get('node'), view.get('node'))

      superview.subviews.remove(view)
      ok not Batman.DOM.containsNode(superview.get('node'), view.get('node'))

## ::removeFromSuperview()

Removes this view from its parent, without killing it.

    test 'removing from the current superview removes the node from the DOM', ->
      superview = new Batman.View()
      view = new Batman.View(superview: superview)

      view.removeFromSuperview()
      ok not superview.subviews.has(view)

## ::die()

Kills this view, which renders it to forever unusable. This has the
following implications:

- The view is removed from its superview
- The view's node is removed from the DOM
- The view's bindings are destroyed
- The view's current subviews are killed

    test 'die kills the view', ->
      superview = new Batman.View()
      view = new Batman.View(superview: superview)

      view.die()
      equal true, view.isDead
      equal 0, superview.subviews.length

## ::.isDead : boolean

True if the view has been killed, false otherwise.

## ::destroySubviews()

Kills every subview of this view.

    test 'destroySubviews kills all subviews', ->
      superview = new Batman.View()
      one = new Batman.View(superview: superview)
      two = new Batman.View(superview: superview)

      superview.destroySubviews()
      ok one.isDead
      ok two.isDead

## ::propagateToSubviews(eventOrKey : string, value : Object)

If `value` is defined, set `eventOrKey` to `value` on the entire subtree.
Otherwise, fire `eventOrKey` on the entire subtree.

    test 'propagateToSubviews propagates events', ->
      superview = new Batman.View()
      one = new Batman.View(superview: superview)
      two = new Batman.View(superview: one)

      superview.on 'eventName', superSpy = createSpy()
      one.on 'eventName', oneSpy = createSpy()
      two.on 'eventName', twoSpy = createSpy()

      superview.propagateToSubviews('eventName')

      equal 1, superSpy.callCount
      equal 1, oneSpy.callCount
      equal 1, twoSpy.callCount

    test 'propagateToSubviews propagates keys', ->
      superview = new Batman.View()
      one = new Batman.View(superview: superview)
      two = new Batman.View(superview: one)

      superview.propagateToSubviews('key', 'value')

      equal superview.get('key'), 'value'
      equal one.get('key'), 'value'
      equal two.get('key'), 'value'

## @viewForNode(node, climbTree = true) : Batman.View

Finds the view acting as the current context for a node — i.e. perform the
reverse mapping of the view tree to the DOM. If you pass `false` for
`climbTree`, it won't traverse up the DOM, and will return `undefined` unless
the node is the view's root.

## ::filter(label : string, filter : function)

Defines a filter on the `View` class for use within the `View` during rendering.


Fix greeting when starting server

Fix greeting when starting server

nodePush Pushserver for Tims Chat
=================================

Copyright Information
---------------------

	"@author	Tim Düsterhus"
	"@copyright	2012-2013 Tim Düsterhus"
	"@license	BSD 3-Clause License <http://opensource.org/licenses/BSD-3-Clause>"
	"@package	be.bastelstu.wcf.nodePush"

Setup
-----

Load required namespaces.

	express = require 'express'
	http = require 'http'
	io = require 'socket.io'
	net = require 'net'
	fs = require 'fs'

Load config

	config = require '../config.js'

Initialize sane values.

	config.port ?= 9001
	config.host ?= '0.0.0.0'
	config.user ?= 'nobody'
	config.group ?= 'nogroup'

Prepare environment

	log = (message) ->
		console.log "[be.bastelstu.chat.nodePush] #{message}"

	thousandsSeparator = (number) ->
		String(number).replace /(^-?\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1,'

	# Ensure our namespace is present
	be = be ? {}
	be.bastelstu ?= {}
	be.bastelstu.chat ?= {}

be.bastelstu.chat.nodePush
==========================

	class be.bastelstu.chat.nodePush

Attributes
----------
		unixSocket: "#{__dirname}/../inbound.sock"
		app: null
		server: null
		io: null
		stats:
			status: 0
			outbound:
				total: 0
				current: 0
			inbound: 0
			messages: { }
			bootTime: new Date()

Methods
-------
**constructor()**

		constructor: ->
			log 'Starting nodePush'
			log "PID is #{process.pid}"
			log "Using port: #{config.port}"

			@stats.bootTime = new Date()

			@initUnixSocket()
			@initServer()

Bind shutdown function to needed events.

			process.on 'exit', @shutdown.bind @
			process.on 'uncaughtException', @shutdown.bind @
			process.on 'SIGINT', @shutdown.bind @
			process.on 'SIGTERM', @shutdown.bind @

Set nice title for PS.

			process.title = 'nodePush - Tims Chat'

**initServer()**
Initialize socket server.

		initServer: ->
			log 'Initializing Frontend'
			@app = express()
			@server = http.createServer @app
			@io = io.listen @server

			@server.listen config.port, config.host, null, =>
				if process.getuid() is 0 or process.getgid() is 0
					try
						log 'Trying to shed root privilegies'
						process.setgid config.group
						process.setuid config.user
						log "New User ID: #{process.getuid()}, New Group ID: #{process.getgid()}"
					catch e
						log 'Cowardly refusing to keep the process alive as root.'
						process.exit 1

Initialize intervals for tick events. The ticks are sent every 15 / 30 / 60 / 90 / 120 seconds.

				setInterval =>
					@sendMessage 'tick15'
				, 15e3
				setInterval =>
					@sendMessage 'tick30'
				, 30e3
				setInterval =>
					@sendMessage 'tick60'
				, 60e3
				setInterval =>
					@sendMessage 'tick90'
				, 90e3
				setInterval =>
					@sendMessage 'tick120'
				, 120e3

				log "Done"

Initialize production environment.

			@io.set 'log level', 1
			@io.set 'browser client etag', true
			@io.set 'browser client minification', true
			@io.set 'browser client gzip', true

Development configuration.

			@io.configure 'development', =>
				@io.set 'log level', 3
				@io.set 'browser client etag', false
				@io.set 'browser client minification', false

Record statistics for Websocket connections.

			@io.sockets.on 'connection', (socket) =>
				@stats.outbound.total++
				@stats.outbound.current++

				socket.on 'disconnect', =>
					@stats.outbound.current--

Show the status page when '/' is requested.

			@app.get '/', (req, res) =>
				res.type 'text/plain'
				@stats.status++
				reply = """
				Up since: #{@stats.bootTime}
				Status page: #{thousandsSeparator @stats.status} Requests
				Outbound: #{thousandsSeparator @stats.outbound.current} now - #{thousandsSeparator @stats.outbound.total} Total
				Inbound: #{thousandsSeparator @stats.inbound}
				Messages:
				"""
				for message, amount of @stats.messages
					reply += "\n	#{message}: #{thousandsSeparator amount}"

				res.send reply

**sendMessage(name)**
Sends a message with the given name.

		sendMessage: (name) ->
			@stats.messages[name] ?= 0
			@stats.messages[name]++
			@io.sockets.send name

**initUnixSocket()**
Initialize PHP side unix socket.

		initUnixSocket: ->
			log 'Initializing inbound socket'
			socket = net.createServer (c) =>
				@stats.inbound++

				c.on 'data', (data) =>
					setTimeout =>
						@sendMessage data.toString().trim()
					, 20
					c.end()

				c.on 'end', ->
					c.end()

				c.setTimeout 5e3, ->
					c.end()

			socket.listen @unixSocket
			fs.chmod @unixSocket, '777'

**shutdown()**
Performs a clean shutdown of nodePush.

		shutdown: (message) ->
			if not message
				log 'Shutting down'
			else
				log "Shutting down: #{message}"

			fs.unlinkSync @unixSocket

			process.removeAllListeners()
			process.exit()

And finally start the service.

	new be.bastelstu.chat.nodePush()

nodePush Pushserver for Tims Chat
=================================

Copyright Information
---------------------

	"@author	Tim Düsterhus"
	"@copyright	2012-2013 Tim Düsterhus"
	"@license	BSD 3-Clause License <http://opensource.org/licenses/BSD-3-Clause>"
	"@package	be.bastelstu.wcf.nodePush"

Setup
-----

Load required namespaces.

	express = require 'express'
	http = require 'http'
	io = require 'socket.io'
	net = require 'net'
	fs = require 'fs'

Load config

	config = require '../config.js'

Initialize sane values.

	config.port ?= 9001
	config.host ?= '0.0.0.0'
	config.user ?= 'nobody'
	config.group ?= 'nogroup'

Prepare environment

	log = (message) ->
		console.log "[be.bastelstu.chat.nodePush] #{message}"

	thousandsSeparator = (number) ->
		String(number).replace /(^-?\d{1,3}|\d{3})(?=(?:\d{3})+(?:$|\.))/g, '$1,'

	# Ensure our namespace is present
	be = be ? {}
	be.bastelstu ?= {}
	be.bastelstu.chat ?= {}

be.bastelstu.chat.nodePush
==========================

	class be.bastelstu.chat.nodePush

Attributes
----------
		unixSocket: "#{__dirname}/../inbound.sock"
		app: null
		server: null
		io: null
		stats:
			status: 0
			outbound:
				total: 0
				current: 0
			inbound: 0
			messages: { }
			bootTime: new Date()

Methods
-------
**constructor()**

		constructor: ->
			log 'Starting Pushserver for Tims Chat'
			log "PID is #{process.pid}"
			log "Using port: #{config.port}"

			@stats.bootTime = new Date()

			@initUnixSocket()
			@initServer()

Bind shutdown function to needed events.

			process.on 'exit', @shutdown.bind @
			process.on 'uncaughtException', @shutdown.bind @
			process.on 'SIGINT', @shutdown.bind @
			process.on 'SIGTERM', @shutdown.bind @

Set nice title for PS.

			process.title = 'nodePush - Tims Chat'

**initServer()**
Initialize socket server.

		initServer: ->
			log 'Initializing Frontend'
			@app = express()
			@server = http.createServer @app
			@io = io.listen @server

			@server.listen config.port, config.host, null, =>
				if process.getuid() is 0 or process.getgid() is 0
					try
						log 'Trying to shed root privilegies'
						process.setgid config.group
						process.setuid config.user
						log "New User ID: #{process.getuid()}, New Group ID: #{process.getgid()}"
					catch e
						log 'Cowardly refusing to keep the process alive as root.'
						process.exit 1

Initialize intervals for tick events. The ticks are sent every 15 / 30 / 60 / 90 / 120 seconds.

				setInterval =>
					@sendMessage 'tick15'
				, 15e3
				setInterval =>
					@sendMessage 'tick30'
				, 30e3
				setInterval =>
					@sendMessage 'tick60'
				, 60e3
				setInterval =>
					@sendMessage 'tick90'
				, 90e3
				setInterval =>
					@sendMessage 'tick120'
				, 120e3

				log "Done"

Initialize production environment.

			@io.set 'log level', 1
			@io.set 'browser client etag', true
			@io.set 'browser client minification', true
			@io.set 'browser client gzip', true

Development configuration.

			@io.configure 'development', =>
				@io.set 'log level', 3
				@io.set 'browser client etag', false
				@io.set 'browser client minification', false

Record statistics for Websocket connections.

			@io.sockets.on 'connection', (socket) =>
				@stats.outbound.total++
				@stats.outbound.current++

				socket.on 'disconnect', =>
					@stats.outbound.current--

Show the status page when '/' is requested.

			@app.get '/', (req, res) =>
				res.type 'text/plain'
				@stats.status++
				reply = """
				Up since: #{@stats.bootTime}
				Status page: #{thousandsSeparator @stats.status} Requests
				Outbound: #{thousandsSeparator @stats.outbound.current} now - #{thousandsSeparator @stats.outbound.total} Total
				Inbound: #{thousandsSeparator @stats.inbound}
				Messages:
				"""
				for message, amount of @stats.messages
					reply += "\n	#{message}: #{thousandsSeparator amount}"

				res.send reply

**sendMessage(name)**
Sends a message with the given name.

		sendMessage: (name) ->
			@stats.messages[name] ?= 0
			@stats.messages[name]++
			@io.sockets.send name

**initUnixSocket()**
Initialize PHP side unix socket.

		initUnixSocket: ->
			log 'Initializing inbound socket'
			socket = net.createServer (c) =>
				@stats.inbound++

				c.on 'data', (data) =>
					setTimeout =>
						@sendMessage data.toString().trim()
					, 20
					c.end()

				c.on 'end', ->
					c.end()

				c.setTimeout 5e3, ->
					c.end()

			socket.listen @unixSocket
			fs.chmod @unixSocket, '777'

**shutdown()**
Performs a clean shutdown of nodePush.

		shutdown: (message) ->
			if not message
				log 'Shutting down'
			else
				log "Shutting down: #{message}"

			fs.unlinkSync @unixSocket

			process.removeAllListeners()
			process.exit()

And finally start the service.

	new be.bastelstu.chat.nodePush()