April 18, 2016

Some thoughts on JAI


This post will require some context, as I doubt many people are aware of what JAI is, or why they should even care.

The TL;DR on JAI is that it's a programming language being developed by Jonathan Blow with an eye towards using it for video game development. JAI is interesting for several reasons. Jon Blow, as a successful game developer, is one of them; he’s basically his own best use case. The other is that Jon presents and discusses his language in depth via streams (and recordings on YouTube), which is where it caught my attention.

My post here was triggered by watching his "Data-Oriented Demo”. I assumed he was going to talk about Entity Component Systems, which I played with in my minimalist experiments. But instead it reminded me of Cobol (an occupational hazard, in my case) and JIT compilation...

By all means watch Jon's presentation first, as I will butcher the details in favour of some brevity. You really want to hear the nitty gritty from the creator of the language anyway. Instead I’ll just focus on my two random connections.

In the data-oriented demo Jon is showing us the syntax and semantics of the “using” keyword. Here is a brief example, based on his presentation:

     Entity :: struct {
          position: Vector3;
     }

     Human :: struct {
          using entity : Entity;
          name: string;
     }

If you’re familiar with programming —and what are you doing reading my blog if you’re not ?— you’ll see that this defines two datatypes, Entity and Human, where Human has a nested instance of Entity. Ignoring the “using” keyword for now you could write:

     print(human.entity.position.x)

and expect the X coordinate of a Human’s position to be printed.

The “using” keyword does two things (in my understanding of it). One is that it lifts the members in the namespace of the given type into the current namespace. So any member in Entity can be addressed as if they belonged to Human, meaning you could shorten the above statement to:

     print(human.position.x)

This gives you the effect of a class-like behaviour without actually having used classes. It also makes the general code more robust to changes. I.e. you could move the “position” from Entity to Human without problem, or even introduce an extra type in between to keep hold of it.

Now, of course, this makes us think of Cobol. —Though it may just be me.— Because the effect is one of allowing for "structure-shy qualifiers”. That is, as long as there is an ‘x’ member found somewhere in a ‘position’ member found somewhere in an instance of Human the code will cope with changes. Well in Cobol you can already do this (minus the types) as follows:

     DISPLAY X OF POSITION OF HUMAN.

Cobol does not care about the exact path from ‘HUMAN’ to ‘X’, as long as there is only one entry in the structure which matches the selector. Without any more ‘using’ keywords we could as easily have written:

     DISPLAY X OF HUMAN.

How is that for robustness to changes ?

So, to some extent, the introduction of the ‘using’ keyword feels like an explicit way of making qualifiers structure-shy. Why not just make all qualifiers behave that way implicitly as in Cobol ?

But there is another side to the “using” keyword, and that is to add flexibility in how data is managed and stored in memory. Let’s make one small modification to the Human type:

     Human :: struct {
          using entity : ^Entity;
          name: string;
     }

Rather than nesting an Entity inside it, this time a Human has a pointer to an Entity instance elsewhere. The general code, and the above print statements, will still work as expected. The crucial point is that the Entity can be part of an array. That is, all Entities can be grouped together in memory and that capability, if you have read anything about game engine design, is essential for ensuring performance. What JAI allows through its ‘using’ keyword is changing the memory layout relatively easily without having to update most of the code. (Again, check Jon’s presentation for more advanced examples.) 

Being able to experiment with different memory management models in a way which is (mostly) transparent to your code is an amazing feature, and something I have not seen before. We have been moving away from manual memory management because it is error prone and cuts through all of your code. Yet in JAI there’s actually some good motivation to get back to handling things yourself.

But then I made my second connection, and a pretty wild one at that: if changing memory management models for different types becomes so painless, could we not get the runtime to do it dynamically and based on actual runtime statistics ? Think of JIT compilation: depending on critical paths in the code found at runtime it will optimise those paths dynamically and transparently, giving you better performance. Now imagine getting JIT behaviour not just for your code, but for your data as well...

Could JAI be setting us on a path to such a magical world ?

June 28, 2015

MarI/O

What do you do when you have a scriptable Super Nintendo emulator ? You create a program which teaches itself to play Super Maria. *duh*

You may know SethBling from his Minecraft creations, or as a Super Mario speed runner, but my favourite thing so far has to be MarI/O. It's a neural network implemented in Lua running inside the SNES emulator. Given enough generations, and the right scoring function, it figures out how to beat Mario levels:



And he shared the source code, though sadly without a clear license.

June 18, 2015

Wherefore art thou, Julia ?

If you ever wanted to play around with the Julia language, take a look at Juno. It's basically the LightTable equivalent for Julia developers, with an embedded run-time and support for live coding.

Very nice.

February 21, 2015

Caves 'n Critters

So I have started playing what is probably one of the geekiest games around: Dungeons and Dragons. A friend of mine wanted to give it a go, and was offering to DM the experience. We quickly found enough party members to actually give it a go, and we haven't looked back since.

We're currently just playing with the default characters, acquanting ourselves with the game mechanics, and getting into the whole roleplaying spirit. But, being geeks, we also quickly started looking at apps which could help us out with all of the bookkeeping which comes with this game.

What we found was that there was no one app for all our different platforms, and certainly not one which would share its data across our devices. Which meant that we couldn't really help each other out very easily.

Now, as loyal readers of this blog you may have already guessed at what's coming. Yes, I decided to write something myself. And yes, I put it on sourceforge. It's called Caves 'n Critters, and it currently looks something like this:


The main features are that it works across all of our devices, which include laptops (Mac and Windows) and tablets (iPad and Android). In addition, any player who is connected gets all updates made by other players. This is most effectively seen in the combat initiative tracking screen:


The current life totals reflect the changes made by players as their characters take damage or heal. When rolling initiative each player just enters their roll, and the initiative list gets sorted automatically across all screens. The DM can indicate the current active player, and that too is shared across screens.

In its current state it's definitely usable, but the experience on tablets could be much better. It seems much harder than it needs to be to make nice apps by means of HTML, CSS and Javascript. The browser gets in the way too much, and some things just feel sluggish...

We'll be tweaking this one further as we keep playing. If anyone else feels like giving it a try, just download the code, read the readme, and let me know how it all went.

October 19, 2014

Eve

If the previous post piqued your interest, then there is now more to be found over at incidentalcomplexity.com. What was initially called Aurora has been renamed to Eve. Looking forward to playing with this one!

September 10, 2014

Projectional Editing

I have written on this blog before about my attempts at building a structural editor which turns the parsing equation upside down. Today I learned there is a name for what I have been trying to create: Projectional Editing. The top hit when googling that term comes from Martin Fowler; which is nice as I based some of my work on his articles on language workbenches.

I stumbled on this terminology through a presentation on InfoQ titled "The Art of Building Tools–A Language Engineering Perspective". It's showing examples of this technique in different contexts. Some pretty low-level programmer stuff, but also in the realm of requirements specification. Very cool.

A related presentation, also on InfoQ, is "Enhancing Notational Flexibility and Usability of Projectional Editors". This is showing off JetBrain's MPS, which is a language engineering workbench used as the backbone by the first presentation. I have stumbled on MPS before some years ago, but I think I may have to take a second look at it.

More interesting still is Aurora, a project being worked on by Chris Granger (of Light Table fame), which I'm desperate to take a closer look at. I'm not sure if Aurora is doing projectional editing, though it sure sounds like it. That and some other pretty crazy stuff (programming in a database !?).

I don't know about you guys and galls, but I'm looking forward to see where all this is going.

August 11, 2014

Hardened Quines are hard

I have mentioned Quines here before as pieces of code which bend the mind. Well, the following Quine bends it a bit further: this one is "radiation hardened".

To refresh everyone's memory, a Quine is a piece of code which, when evaluated, yields its own source code. Well, the linked Quine is one which still functions if you delete any one character!

Who does it better ?

April 28, 2014

core.logic-o

While exploring Clojure's core.logic a bit, I stumbled on a set of just amazing videos. Clojure's core.logic is based on an implementation of miniKanren. If you don't know what that is, don't worry, I did not either. But it is really simple: MiniKanren is a DSL for logic programming based on three logical operators (==, fresh and conde) and one inference operator (run). If you take that you can do some really cool stuff. What exactly ? Well, that's where these videos come in:
I'm purposefully not saying what exactly is being shown. Just pick any one and you'll probably catch the bug. (Or maybe that's just me. :-))

April 10, 2014

Minimalist Parser Combinators

Now over at my github account: a minimalist implementation of parser combinators. Parser combinators provide an easy yet powerful way of implementing parsers, without the need of understanding compiler theory or formal grammars (though it can't hurt, of course). They also form the basis for my Koopa project, precisely because you can easily extend this technique to fit your needs.

This minimalist implementation may be slightly too minimalist, though. It only tells you whether something can be parsed or not. There is no way to extract anything useful while doing so —yet.

April 01, 2014

Minimalist Entity/Component System

I just uploaded a new addition to the minimalist code series. This time it's a minimalist version of an Entity/Component System. An ECS is a bit of a specialized architecture for modeling complex systems of dynamic objects. The origins for such systems come from the gaming world, but it has made its way into very different kinds of applications (the LightTable IDE is a great example here). If you're interested, the Entity Systems Wiki is a great resource for going deeper.

Javascript makes it really easy to set up such a system. In fact, the example I added is way more complex and took much longer to write than the actual engine itself. I was debating with myself whether or not to go for a more fluent API than what I provided now, but I was somewhat worried that I would be explaining the fluent part more than the actual ECS principles. If anyone is still interested in a more fluent version, though, let me know and I'll spend some time on that.

March 25, 2014

Make Install: Polycode

I somehow stumbled on Polycode, which is an interesting "free open-source framework for creating crossplatform games and interactive applications". It reminds me a bit of Processing, except that you use C++ or Lua for creating applications.

In addition to supporting 2D and 3D applications, it features a large selection of asset loaders (including Blender, of course) and has a Unity-like IDE. Runs on all major platforms, though there are no ready-to-download executables yet. You'll have to build everything from source to get started.

As an added bonus, there is a blog linked to the polycode. Always nice to see developers writing about their pet project.

March 15, 2014

Minimalist Dataflow Engine

I'm really enjoying these minimalist literate programming exercises, so here is another: a minimalist dataflow engine named "dfntly". It is very loosely inspired by the excellent Knockout library, but obviously has much fewer features. I would like to add some support for observable arrays, for example, and for asynchronous calculations where the dataflow engine only calculates further when the reply comes in. But that's something for another day.

In the meantime, if you feel like it, give it a go!

March 10, 2014

On "The Next 700 Asychronous Programming Models"

I was watching this talk by Philipp Haller on InfoQ on "how to make Rx programming more natural and intuitive by generalizing Scala's Async". The cliffnotes are this: unify the two by implementing async through observables. Clever.

Now, while the result was interersting I got a bit "stuck" thinking on this example from the presentation:

val futureDOY: Future[Response] =
  WS.url("http://api.day-of-year/today").get
val futureDaysLeft: Future[Response] =
  WS.url("http://api.days-left/today").get

val respFut = async {
  val dayOfYear = await(futureDOY).body
  val daysLeft  = await(futureDaysLeft).body
  Ok("" + dayOfYear + ": " + daysLeft + " days left!")
}

What it's trying to do is retrieve data from two remote services and compose the results in some way (don't worry about what it's really trying to achieve; it's one of those hypothetical examples which academics are really good at; I know, I used to be one). Now, as you may have noticed the services are consumed in an asynchronous way. That's where the need for futures and explicit waits for their results comes in.

Having been playing a bit with futures and their composition for the minimalist asynchronous process virtual machine I understand the mind bending it can take to get this right in more realistic examples. As a programmer you constantly have to be aware of what methods return results which are immediately available (i.e. are synchronous) and which ones are not. Because if you get it wrong the results will be unexpected and probably quite annoying to debug.

So here comes my question: rather than trying to come up with lots of creative ways of composing asynchronous behaviours and avoiding callback hell, why not stick to the principle of least surprise and make all asynchronous calls act as synchronous ones by default ? What is really stopping the above code from being as simple as:

val dayOfYear = WS.url("http://api.day-of-year/today").get.body
val daysLeft  = WS.url("http://api.days-left/today").body
val respFut = Ok("" + dayOfYear + ": " + daysLeft + " days left!")

A programmer's default mindset, I would argue, is that code is synchronous. By making that the default the obvious solution becomes a correct one.

Asynchronous execution, if wanted, can still be supported by explicitly requesting it. So another way to write the example could be:

val futureDOY: Future[Response] =
  async { WS.url("http://api.day-of-year/today").get }
val futureDaysLeft: Future[Response] =
  async { WS.url("http://api.days-left/today").get }

val respFut = async {
  val dayOfYear = futureDOY.body
  val daysLeft  = futureDaysLeft.body
  Ok("" + dayOfYear + ": " + daysLeft + " days left!")
}

While not as concise as the earlier rewrite at least it removes all doubt about which parts of the code don't want to wait for specific results.

Anyway, just wanted to get this off my mind. If you like, or think I'm just blowing smoke, let me know.

February 22, 2014

Minimalist Asynchronous PVM

So adding support for asynchronous tasks turned out not to be so difficult. With a little help of Q's promises and support for composing them all it took was a minor rewrite of the main tick function...

Anyway, this version of the minimalist PVM can be found here, together with an example which queries the OpenWeatherMap API.

Note that in the process of doing this I also added some minor tweaks to the basic version of the PVM; the most useful of which is the ability to define a starting runtime state for the process upon activation. I extended the examples there as well to showcase this.

February 18, 2014

Minimalist Literate Programming

As a quick follow-up to the minimalist PVM you can now find a very simple literate programming tool over at my github. It's a single Perl script which converts source code into a Markdown document. It does this by extracting the text from the comments in the source code, and wrapping the code itself in code blocks. Want an example of the output ? The README.md for the tool is exactly that. (Self-documenting code FTW!)

February 15, 2014

Minimalist Process Virtual Machine

Over at my github account (see, I do have one) I just added a minimalist implementation of a Process Virtual Machine (PVM).

Wait, what ?

Let's start with what a PVM is. You can find a thorough description of it here, but in brief it is an engine which can drive automated business processes and workflows. It actually forms the core of JBPM and Activiti. (If you really feel like geeking out on workflow engines you should definitely head over to Joram Barrez's blog, which has all sorts of Activiti craziness in it.)

I really wanted to figure out what makes such an engine tick, and while I can look at the source code for JBPM and Activiti they were never meant as an educational example. These engines have real work to do, and so come with usual amount of hardening and boilerplating. Rather than deep-diving through all that I wanted to see what a minimalist implementation could look like.

When it comes to minimalist implementations a lot depends on your choice of language. Ideally you want something which is really flexible without imposing a lot of structure. Prototype-based languages are a great fit and, as it so happens, Javascript is a popular example of one.

So that's where I went. I've got a minimalist PVM capable of running in a Node.js environment. As you'll see there's very little code to it; and I actually spent most of the time getting everything into the form of a literate program.

Because it is very minimalist there are certain features it does not (yet) have. The big ones are wait states (e.g. for human interaction), asynchronous tasks (e.g. for doing IO or REST calls), and persistence. In a future version I'll see if I can add those in a minimalist way as well, but for now this will do to satisfy my curiousity.

If you like, let me know; and feel free to experiment further.

November 27, 2013

Make Install: Solarus

Solarus is an open source Zelda-like 2D game engine. How Zelda-like, you may be wondering ? Well...



I'd call that pretty convincing. :-)

For the curious, it has a C++ core, and uses Lua for scripting the actual games.

November 26, 2013

Styling

Not much to tell, but I wanted to show the latest progress:

I have tweaked the style a bit to match that of the phone app. Usability has also improved. You can now select the dataset to view by entering the user's name in the top left. You can also quickly jump to the previous or next day in the top right. And the selected day is also highlighted in the calendar.

November 18, 2013

Brain Graphs

I haven't been able to do much work on Brain Drain, but I did want to show you the current state of the web app, which I use for inspecting the collected data.


(Note: the screenshot is showing a ficticious data set. I sincerely hope no-one has this many headaches. The data is generated by another Javascript script, which you can also find in SVN.)

There are two parts to the visualization. The bottom part shows a calendar, focused on the current year. I based this off one of the many D3 examples. The main difference with the stock calendar sample is that you can select any date, and it will show the data for that date in the top part.

The top graph, then, shows the actual collected data. Each bar represents an individual data point. The height of the bar, and its color, represents the pain level. They are placed on the horizontal axis based on the time of day. When moving the mouse over a bar you also get a popup which shows the exact level and all tags which were added by the user at the time of registration.

The main missing feature right now is a way to choose the correct dataset. The database can store datasets for multiple users, but there is no way to select which one you want (other than hacking the URL, which I set up as a temporary solution). Apart from this limitation the interface works just fine, but would benefit from some usability and layout tweaks. Simple next/previous buttons for both the day and year would be nice, for instance. I'm also thinking of adding a tag-based search, or even graphs which group data by time-of-day, day-of-week, tag, etc.

From a developer point-of-view I can't stress the benefits of D3 enough. Once you understand its functional model, and with the help of some samples, you can easily do complex visualizations and interactive graphs with a limited amount of code. D3 has quickly made it on my list of favourite tools.

Well, that's it for now. Next posts on Brain Drain will likely just be showcasing further tweaks, though I do hope I can show you some more interesting stuff soon. As things stand, however, I'm using the application more than I'm developing it, and it has already reached most of the goals I set for it.

November 10, 2013

CanHasTagsNow

The phone app has reached a point where it has the minimum required functionality. A user can now take measurements, add custom defined tags to them, and upload everything to the server for storage.

It also has an entirely new look and feel. If you compare the following screenshot with the version from last week you should notice some differences:


The app now has three pages, which can be navigated by swiping left and right. The first page allows you to take a measurement: simply drag the slider to the desired level, then hit the log button. The second page lets you select tags and define new ones. And the final page is used for uploading everything to the server.

As you know I'm building this with Phonegap, which means all of the above is nothing more than HTML, CSS and Javascript. You might expect —at least I did— that setting up such a layout would require quite a bit of scripting, but actually it is mostly based on CSS3's multi-column layouts.

Here's the trick: set the column-count to 'auto' and define the height of your element to be 100%. This will create columns which take up the height of the viewport. Then use a small bit of Javascript to set the column width to the width of the viewport (ideally you'd use viewport relative lengths instead, but this does not work on the phone) and now you have split up your content into screen-sized pages. With a little help of Hammer (the Javascript library, not the artist) you can then capture swipe actions and offset the element to show the right page.

(Figuring out the offset was a bit tricky. Given that visually you're getting a horizontal layout of elements you might think that you can just query the width of each element, divide that by the width of the viewport, and you'd end up with the correct number of pages. You'd be wrong. What I found was that the width actually stays constant and it's the height of the elements which changes. So you have to divide the element's height by the height of the viewport to deduce the right page count. Weird.)

The bigger struggle was the taglist. As the number of tags can grow over time so can the length of this section. My initial thought was to just let it grow in length. The pagination trick would just split up the content accordingly and I could still swipe through pages of tags. I gave this a try, and it worked as advertised, but it didn't look right and it didn't feel right. The reason it didn't look right is that browsers still are very bad at dealing with breaks in content. The reason it didn't feel right is that the distance to the upload functionality was now variable, which makes for a bad user experience. So instead I opted to limit the tag list to one visible page with its own vertically scrolling element inside.

And that was about it. The rest was figuring out the more detailed CSS stylings and getting the interactions in place. I'm still going to be playing around with the overall style, as I'm not sold on it yet. And I need to clean up and sanitize the scripting. But all in all it's in a usable state, and I'm pretty happy with what I've got.