<file_sep>---
title: 0.2.0 - Usernames
date: 2015-03-10
layout: post
---

Just deployed version 0.2.0 of the SceneVR server. It now supports usernames! [Claim a username](//login.scenevr.com/users/sign_up) now at login.scenevr.com.

## Behind the scenes

I've been thinking about authentication for scenevr for a long time. Initially I thought of just letting people name themselves whatever they want, with name collisions, and no promise that the person is who they say they are, but I didn't like that idea, because I wanted to be able to do authentication on names (eg, if `player.name=='bnolan'` then they can do god-mode stuff to the scene). So I had a hack at doing an authentication server using oauth or openid, but to be honest, they're just so fucking complicated, and didn't have good support for automatically granting tokens. So eventually I settled on a solution using [JSON Web Tokens](http://jwt.io/) which came together quickly and works well. I also updated the renderer so that if a `<player />` has their name attribute set, then they will have a name above them, and their name will show up in the chat logs.

<img src="/images/blog/usernames.png" class="screenshot" />

## Anonymity

I like [this post](https://highfidelity.com/blog/2014/03/identity-in-the-metaverse/) by high fidelity. Basically, you shouldn't be forced to display your username while you wander around scenes. Sure, in the [homeroom](//client.scenevr.com/) it's cool to have your name. But maybe if you're visiting /r/gentlemanboners, you're not so keen on everyone seeing you wander around the gallery.

That's why anonymity is built in to scenevr. You aren't required to log in to access scenes, and you can transition from authenticated (with a name over your avatar) to anonymous at any time, without leaving the room.

## Try it out!

So go try it out, just click the 'login' button in the top right of the [client](//client.scenevr.com) and you can sign up and then log in so that everybody in scenevr knows your name. It's like the bar in cheers. Talking of which, that'd make a good scene.

<img src="/images/blog/cheersbar.jpg" class="screenshot" /><file_sep>---
title: Box
primary_navigation: true
---

# Box

A box is a simple cube. It inherits from [Element](/element.html).

## Sample XML

```xml
<box id="cubey" position="1 2 3" scale="1 1 1" style="color: #f07" />
```

## Screenshot

<img src="/images/box.png" class="screenshot" />

## Styles

### color

The color of the box. Can be set using hexadecimal code or color names. For example to set every box to be red, use the following code.

```javascript
document.getElementsByTagName("box").forEach(function(box){
    box.style.color = '#ff0000';
});
```

### texture-map

A texture map that is applied to the box. Texture-maps are lambertian shaded. Textures should be sized as a power of 2 (eg 256x256, 512x512).

```
style="texture-map: url(/images/crate.png)"`
```

### texture-repeat

How many times is the texture repeated in the U and V directions.

```
style="texture-map: url(/images/grid.png); texture-repeat: 100 100"
```
<file_sep>---
title: SceneVR downloadable IDE
date: 2015-11-30
layout: post
---
<div class="md"><p>Hi all, long time no post! I&#39;ve been working on a downloadable version of SceneVR that has an installer and is a quick and easy way to let you start building Scenes, without having to install npm or understand how node.js works.</p>

<p><a href="http://i.imgur.com/a0BUlMT.png">This is how the editor looks</a>.</p>

<p>I&#39;m working out the last few bugs today and hope to get it released. It will make it much much easier to create scenes on your own computer, and the installer also acts as a server, so people on your own LAN can connect to your server and walk around the scenes as you edit them.</p>

<p>I&#39;ve also added google cardboard support to the client, so you can use your phone to load scenes.</p>
</div><br /><a href='https://www.reddit.com/r/scenevr/comments/3urgld/scenevr_downloadable_ide/'>Read comments on reddit...</a><file_sep>---
title: Update getting started instructions
date: 2015-04-02
layout: post
---

[@qster123](//github.com/qster123) pointed out that the getting started docs were incomplete for windows users, so I updated them to have better instructions. You don't require git to get started, and it explains that the server autorestarts when you make changes. :)<file_sep>---
title: Gamepad support and Deltas
date: 2015-03-02
tags: server
layout: post
---

Big news today. I merged in the Gamepad support pull request from @brodavi, so you can now walk around the scene using an xbox 360 controller. You need to click the `A` button before the gamepad will be recognized and the thumbsticks enabled.

Today I also committed the `deltas` branch.

### Before deltas

Before the delta branch, the scenevr server sent the state of *every single element in the scene* 5 times a second to every connected client.

### After deltas

Using a bunch of `object.observe` calls, the scenevr server now keeps track of what elements are changing (because they're animated, or responding to user behaviour) and only send those over the wire. This results in:

* Much lower CPU utilisation on the server
* Less network traffic
* Can support more concurrent users
* Simpler client side change detection

It's a big win, and although there are still a few bugs to iron out, it's deployed on scenevr.hosting and client.scenevr.com, so you can try it out now.

Note that this change requires that you upgrade your version of node to 0.12.0 (the latest release).

### Changed the face

@ujelleh had complained that the face was too creepy. So I replaced it with the look of disapproval face. 

ಠ_ಠ<file_sep>---
title: Roadmap
primary_navigation: false
position: 5
---

# Roadmap

### Avatar customisation

Allow users to set girth, height and color of avatars. Make a scene for choosing a face. Render a face on the avatars.

### Friend list

Keep a list of your friends, be able to message them in game (voice message or text chat), and teleport to their location.

### Google Cardboard

Use the hmd polyfill to support google cardboard. Investigate navigation techniques that will work with the one bit 'magnet' input system. Probably look at the ground and click to teleport.

### Physics on the server

Use bullet physics on the server, with a fallback to cannon.js, add physical attributes to elements so they can be simulated on the server.

### \<group /\> element

Create a group element for nesting transforms, allows things like:

```xml
<group position="1 2 3">
  <box />
</box>
```

### Break server into smaller modules

As per the npm philosophy, break the server into several smaller modules, so that people can re use the scenegraph/dom code for other purposes and projects.

### Persistence

Investigate and expose a persistence method for scenes, something like localStorage, or webSQL. Possibly use redis for this?

### Support convexpolyhedra collision meshes

Create a model format for representing polyhedra as collision meshes (possibly create hulls around .obj models), to allow collision models that aren't cube.

### Add \<sphere /\> element

Allow spheres, potentially with `subdivision` count as an attribute.

### Add \<light /\> element

Allow point lights and ambient light to be set as an element.

## Previous goals

These are things that used to be on the list but are on the back burner for now.

### Unity client

Investigate porting the web client to unity (c#), and measure the performance advantages. This is particularly with a goal to having a highly performant mobile client. Investigate opensource licenses that can be used with Unity projects and plugins. Find out how to render to texture for each platform (for the billboards).

### Gear VR

Try using the chrome webview, or the unity client, to create a gear vr + bluetooth controller mobile interface for SceneVR.

### Hosting

Create a hosting server that allows people to easily serve SceneVR scenes. Have some error handling (or provide integration with raygun.io) for reporting errors that occur in the scene.

### Blender exporter

Take the existing blender export code and make it work well, generating entire scene files with collision meshes and seperate .obj objects, keeps existing blender object names and converts them into `id` attribute.


## Performance

SceneVR is written in pure javascript at the moment, with a few node.js binary modules on platforms that support them. The client, server and scripts are all written in javascript. Earlier in the lifecycle of SceneVR, I wrote a server in c++, that embedded v8. And I have also worked on various native viewers for the SceneVR protocol. As the project progresses, there is no reason that parts of the client or server cannot be replaced by close-to-the-metal components, with a native fallback for cases where ultra-performance isn't required.

For example, cannon.js can be augmented with bullet. The websocket protocol can be augmented by raknet. The dom-lite implementation could be augmented with the dom implementation in webkit or firefox. The client can be rewritten in unity, unreal, jmonkeyengine or ogre. Some of these libraries already have node.js bindings, others would need new bindings written, but with node-gyp, it's relatively straightforward to create bindings to existing libraries. It would even be possible to write the entire server in c++, embedding v8, although this would prevent people extending their scenes with custom node modules.

In summary, there is a long path ahead for optimisations to SceneVR, but we won't be taking any steps until we are forced to by performance bottlenecks.

In the words of [<NAME>](http://c2.com/cgi/wiki?PrematureOptimization):

 "Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: **premature optimization is the root of all evil**. Yet we should not pass up our opportunities in that critical 3%."
<file_sep>---
layout: post
title: "Making a door"
date: 2015-04-13
---
 
I just put up a [gist of making a door](https://gist.github.com/bnolan/a740dccdde9c0d3cb5ad) using SceneQuery. There's a few things going on here. First up you'll need to download [scenequery](http://github.com/scenevr/scenequery) from github. Next up create two grey walls, and a pink door.

<img src="https://pbs.twimg.com/media/CCbX14DUAAAoaBX.png" class="screenshot" />

Then you need to add a `click` event handler to the door. We store the state of whether the door is opened or closed by using a css class. This doesn't actually have any effect on the display of the door, it's just a handy place to store some state.

Now, we could have the door open instantly, but its cooler if we take 1 second (1000 milliseconds) for the door to animate open. To do this, we use the `animate` method in SceneQuery. Note that at the moment you can only animate position and rotation. So we work out the state the door needs to move to, then animate the door. And boom! You have an animated dooor.

```html
<scene>
 
  <spawn position="0 0 10" />
 
  <box class="wall" style="color: #ccc" scale="10 4 0.2" position="-6 2 0" />
  <box class="wall" style="color: #ccc" scale="10 4 0.2" position="6 2 0" />
 
  <box class="door" style="color: #f07" scale="2 4 0.2" position="0 2 0" rotation="0 0 0" />
 
  <script src="scripts/scenequery.js" />
 
  <script>
    var door = $('box.door').addClass('closed');

    door.click(function (e) {
      var endRotation, endPosition;

      if (door.hasClass('closed')) {
        // open door
        endRotation = new Euler(0, -Math.PI / 2, 0);
        endPosition = new Vector(1, 2, -1);
        door.removeClass('closed');
      } else {
        // close door
        endRotation = new Euler(0, 0, 0);
        endPosition = new Vector(0, 2, 0);
        door.addClass('closed');
      }

      door.animate({
        rotation : endRotation,
        position: endPosition
      }, 1000);

    });
  </script>
</scene>
```

<file_sep>---
title: New Homeroom
date: 2015-02-28
tags: homeroom
layout: post
---

I released a new homeroom today. It is a gallery with several tall thin windows looking to the east, and corridors off to the three wings, the alien room (all hail our alien overlord), the reddit gallery room (make sure you click the portals to visit the galleries) and a room that is currently empty but will become a link to scenes that people submit to [/r/scenevr](//reddit.com/r/scenevr).

<img src="/images/blog/homeroom.png" class="screenshot" />

The scene was modelled originally in Sketchup (taking care to make sure the faces are facing the right way and deleting bits of geometry that you can't see from inside the scene). It was then exported to blender where I set up lighting, merged all the geometry together, and then baked the lights.

Because SceneVR doesn't support mesh collision at the moment, I had to create a seperate collision model for the homeroom.

```xml
<!--  Gallery model with collision disabled -->
<model src="/models/home.obj" position="0 0.01 0" style="collision: none; color: #555; light-map: url(/textures/home-lightmap.jpg)"/>
```

I did this by placing about 30 boxes around the walls and corridors. I then use our blender export script which outputs a bunch of invisible boxes that are used only for collision:

```xml
<!--  Collision  -->
<box position="0.16626548767089844 -1.505699634552002 -0.6487710475921631" scale="80.0 2.0 200.0" rotation="0.0 0.0 0.0" style="color: #f0a; visibility: hidden;"/>
<box position="-3.6149256229400635 6.710185527801514 1.4967803955078125" scale="2.0 19.231510162353516 2.0" rotation="0.0 0.0 0.0" style="color: #f0a; visibility: hidden;"/>
<box position="5.27642822265625 6.710185527801514 1.4967803955078125" scale="2.0 19.231510162353516 2.0" rotation="0.0 0.0 0.0" style="color: #f0a; visibility: hidden;"/>
```

The rest of the elements were then placed manually around the scene, as well as an elevator and some sliding panels that hide links to reddit galleries. The galleries are auto-generated using the script in [scene-scripts](https://github.com/bnolan/scene-scripts).

The new homeroom has been posted a few places around the internet, so there have been people joining the room every few minutes all day - it's been great chatting with you all!<file_sep>---
layout: post
title: "An open virtual world"
date: 2015-04-17
---

I didn't start SceneVR because I wanted to build the eponymous virtual world.

I built it because I want there to be an opensource, open natured virtual world, that everyone can contribute to and be in. I don't want a hundred different virtual worlds that don't interoperate. I want to be able to walk from one room to another room, scene to scene, world to world, without leaving your browser or client.

## JanusVR

James and I have been talking for a while. During a chat last week, we got to understand each other a bit better, and I mocked up a proxy that allowed Janus to connect to SceneVR worlds. After that demo, James blew my mind by adding support for Scene markup to Janus.

The thing with Janus, is that James invented most of this shit.

* Portals. James invented them.
* Rooms with html-like markup. James invented that.
* A white floor with a grid on it and a skybox in the distance? Well, the matrix invented that, but James reintroduced it to the conscience. ;)

## Altspace and Convrge

Altspace and Convrge are doing awesome stuff in the VR space. They have nice clients and altspace has a javascript API coming out.

But they're all seperate worlds.

What is the point of making a bunch of worlds that don't interoperate?

I really want us to work together to make it so you can walk from one world to another. That doesn't mean that I want everyone to build their worlds in Scene, but I really want is to make a way that you can walk straight from Janus to Scene to Altspace to Convrge.

Let's make it happen.<file_sep>---
title: Billboard
primary_navigation: true
---

# Billboard

A billboard is a white box that has an html page as a texture on the front face. It inherits from [Element](/element.html).

## Sample XML

```xml
  <billboard id="hello" position="0 1 0" scale="2 2 0.2"><![CDATA[
      <h1>Hello world</h1>
      <br />
      <center>
        <img src="images/smiley.png" />
      </center>
  ]]></billboard>
```

## Screenshot

<img src="/images/billboard.png" class="screenshot" />

## Scripting

You can change the content of a billboard `cdata` node by assigning to the `data` attribute. This will cause the billboard to be re-generated (for doing a scoreboard, or other dynamic data). Note that re-generating billboards can be expensive, try and not do it more than once per second.

```javascript
  document.getElementById("hello").firstChild.data = '<h1>It has all changed</h1>';
```

## Notes

The html content inside a billboard must be enclosed in a `<![CDATA[ ... ]]>` block. This is so that the scene parser doesn't have to try and parse all the html on the server, but can instead send it straight to the client, where the client renders it.

## Limitations

Because of [limitations](https://code.google.com/p/chromium/issues/detail?id=294129) in some browsers, scenevr cannot render the html directly to a texture, but instead uses [html2canvas](http://html2canvas.hertzen.com/) to convert the html into a texture. This means that scenevr only supports a subset of html. You cannot use `form`, `iframe`, `embed` or many other things. Also note that the html is only rendered once and you cannot interact with it. So you can't click on links embedded in the html, nor will animated gifs work correctly.

These are some pretty serious limitations, but the goal for billboards, is to have an easy way to render text, images and tables, which html is great for. Although it is possible to use css3 to embed fully interactive web pages in a scenevr scene, that has many limitations (it doesnt work in rift mode, depth sorting gets broken) and is extremely slow. Over time we expect more html features to be rendered correctly, and it would be cool to be able to interact with forms, but for now, just use billboards to render static text and images.

Billboards have a physical body, so you can collide with them. Most of the galleries just use plain billboards.<file_sep>---
title: Scene client can now be loaded from other domains
date: 2015-05-04
layout: post
---
<div class="md"><p>I just published the scene-client 1.0.2. This is part of my goal to make SceneVR work so that you can include scenes on your own websites, by just including a script tag and a bit of javascript. This release.</p>

<p>Similair to the way the google maps api lets people embed maps on their own site the scene client will eventually be usable so you can have scenes embedded on your site.</p>

<p>There will probably be some limitations to this initially, like you will be anonymous, and if you enter a portal that takes you elsewhere on the internet, you&#39;ll be redirected to the full scenevr client (as scenevr.com), but it&#39;ll be a great way for putting your content on your own server.</p>

<p>This is all part of upgrading scenevr.com with the new server i&#39;m working on, that interoperates with the rest of the internet a lot better, and makes Scene less of an island and more a part of the web.</p>
</div><br /><a href='http://www.reddit.com/r/scenevr/comments/34sc3g/sceneclient_102_scene_client_can_now_be_loaded/'>Read comments on reddit...</a><file_sep>require 'json'
require 'open-uri'
require 'date'
require 'htmlentities'

json = JSON.parse(open('https://www.reddit.com/r/scenevr.json').readlines.join)

json['data']['children'].each do |child|
  child = child['data']

  next unless child['selftext_html']
  next unless child['author'] == 'captainbenis'

  date = DateTime.strptime(child['created'].to_s,'%s').strftime('%Y-%m-%d')
  title = child['title'].gsub(/:/,' ')

  slug = date + '-' + title.downcase.gsub(/[^a-z]+/,'-').slice(0,50).sub(/^-+/,'').sub(/-+$/,'') + '.md'

  html = HTMLEntities.new.decode(child['selftext_html'])
  html = html.gsub(/<!--.+?-->/,'')
  html += "<br /><a href='#{child['url']}'>Read comments on reddit...</a>"

  post = "---\ntitle: #{title}\ndate: #{date}\nlayout: post\n---\n" + html

  next if File.exists?('source/posts/' + slug)

  File.open('source/posts/' + slug, 'w') { |f| f.write(post) }

  puts slug
end

<file_sep>---
title: Replacing logins with something else...
date: 2015-05-01
layout: post
---
<div class="md"><p>I&#39;ve decided that running a login server, with username / password / captchas / email reset / etc isn&#39;t a key component of what we&#39;re trying to do with Scene.</p>

<p>The biggest problem is the friends list. When you log into scene, your friends should be highlighted in a different color, and you should be able to see which Scene they are in, and teleport straight to them to join them. To do this requires a social graph, and there are two options:</p>

<p><strong>Create a social graph</strong>, this would mean creating a way to add friends in Scene, and start to build up a network. This would be fun to code up, and valuable for Scene the company to own, but it&#39;d be a massive pain the ass, and how many people can be bothered re-adding all their friends to a new social network.</p>

<p><strong>Use an existing social graph</strong>. This is my preferred option. If you facebook login and instantly you can see where all your friends are in Scene, I think this is a big win.</p>

<p>Real names. In the first iteration of this functionality, I&#39;m going to get rid of handles, and when you&#39;re in Scene you&#39;ll appear with just your first name to identify you. This isn&#39;t going to be a long term solution, and nicknames will probably come back, but this is just a first cut to get things moving.</p>

<p>I&#39;ll also make it easier to switch between logged in and anonymous mode, so that if you want to go into bobs-porn-den, that won&#39;t show up on your friends radar. The radar app, that shows where your friends are and lets you warp to them will probably be a little node.js app that I&#39;ll put on github and anyone can run.</p>
</div><br /><a href='http://www.reddit.com/r/scenevr/comments/34gpfj/replacing_logins_with_something_else/'>Read comments on reddit...</a><file_sep>---
title: Protocol
primary_navigation: true
---

# SceneVR Protocol

This document describes the SceneVR wire protocol. This document is mostly of interest to people build alternative SceneVR clients or servers.

## Overview

A SceneVR client connects to the server over websockets. As soon as a client connects, the server will send xml packets describing the scene.

## Websockets

To connect to a scene, connect to the url specified in the location bar, with a websocket connection on port 8080. So for example this url:

    http://client.scenevr.com/?connect=chess.scenevr.hosting/chess.xml

You would establish a websocket connection to:

    ws://chess.scenevr.hosting:8080/chess.xml

You can also connect to port 80 for websockets, except some ISPs block websocket upgrade requests on port 80, so use 8080.

The `protocol` parameter of the websocket should be `scenevr`.

```javascript
var socket = new WebSocket("ws://chess.scenevr.hosting:8080/hello.xml", "scenevr");
```

## Packets

The first packet a client will recieve is the `ready` event. This will tell the client what UUID has been assigned for the player. This allows the client to identify the `<player />` object that is their own avatar, and not render it.

```xml
<packet><event name="ready" uuid="6693fc3e-cfba-43cb-a0f4-1e3a980d63a3" /></packet>
````

A client is responsible for physics and movement of their own avatar, so can ignore `<player />` packets about their own uuid.

## Packet format

Packets are valid xml wrapped inside a `<packet />` element. At this stage, SceneVR doesn't support nested transforms, so all elements inside the packet can be added directly to the scene. Some elements have `CDATA` elements inside them. eg:

```xml
<billboard uuid="a6d25ec5-42f5-41a5-95f9-040474ed8804" position="-2 1 0" rotation="0 1.5700000000000003 0" scale="2 2 0.25"> <![CDATA[ <h1>Welcome to SceneVR</h1> <p> There are two boxes for you to enjoy. One is <span style="color:#f70">orange</span> and one is <span style="color: #0af">aqua</span>. </p> <p> There are also some little voxel men, courtesy of @mikeloverobots. </p> <center> Enjoy <span style="background: #333; padding: 5px; display: inline-block; color: #f70">VR</span> ! </center> ]]> </billboard>
```

The CData is used so that the clients don't have to decode html inside `<billboard />` tags twice, but can instead recieve it as text, then pass it onto a html renderer. (Due to browser security limitations, billboards cannot have iframes, inputs, embeds etc, they are best treated as a static texture).

## Create / update / delete

The server does not maintain a list of what elements the client has seen, but instead sends all changing elements to the client, whenever an element changes. So for example - the teapot in the [homeroom](http://client.scenevr.com/) has a `setInterval` that continuously rotates the teapot. This means that the `rotation` attribute of the `<model />` is constantly changing. That means that at 10hz (the current update frequency), the element is sent to all connected clients.

To process a packet, the client parses the packet, then for each child element, looks up first:

### Is it an element we have seen before?

```xml
<box uuid="7334d64b-3989-4ca5-bbc1-f05bc6704e6e" id="home" style="color: #555555" position="2.5 0.25 3.5" rotation="0 0 0" scale="1 0.5 1"></box>
```

If we look up the UUID and find this uuid in our local scenegraph, we need to make a decision. Have only the position and rotation of the element changed? If so, just interpolate the previous position and rotation to the new position and rotation (do the interpolation over the network timestep, currently 100ms, but in the future this will be server-definable).

To tell if only the position and rotation changed, you need to keep a copy of the parsed XML from when you created the object in your scenegraph. You can use a userData for this. For example (pseudocode):

```javascript
var packet = parseXML("<box uuid='1234...' position='1 1 1' style='color: #f0a' />");
var box = new OpenGL.Box()
box.position = StringToVector(packet.position);
box.setColor(packet.style..color)
box.userData = packet;
```

In this pseudocode, we can then do a test when we recieve a new packet. If only the `position` and `rotation` attribute have changed, then we can interpolate the existing element. If the style attribute has changed, then we need to destroy and regenerate the element, to apply the new styles.

The `if_substantial_change` then `destroy_and_regenerate` is a very naive way to make sure that the scenegraph reflects the current server state of an element, but it is the easiest way to get started. Feel free to optimise this step as you see fit.

### Is it an element we haven't seen before?

```xml
<box uuid="7334d64b-3989-4ca5-bbc1-f05bc6704e6e" id="home" style="color: #555555" position="2.5 0.25 3.5" rotation="0 0 0" scale="1 0.5 1"></box>
```

Using the uuid attribute, we look up to see if we have this element in our local scenegraph. If we don't, then we create the element and add it to our scenegraph with the uuid attribute so that we can look it up in the future. The attributes of an element are parsed as per their description in the relevent API docs on scenevr.com. 

*The wire serialization of elements is identical to the markup used to define a scene*. The only addition is the uuid which is only used for wire serialization.

### Is it a `<dead />`?

```xml
<dead uuid="1234-1234-1234-1234" />
```

If it is a dead packet, look up the corresponding object in our local scenegraph by using the uuid attribute, and remove that object from the scenegraph. This is an instanteneous action, no need to fade out the object, just prune it from the scenegraph and the physics simulation.

### Is it an `<event />`?

```xml
<event name="ready" uuid="6693fc3e-cfba-43cb-a0f4-1e3a980d63a3" />
```

Events are basically remote procedure calls, and are treated seperately from other elements in the packet. See *events* below.

## Send player position

At the server update frequency (currently 5hz), the client should send the current position of the player. This packet is sent like this:

```xml
<packet><player position="1 2 3" rotation="0 1.571 0" /></packet>
```

Only the position and rotation attributes are considered by the server. There is no need to send the UUID with the player packet. To keep the load easier on the server, you should bundle together player updates with events that you are going to send, and send them all in one packet at the server update frequency (10hz).

## Send click events

If the player clicks on an element, send the click event, with the UUID of the element that was clicked:

```xml
<packet><event name="click" uuid="1234..." point="1 2 3" /></packet>
```

The point is a Vector that represents the point at which the player clicked on the element. This is important for the chessboard for example, to work out where on the board the player clicked.

## Send collide events

If the player collides with an element (touches it), send a collide event. You should only send a collide event every time the player touches a different object. If a player jumps off an object and lands on the same object, you should send another collide event, but throttled so that you don't send two collide events for the same UUID more than once every 500ms.

See `addPlayerBody` in client.js in the web client for more details on this.

The normal is a vector pointing from the object in the direction of the player, representing the direction the object is pushing against the player.

```xml
<packet><event name="collide" uuid="1234..." normal="-1 -2 -3" /></packet>
```

## Send chat events

To post a message to the chat channel for the current scene, send a chat element.

```xml
<packet><event name="chat" message="I love big butts and I cannot lie" /></packet>
```

Players are anonymous by default, so your chat messages will be posted anonymously. See authentication below.

## Receieve chat message

A chat message is recieved like this:

```xml
<packet><event name="chat" from="toastman" message="I love big butts and I cannot lie" /></packet>
```

## Recieve respawn event

If a player 'dies' (this event is usually triggered by game logic, eg when you collide with a ghost in puckman), you should `respawn` them, send them back to the spawn point, and add a message to the chat log saying why they died.

```xml
<packet><event name="respawn" reason="you touched a deadly ghost" /></packet>
```

## Restart event

If you are connected to a local scenevr server that is running in development mode (the default), then when the server detects a change to the scene files (because you pressed save in your editor), it sends a restart event to all connected clients.

```xml
<event name="restart" />
```

If the client recieves this message, it should disconnect from the server, remove all objects in the local scenegraph, then reconnect 1000ms later to the server. The player should stay where they are and not respawn (ignore the `<spawn />` element) but the scene should reload around the player.

## Authentication

Authentication is achieved by presenting a web surface (an iframe in the web client) that points at:

    http://login.scenevr.com/

This is the scenevr login server. Once the player logs in, the login server uses postMessage to say that the player is now logged in and you can request an authentication token.

```html
<script>
  window.parent.postMessage(JSON.stringify({ 
    message : "auth"
  }), "*");
</script>
```

You should write a hook that detects a call to `postMessage`, you can now trust that the player is logged in.

You need to save the session cookies set for the domain `login.scenevr.com`, these are used in the next step to get a token to authenticate with the current room.

Using the cookies, you can see if the user has logged in by resquesting:

  http://login.scenevr.com/session/status.json

If you have set the cookies correctly and formed the request, this will return json like:

```javascript
{"name":"toastman","id":16}
```

Note that the login server currently doesn't use SSL, but SSL will be added and *required* soon.

## Get an authentication token

Using these cookies - do a `GET` request to this url:

  http://login.scenevr.com/session/token.json?host=chess.scenevr.hosting

The server will respond like so:

```javascript
{"token":"<KEY>"}
```

This is a [json web token](http://jwt.io/) that is signed by the servers private key. All SceneVR servers have the login servers public key embedded in them, so can prove that this is a valid token for authenticating the user to this SceneVR server at this time. Tokens expire after a specified period, so you should get a new token every time you connect to a scene and want to authenticate the user.

## Sending tokens to the server

To authenticate the client - send the value of the token to the server:

```xml
<packet>
  <event name="authenticate" token="<KEY> />
</packet>
```

The client should now be authenticated and you can post messages to the chat channel and you will appear as that player. You will also have your name above the pegman avatar when people see you.

## OpenTok

We use opentok / webrtc for voice chat. This section will be added later... Email ben to remind him to finish this if you need details.

<file_sep>---
title: SceneQuery
primary_navigation: false
---

# SceneQuery

Can you write a web page with jQuery? If you can, then you can create a Virtual Reality scene with SceneQuery, a version of jQuery for SceneVR.

First, a bit of an introduction to SceneVR.

The core of SceneVR

## Example

```xml
<scene>
  <box id="door" position="0 1 0" scale="2 2 2" style="color: #555" />
</scene>
```

This is our door. We want to add 
<file_sep>---
title: Chess
date: 2015-03-04
tags: scene
layout: post
---

I finished up a multiplayer version of chess tonight. It uses [chess.js](https://github.com/jhlywa/chess.js/) to handle the logic, and implements the interactivity and multiplayer using scenevr.  [Try it out!](http://client.scenevr.com/?connect=chess.scenevr.hosting/chess.xml) You can see the [source code](http://chess.scenevr.hosting/chess.xml), it is about 180 lines of javascript.

<img src="/images/blog/chess.png" class="screenshot" />

It's been fantastic watching people play the game. Currently anyone can play, but what tends to happen is that people cluster at the viewing platform at each end, and one person jumps down and makes a move. It's a pretty fun emergent behaviour watching people play. There are a few bugs (castling, promotion doesn't work) that need fixing, I've added [issues for them on github](http://github.com/scenevr/chess/issues), if anyone wanted to have a crack at them that'd be awesome, but otherwise it's looking pretty good.
<file_sep>---
title: Script
primary_navigation: true
---

# Script

An inline, or externally referenced javascript block. These blocks are executed after the dom has been loaded. 

## Notes

Even though the script block is evaluated on the server, by a node.js process, it is run in a sandbox, so you cannot access many of the node.js built ins. When scripting with SceneVR, you should refer only to documented attributes and methods of the elements. It may be possible to escape out of the sandbox, but use of SceneVR internals is not supported, and your scenes may break in future versions. Note that the node.js sandboxing doesn't prevent you from creating infinite loops. If you create an infinite loop, your server will grind to a halt.

Due to limitations in the way we parse the scenes at the moment, you may not get a correct line number when an error is reported. This will be improved in future versions.

All scripts run in the same context.

## Sample XML

```xml
<script src="scripts/chess.js"></script>

<script>
    var game = new Chess;
    console.log(game.gameOver());
</script>
```

NB: If you are embedding html in strings in your javascript, or using < and >, you need to wrap your script inside a cdata.

```
<script>
  <![CDATA[
    console.log("This is some <b>html</b>");
  ]]>
</script>
```

## Attributes

### src

If specified, the script will be synchronously loaded from an external file and evaluated. Scripts must be local, you cannot reference files over http.

## Global scope

The following members are in the global scope. See [scene.js](https://github.com/bnolan/scenevr/blob/master/elements/scene.js) for an up to date list of members exported to the global scope.

### document

The document object representing this scene. Access `document.scene` for the root level scene element.

### Vector

The [vector](/vector.html) class, derived from the three.js vector class.

### Euler

The euler class, derived from the three.js euler class, for rotations.

### XMLHttpRequest

The [XMLHTTPRequest](http://www.w3.org/TR/XMLHttpRequest/) class, an implementation of the w3c spec. It has no cross-domain restrictions.

### console

A minimal console, only has `console.log`. Logs as a chat message to connected clients, as well as to the server console.

### setTimeout

A proxied setTimeout that catches errors in user code without bringing down the server.

### setInterval

A proxied setInterval that catches errors in user code without bringing down the server.
<file_sep>---
title: Seperated scene-dom from the server
date: 2015-05-11
layout: post
---
<div class="md"><p>More sexy backend changes that no-one except Ben and Sam will see, but we&#39;ve seperated the scene loading code from the server. The big goal here, is to make it so that you can load scene files directly in the client, and simulate them in the client.</p>

<p>This means that you can make Scenes without requiring a server. Sadly, these scenes will be single player only, but it makes it much easier for you to create scenes without having to install node.js and all that stuff. For example, we&#39;ve forked <a href="http://glslb.in/">glslbin</a> and are going to make <a href="https://github.com/scenevr/bin">bin.scenevr.com</a>, which will let you quickly hack up scenes in the browser. And then once you&#39;ve built something cool and want to put it online, you can deploy to heroku via one-click deploy.</p>

<p>I&#39;ve also been working on the new web client, which uses all the same rendering code, but has way nicer web interaction, like when you paste a link to a scene to reddit, twitter or facebook, you will get a pre-rendered screenshot of what the scene looks like. We also put a little summary of the scene (all the html content and links in it) in a &lt;noscript /&gt; tag, so that google can index your scene and you can use google site search to search for a scene that you found on scenevr.</p>

<p>Finally, we&#39;re working on making the reddit galleries work for any reddit gallery, not just the 3 pre-defined ones.</p>

<p>So there&#39;s been a bunch of behind the scenes work, but this will all lead to some nice user-facing features in the next few weeks.</p>
</div><br /><a href='http://www.reddit.com/r/scenevr/comments/35jlgl/seperated_scenedom_from_the_server/'>Read comments on reddit...</a><file_sep>---
title: Moving docs to docs.scenevr.com
date: 2015-05-04
layout: post
---
<div class="md"><p>The client.scenevr.com/?connect URL is needlessly complex, I&#39;m going to put the scenevr world at <a href="http://www.scenevr.com">www.scenevr.com</a>, and move the docs and blog to docs.scenevr.com.</p>

<p>So now whenever someone goes to check out scenevr, they&#39;ll be launched straight into virtual reality, instead of having to click the &#39;try now&#39; link.</p>

<p>This is also part of an effort to put more focus on VR in scenevr, so instead of having lots of web components, try and move as much into VR as possible. For example, the face configurator that I was working on, that&#39;s being redeveloped as a VR scene, instead of a seperate web page.</p>

<p>The UI is also going to undergo a bit of a redesign to make mobile and clients using VR (cardboard / rift) more of a first class citizen in the world, at the moment the VR experience works best for the pc master race, and I want everyone to be included.</p>

<p>Except for console (unless someone with a console development license wants to port the unity client to xbox / ps). :)</p>
</div><br /><a href='http://www.reddit.com/r/scenevr/comments/34roh0/moving_docs_to_docsscenevrcom/'>Read comments on reddit...</a><file_sep>---
title: Puckman
date: 2015-03-14
layout: post
tags: game
---

I deployed puckman today, it's based on [pacman.js](https://github.com/daleharvey/pacman) by @daleharvey. It was pretty easy to convert to SceneVR.

<img class="screenshot" src="/images/blog/puckman.png" />

I first iterated over the pacman.map variable, and create a box for every wall in the map. Each box has a large dark blue box, and a small bright blue border around it. I then create all the little pills, which are set to `collision-response: false` which means that the script can detect touching them up, but walk straight through them. Then the ghosts are instantiated and simulated 10 times a second by the pacman.js code.

Then it's a simple case of adding a `<model />` for each ghost (pacman.js tells you what color to make them, pink or green etc, or blue when they're vulnerable, or grey when they're dead), and looking for collision events with the ghosts and killing the player, or eating the ghost.

View the [source here](http://puckman.scenevr.hosting/game.xml).  <file_sep>---
title: Plane
primary_navigation: true
---

# Plane

A plane is a plane on the x-y axis, it's depth in the z dimension is 0. It inherits from [Element](/element.html). If you want a horizontal plane, rotate your plane by approximately `-1.5708` radians on the y axis as in the following example. Planes are finite, they will only be as large as the specified scale in the x and y dimensions.

## Sample XML

```xml
<plane style="texture-map: url(/images/stones.jpg); texture-repeat: 1000 1000;" scale="1000 1000 0" position="0 0.01 0" rotation="-1.5708 0 0" />
```

## Screenshot

<img src="/images/plane.png" class="screenshot" />

## Styles

### color

The color of the plane. 

### texture-map

A texture map that is applied to the plane. Texture-maps are lambertian shaded.

```
style="texture-map: url(/images/crate.png)"`
```

### texture-repeat

How many times is the texture repeated in the U and V directions.

```
style="texture-map: url(/images/grid.png); texture-repeat: 100 100"
```
<file_sep>---
title: Lots of backend work
date: 2015-05-17
layout: post
---
<div class="md"><p>You might not have noticed a bunch of changes on the front of SceneVR lately, but we haven&#39;t been idle. We&#39;ve been making a new frontend that can be indexed by google, so that your scenes get good search engine ranking, and when you paste a link to your scene, reddit, twitter and facebook (and anyone else that uses opengraph tags) can display a thumbnail of your scene to encourage people to try out your scene.</p>

<p>We&#39;ve also been working on a large change to make it so that you can develop scenes in the browser without requiring a node.js server. Hopefully you&#39;ll start to see some of this come to fruition soon!</p>
</div><br /><a href='http://www.reddit.com/r/scenevr/comments/36aver/lots_of_backend_work/'>Read comments on reddit...</a><file_sep>---
title: Semistandard
date: 2015-03-30
layout: post
---

So today was a fun productive day on SceneVR. I spent the weekend at a great node conference in christchurch, and met <NAME>, substack, <NAME> and feross (amongst others), and after seeing all their great work, I got inspired to tidy up the source code to the SceneVR server.

So now the code is semistandard compliant (semistandard is a great code linter based on standard, but with semicolons, because I prefer them).

The server for scenevr was originally written in coffeescript, and about 2 months ago, I transpiled it all to javascript, and started coding purely in javascript. However, there were still a few coffeescript classes left around (in the specs), and the javascript was pretty ugly, using weird `for()` loops instead of nice clean .forEach. So today I set up the package to lint with `semistandard` and fixed up the whole server, deleted a bit of unused code, and removed pretty much all the ex-coffeescript grossness.

While I was at it, I ported the specs from jasmine to using [tape](https://github.com/substack/tape) by substack. It's a great testing library, and super lightweight. I found a few weird errors while fixing up the tests, but they're all fixed up, and now the tests pass yay!

I added a little badge to the readme that shows that SceneVR gets about 1000 downloads a month on NPM, which is cool.

## Future

In the future for scenevr, I'd like to break the code into some smaller modules that can be independently published to NPM. This might be handy for people that want to make alternative scenevr servers, or want to use the scenevr code to write intelligent agents that connect to scenevr clients.

I'd also like to get rid of the forked Vector, Euler and Dom-Lite classes, and instead use the original versions from NPM, and just extend them as necessary to add code to them, instead of hacking up the source code. I think I can probably do this now that we use `object.observe`.

I'd like to replace the current `dirtyNodes` code with something modelled on the [mutationobserver](https://developer.mozilla.org/en/docs/Web/API/MutationObserver) API. That'd make the code a bit nicer, and I could release a nice module around that.

After talking with <NAME>, he gave me some ideas about how to more efficiently send updates over the wire, and how to send nested elements efficiently. I'm really keen to have a go at this, since grouped transforms would be really handy for scene creation.

I'd also like to remove the current UUID code and move to using `nodeid` instead, because that'll be more space efficient on the wire, and because all node ids are generated on the server, there's no need to use UUIDs.

Productive day!<file_sep>---
title: Big refactor for code cleanliness
date: 2015-03-31
layout: post
---
<div class="md"><p>The server code was getting pretty gross, so I did some work to get the tests passing, made the code pass the semistandard linter and made some effort to get rid of the forked libraries. I&#39;d like to refactor the server into a bunch of small mode modules eventually.</p>
</div><br /><a href='http://www.reddit.com/r/scenevr/comments/30z92o/big_refactor_for_code_cleanliness/'>Read comments on reddit...</a><file_sep>---
title: Working on general performance work and Safari / IE support
date: 2015-04-28
layout: post
---
<div class="md"><p>I&#39;ve discovered that scene doesn&#39;t work very well on safari on Mac, and the keyboard controls aren&#39;t very good for IE either, so I&#39;m working on polishing up those two platforms to make it easier to develop on those browsers :)</p>
</div><br /><a href='http://www.reddit.com/r/scenevr/comments/3437q0/working_on_general_performance_work_and_safari_ie/'>Read comments on reddit...</a><file_sep>---
title: Are all your blender models coming out as black?
date: 2015-05-26
layout: post
---
<div class="md"><p>Make sure you have clicked <a href="http://i.imgur.com/3Fd5nKi.png">write normals</a> in the blender export options.</p>
</div><br /><a href='http://www.reddit.com/r/scenevr/comments/37b8bm/are_all_your_blender_models_coming_out_as_black/'>Read comments on reddit...</a><file_sep>---
title: .mtl support added!
date: 2015-04-09
layout: post
---
<div class="md"><p>You can now use .mtl files like this:</p>

<p>&lt;model obj=&quot;x.obj&quot; mtl=&quot;x.mtl&quot; /&gt;</p>

<p>If you link to images inside your mtls, you should use relative paths. This means you might need to open your .mtl file in a text editor and change the code like this:</p>

<p>newmtl armchair_part4</p>

<p>Ns 96.078431</p>

<p>Ka 0.000000 0.000000 0.000000</p>

<p>Kd 0.640000 0.640000 0.640000</p>

<p>Ks 0.500000 0.500000 0.500000</p>

<p>Ni 1.000000</p>

<p>d 1.000000</p>

<p>illum 2</p>

<p>map_Kd /textures/armchair_part4_d.jpg</p>

<p>This will load the textures from your /textures/ directory in your SceneVR scene.</p>

<p>This makes it way easier to create scenes with multiple materials in your .obj files. Check out the chairs in the homeroom, which now have fancy textures instead of just being a boring color.</p>
</div><br /><a href='http://www.reddit.com/r/scenevr/comments/31zfrd/mtl_support_added/'>Read comments on reddit...</a><file_sep>---
title: Link
primary_navigation: true
---

# Link

A link is a floating globe that when clicked, turns into a portal to another scene. It inherits from [Element](/element.html).

## Sample XML

```xml
<link href="/challenge.xml" position="-0.8 1 2" rotation="0 1.57 0" />
```

## Screenshot

<img src="/images/link.png" class="screenshot" />

## Attributes

### rotation

The rotation of a link is important, because even though links are represented as spheres, when they are opened, they become a 2 dimensional circle, and players can only enter a portal by going into the sphere perpendicularly, so you must rotate the link to make it possible for players to run through it.

### href

This is the destination url. These urls are merged with the url of the current scene, so you can use relative urls like `/next-scene.xml` to link to another scene in the current scenes directory, or a complete url like `ws://home.scenevr.hosting/home.xml` to link to the home scene.

## Notes

When you go through a portal, a back link portal is generated at the spawn of the next scene, so you can go back to the previous scene. However, these portals go away if the page is reloaded. However, people can always use the back button to go back to a previous scene.<file_sep>---
title: Got server-side lightmap rendering partially working...
date: 2015-10-28
layout: post
---
<div class="md"><p>I can now edit a scene in the browser, and then run a command on the server to render that scene using lightmaps. I&#39;m not working on having multiple types of blocks. I&#39;ll probably use the EGA color palette, with 16 flat colored diffuse blocks and 16 emissive blocks.</p>
</div><br /><a href='https://www.reddit.com/r/scenevr/comments/3qhqya/got_serverside_lightmap_rendering_partially/'>Read comments on reddit...</a><file_sep>---
title: Thinking of deprecating the hosting service...
date: 2015-04-30
layout: post
---
<div class="md"><p>Hey all,</p>

<p>I had a meet up with my advisors tonight @traskjd and @sminnee, and we talked through a bunch of stuff, and one of the things that I want to do is to turn off new signups for the hosting service, and instead make it way easier for people to deploy their scenes to heroku.</p>

<p>I&#39;ve come to this decision because in using scenevr locally, I find the hosting service to be a bit of a pain, because it&#39;s not easy to just create a new scene, then type a few lines and deploy it, instead you have to drag and drop into the browser, and every time you change one file, you have to reupload the entire scene.</p>

<p>I could fix this, but I think a better option would be to use Heroku, because then I could just type <code>git push heroku</code> and the new version of the scene would be online. This is a great step forward in workflow for anyone who is regularly working on scenes, and I want to promote more people to work on scenes, instead of just hacking them up once and letting them fallow.</p>

<p>On the negative side, is that some people consider heroku quite a technical tool to get started with. This isn&#39;t true though! This evening I added a <a href="https://devcenter.heroku.com/articles/heroku-button">deploy to heroku</a> button to Puckman:</p>

<p><a href="https://github.com/scenevr/puckman#deploy-to-heroku">https://github.com/scenevr/puckman#deploy-to-heroku</a></p>

<p>There you go, just click that button and set up your own free instance of puckman on heroku. I let heroku create a hostname for me and it hosted it at:</p>

<p><a href="http://still-inlet-1130.herokuapp.com/">http://still-inlet-1130.herokuapp.com/</a></p>

<p>You can go there and try out puckman.</p>

<p>So what does this mean for the hosting app? Well, I still have to do some investigation before I am ready to unreservedly recommend heroku for scenevr hosting, but if all goes well, i&#39;ll turn off new sign ups for the hosting service. I won&#39;t turn off the scenevr hosting any time soon, so current users will have months to move their content off, but you can look forward to a bunch of tutorials and some work on the code to make deploying your scenes regularly much much easier!</p>
</div><br /><a href='http://www.reddit.com/r/scenevr/comments/34e3o0/thinking_of_deprecating_the_hosting_service/'>Read comments on reddit...</a><file_sep>---
title: Working at a clients office this week...
date: 2015-09-23
layout: post
---
<div class="md"><p>So there probably won&#39;t be any releases. I&#39;m concentrating on getting the voxel support, plus a public sandbox working. Had some fun making stairs the other day, it seems the peg man will happily run up stairs with a 20cm run and 10cm drop.</p>
</div><br /><a href='https://www.reddit.com/r/scenevr/comments/3lzij5/working_at_a_clients_office_this_week/'>Read comments on reddit...</a><file_sep>---
title: Reddit
---

# Reddit Galleries in Virtual Reality

SceneVR converts web content into virtual reality spaces that you can share with your friends. Enter
the name of your favourite subreddit below to turn it into a virtual reality scene. Share the URL
of your scene with your friends, and you will see them when they join the scene.

<form action="#" class="enter-destination">
  <h3>Enter a subreddit:</h3>

  <p>
    Turn any reddit gallery into a virtual reality space that you can share with your friends.
  </p>

  <div>
    /r/ <input type="text" id="sub" value="aww" /> <button type="submit">Enter VR</button>
  </div>
</form>

## What will it look like?

Subreddit galleries will take any direct image
links and turn them into billboards that you can walk around and view. Galleries are viewed like
first person games if you are used to using them, where you use the WASD keys to move around,
and the mouse to look. If you are on mobile, you can navigate the galleries using two thumbpads.

<img src="/images/subreddit.png" class="screenshot" />
<cite>This is how subreddits appear in VR.</cite>

<img src="/images/friend.png" class="screenshot" />
<cite>This is how other people will appear in VR.</cite>

## How do I view it on my rift?

Oculus Rift support is currently being reworked to work better with the latest 0.6.0 driver release. We
will update this page when rift support is working.

## How do I view on google cardboard?

We currently don't have any google cardboard support, but we are working on it.

<script>
  $('form').submit(function (e){
    var sub = $('form #sub').val();
    window.location = 'http://scenevr.com/wss/scene-reddit.herokuapp.com/gallery.xml?subreddit=' + sub;
    e.preventDefault();
  });

  $('#sub').focus();
</script>

<file_sep>
all:
	ruby autoblog.rb
	middleman build
	s3cmd sync --add-header='Cache-Control: public, max-age=43200' --recursive ./build/* s3://docs.scenevr.com/

