Monday, March 05, 2012

I need to be there by 9: Transit times in Toronto aboard the TTC

I recently realized that with all of the open data initiatives pursued by the government, it's possible for amateurs to grab this data and process it themselves. That's, of course, the whole point of open data initiatives, but I hadn't realized until the last few months that that included me.

With my interest in transit, I decided to grab some of the online transit data and see what I could do with it. Since Google has managed to convince everyone to put their transit route and timing information online in the form of GTFS, I decided that a good first step in playing with transit data would be to grab this GTFS feed for the TTC and chart out transit times in the city. The result is below. It shows how early you have to leave from various parts of the city to reach either Queen or Osgoode subway stations before 9am.

Data, imagery and map information provided by MapQuest,
Open Street Map and contributors, CC-BY-SA.

Why downtown during rush hour?
I decided to chart out transit times to downtown during rush hour because this is the most common transit pattern. Most people want to go downtown, and they need to go during rush hour. Even if you do want to go somewhere other than downtown, it's often fastest to still go downtown first because transit systems are usually optimized for taking people to and from downtown the fastest. Of course, the chart isn't representative of off-peak travel times. And sometimes transit systems are overly oriented towards moving people downtown, so it might actually easier to go downtown than to go to the local mall on transit, for example. I was thinking of maybe trying to calculate the transit times to various points in the city, or maybe calculate the transit time needed to reach 70th percentile of the city from any particular location, or maybe the time needed to get 5km away from any location, but doing that would require more complicated coding, and I was feeling lazy, so I opted for the simpler calculation of how long it takes to get downtown.

Simulation Setup
I took the GTFS data for Wednesday, February 15. I took all of the bus stops and transit stations in the data feed and used the transit time information to simulate how long it would take to move between the various stops. In the transit simulation, people are able to walk between stops for a distance of up to 100m at a time at a speed of 4km/h. In reality, some people are willing to much further than 100m if it saves them time, but the 100m restriction prevents the simulation from letting people do things like walk across a highway or across the Don Valley or something. During the simulation, people might walk for a total distance of more than 100m, but they will only walk up to 100m between any two stops. The walk time is simply the time needed to walk the straight line distance between the GPS coordinates of two stops--it doesn't take into consideration buildings in way, terrain, crossing the street, etc.

Weaknesses with the Model
One of the weaknesses of this approach is that it assumes that transit system adheres perfectly to the GTFS data. In reality, buses don't arrive and leave perfectly according to the schedule. People don't try to arrange their bus transfers so that they have exactly 5 seconds to make a transfer. Buses and subways are often late, so people normally would take earlier buses than what the chart shows because they need to ensure there's enough buffer time to make a transfer. There is no sensitivity analysis done on the data--so if I were to run the simulation again but calculate when people would need to leave to get to downtown by 8:55, the calculated transit times might end up being dramatically different. Also, the rule of thumb is that people consider waiting for a transfer to feel like twice as long as actually riding on transit, and that "feel" isn't incorporated into the model either.

Obvious Anomalies in the Map
If you look at the map, you'll notice that there are a lot of purple dots along the Bloor subway line. I suspect that those dots refer to a late-night/early-morning bus that runs when the subway is closed. Due to the 100m walking restriction, those stops can only be "reached" by those overnight buses, but those buses probably don't run during the rush hour since people can just walk a few hundred metres and take the subway instead. I haven't verified this yet.

Previously, I thought that GO Transit doesn't come often enough and that the distances within the city were small enough, that simulating GO Transit wouldn't be useful. But looking at the map now, it looks like that if GO trains come at least twice an hour, then they might provide a benefit for people living at the outer limits of the city, so I might have to incorporate GO data into the simulation later as well.

On the map, you can see the effect of subway lines in the suburbs. Around the subway stations, the transit times are much lower than in the surrounding areas. If you live near a subway station, then you get decent transit times to downtown. Otherwise, you need to take a bus to the station first, which increases your travel time. This effect is particularly prominent on the Sheppard subway and the eastern end of the Bloor subway. Overall, having a subway somewhere in the neighbourhood does seem to improve overall travel times though.

Another annoyance with the way this map is generated is that it's hard to separate the effect of frequency of service from the effect of speed of service. Are poor transit times in some areas caused by infrequent service so people have to wait a long time for transfers or are the times caused by buses moving slowly through congested parts of the city? It's also hard to compare public transit times vs. car times because there's no easy way to calculate how long it takes to drive through the city during rush hour. Oh well, I think it makes a good first step at analyzing some of this public data though.

Monday, February 27, 2012

February 2012 GO Transit Zone Map

GO Transit has a fairly opaque pricing scheme. Although the system is based on fare zones, they never tell you how the fare zones work. When you pay, do you pay according to the number of zones that you pass through? Or do you pay by distance between the zones? If you have a monthly pass between two locations, do you also get free travel on GO within those zones that are between those two locations? What happens if there are two routes between two locations, possibly using different zones? Maybe your fare pays for travel in one central zone plus all nearby zones up to a certain distance? Can you tack on an additional zone onto your travel at lower cost?

Fare zone systems can get pretty complicated, so I understand that, for normal people, GO only provides a little online web page where they can enter a source and destination and have GO spit out a total fare. But for the curious, how does the system actually work? For individual bus stops, GO does tell you their fare zone, but I couldn't find a map of all the fare zones on the GO web page. Apparently, even in the GO Transit bylaws discussing the cost of travel, it simply lists a bunch of destinations and then lists the fares for travelling between different pairs of destinations.

So, in an effort to get some insight into how the GO fare zone system worked, I decided to generate a fare zone map for GO. First, I went to the GO website and downloaded the list of stations, their GPS coordinates, and  their fare zones. Then, I put them into the data into a Voronoi diagram generator with the latitude and longitude simply used directly as x and y coordinates. I used Shane O'Sullivan's rewrite of Steven Fortune's original Voronoi code--I needed extra precision though, so I had to use a search and replace to change all the "float"s to "double"s. From there, I took the Voronoi diagram, did a Mercator projection, generated an SVG diagram, overlayed it on an OpenStreetMap map, and I was done.

Data, imagery and map information provided by MapQuest,
Open Street Map and contributors, CC-BY-SA.

My use of Voronoi to generate the diagram obviously has some problems. GO does not provide ferry service, so the zones do not actually extend into Lake Ontario like the diagram shows. There might be zones missing because there are no stops there. Zone 60 ended up being split into two parts because there wasn't a station between Richmond Hill and Vaughan to force the zone to merge together.

Unfortunately, the fare zone map didn't provide me much additional insight into how the fare zone system of GO might work. The zones seem to be irregularly sized, so I think that maybe the GO fare zone system may be more ad hoc with no particular attempt made to let riders buy arbitrary travel in certain zones (i.e. it's optimized for a commuter travel pattern where a commuter always takes the same journey between two locations every day). Oh well.

Saturday, February 04, 2012

Eglinton Subway: the Nuclear Option

Eight billion dollars! Eight billion dollars so that people in Scarborough can ride the subway to Eglinton? Are you kidding me? People want to go downtown. They don't want to go to Eglinton. Why are we adding half an hour to everyone's daily commute? Every single day, the amount of time wasted over all those people will be measured in YEARS. We're going to spend $8 billion dollars to build a vast transportation system for moving people some place that they don't want to go?

This is the worst kind of government waste. It's pure ego-driven excess. Times are tight, yet the politicians somehow think it's ok to waste taxpayer dollars on some pie-in-the-sky dream? This gravy train has got to stop.

Background

I thought the small-time transit politics in Ottawa were bad, but in Toronto, they're even worse. Right now, in Toronto, they're debating whether to spend $8 billion for a subway on Eglinton or $6.5 billion for a subway/light-rail combination. The debates are heated. The politics are nasty. And it's all pointless because both plans are a colossal waste of money.

The sad reality is that the smaller the government, the smaller the politicians. At the federal level, we get our best and brightest politicians. At the provincial level, we get some medium-level politicians. At the local level, no one votes and no one cares, so we end up with what's leftover: the least-experienced small-town politicians in the country. Yet somehow we're entrusting this lowest level of government with the decision on what to do with the biggest consruction mega-project in Canada?

This $8 billion dollars isn't local money either. It's provincial money. From Ottawa to Thunder Bay, Windsor to North Bay, we're all going to be paying higher taxes so that the local politicians in Toronto can strut around like peacocks boasting how they built a subway.

This is provincial money that's being spent, and it's time that the more experienced and more accountable politicians at the provincial level impose some provincial level-headedness on how our money will be spent.

The Case Against Subways

Trains and subways are shiny little toys, and politicians love spending money building them. The problem with trains and subways is that they are almost always a waste of money. They're always over-designed and over-built, and usually the same transit results could have been achieved using much cheaper technology.

Which mode of public transportation is the fastest? The bus.

Which mode of public transportation comes most often? The bus.

Which mode of public transportation is the cheapest to build? The bus.

So why exactly are we spending $8 billion dollars on a subway? Because they're nice? We're spending $8 billion dollars for "nice?" No politician who understands transit would propose building a subway. If you want immediate improvements in transit for the least amount of money, you always go for buses. There are a few limited situations where it makes sense to build subways and light-rail. But 99 times out of 100, if a politician is trying to build something involving trains, then they're wasting your money.

Politicians generally don't use public transit, so their only experiences with public transit are often only from when they're a tourist in foreign country or from the times of their youth. The systems they've used tend to be old and out-dated. Public transit technology has evolved and improved tremendously over the last few decades. You cannot use 1960s transit experiences to guide the building of transit networks in 2010s.

A modern subway is designed to move hundreds of thousands of people per day. This is the size of a medium to large Canadian city. Unless you need to move an entire city's worth of people from one location to another, you do NOT build a subway. Unless the entire population of Scarborough suddenly decided to give up their cars and ride the subway to Eglinton every day, it would not be worthwhile building a modern subway between those two locations. The current ridership on the Eglinton bus is around 50 thousand per day. Notice that 50 thousand is nowhere near the 500 thousand number you want for a subway. The technology for buses and streetcars have advanced to the point where they can be stretched to handle ridership below the hundred thousand range at a fraction of the cost of building a subway.

Many of these subway proponents try to justify a subway by claiming that decades from now, the city will grow to a size where a subway would make sense. This is pure wishful thinking. Toronto already has a backlog of necessary transit improvements that we need done now. But instead of spending money on fixing those problems, we're going to spend money to fix a problem that may or may not happen 50 years in the future? How does that make sense? Do these proponents have some deep insight into the transit needs of Torontonians? The sad fact of the matter is that most subway proponents are car drivers who have never ridden public transit before, and certainly wouldn't use the subway after it has been built either.

The reality is that we live in the age of the car. In the 50s and 60s, Canada was poorer and cars were more expensive, so people rode more transit. The public transit system was actually profitable! Construction was also cheaper back then, so building subways was very affordable. Cities were designed for people riding around in public transit and walking everywhere. But we're richer now, cars are cheaper, and we've redesigned our cities around the car. The city is more spread out, and most people get around by driving. The government does have a responsibility to provide adequate transportation for those who are unable to drive, but the idea that we're going back to days when everyone rides transit everywhere is a pipe dream. If you own a car, and you don't need to go downtown during rush hour, then it never makes sense for you to use public transit. Building extravagant transit mega-projects in the hope of encouraging these car drivers to use transit is just a waste of money. We do need transit, and we should spend money to build a better transit system. But subways are definitely inappropriate for a modern day transit system.

California, you may be surprised to hear, is the birthplace of the anti-tax movement. Despite their reputation for high taxes, Californians were the first to become fed up with their tax dollars being wasted by government, so they held a referendum and banned tax increases. Do you know something else they did in California? They banned subways. They became fed up with their tax dollars being wasted on costly and unnecessary subway projects, so they held a referendum and banned their tax dollars from being spent in subways in LA. A similar policy would definitely be appropriate for Toronto.

The Nuclear Option

With all the bickering in Toronto about whether to build a subway or subway/LRT-combination, or about whether the mayor's decision to build a subway was even legal, now would be an appropriate time for the premier to make use of the nuclear option: he should cancel the subway.

In this time of fiscal austerity, we can ill afford to squander $8 billion dollars on an unneeded subway. For $8 billion dollars, we could run the TTC at no cost to the city for 10 years. Mr. McGuinty knows that the subway is a waste of money, which is why he was so reluctant to fund it in the first place. With a report coming in February on all the massive government cutbacks needed to balance the budget, he has the political cover necessary to kill it. In fact, he doesn't even need to do it himself. He could simply let Metrolinx kill it for him, allowing him to avoid any possible political repercussions

Afterward, he should then impose some restrictions on the funding of new transit projects in Ontario, so that mayors stop wasting taxpayer money on these ridiculous transit plans.

Transit Funding Restrictions

There is a well-known story about a university that built many new buildings with grassy fields between them. The university had to build paved walkways over the grass between the buildings, but it couldn't decide where to put them. Should the walkways go along the sides of the buildings? Or maybe all the paths should meet at a single point in the middle of the field? In the end, the university had a brilliant idea. They planted the grass but didn't build any walkways. Over the next year, students walked over the grass, wearing it down, and making dirt paths through the grass. At the end of the year, the university simply paved over the dirt paths, so that the paths followed the natural movements of the students.

The Ontario government should impose transit funding restrictions to require this sort of thinking on transit development. Instead of expensive grand schemes for redesigning the transit movement of Ontarians, we should have incremental, modest improvements that serve a proven need.

In particular, no funding should be given to light-rail projects unless an existing bus bus transit line with high ridership has proven the need for one. And no funding should be given to new subways unless a light-rail line with high ridership has proven the need for one.

Even with these restrictions, it is inevitable that some unnecessary and poorly conceived projects will be built. To limit the amount of taxpayer damage that result from misguided projects, there should also be a billion dollar limit on individual transit projects. Some may argue that this limit prevents the building of larger, transformative transit projects. I would argue that that is a good thing and that if a city has a good long-term transit plan, then there's no reason a large project can't be broken into smaller incremental parts.

Soothing the Pain

Canceling the subway will make a lot of people angry, so the Premier would have to offer some alternative projects as a compromise. Following the grand government tradition, these alternatives projects can be promised, but never actually built. To keep the Eglinton people happy, a billion dollars of bus tunnel will be built through the most heavily trafficked portions of Eglinton. To please the transit advocates, one of the Queen or King streetcar lines should be buried through parts of downtown. The left will think of it as a down-payment on a downtown relief line while the right will be happy that they eliminated a streetcar. The Scarborough people will get an electrified GO-train line to downtown, possibly with a spur line to Scarborough Town Centre so that it can form a proper transit hub. The Etobicoke people are already getting an airport GO-train, and it should be modified to serve their needs better. As for actual transit users, the people we're actually supposed to be helping, they'll get funding for bus rapid transit, lots and lots of it.

Saturday, January 21, 2012

Egit and Github: Pulling from a Master Repository and Pushing into Your Own Forked Repository

So I'm new to the world of git and Github, so I'm trying to figure out how all this stuff works. Making things more complicated is the fact that I'm using Eclipse and its egit plugin, but most of the documentation on working with Github assumes that you're working with the command-line version of git. Although there is some documentation on how to use egit with Github, it mostly assumes that you created your own repository in git for your own projects. Github encourages people to take an existing project, fork it, and then work with your own copy of the repository though. This then makes things difficult when you need to pull in changes from the original master repository and stick them in your own repository.

Again, there is documentation on how to do get your forked repository in-sync with the master repository, but I'm still trying to feel my way about how to do this in Eclipse with egit. So far, here are some sets of instructions that seem to work with Eclipse Indigo 3.7 (but I'm still feeling my way around though, so I could be wrong).

So I'm assuming that you've forked a repository on Github, and you've successfully used the egit defaults to make a local repository based on your fork. So in the Git Repository Exploring perspective of Eclipse, you go into your repository.

  1. In the Remotes section, right-click and choose "Create Remote"
    1. Set the name to "upstream" and configure it for fetch
    2. the URI should be set to the git URI of the original master repository on Github that you forked
    3. "Add" a RefSpec
    4. the source should be master, and the destination should then be automatically filled in to refs/remotes/upstream/master
    5. Save your changes
  2. In the Remotes section, expand the upstream configuration, right-click the green incoming arrow, and choose Fetch
  3. After fetching, I think the latest changes are now available in your local repository, so now you want to apply those changes to your local branch, and then push them out to your forked repository
  4. So make sure you have your local master checked out or whatever
  5. Right-click your repository and choose Merge...
  6. Merge in from upstream/master
  7. And then you can push everything back into your forked repository on Github with a simple Right-click on your repository and Push.

It looks like egit might also support some sort of special Upstream configuration or something, so that egit will automatically track the master version of a fork, but it looks like the forked repository needs to be configured a special way, and I don't know how to get Github to do this. I imagine if you dig into egit's property files, there'll be some way to enable it, but I can't figure it out yet.

Monday, January 16, 2012

Thinking about Diagrams and Figures with Constraints

I have a small website for teaching kids to program, and I've long wanted to translate it into French and other languages. Being a website geared towards kids, the website has lots of diagrams and figures. Many of these diagrams contain text, so I would need to new versions of about 100 diagrams for each additional language I wanted to support with my website. Obviously, sitting around redrawing the diagrams for each new language would be impractical, especially for languages that I'm personally not familiar with. So I need some system that will let me define my diagrams in a generic way, substitute in different translations for the text, and then generate different versions of the diagrams for different languages.

The crux of the problem is that text might be different sizes in different languages. In English, you might use one word to describe something, but another language might use 5 words to describe the same thing. As a result, the diagrams need to lay themselves out differently depending on the size of the text. I've been trying to find a tool to do that, but I've been having problems figuring out what terms to use in the search. Right now, I'm just trying to understand what sort of tools are available in the space or, given that I probably have to write a chunk of code to substitute in the text translations anyway, how hard it would be to write a simple one from scratch.

Internationalization is a common problem in user interfaces, so coders commonly use a constraint-based layout scheme for their user interfaces in order to avoid this problem. Basically, you have some simple patterns or templates that define how UI elements should be arranged with respect to one another, and then you stick UI widgets into those templates. So you might have a row of widgets, or a grid of widgets, etc. This doesn't necessarily work too well for diagrams because the layouts tend not to be as rigid as in UIs. I was thinking that I could build a more complex version of the system where the diagram designer simply inputs arbitrary layout constraints (e.g. the right side of this element should touch the left side of this other element), and then everything would be fed into a solver of a linear system of equations to get the final layout.

I'm a little concerned though that it might get tedious describing all of the constraints needed to solve a full system. Plus, these constraints might be too rigid in that you can't say, "I need a circle as big as possible to fill that space between the elements" or "make the font size as big as possible as long as the width isn't too big." Of course, doing something like that might require a system that uses linear programming or some other mathematical optimization technique underneath, and it might be tricky to translate constraints from a diagram design into the proper set of inequalities and objective functions without totally confusing the diagram designer.

There are various "constraint-based diagram editors" available, but most of these tools are designed from drawing large graphs (e.g. org charts). Given a bunch of inter-connected diagram elements, these tools will use spring systems or other techniques to find a good planar embedding of the graph. Some of my diagrams could be laid out this way, but I'm not sure if this approach is simultaneously too heavy and too underpowered for the types of diagrams I want. My diagrams don't really fit into those graph models, so I'd be worried that the mismatch of diagram types would make it difficult to get the results I wanted.

I also looked at some constraint solver systems that I could maybe build up into a diagram tool since that would give me the most flexibility in terms of how constraints could be expressed. Unfortunately, constraint solvers are actually a technical term used to refer to specific AI-like problems like SAT, etc. They specialize in solving binary constraints. Although they can also work with real numbers, it seems that some of them solve the problem by discretizing the real number line and then using standard binary constraints to solve things.

Perhaps what I need is some sort of symbolic computation engine that can work with intervals. Does that even exist? Perhaps I'm going overboard with this whole diagramming thing.

Thursday, November 10, 2011

WebGL Pre-Tutorial, Part 2: Drawing a 2d Triangle

This part of the pre-tutorial will show you how to write a very basic WebGL program that draws a 2d triangle on the screen.


Unfortunately, even the simplest WebGL program is somewhat long and involved. Below is the complete code for the program followed by more detailed explanations of the different parts of that code.

<!doctype html>

<canvas width="500" height="500" id="mainCanvas"></canvas>

<script>
function main()
{
   // Configure the canvas to use WebGL
   //
   var gl;
   var canvas = document.getElementById('mainCanvas');
   try {
      gl = canvas.getContext('webgl');
   } catch (e) {
      throw new Error('no WebGL found');
   }

   // Copy an array of data points forming a triangle to the

   // graphics hardware
   //
   var vertices = [
      0.0, 0.5,
      0.5,  -0.5,
      -0.5, -0.5,
   ];
   var buffer = gl.createBuffer();
   gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
   gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

   // Create a simple vertex shader
   //
   var vertCode =
        'attribute vec2 coordinates;' +
        'void main(void) {' +
        '  gl_Position = vec4(coordinates, 0.0, 1.0);' +
        '}';

   var vertShader = gl.createShader(gl.VERTEX_SHADER);
   gl.shaderSource(vertShader, vertCode);
   gl.compileShader(vertShader);
   if (!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS))
      throw new Error(gl.getShaderInfoLog(vertShader));

   // Create a simple fragment shader
   //
   var fragCode =
      'void main(void) {' +
      '   gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);' +
      '}';

   var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
   gl.shaderSource(fragShader, fragCode);
   gl.compileShader(fragShader);
   if (!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS))
      throw new Error(gl.getShaderInfoLog(fragShader));

   // Put the vertex shader and fragment shader together into
   // a complete program
   //
   var shaderProgram = gl.createProgram();
   gl.attachShader(shaderProgram, vertShader);
   gl.attachShader(shaderProgram, fragShader);
   gl.linkProgram(shaderProgram);
   if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS))
      throw new Error(gl.getProgramInfoLog(shaderProgram));

   // Everything we need has now been copied to the graphics
   // hardware, so we can start drawing

   // Clear the drawing surface
   //
   gl.clearColor(0.0, 0.0, 0.0, 1.0);
   gl.clear(gl.COLOR_BUFFER_BIT);

   // Tell WebGL which shader program to use
   //
   gl.useProgram(shaderProgram);

   // Tell WebGL that the data from the array of triangle

   // coordinates that we've already copied to the graphics
   // hardware should be fed to the vertex shader as the
   // parameter "coordinates"
   //
   var coordinatesVar = gl.getAttribLocation(shaderProgram, "coordinates");
   gl.enableVertexAttribArray(coordinatesVar);
   gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
   gl.vertexAttribPointer(coordinatesVar, 2, gl.FLOAT, false, 0, 0);

   // Now we can tell WebGL to draw the 3 points that make 

   // up the triangle
   //
   gl.drawArrays(gl.TRIANGLES, 0, 3);
}

window.onload = main;
</script>

The first part of the HTML page creates the HTML element where the actual 3d drawing will occur. WebGL uses the canvas element to define its drawing surface, which can also used in HTML5 for doing 2d drawing.

<canvas width="500" height="500" id="mainCanvas"></canvas>

Then, we get into the actual code. First, we need to configure the canvas for use with WebGL instead of for 2d drawing by grabbing a WebGL context object that lets us invoke WebGL commands on the canvas.

var gl;
var canvas = document.getElementById('mainCanvas');
try {
   gl = canvas.getContext('webgl');
} catch (e) {
   throw new Error('no WebGL found');
}

Next, we have an array holding the coordinates of the three points that make up a triangle.
As mentioned in part 1, we need to copy this triangle data to the graphics hardware before we can draw it. This is done by using createBuffer() to tell WebGL to that we want to set aside some memory at the graphics hardware for our data, bindBuffer() to select this buffer as something we want to manipulate, and then bufferData() to actually copy the triangle data to the currently selected buffer in the graphics hardware.

var vertices = [
   0.0, 0.5,
   0.5,  -0.5,
   -0.5, -0.5,
];
var buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);

The “vertices” array that holds the triangle data is put inside a Float32Array object before being sent to the bufferData() call. This Float32Array object specifies how the array data should be laid out in memory. JavaScript is purposely vague about the exact memory layout of objects, but these details are important when working with graphics hardware. In this case, we specify that the triangle data should be stored as consecutive 32-bit floating point numbers.

As mentioned in part 1, the WebGL graphics pipeline requires us to define vertex shader and fragment shader programs in order to draw anything on the screen. We first define the vertex shader program.

var vertCode =
     'attribute vec2 coordinates;' +
     'void main(void) {' +
     '  gl_Position = vec4(coordinates, 0.0, 1.0);' +
     '}';

var vertShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertShader, vertCode);
gl.compileShader(vertShader);
if (!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS))
   throw new Error(gl.getShaderInfoLog(vertShader));

The actual code for the vertex shader is held in a string. The vertex shader allows us to move the points of a triangle or other small transformations before they are displayed. Each point that makes up a triangle is given to the vertex shader, and the vertex shader program returns the final position of the point, plus additional data that it may want to specify. In our case, we don't need to move the points around, but we need to put the data in a proper form for WebGL. WebGL displays the parts of triangles that fit inside the 3d cube between (-1,-1,-1) and (1,1,1). Our triangle coordinates are only (x,y) values, so we need to specify an extra z value so that WebGL can determine where the triangle is in 3d space. We just use 0 for this z coordinate. In fact, WebGL needs us to specify four values: x, y, z, and a fourth value that is normally always 1. So our vertex shader will take the 2d (x,y) coordinates for a point in the triangle and transform it to (x,y,0,1).

attribute vec2 coordinates;
void main(void) {
  gl_Position = vec4(coordinates, 0.0, 1.0);
}

Next we define the fragment shader.

var fragCode =
   'void main(void) {' +
   '   gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);' +
   '}';

var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragShader, fragCode);
gl.compileShader(fragShader);
if (!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS))
   throw new Error(gl.getShaderInfoLog(fragShader));

A fragment shader controls the color of each pixel making up the triangle. For each pixel, a fragment shader should return four numbers describing the color: the amount of red, the amount of green, the amount of blue, and the amount of transparency. If we look at the code for the fragment shader, we can see that the fragment shader is fairly simple. It simply uses the same color for every pixel: an opaque white color.

void main(void) {
   gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}

After defining a vertex shader and fragment shader, we need to put these two shaders together in a single program for drawing things.

var shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertShader);
gl.attachShader(shaderProgram, fragShader);
gl.linkProgram(shaderProgram);
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS))
   throw new Error(gl.getProgramInfoLog(shaderProgram));

Now that we've copied the triangle data and shader programs over to the graphics hardware, we're finally ready to do some drawing. First, we clear the drawing surface to black so that the white triangle we're drawing will show up.

gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);

Then we specify which shader program to use for drawing.

gl.useProgram(shaderProgram);

We then tell WebGL to feed our buffer of triangle data through this shader program. To do this, we need to specify how the values in this array of points should be given to the program. We want our point data to be given to the vertex shader as the “coordinates” variable. So we get a handle for this variable and configure the variable. We then select our buffer of data, and use vertexAttribPointer() to specify that the buffer should be divided into groups of two floating-point numbers, and these numbers should be fed into the shader program as the “coordinates” variable.

var coordinatesVar = gl.getAttribLocation(shaderProgram, "coordinates");
gl.enableVertexAttribArray(coordinatesVar);
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.vertexAttribPointer(coordinatesVar, 2, gl.FLOAT, false, 0, 0);

Finally, now that we've properly configured everything, we can now instruct WebGL to actually draw something. We tell it to take the three (x,y) points in our array, feed them through the shader program, and draw the result as a triangle.

gl.drawArrays(gl.TRIANGLES, 0, 3);

So this is the end of the pre-tutorial. To include anything more would turn this into an actual tutorial.

Here is part 1 of the pre-tutorial in case you missed it.

Sunday, November 06, 2011

WebGL Pre-Tutorial, Part 1

I've recently tried to learn WebGL, and it turns out that it's pretty complicated. Most of the tutorials that I've found on the web have been geared towards getting the learner doing 3d as quickly as possible by skipping over a lot of details. This is probably what most learners want, but I find that this approach doesn't suit my learning style. I, personally, want to understand the details so that I can write my own 3d code instead of haphazardly cutting and pasting together code snippets that I've found on the Internet. People who just want to do 3d as quickly as possible would probably be better served by using a higher-level 3d graphics engine. The purpose of this pre-tutorial is to fill in some of the details that are left out of other WebGL tutorials. This should make it easier to understand what the code in those tutorials is trying to do. I will try my best to keep the explanations of this pre-tutorial as simple as possible, but WebGL is inherently a pretty low-level API, so it helps if people have some limited systems and 3d programming experience first.

WebGL is the JavaScript version of the 3d library OpenGL ES 2.0. OpenGL ES 2.0 is targeted as a low-level 3d API for phones and other mobile devices. Unlike the full OpenGL for desktop computers, OpenGL ES 2.0 leaves out support for high-precision numbers, which are mostly needed for scientific computation or engineering design, and it leaves out support for a lot of older library calls that aren't used in modern 3d programs. Despite this missing functionality, OpenGL ES 2.0 and WebGL are still great for games, and they are designed to provide good performance on modern 3d graphics hardware.

WebGL is designed for a hardware architecture like that shown below:


The architecture assumes that a machine's graphics hardware is separated from its CPU. The graphics hardware likely has separate memory from the CPU. The graphics processing unit (GPU) specializes in running multiple copies of a single program at the same time. Unlike a normal CPU, these programs must be small and simple, but a GPU can run many, many copies of these programs simultaneously, making it faster than a normal CPU for graphics tasks. With this sort of hardware architecture, one of the biggest bottlenecks for fast 3d programs is the communication between the CPU and GPU.

The general design philosophy of WebGL is based on the idea that this communication between CPU and GPU should be minimized. Instead of repeatedly sending instructions and graphics resources from the CPU to the GPU, all of this data should be copied over only once and kept on the GPU. This minimizes the communication that needs to happen between the CPU and GPU. The communication that does happen is batched together into clumps so that the GPU can work independently from the CPU.

WebGL Graphics Model


WebGL presents a certain abstract model of how the graphics hardware works to the programmer. In the WebGL graphics model, the window or area where 3d graphics are displayed is modeled as a cube. The (x,y,z) values of one corner of the cube is (-1,-1,-1), and the values of the opposite corner are (1,1,1).


An x value of -1 refers to the left side of the window while an x value of 1 refers to the right side of the window. Similarly, a y value of -1 refers to the bottom of the window while a y value of 1 refers to the top of the window. Different z values refer to how close or how far an object is.

You create graphics by drawing triangles in this cube. If you provide the 3d coordinates of the three corners of a triangle, WebGL will draw them on the window. Since the sides of the cube refer to the sides of the window, WebGL will chop off any parts of the triangle that fall outside of the cube.


Triangles are a little limiting, and it takes a lot of communication overhead to transfer all the triangle coordinates from the CPU to the GPU. To overcome this problem, WebGL offers two mechanisms for programming how these triangles are displayed.

The first mechanism is called the fragment shader. When drawing the pixels that make up a triangle, WebGL runs a little program for each pixel that says what color the pixel should be. You can have the triangle be a single color, rainbow-colored, or even a complex pattern.


The second mechanism is called the vertex shader. The main purpose behind the vertex shader is to reduce the amount of communication between the CPU and GPU. Suppose you have a complex 3d model made up of lots of triangles, and you send all of these triangles to the GPU to draw them. If you then want to move the model over to the left a little bit, you would normally need to change the positions of all the points of all the triangles and then send all those new coordinates from the CPU to the GPU. This is a bit wasteful because the coordinates of all those triangles are already stored at the GPU. You just wanted to move them a bit, but you had to send all the coordinates a second time. With a vertex shader, you can send a program to the GPU that will enable the GPU to rewrite the coordinates of all the triangles itself. This means you only have to send the triangles of the 3d model once, plus a little program for moving the coordinates of the triangles.



So the WebGL graphics model can be thought of as a pipeline that processes triangles through different stages. You initially provide WebGL with some triangles to draw. The triangles can be moved around and shifted by vertex shader programs. Any triangles that fit within the cube at (-1,-1,-1) and (1,1,1) will be drawn. WebGL does this by running a fragment shader program for each pixel of the triangle to determine which color to draw there.


Part 2 of the pre-tutorial demonstrates some code for a very basic WebGL program.

Saturday, September 24, 2011

Arabic Support in Java

So a few months back, I started working on an Arabic version of JavaScript, which required me to figure out how to write an Arabic Java program. To my surprise, Java actually has pretty lousy support for BIDI and Arabic.

Now, I always suspected that the old Sun severely understaffed its Java UI group and I always had this odd feeling that their UI programmers never actually programmed any real applications using their UI frameworks. The fact that Java, the major enterprise programming language of the last decade, still doesn't properly support Arabic even after all these years of development just tells you everything you need to know right there. IBM/eclipse, with its SWT UI framework for Java, has had proper Arabic support for a long time now. Instead of doing everything alone, why didn't Sun get help from others when developing Java? Why? Mind you, they rely heavily on proper OS support for Arabic while Java's Swing framework is designed in such a way that they have to reimplement Arabic support from scratch. And the Unicode character encoding was specifically designed so that text processing of Unicode is easy but the handling Unicode in a GUI is the most awfully complicated piece of code possible. But still, we're at Java 7 now, and they should have been able to get this basic piece of infrastructure supported by now.

It makes me wonder which programming languages computer science students are taught in the Arab world. It can't be Java. What's the point of learning a programming language that can't properly handle the input and display of your native language? I guess it must be C# or something.

Anyway, this is what I found. I was working in Windows in Java 6, so my observations may be specific to this combination.

In AWT, I tried setting the text direction using applyComponentOrientation(), but I could never get that thing to work. The text always stayed left-to-right using AWT widgets. In both AWT and Swing, there's a setLocale() method, but I have yet to figure out whether that method actually does anything. I suspect it doesn't do anything. So basically, I don't think there's any BIDI support in AWT. This is somewhat annoying because Windows has reasonable BIDI and Arabic support, so if Java simply passed on this text orientation information from AWT to Windows, then we could simply use AWT for our UIs, and everyone would be happy. Unfortunately, it doesn't.

In Swing, the applyComponentOrientation() method did seem to properly set the text orientation, so there's some good support for bi-directional text there. Unfortunately, for Arabic text, you also need support for text numeric shaping. Although some Arab nations use western number symbols (which, as you probably know, are called Arabic numerals, which makes things nice and confusing for everybody), most Arab nations have their own number symbols. Unicode, in its infinite wisdom, decided that these symbols will actually be encoded in character streams as western digits 0-9, but the UI will be responsible for automatically substituting in different number shapes when the characters are actually displayed. The Java graphics libraries actually have some support for numeric shaping when displaying text, but it's sort of broken. Java doesn't automatically extract region and locale information from the OS, so it defaults to guessing which numeric shapes it should use. If the string you're displaying starts with numbers, there's no initial context for the numeric shaper to use in guessing which number forms to use, so it will default to Western shapes. Also, the Java numeric shaper only reshapes numbers and forgets to reshape the decimal point and thousand separator. I tried a release candidate for Java 7, and this problem was still there. Does anybody at Sun/Oracle actually use their UI framework in real applications? Anyway, even this broken support for numeric shaping isn't actually enabled in Swing, so you can't display numbers in Arabic. In the Java 7 release candidate, programmers could manually enable Arabic numeric shaping in rich text widgets (i.e. JTextArea), but it wasn't clear whether that support was also added to other widgets like JButton or JLabel, etc. In any case, given the brokenness of Java numeric shaping, that isn't exactly a big win.

So in the end, if you want to build an Arabic GUI in Java, use SWT. Eclipse now has a free GUI builder available called Window Builder, and even though I didn't actually know any SWT, I was able to throw together a SWT GUI in a couple of hours with almost no work. GUI builders are awesome. Previously, I was always concerned that I would lose some flexibility in the code I could write, but the one in Eclipse is a real dream and saves a lot of time. I really should have paid money to buy one years ago.

Saturday, August 13, 2011

Getting Type 1 Postscript Fonts from pdflatex

For the past several years, I've been using pdflatex to generate PDFs from my LaTeX, and it usually works like a charm. All modern versions of pdflatex correctly use type 1 (vector) postscript fonts and not type 3 (bitmap) fonts.

Just today, I was generating a PDF for a camera-ready, but whenever I looked at the list of fonts in the document, I kept seeing type 3 fonts there. I couldn't figure out where those type 3 fonts were coming from. I initially thought they might be from some figures, but that ended up not being the case. After playing with my document for a while, I discovered that the problem was that I was using some non-English characters, which was causing problems for LaTeX. Apparently my default installation of LaTeX had type 1 fonts that only covered the standard English character set (plus some accents). When I used characters like French guillemets quotation marks, LaTeX would need to use type 3 fonts because those were the only versions of the fonts with those characters. Using \usepackage[T1]{fontenc} did nothing since my LaTeX installation simply didn't have the necessary fonts.

Fortunately, there is a package called cm-super that seemed to contain the necessary fonts. I couldn't figure out how to coax my Fedora TexLive distribution to download this package, so I tried to grab it in Windows using MiKTeX. Unfortunately, the package is fairly large, and MiKTeX kept killing my computer while trying to download it. The download would start quickly, but gradually slow down to a crawl while my cpu utilization would go upwards. I suspected MiKTeX was doing something silly like storing the file in memory, but in a linearly expanding buffer of some sort. My Thinkpad X61t has always had heat problems, and running with high cpu usage for such long periods kept causing my laptop to overheat and die before the download would finish. Fortunately, I was able to download the packages plus some index files directly from a mirror, and get MiKTeX to load the package locally instead of from the Internet. Some people also needed to do the usual MiKTeX oddness to get things to work right afterwards.

But everything seemed to work ok once I had cm-super installed. My PDFs contained only type 1 fonts. I really don't have a strong understanding of why cm-super isn't included in my default LaTeX installation. Are the fonts too big? Is the quality of the fonts not as good as the default ones? I have no idea. But it looked ok to me, so I'm going with it.

Sunday, May 08, 2011

How to Use Constructors and Do Inheritance Properly in JavaScript

With all my complaints about how difficult it is to find good documentation about how to do inheritance properly in JavaScript, I thought it might be useful to write a blog post about it, so then it would be easier (for me, at least) to find information about the topic.

Constructors

So, let's suppose you have a program, and you need to have a Student object. Students have a name and an array of courses that they are taking. The quickest way to create a Student object is to use the object literal syntax:

var student = { 
   name: 'Joe', 
   courses: [],
   addCourse: function(course) { courses.push(course); } 
};

If you need to create many Student objects, you can simply create a function that creates them for you:

function makeStudent(student_name) {
   return {
         name: student_name, 
         courses: [],
         addCourse: function(course) { courses.push(course); } 
      };
}
var student = makeStudent('Joe');

You can also use a constructor function, which essentially does the same thing:

function Student(student_name) {
   this.name = student_name;
   this.courses = [];
   this.addCourse = function(course) { courses.push(course); };
}
var joe = new Student('Joe');
var ann = new Student('Ann');
var sue = new Student('Sue');

There is a small problem with using constructors in this way. When you create many Student objects, the same name, courses, and addCourse properties show up in each Student. Everything still works, but it's not as efficient as it could be.


To make things more efficient, we need all the Student objects to share some properties instead of having separate, identical properties in each Student. For objects to share properties, we need to make use of JavaScript prototypes. In JavaScript, every object has a prototype object. When you read a property, JavaScript first looks if the property exists in the current object, if it doesn't, JavaScript then looks to see if the property exists in the chain of prototype objects. When you write to a property, the property is changed in the current object and not the prototype. Different Student objects can share the same prototype. Initially, all the properties of the prototype will appear as properties of the Student. As the Student objects change, they will get their own versions of the properties.

What all this amounts to is that prototypes are useful for describing the initial, "prototypical" view of what a certain type of object should look like. Over time, objects will change and stray from looking like the prototype, but that's fine.

For our Student example, let's first create a generic Student object that can serve as a prototype.

var studentPrototype = {
   name: 'Generic Name',
   courses: [],
   addCourse: function(course) { courses.push(course); } 
};

Now, in order to create objects that have this object as a prototype, you need to set the prototype field of a constructor function. When you create an object using the constructor, the constructor will set the prototype of the object to whatever its prototype field is set to. It can be a bit confusing. Setting the prototype field of a function does not change the prototype of that Function object. In general, JavaScript does not provide a variable where you can set or get the prototype of an object. You have to do it all indirectly by using these constructor functions.

var studentPrototype = {
   name: 'Generic Name',
   courses: [],
   addCourse: function(course) { courses.push(course); } 
};
function Student() {
}
Student.prototype = studentPrototype;

Now, when you create Student objects using the constructor, you will get objects that share a lot of fields.

var joe = new Student();
var ann = new Student();
var sue = new Student();


As you set the names of the Student objects, the prototype remains the same, but the name property of the individual Student objects will be set. This name property in the individual objects essentially "overrides" the name property of the prototype.

joe.name = 'Joe';
sue.name = 'Sue';


You can also set the name inside the constructor function, which will give the same result:

var studentPrototype = {
   name: 'Generic Name',
   courses: [],
   addCourse: function(course) { courses.push(course); } 
};
function Student(student_name) {
   this.name = student_name;
}
Student.prototype = studentPrototype;

var joe = new Student('Joe');
var sue = new Student('Sue');

Unfortunately, a problem happens though when you start dealing with courses.

joe.addCourse('math');
alert(sue.courses);

Somehow, Sue ends up enrolled in the math course, even though the course was only added to Joe. It seems that when modifying the courses property, the property of the prototype gets modified and not of the Joe object. Since all the Student objects share the same courses property of the prototype, it looks like Sue is taking math.


The problem is that the courses property of Joe is never written to. When addCourse is called, the method reads the courses property and gets an array. The "math" course is then added to this array. The array is modified, but the courses property is never written to, so Joe ends up modifying the prototype's array of courses instead of creating its own copy that isn't shared. To get around this problem, we should create a new array of courses for each Student, and assign it to the courses property in the Student constructor function.

Constructors Summary

When you want to create many objects with the same structure, you should use constructors and prototypes. You should take all the properties of these objects and divide them up into

  • properties that are constant and that can be shared between different instances of an object (i.e. methods)
  • properties that are unique to each object and that can be different in each object (i.e. data fields and pretty much everything that isn't a method)

Constant properties should be put into the prototype of the objects while the other properties should be set in the constructor function.

So suppose we want to be able to make multiple Student objects:

student = { 
   name: 'Joe', 
   courses: [],
   addCourse: function(course) { courses.push(course); } 
};

The method addCourse is the same between all Student objects, so it should appear in the prototype. The other properties will be set in the constructor.

var studentPrototype = {
   addCourse: function(course) { courses.push(course); } 
};
function Student(student_name) {
   this.name = student_name;
   this.courses = [];
}
Student.prototype = studentPrototype;

var joe = new Student('Joe');


Inheritance

Inheritance in JavaScript is less useful than in class-based object-oriented languages. JavaScript has a dynamic type system, so inheritance is not used to indicate which objects share the same interfaces. Inheritance is only used in JavaScript for code reuse. If you have many different objects that all have the same interface (e.g. in a graphics system, you might have objects for different shapes like lines and circles, and these shapes all understand a draw command), these objects do NOT need to inherit from the same base object unless these objects share code for implementing these interfaces.

The easiest way to think about inheritance hierarchies in JavaScript is to ignore it and to simply focus on the concept of prototypes.

Suppose we have a program that makes use of Student objects, which have the fields name and courses in addition to a method called addCoruse, as in the previous section:

function Student(student_name) {
   this.name = student_name;
   this.courses = [];
}
Student.prototype.addCourse = function(course) {
   courses.push(course);
};

Some of the students are special because take their courses via the Internet. For these students, we not only need to know their name and the courses they are taking, but also their e-mail information so that lectures and homework can be e-mailed to them. We'll use an InternetStudent object to represent these types of students.

function makeInternetStudent(student_name, student_mail) {
   return {
      name: student_name,
      courses: [],
      addCourse: function(course) { courses.push(course); },
      email: student_email,
      sendEmail: function(subject, body) { ... }
   };
}

To make a constructor for an InternetStudent, we need a prototype that serves as a good initial template for what an InternetStudent object looks like. Since an InternetStudent shares most of the properties of a Student object, we can use a Student as the prototype.

function InternetStudent() {
}
InternetStudent.prototype = new Student('GenericName');


There are two new properties in an InternetStudent that aren't in a Student: an emailfield that varies from student to student and a constant sendEmail method. The field should go in the constructor function while the method should be added to the prototype.

function InternetStudent(student_name, student_email) {
   this.name = student_name;
   this.email = student_email;
}
InternetStudent.prototype = new Student('GenericName');
InternetStudent.prototype.sendEmail = function(subject, body) { ... };

As in the section on constructors, you have to be careful when dealing with prototypes that you don't accidentally share data structures between different objects. In the above example, the courses array is shared between all InternetStudent objects because they all use the version in the prototype even though each InternetStudent should get their own separate array.

If you recall, the prototype contains all the properties of an object that shouldn't change between different objects while the constructor function initializes the properties that do change from object to object. The constructor function for Student objects creates new name and courses properties for each Student object. We can use that function to create new versions of these properties in the InternetStudent through constructor chaining:

function InternetStudent(student_name, student_email) {
   // Chain the constructor
   Student.call(this, student_name);

   // Initialize the fields that are unique to InternetStudent objects
   this.email = student_email;
}
InternetStudent.prototype = new Student('GenericName');
InternetStudent.prototype.sendEmail = function(subject, body) { ... };

var john = new InternetStudent('John', 'john@example.com');

And we're done.


Inheritance Summary

Inheritance is used for code reuse in JavaScript. In JavaScript inheritance, instead of using a plain Object as a prototype in a constructor, you create some other type of object to use as a prototype base instead.

As always with prototypes, you have to be careful not to accidentally share data structures in your objects. This is especially important when inheriting from something other than a plain Object because you may not know all of the internal data structures of the object you are inheriting from. If you are careful to initialize all non-constant data fields in your constructor functions, you can use constructor chaining to properly initialize these inherited internal data structures.

Monday, April 04, 2011

JavaScript Constructors Were a Mistake and Should Be Removed

For a long time now, I've been uncomfortable with JavaScript's syntax for constructors, but I could never quite figure out what was wrong with them. They always seemed sort of cumbersome and rigid. In fact, for most of my code, I created my objects almost exclusively using the object literal syntax instead of using constructors. The object literal syntax for creating objects simply seems so natural and spontaneous in comparison to using constructors.

JavaScript constructors simply feel like a weird hack. They're normal functions except you call them with new. In fact, all functions have extra fields for tracking prototypes that are only used when you use functions as a constructor. It also seems incongruent that JavaScript objects are not class-based and can be dynamically changed at any time, yet you're expected to put all your object construction code in one place in a single function. I would personally avoid using JavaScript constructors in all situations, but you can only make use of inheritance and reuse if you use constructors.

But constructors just end up feeling even more cumbersome once you start using them for inheritance. Theoretically, the inheritance model of JavaScript is very simple. Every object has a prototype object. When you use a property, JavaScript first looks if the property exists in the current object, if it doesn't, JavaScript then looks to see if the property exists in the chain of prototype objects. But when you actually go about trying to use inheritance in JavaScript, everything suddenly becomes really complicated. Every time I want to use inheritance, I always end up having to search on the Internet for tutorials about how to do it because it simply never sticks in my mind. There's something with the way constructors and inheritance are implemented in JavaScript that somehow makes the simple concept of prototype inheritance completely confusing to me. If you search for "JavaScript inheritance," you end up with all sorts of weird frameworks for abstracting away the inheritance process. It's actually somewhat hard to find good documentation on how to do inheritance (actually, the Mozilla docs that I linked to are very confusing as well because their description of constructor chaining is hard to grasp). I think that part of the problem is that the using constructors to create objects simply doesn't fit well with the prototype model of objects. If I'm creating an abstract base object that other things will inherit from, why do I need to create a constructor for allowing anybody to create multiple instances of that object, then use that constructor to make a single instance, and then inherit from that one instance? It just seems weird that if I want a single Employee base object that other objects will inherit from, I need to create an Employee constructor object, create the Employee, and then use this instance as a prototype in other constructor functions.

After many years of having these JavaScript issues gnaw at me, I've recently started to realize that my unease with constructors and inheritance wasn't a problem with me but a problem with JavaScript. Constructors are simply a mistake in the language and should be removed. It is, of course, impractical to literally remove constructors from the JavaScript language, but they should be deprecated, and all documentation should cease to mention them in reference to objects. JavaScript constructors attempt to impose a class-based object model onto JavaScript, but JavaScript is prototype-based, so it simply doesn't work. Because JavaScript is somewhat inspired by Java, there was an attempt to bring in some Java's object syntax into the language, but Java's constructors simply don't work in JavaScript. And I know that people really want class-based inheritance in JavaScript as evidenced by the fact that people keep trying to add class-based inheritance into JavaScript, but class-based inheritance doesn't exist in JavaScript now, so there's no point in trying to fit a square peg in a round hole. Fortunately, ECMAScript 5 has a new Object.create method that offers a reasonable alternative syntax for creating objects. This method can also be retrofitted into older versions of JavaScript as well (albeit with a performance penalty).

When using Object.create() to create objects, the code for creating an inheritance hierarchy then ends up closely matching the inheritance hierarchy itself:

Employee = {
      department : '',
      giveBonus : function(bonus) {...},
      handleVacation : function() {...},
   }

WageEmployee = Object.create(Employee, {
      wagePerHour : 10 
   });

SalaryEmployee = Object.create(Employee, {
      salaryPerYear : 50000 
   });

When you need to create multiple instances of the same type of object, you can still create a function to do that, instead of an explicit constructor.

function createSalariedEmployee(name, salary) {
   var emp = Object.create(SalaryEmployee);
   emp.name = name;
   emp.salaryPerYear = salary;
   return emp;
}

Sometimes you need to do constructor chaining in order to handle state that cannot be safely be stored in a prototype. For these situations, I would suggest having an initialization method in each object that can be chained (similar to Smalltalk conventions).

Employee = {
   __init__ : function(name) { this.name = name; },
   department : '',
   giveBonus : function(bonus) {...},
   handleVacation : function() {...},
}

WageEmployee = Object.create(Employee, {
      __init__ : function(name, wage) {
         Employee.__init__.call(this, name);
         this.wagePerHour = wage;
      } 
   });

var newEmployee = Object.create(WageEmployee);
newEmployee.__init__('John', 10);

I think this approach for creating objects is less confusing than using constructors. It's definitely a lot cleaner for singleton objects and for abstract objects. It may not be that great for flat hierarchies, where programmers want to create many instances of the same object, but it's not a big loss there either.

Friday, April 01, 2011

Scaling Up the Transitway

I was recently late for a train and had to rush across Ottawa from the west-end to the train station.Unfortunately, what is normally a quick dash across downtown on the Transitway turned into a grueling crawl. Most of the pain is entirely self-inflicted though. The Transitway buses ran on dedicated bus lanes through downtown, so the buses didn't have to weave through waves of cars. No, the problem was that there were just too many buses. The Transitway is used above its capacity, so during rush hour, the Transitway becomes a long line of bumper to bumper buses. The Transitway in downtown is just a single lane, so there's no passing of other buses, and every bus needs to stop at the bus stops, and then stop at the traffic lights, so you have to wait ages for every bus in front of yours to move forward a bit, load and unload passengers, wait at the light, and move on. If there are five buses in front of yours, you have to wait in turn for each bus to stop, board passengers, and then move on. It's brutal.

Given these capacity problems, it's clear to me that the current model for how to run buses along the Transitway through downtown just isn't very efficient any more. Ideally, more bus lanes would be provided downtown, but that isn't going to happen. The LRT through downtown will solve the capacity problems, but it'll be many years before that gets built, if ever. Until then, it would be nice if we could find some way to scale up the capacity of the Transitway a bit so that it can be used more efficiently.

I think it's time to remove the express buses from the Transitway in downtown. I know that one of the main advantages of a Bus Rapid Transit system like the Transitway is that people can take one bus from downtown and have it zip along a transit corridor, leave the corridor, and then deliver people directly to their houses. Transit users don't have to transfer, and they can time their arrivals at bus stops so that they don't have to wait around much. Unfortunately, insufficient capacity on the Transitway through downtown makes this model extremely inefficient. Traveling through downtown takes much too long, and all the traffic makes the arrival times of buses unpredictable. Previously, I've complained that Larry O'Brien's plan for having an underground downtown train line to be silly because it eliminates the advantage of express buses (i.e. no transfers) and makes it impossible for transit users to cross the city efficiently. But I'm now thinking that he might have been on to something. The capacity problems in downtown are so bad that the amount of time needed to get through downtown is beginning to outweigh the advantages of being able to take a single bus home from downtown. Having 20 different express buses all lined up with each one having to stop to let a few people on board, delaying all the buses behind it, just doesn't work. Instead, there should be single bus crossing downtown that moves people to a bus station/terminal where people can then transfer to their express buses. If there's only a single cross-downtown bus available, it would be more efficient because bus users would all simply board onto the first bus that arrives, and they'll fill the bus to capacity. There'll be no need to have a long line of somewhat full express buses inching across downtown. These cross-downtown buses could then deposit passengers off at large bus stations with bus loops where there's space for buses to stop and wait for large numbers of people to board buses. Hurdman and Bayview probably make the most sense as these bus transfer points. This proposal is similar to the initial phase of the current LRT plan in that there'll be a high capacity transit system just for downtown which focuses only on moving people to transfer points outside of downtown where people can transfer to buses for the rest of their journeys home.

It might also be possible to improve the efficiency of the downtown portions of the Transitway by having some sort of preboarding system. Other BRT systems do this, where they treat their bus systems like a subway. People have to pay before boarding a bus, and go through a turnstile into a loading/unloading zone. Then, when the bus comes, people can just jam themselves into the bus from whatever door is available since everyone in the loading/unloading zone has already paid. As a result, the loading and unloading of buses can be done faster.

Friday, February 18, 2011

HTML5 Audio is Still Too Immature to Use in Games

I made a little HTML game a year and a half ago that made some basic use of HTML5 audio, and it worked well enough, but it was very finicky, but I could see HTML5 audio eventually being useful once it matured.

Recently, I reprogrammed an old XNA game I wrote into HTML5 (I never want to go near XNA coding or the XNA community ever again), and I was hoping to program a much more extensive audio engine for the game. Unfortunately, I found HTML5 audio support to be just as finicky as before. Apparently the iPhone/iPad can't play more than one audio stream at once, meaning you can't play music and sound effects at the same time, so it's not possible to make HTML5 games that work well on the iPhone and iPad (basically, all of Apple's talk about HTML5 being superior to Flash on the iPhone and iPad was just propaganda and not reality). Firefox doesn't play short audio files, so the bips, clicks, and other sounds for button presses won't play. Chrome (and possibly Safari too) will not let you play an audio file more than once unless you serve the file from certain types of web servers. The audio in Chrome just sort of dies out after a while anyway, so you don't get any sound after a while. The Internet Explorer 9 Release Candidate seems to only support mp3 files for audio, and using mp3 files in games requires the payment of a licensing fee of $2500 to the mp3 licensing guys. So basically, it's not possible to build a very basic, reliable sound engine for HTML5 games right now.

This struck me as strange though because there are plenty of HTML5 demos and games that have extensive sound support. How can they pull off reliable sound while I can't?

They cheat, of course. All of these games make use of one of these common JavaScript sound libraries like SoundManager2. The dirty little secret is that these libraries will always use Flash for their sound unless Flash support isn't available. Flash is able to offer reliable, solid sound support across many platforms, so developers are able to build solid sound engines for their HTML5 games on top of it. If you try using pure HTML5 audio, things just fall apart.

Perhaps by this time next year, it will be possible to build a pure HTML5 game with good sound and graphics. I haven't used Firefox 4 yet, but I have high hopes for it. Until then, I think Flash is still the only viable platform for online games.