<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>blog.joa-ebert.com - Blog of Joa Ebert</title>
	
	<link>http://blog.joa-ebert.com</link>
	<description>Hacks, Cross-Compilers and other Weirdness.</description>
	<lastBuildDate>Fri, 15 Feb 2013 17:53:36 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/je2050" /><feedburner:info uri="je2050" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Factory Reset</title>
		<link>http://feedproxy.google.com/~r/je2050/~3/MibHI1i4OnI/</link>
		<comments>http://blog.joa-ebert.com/2013/02/15/factory-reset/#comments</comments>
		<pubDate>Fri, 15 Feb 2013 17:53:36 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[news]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[2013]]></category>
		<category><![CDATA[audiotool]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=941</guid>
		<description><![CDATA[Leaving something behind you is never easy when you put your whole heart into it. Five years of Audiotool have shaped me, taught me and left their scars. As of November 2012 I am no longer involved in the project and wish the team all the best and success in pursuing the democratization of music [...]]]></description>
				<content:encoded><![CDATA[<p>Leaving something behind you is never easy when you put your whole heart into it. Five years of Audiotool have shaped me, taught me and left their scars. As of November 2012 I am no longer involved in the project and wish the team all the best and success in pursuing the democratization of music production.</p>
<p>Of course, every end is a new beginning. For me this means that I am going to start a whole new adventure. Luckily I am not alone in this because starting from scratch is never easy. Together with my colleague Tim Richter we are going to pursue our ideas of a multi-platform development kit.</p>
<p>2013 will be a roller-coaster. I am all in.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2013/02/15/factory-reset/" size="standard" count="true"></div></div>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2013/02/15/factory-reset/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		<feedburner:origLink>http://blog.joa-ebert.com/2013/02/15/factory-reset/</feedburner:origLink></item>
		<item>
		<title>Continuous Deployment</title>
		<link>http://feedproxy.google.com/~r/je2050/~3/d9ARa2ohw00/</link>
		<comments>http://blog.joa-ebert.com/2012/05/11/continuous-deployment/#comments</comments>
		<pubDate>Fri, 11 May 2012 15:36:44 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[misc]]></category>
		<category><![CDATA[audiotool]]></category>
		<category><![CDATA[continuous deployment]]></category>
		<category><![CDATA[continuous integration]]></category>
		<category><![CDATA[future joa]]></category>
		<category><![CDATA[shell scripting]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=918</guid>
		<description><![CDATA[Much has already been said about Continuous Deployment. Etsy made it famous once and we integrated our own solution about two weeks ago. The reason why I integrated it into our system was quite simple: the only person who could perform a deploy was me. This was hindering the rest of the team of course. [...]]]></description>
				<content:encoded><![CDATA[<p>Much has already been said about <a href="http://timothyfitz.wordpress.com/2009/02/10/continuous-deployment-at-imvu-doing-the-impossible-fifty-times-a-day/">Continuous Deployment</a>. <a href="https://github.com/etsy/deployinator" target="_blank" title="Deployinator">Etsy</a> made it famous once and we integrated our own solution about two weeks ago.</p>
<p>The reason why I integrated it into our system was quite simple: the only person who could perform a deploy was me. This was hindering the rest of the team of course.</p>
<p>Our architecture allowed &#8220;hot&#8221; deployments already. That means users who were already using the Audiotool application did not notice a deploy happened at all. This is of course only possible as long as there are no new dependencies on the API.</p>
<p>The Audiotool startup process is a very important ingridient. We have a boot sequence which loads a configuration file upfront. In this configuration file is a version number. The version number is used to load all dependencies the application needs to start. We have put a repository server in place which serves SWF files based on this version and they get cached till the end of time.</p>
<p>If a user started Audiotool when version 1.1 was online and we update to 1.2 in the meantime the user would still load all audio plugins for version 1.1. There are some cases when a hot deployment is not possible (yet) and we call this a scheduled update.<br />
This pushes a message into Audiotool, notifying users that they should save their song and restart the application. But this is not part of the blog post and a scheduled update is very rare. We did it twice last year, once this year.</p>
<p>When we did a deploy it was basically done like this:</p>
<ol>
<li>Make sure all changes are checked in.</li>
<li>Update a default version key in some source files in case the boot sequence cannot load the configuration for whatever reason.</li>
<li>Update the Nginx configuration so that some verison-less files like our embed player are routed correct.</li>
<li>Create a tag for the repository.</li>
<li>Create a clone of the tag.</li>
<li>Execute <code>mvn -Pdeploy-to-live deploy</code> in the clone. This command already updates all plug-ins on audiotool.com and puts new metadata in place.</li>
<li>Copy all SWF files form a local directory to S3.</li>
<li>SSH into a server and update the configuration file Audiotool parses at startup.</li>
<li>Reload the Nginx configuration.</li>
</ol>
<p>A lot of steps. This means a lot can go wrong of course. And even though we had all those steps written down in an internal Wiki it is still hard to do all this. You need the appropriate SSH keys to log into some servers, uploading files to S3 requires a tool which is also configured and not everyone is comfortable with editing a Nginx configuration file on an Amazon server through the terminal.</p>
<p>There was only one deployment that happened without me. I was at FITC Amsterdam in 2010 at that time and it was a long phone call. Obviously something had to change.</p>
<p>The first step was to get rid of all the manual configuration hassle. The configuration file that one needed to change via SSH had to go so I made it a dynamically created file by the web server. The actual version is pulled from the database and this made <del datetime="2012-05-11T14:36:13+00:00">our</del> my life much easier already. But still this was not what I wanted. Of course nothing really changed. You still had to perform the S3 upload, SSH into a server and so on.</p>
<p>But since the configuration was already served via the web server I could start automating more things. Even better: with our last major update we dropped the version number from Audiotool. User&#8217;s would stop expecting to see big changes and a version number that increases. Instead we focus on being much more active and to push changes online as quick as possible.</p>
<p>Since I already wrote some shell scripts for myself to deploy various server applications with a single command I started doing the same for the whole Audiotool application. </p>
<p>The first step was to get rid of the default version in some of the ActionScript source files. I simply <code>[Embed]</code> a text file now which contains the version information. A single text file is so much easier to change.</p>
<p>Then I added an API call which allows me to change the version information online. That way a new version can be released easily without any human interaction. With the API call in place and a text file containing all important configuration parameters the last issue was the Nginx configuration. But a small script on the server should do the job.</p>
<p>So I started writing a little script which performs all the necessary tasks:</p>
<ol>
<li>Create a clone of the repository.</li>
<li>Get the id of the current revision.</li>
<li>Create a tag for the revision like <em>YYYY-MM-DD_REVISION</em>.</li>
<li>Replace the default version with the revision.</li>
<li>Execute the Maven command to deploy some metadata and build all SWF files.</li>
<li>Upload all SWF files to S3.</li>
<li><em>curl</em> our API with the revision information.</li>
<li>SSH into a server at Amazon to update Nginx.</li>
<li>Cleanup.</li>
</ol>
<p>That&#8217;s all there was to it. Since I do not have that much experience with shell scripting the most annoying part was to figure out a way to replace the text in a file. After looking through all examples of possible/impossible <code>sed</code> and <code>awk</code> options I got lucky with <code>sed -i "/@build.version@/ s//${HG_VERSION}/g" ${HG_CLONE}/default.version.txt</code>. This basically replaces <code>@build.version@</code> with the content of <code>${HG_VERSION}</code>. I know, magic. I just want to write it down here so Future-Joa can Google this and come back in five years getting a quick answer.</p>
<p>With the shell script at our disposal we simply had to hook it into TeamCity, a fantastic continuous integration solution by the way. After configuring some command line tools on the CI server we were ready to go.</p>
<p>The results speak for themselves. We made already twenty deployments during the last two weeks. That is about as many deployments as we did since we started Audiotool. Because deployments become less scary and everyone can trigger them we are able to iterate quicker and get rid of a lots of bugs. In fact it makes it also much easier to reason about your program. If you push hundreds of new features and get a null pointer exception: good luck. However if you just changed one little thing and get loads of bug reports it is quite easy to identify what could be the possible culprit. Of course this is only a Flash problem since there are no stack traces in the release player. But I guess if you build a JavaScript application you would have similar problems.</p>
<p>I can only recommend doing the same. Especially for your own sanity. 100% automated deployments are really cool and stress free! It is also much easier to setup than you might expect.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2012/05/11/continuous-deployment/" size="standard" count="true"></div></div>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2012/05/11/continuous-deployment/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://blog.joa-ebert.com/2012/05/11/continuous-deployment/</feedburner:origLink></item>
		<item>
		<title>Collateral Damage</title>
		<link>http://feedproxy.google.com/~r/je2050/~3/JTnqtcc3V74/</link>
		<comments>http://blog.joa-ebert.com/2012/03/28/collateral-damage/#comments</comments>
		<pubDate>Wed, 28 Mar 2012 17:05:28 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[Flash]]></category>
		<category><![CDATA[news]]></category>
		<category><![CDATA[adobe]]></category>
		<category><![CDATA[apparat]]></category>
		<category><![CDATA[flash player]]></category>
		<category><![CDATA[opensource]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=874</guid>
		<description><![CDATA[I am no longer committed to supporting any Flash related open-source projects. Here is why. When I started using the Flash Player it was quite easy to reach its limits. However you were able to get around those limitations with clever hacks and debatable optimization techniques. I was always keen to share my knowledge with [...]]]></description>
				<content:encoded><![CDATA[<blockquote><p>I am no longer committed to supporting any Flash related open-source projects.</p></blockquote>
<p><!-- more -->Here is why. When I started using the Flash Player it was quite easy to reach its limits. However you were able to get around those limitations with clever hacks and debatable optimization techniques. I was always keen to share my knowledge with the community and to explore all possible options to achieve best performance.</p>
<p>The Flash Player has been hibernating for half a decade now. The only glimpse of performance was finally a set of specialized op-codes which allow you to modify an array of bytes. In layman&#8217;s terms this means it was finally possible to do <code>a[b] = c</code> with an acceptable performance. So I wrote a tool which allows you to do just that and many other things. I have spent a good time of my free time trying to improve the performance of the Flash Player and contributing all my code to the community.</p>
<p>As a reminder: I <a href="http://blog.joa-ebert.com/2009/09/28/fotb-recordings/">showed</a> some drastic performance improvements at Flash on the Beach in 2009. That was three years ago. It was not necessary to modify the Flash Player and it was not necessary to modify the ActionScript language. </p>
<p>The <a href="http://www.adobe.com/devnet/flashplatform/whitepapers/roadmap.html">Adobe roadmap for the Flash runtimes</a> states that Flash Player &#8220;Dolores&#8221;</p>
<ul>
<li>will support ActionScript Workers</li>
<li>comes with improved performance for Apple iOS</li>
<li>and  ActionScript 3 APIs to access the fast-memory op-codes</li>
</ul>
<p>This player should be released in the second half of 2012. The &#8220;Next&#8221; Flash Player will finally include</p>
<ul>
<li>modernizing the core of the Flash runtime</li>
<li>work on the VM</li>
<li>updates to the ActionScript language</li>
</ul>
<p>This is planned for 2013 apparently. And what can we expect? Type inference, static typing as a default, and hardware-oriented numeric types. Hooray, so it will be finally possible in 2013 to write <code>a[b] = c</code> without having to use some weird fast-memory op-codes. If we look back to the year 2009 this makes me really sad.</p>
<p>With the introduction of the <a href="http://ncannasse.fr/blog/adobe_announce_speed_tax">speed tax</a> you will now have to license your application. No matter if you make money out of it or not. Now I think that 9% is a decent number and I can understand Adobe&#8217;s position on this. In fact it is much more friendly than the 30% Google or Apple take. However the AppStore was an invention. What is the invention here? Squeezing money out of an already existing feature, and suddenly making it unavailable after people have been relying on it for years to push the boundaries of the platform and actually innovate?</p>
<p>But for the hell of it, <b><code>a[b] = c</code> is not a premium feature.</b> Nor are hardware accelerated graphics. That is what I would expect from any decent runtime.</p>
<p>Limiting the capabilities of a runtime &#8212; by defaulting back to software rendering for instance &#8212; will make it less attractive to use it in the first place. You are probably not interested to go through a signing progress for a small demo. So your performance might be crap, people will complain about the Flash Player taking 100% CPU because its using software rendering (YEY! 2013!), laptop fans will start to dance and you will look like a bad developer because that other guy got the same thing running with hardware acceleration. Or you could use a different technology.</p>
<p>Why is this bad? Because apparently this signing with a $50k threshold targets the enterprise and small developers seem to be acceptable collateral damage. However thinking about the next five to ten years: who is going to write ActionScript code if it is no longer attractive to play around with it in the first place?</p>
<p>We still rely on the Flash Player at <a href="http://www.audiotool.com/">audiotool.com</a>. I am still developing for it and we will probably have to use it as long as there is no alternative. Me no longer supporting open-source tools is just me no longer spending <strong>my</strong> personal time for a platform that I would not use for private stuff. Work is of course not always about fun. But fortunately I am able to spend 90% of my time writing Scala code.</p>
<p>I will finish this blog post with some <a href="http://blogs.unity3d.com/2012/03/28/unity-flash-update/">bad karma</A>:</p>
<blockquote><p>It’s also worth noting that the new Adobe license will prohibit scenarios where you’d have the first level of a game in the Flash Player, and the full experience inside the Unity Web Player. Alas, this is something you’ll need to be aware of if you were considering such a route.</p></blockquote>
<p>You will not only pay for the features. You are also welcome to cede some of your rights.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2012/03/28/collateral-damage/" size="standard" count="true"></div></div>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2012/03/28/collateral-damage/feed/</wfw:commentRss>
		<slash:comments>35</slash:comments>
		<feedburner:origLink>http://blog.joa-ebert.com/2012/03/28/collateral-damage/</feedburner:origLink></item>
		<item>
		<title>Project Hiddenwood</title>
		<link>http://feedproxy.google.com/~r/je2050/~3/lSPOH3Q6O7Y/</link>
		<comments>http://blog.joa-ebert.com/2011/11/11/project-hiddenwood/#comments</comments>
		<pubDate>Fri, 11 Nov 2011 11:12:01 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[news]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[audiotool]]></category>
		<category><![CDATA[hiddenwood]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[ios]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=863</guid>
		<description><![CDATA[This years FOTB was special. At the end of my session I showed a sneak preview of project Hiddenwood. I demonstrated complete playback of Audiotool tracks on stage &#8212; in a browser. Now that does not sound too special&#8230; But then again, the playback was done using JavaScript only and calculated in realtime. Audiotool is [...]]]></description>
				<content:encoded><![CDATA[<p>This years FOTB was special. At the end of my session I showed a sneak preview of project Hiddenwood. I demonstrated complete playback of Audiotool tracks on stage &#8212; in a browser. Now that does not sound too special&#8230;</p>
<p>But then again, the playback was done using JavaScript only and calculated in realtime.</p>
<p>Audiotool is a complex piece of software so you might ask how one could torture themselves by implementing it in JavaScript? We didn&#8217;t. Instead we started building our own vision of a cross-platform application framework a couple of months ago.</p>
<p>Introducing project Hiddenwood.</p>
<p>Hiddenwood is a collection of libraries and tools specifically designed to support different devices and platforms. The core libraries are the &#8220;driver layer&#8221; and always platform-specific with a platform-independent interface.<br />
On top of that we provide a basic layer of libraries like our UI system, animation framework or managed collections which guarantee 0% garbage collection activity and have been battle-tested in Audiotool.</p>
<p>The framework is all about speed and consistency. The rendering pipeline is optimized for OpenGL and although we offer something similar to Flash&#8217;s display list a lot of features are not available because they would compromise the speed.</p>
<p>Speaking about speed: we are always interested in staying as native as possible on our target platform. So for the browser we emit JavaScript, for Android you will get the full DalvikVM performance and for the desktop you will get JVM performance. This approach has also another very important aspect. If you want to go platform-specific for certain features you can do that.<br />
For instance if we want to render Audiotool songs on the server using a fork-join pool for our audio calculation this is possible and might not make sense on an Android device.</p>
<p>You write Java code and the supported platforms are native desktop applications, Android (minimum requirements  are Gingerbread and OpenGL ES 2.0) and modern browsers. Now for browsers we even go one step further and support multiple options. That means if WebGL is not available we simply fallback to a normal canvas based render-engine. The same applies to some of the Android drivers.</p>
<p>iOS is of course important as well and we are actively researching the best option that will give us the most flexibility and performance.</p>
<p>We are currently working on two real applications built with Hiddenwood. So far it is a real pleasure to enjoy quick build times and simply test what you want on the desktop with great debugging capabilities. When you are ready you can try the same app on Android or in the browser &#8212; which might take a little bit longer to compile.</p>
<p>Because we see Hiddenwood as an application framework there are a lot of goodies built-in like a sprite-sheet based class generator. Think <code>Image mixerBackground = Textures.mixer.background();</code> where <em>mixer</em> was the folder name and <em>background</em> the name of the file.</p>
<p>We believe that as a developer you really do not care about what kind of technology you are using and just want a great result. We also think that you should be able to reuse platform-independent code across multiple projects. However we do not want to take power away from the developer because if you know what you are doing: go for it.</p>
<p>Of course we are not the only ones with this idea. Nicolas Cannasse saw the signs years ago and invented <a href="http://www.haxe.org/" target="_blank" title="haXe">haXe</a> which gives you a comparable experience and Google released <a href="http://code.google.com/p/playn/" target="_blank" title="playN">playN</a> a couple of weeks ago which takes a similar approach (and requires another 25 committers :P).</p>
<p>But when we started Hiddenwood we wanted the Java tooling experience and playN was not public at that time. We also think that a game engine is not what you want to use for all kinds of applications. So we like to be able to give people the freedom to build their own game engine on top of Hiddenwood &#8212; and calculate physics in a different thread peut-être.<br />
Speaking about threading: the only possible solution that works across all platforms is a shared-nothing architecture which we put in place. However if you write platform specific code you can use of course everything the platform offers and a lot of the Hiddenwood core libraries like the network- or cache-layer make use of multiple threads.</p>
<p>In the end what makes Hiddenwood special in my opinion is that we do not believe in <em>write once run anywhere</em> because that just does not make sense. The essence and philosophy behind Hiddenwood is to write platform-agnostic code using kickass-libraries and being able to reuse that. Audiotool on a tablet would look completely different from Audiotool running in a browser. And Audiotool on iOS would probably be also a little bit different from Audiotool on an Android device because there are simply different paradigms you should respect.</p>
<p>I hope that we can share more information with you soon. With the news of mobile Flash Player being deprecated and the ongoing demand for cross-platform development we have exciting times ahead of us. I am also super excited about the (beautiful <3) applications which we are going to release in the not so distant future.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2011/11/11/project-hiddenwood/" size="standard" count="true"></div></div>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2011/11/11/project-hiddenwood/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		<feedburner:origLink>http://blog.joa-ebert.com/2011/11/11/project-hiddenwood/</feedburner:origLink></item>
		<item>
		<title>First look at Dart</title>
		<link>http://feedproxy.google.com/~r/je2050/~3/GM3NxkTMHjc/</link>
		<comments>http://blog.joa-ebert.com/2011/10/11/first-look-at-dart/#comments</comments>
		<pubDate>Tue, 11 Oct 2011 09:35:23 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[misc]]></category>
		<category><![CDATA[dart]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=849</guid>
		<description><![CDATA[In this post I want to give you a short introduction to Google&#8217;s new language called Dart. Personally I am quite disappointed that Dart looks a lot like Java 8 with some tweaks here and there. Although the language is in its early stages I wonder why pattern matching was not a top-priority to the [...]]]></description>
				<content:encoded><![CDATA[<p>In this post I want to give you a short introduction to Google&#8217;s new language called <a href="http://www.dartlang.org/" target="_blank">Dart</a>. </p>
<p>Personally I am quite disappointed that Dart looks a lot like Java 8 with some tweaks here and there. Although the language is in its early stages I wonder why pattern matching was not a top-priority to the language team since Dart relies heavily on message passing. More on that in a second.</p>
<p>Since Dart should scale from small scripts to full applications it is nice to see support for generics from the start, optional typing and functions as first-class citizens.<br />
However that makes Dart look more like a better Java than JavaScript.</p>
<p>What makes Dart more of a web language is how you perform concurrent computations. This is done by shared-nothing message passing. The same way you do it with workers in JavaScript, actors in Erlang or Scala and hopefully quite soon in the Flash Player. We should not forget Go in this equation since it was also an effort to try out concurrency via channels that can send and receive messages. If we look a little bit more into Dart we can see some of the same ideas.</p>
<p>A worker in Dart are called <code>Isolate</code> <a href="http://www.dartlang.org/docs/api/Isolate.html#Isolate::Isolate" title="Isolate" target="_blank">[1]</a>. This makes sense since it runs completely isolate from the rest of your program. What is nice about the Dart approach is that you do not have to deal with files anymore when using an <code>Isolate</code>. JavaScript requires you to perform the task of having some special file lying around somewhere that adheres to the Worker protocol. When I write my application, I do not want to think about files that have some special top-level logic in them. Especially, I do not want to write a custom file at runtime using a blob-builder.</p>
<p>Dart embeds this from the start just like Go does. You will have a lot of <code>Isolate</code> objects communicating via a <code>SendPort</code> <a href="http://www.dartlang.org/docs/api/SendPort.html#SendPort::SendPort" title="SendPort" target="_blank">[2]</a> and a <code>ReceivePort</code> <a href="http://www.dartlang.org/docs/api/ReceivePort.html#ReceivePort::ReceivePort" title="ReceivePort" target="_blank">[3]</a>. The <code>Promise&lt;T&gt;</code> <a href="http://www.dartlang.org/docs/api/Promise.html#Promise::Promise" title="Promise" target="_blank">[4]</a> is just like Java&#8217;s <code>Future&lt;T&gt;</code> a holder for a value that can be computed later. I just wonder why they did not implement a read-only and write-only view on them. It would be nice if <code>Promise&lt;T&gt;</code> would be extended with methods like <code>map</code>, <code>flatMap</code> etc. because your code would be less spaghetti.</p>
<p>With no further ado I would like to explain some code now that you know how Dart works. Basically we calculate the n-th Fibonacci number with a very expensive approach. You would never do this in reality. Let us define <code>fib(x) = fib(x - 1) + fib(x - 2)</code> with <code>fib(1) = 1</code> and <code>fib(2) = 1</code>. So <code>fib(3)</code> is <code>fib(2) + fib(1)</code> which is <code>1 + 1</code>. Sorry for to bore you to death.</p>
<p>If we implement this in pseudo-code we get something like this:</p>
<p><code>
<pre>int fib(int x) {
  return x < 3 ? 1 : fib(x - 1) + fib(x - 2);
}</pre>
<p></code></p>
<p>If you would like to make this multi-threaded with Scala you could wrap the calls to <code>fib</code> into a <code>Future[Int]</code> like this:</p>
<p><code>
<pre>def fib(x: Int) =
  x match {
    case 1 | 2 => 1
    case _ =>
      val n1 = future { fib(x - 1) }
      val n2 = future { fib(x - 2) }
      n1() + n2()
  }</pre>
<p></code></p>
<p>We want to do the same with Dart. Since it is a language targeted for the web we get no access to blocking calls. The Scala code blocks when <code>n1()</code> or <code>n2()</code> is called. In layman's terms: we wait until the value has been computed.</p>
<p>Since there is no support for continuation passing style like C#'s <code>async</code> we have to write a lot of callbacks now.</p>
<p>This is the entry-point for the Dart version of this:</p>
<p><code>
<pre>main() {
  int n = 7;

  print("Computing fib($n) ... ");

  new FibIsolate().spawn().then(
    (port) =>
      port.call(n).receive(
        (value, port) => print("fib($n) = $value")
      )
  );
}</pre>
<p></code></p>
<p>First of all we see string-interpolation which is nice. Then we create a <code>FibIsolate</code> which I will show you in a second. When you create an <code>Isolate</code> it does not do anything so we have to call <code>spawn()</code> to perform the actual computation. However <code>spawn</code> returns us only a <code>Promise&lt;SendPort&gt;</code> which we can only use when available. This is done with the <code>then</code> method. <code>then</code> takes a function as an argument.<br />
There are multiple ways we could do this. <code>then((x) => ...)</code> is the same as <code>then((x) { ... })</code>. You are only allowed to use the first form for a single expression but you do not need to write all that boilerplate. In fact you are even allowed to omit a semicolon. Hell Yeah!</p>
<p>So when we get a <code>SendPort</code> which happens to be the case when our function is called we can send some value via the <code>call</code> method. Why use <code>call</code> and not <code>send</code>? <code>call</code> returns a <code>ReceivePort</code> which allows us to wait for the result. We do this by calling <code>receive</code> on the <code>ReceivePort</code> with a closure to print the value we get back.</p>
<p>Now let's have a look at the implementation of <code>FibIsolate</code>.</p>
<p><code>
<pre>class FibIsolate extends Isolate {
  main() {
    port.receive((n, replyTo) {
      switch(n) {
        case 0:
          replyTo.send(0); break;

        case 1:
        case 2:
          replyTo.send(1); break;

        default:
          Promise&lt;int&gt; n1 = new Promise&lt;int&gt;();
          Promise&lt;int&gt; n2 = new Promise&lt;int&gt;();

          new FibIsolate().spawn().then(
            (port) =&gt;
              port.call(n - 1).receive(
                (n, port) =&gt; n1.complete(n)
              )
          );

          new FibIsolate().spawn().then(
            (port) =&gt;
              port.call(n - 2).receive(
                (n, port) =&gt; n2.complete(n)
              )
          );

          n1.then(
            (x) =&gt; n2.then(
              (y) =&gt; x + y
            )
          ).flatten().then(
            (x) =&gt; replyTo.send(x)
          );
      }
    });
  }
}</pre>
<p></code></p>
<p>First of all we have to extend from <code>Isolate</code>. The <code>main()</code> function of an <code>Isolate</code> is its entry-point. Now something that really bugs me is the amount of indentation. Nearly every second <code>Isolate</code> which you are going to write has this form. Your actual logic starts at the fifth indentation level.</p>
<p>In the <code>main</code> method we immediately start listening for messages via the <code>Isolate</code>'s <code>ReceivePort</code>. Then we need to react on the message via a switch case. Now although it might look simple in this case it is very sad that Dart does not come with proper pattern matching since you will need to write a lot of switch-case in Dart code. If you have ever seen <a href="http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-4" title="Scala for Java refugees (Part 4)" target="_blank">pattern matching in action</a> using Scala you never want to go back to a dumb switch statement.</p>
<p>In the <code>default</code> case it gets a little bit more interesting. We need to spawn two new instances of <code>FibIsolate</code> since we want to do this recursive. We need to receive their result and when we have both results we want to perform the addition and send our value back to the caller.</p>
<p>Since there are no blocking calls we create a <code>Promise&lt;int&gt;</code> for each <code>FibIsolate</code>. When can complete the <code>Promise&lt;int&gt;</code> once we receive a value from an isolate. This allows us to combine both <code>Promise&lt;int&gt;</code> objects and wait on their results. Why do we not nest the <code>FibIsolate</code> you might ask. Because we want to spawn both at the same time so the computation can happen in parallel.</p>
<p>The actual nesting happens in the <code>n1.then((x) =&gt; n2.then((y) =&gt; x + y))</code> construct. However the return type of <code>n1.then((x) =&gt; n2.then((y) =&gt; ...)</code> is no longer <code>Promise&lt;int&gt;</code> but <code>Promise&lt;Promise&lt;int&gt;&gt;</code>. Fortunately someone thought about this case and there is a <code>flatten()</code> method which turns the <code>Promise&lt;Promise&lt;int&gt;&gt;</code> into a <code>Promise&lt;int&gt;</code> we just have to await and the finally reply with the computed value.</p>
<p>However remember the definition of <code>fib(x)</code>? The case for 1, 2 and 0 is quite simple because we can reply with the value immediately. And we do this by calling <code>send</code> on the <code>SendPort</code> which I named <code>replyTo</code>.</p>
<p>You can take a look at the full example running in the browser <a href="http://try.dartlang.org/s/YwsV" target="_blank">here</a>.</p>
<p>What I like about Dart is that someone thought about workers and made them first-class citizens. Pattern-matching is on the road map and they will hopefully copy Scala. There are however a lot of things that I dislike.</p>
<ol>
<li>Semicolons are required but optional for shorthand <code>(x) =&gt; x</code></li>
<li>The <code>return</code> keyword is required but optional when used with <code>(x) =&gt; x</code></li>
<li>No control about concurrency. Are my isolates CPU or I/O bound?!</li>
<li>No syntactic sugar for writing an Isolate</li>
<li>Not DSL friendly like Scala or maybe even Kotlin</li>
<li><code>int</code> disguises itself as a primitive but is an object instead</li>
<li>Missed the opportunity to embed continuation passing style into the language from the start</li>
<li>Function is the only function-type</li>
</ol>
<p>The type-system can be argued as well. I did not find anything about type erasure yet. Personally Dart feels much more like Java and Go than JavaScript. But in the end I would be quite happy if Dart could replace JavaScript since it is a step in the right direction from my personal point of view.</p>
<p>[1] <a href="http://www.dartlang.org/docs/api/Isolate.html#Isolate::Isolate" target="_blank">http://www.dartlang.org/docs/api/Isolate.html#Isolate::Isolate</a><br />
[2] <a href="http://www.dartlang.org/docs/api/SendPort.html#SendPort::SendPort" target="_blank">http://www.dartlang.org/docs/api/SendPort.html#SendPort::SendPort</a><br />
[3] <a href="http://www.dartlang.org/docs/api/ReceivePort.html#ReceivePort::ReceivePort" target="_blank">http://www.dartlang.org/docs/api/ReceivePort.html#ReceivePort::ReceivePort</a><br />
[4] <a href="http://www.dartlang.org/docs/api/Promise.html#Promise::Promise" target="_blank">http://www.dartlang.org/docs/api/Promise.html#Promise::Promise</a></p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2011/10/11/first-look-at-dart/" size="standard" count="true"></div></div>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2011/10/11/first-look-at-dart/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://blog.joa-ebert.com/2011/10/11/first-look-at-dart/</feedburner:origLink></item>
		<item>
		<title>Real-world functional Scala</title>
		<link>http://feedproxy.google.com/~r/je2050/~3/mdHb1iOq4oI/</link>
		<comments>http://blog.joa-ebert.com/2011/07/11/real-world-functional-scala/#comments</comments>
		<pubDate>Mon, 11 Jul 2011 15:33:36 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[misc]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[functional]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=797</guid>
		<description><![CDATA[If Java is a get shit done™​ language then Scala is a get shit done fast™​ language. The reason is that the signal to noise ratio is very high and that concise code is easier to reason about which makes it less error prone. When understanding Scala it is sometimes important to have a look [...]]]></description>
				<content:encoded><![CDATA[<p>If Java is a <em>get shit done</em>™​ language then Scala is a <em>get shit done fast</em>™​ language. The reason is that the signal to noise ratio is very high and that concise code is easier to reason about which makes it less error prone.</p>
<p>When understanding Scala it is sometimes important to have a look at some real-world examples &#8212; especially when it comes to functional programming. When I first started using Scala I had a hard time understanding some of the constructs used by other people. In this blog post I want do explain some of them. The first example is a classic one. You want to debug some structure and output all elements which have a condition set.</p>
<h3>Printing Elements of a Collection</h3>
<p>You will find this in every first-steps guide for Scala. What I like about it is the fact that you have only little amount of code to write if you want to inspect a certain structure.</p>
<pre class="brush: scala; title: ; notranslate">list filter { _.condition } foreach println</pre>
<h3>Flattening a Collection</h3>
<p>Convert a collection of collections to a flat collection. For instance you have a <code>List&lt;List&lt;String&gt;&gt;</code> in Java and want to get a <code>List&lt;String&gt;</code> instead.</p>
<pre class="brush: java; title: ; notranslate">
final List&lt;String&gt; newList = new LinkedList&lt;String&gt;();
for(final List&lt;String&gt; innerList : oldList) {
  newList.addAll(innerList);
}
</pre>
<p>A lot of code for a common operation. Probably the reason why the Google Guava library supports <code>Iterables.concat(oldList)</code> to get the same result. So how is this done in Scala?</p>
<pre class="brush: scala; title: ; notranslate">val newList = oldList.flatten</pre>
<p>A simple operation which is very powerful. Let me give you another example. Suppose you have a <code>List[Option[T]]</code> for some <code>T</code>. Before understanding Scala very well and before reading this <a href="http://www.codecommit.com/blog/ruby/monads-are-not-metaphors" target="_blank" title="Monads are not metaphors.">excellent article</a> about monads I once wrote shameful code like this.</p>
<pre class="brush: scala; title: ; notranslate">
val listOfOptions: List[Option[Int]] = 
  List(Some(1), None, Some(3), None, Some(5))

// don't do this!
val listOfDefinedValues: List[Int] = 
  listOfOptions filter { _.isDefined } map { _.get }

println(listOfDefinedValues) //List(1, 3, 5)
</pre>
<p>When encountering such a construct an alarm should raise in your head, telling you there must be a better way to do this. <code>flatten</code> to the rescue. <code>println(listOfOptions.flatten)</code> would do the job.</p>
<pre class="brush: scala; title: ; notranslate">
val listOfOptions: List[Option[Int]] =
  List(Some(1), None, None, Some(2))

println(listOfOptions.flatten) //List(1, 2)
</pre>
<h3>Using <code>flatMap</code> for good</h3>
<p>Although <code>flatMap</code> might sound esoteric at first it is a very helpful operation. So first of all you know there is the <code>map</code> operation which is extremely useful in a sense like this.</p>
<pre class="brush: scala; title: ; notranslate">&quot;hello world&quot; map { _.toUpper }</pre>
<p>So what is the deal with <code>flatMap</code>? It would not work in this case and the compiler would raise a type error. That is because a collection is expected as the result.</p>
<p><code>flatMap</code> makes a lot of sense when you have a collection and need to pass every element into a function that would then again return a collection.</p>
<pre class="brush: scala; title: ; notranslate">
val list = List(1,2,3,4)

def intToListOfChars(i: Int) = 
  i.toString.toList

val listOfListOfChar: List[List[Char]] =
  list map intToListOfChars
</pre>
<p>As you can see calling <code>map</code> with <code>intToListOfChars</code> creates a list of lists and we could later <code>flatten</code> that list agin. Or we simply use <code>flatMap</code> which does all of this in one step.</p>
<pre class="brush: scala; title: ; notranslate">val listOfChars = list flatMap intToListOfChars</pre>
<p>Still this example is pretty awkward. But imagine you have a method like <code>trimToOption(value: String): Option[String]</code> which trims a string and returns <code>None</code> if the string is empty or null (for whatever reason).</p>
<p>If you write a webapplication which expects user input you are probably working with a lot of <code>Option[T]</code> values (or Box[T] in case of Lift). For example like this:</p>
<pre class="brush: scala; title: ; notranslate">val description: Option[String] = 
  extractDescription(request)</pre>
<p>Now you also want to trim that description. Here are a couple of ways on how to do it using <code>trimToOption</code>.</p>
<pre class="brush: scala; title: ; notranslate">
// not so nice
val trimmed1 = trimToOption(description getOrElse &quot;&quot;)

// ugly as hell
val trimmed2 = description match {
  case Some(desc) =&gt; trimToOption(desc)
  case None =&gt; None
}

// kind of ugly
val trimmed3 = (description map trimToOption).flatten

// yey! :)
val trimmed4 = description flatMap trimToOption 
</pre>
<p>So you see that <code>flatMap</code> is actually a pretty usable function.</p>
<h3>Passing a Tuple to a Function</h3>
<p>Sometimes you have to pass a tuple to a function and instead of the tuple you would like to pass each value of the tuple as a parameter.</p>
<pre class="brush: scala; title: ; notranslate">
val listOfStrings =
  List(&quot;Hello&quot;, &quot;World&quot;)

val withIndex = listOfStrings.zipWithIndex

println(withIndex) //List((Hello,0), (World,1)))
</pre>
<p>So now imagine you have a method like this:</p>
<pre class="brush: scala; title: ; notranslate">
def printStringWithIndex(value: String, index: Int) =
  println(index+&quot;: &quot;+value)
</pre>
<p>In this case <code>withIndex foreach printStringWithIndex</code> would not work because we pass a tuple to that method. Scala has a nice built-in method called <code>tupled</code> which takes a function and converts it to one accepting a tuple.</p>
<pre class="brush: scala; title: ; notranslate">withIndex foreach (printStringWithIndex _).tupled</pre>
<h3>Using the Compiler</h3>
<p>Imagine you have a class with a type parameter like <code>CustomList[T]</code> and now you want to have a method which is implemented only for some kind of <code>T</code>. Obviously one way would be to use traits and mix them in on demand. But it gets more and more complex.</p>
<p>Fortunately we can let the compiler proof the evidence of a type at a position in our code.</p>
<pre class="brush: scala; title: ; notranslate">
class Foo[T](bar: T) {
  // only allow this method if T is a String
  def length()(implicit proof: T =:= String) = 
    bar.length
}

val foo1 = new Foo(123) //works just fine
foo1.length //does not compile.

val foo2 = new Foo(&quot;hello&quot;)
foo2.length //5
</pre>
<p>This is great because it allows us to introduce phantom types and to write less code for certain structures. For instance we have a <code>Connector[A]</code> in <a href="http://www.audiotool.com" target="_blank"/>Audiotool</a>. This connector accepts connections to other connectors. It is either an input or an output and it transmits an abstract signal. You can only connect an output with an input. A Connector accepts only connections of its own type and <i>virtual</i> connections. This means the following example would be uber-cool code. Unfortunately we did not write Audiotool in Scala ;)</p>
<pre class="brush: scala; title: ; notranslate">
class Connector[A] {
  add[B](conn: Conn[A, B])(implicit proof: A =:= B)
    { ... }

  add(connection: VirtualConn[_, _])
    { ... }
}
</pre>
<p>Note: This is in fact not a real example since it would not work. You could only connect an output with another output but I think you might get the idea and it is easier to follow.</p>
<h3>Conclusion</h3>
<p>Functional programming might seem weird. Constructs like <code>=:=</code> or <code>flatMap</code> are awkward at first but make complete sense. Using Scala and picking some of the functional idioms which you think are right and well understood in your team can increase productivity and lead to less bugs.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2011/07/11/real-world-functional-scala/" size="standard" count="true"></div></div>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2011/07/11/real-world-functional-scala/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://blog.joa-ebert.com/2011/07/11/real-world-functional-scala/</feedburner:origLink></item>
		<item>
		<title>Go channels with Scala</title>
		<link>http://feedproxy.google.com/~r/je2050/~3/KtmJ5GYRKzs/</link>
		<comments>http://blog.joa-ebert.com/2011/06/01/go-channels-with-scala/#comments</comments>
		<pubDate>Wed, 01 Jun 2011 11:21:10 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[c++ and others]]></category>
		<category><![CDATA[channel]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[go]]></category>
		<category><![CDATA[multithreading]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=786</guid>
		<description><![CDATA[Since I had to spend 10h in a train this weekend I was looking at some food for thought. For a long time I had a couple of slides about the Go language on my machine and so I started reading. Go comes with a different concepts for synchronization. Channels are a construct baked into [...]]]></description>
				<content:encoded><![CDATA[<p>Since I had to spend 10h in a train this weekend I was looking at some food for thought. For a long time I had a couple of slides about the <a href="http://golang.org/" target="_blank" rel="nofollow">Go language</a> on my machine and so I started reading.</p>
<p>Go comes with a different concepts for synchronization. Channels are a construct baked into the language. They allow you to communicate between different go-routines etc. Basically I stopped reading after I came across the Channels section.</p>
<p>A channel allows you to send and receive data from it. Much like a Scala actor. By default a channel is performing blocking send and receive operations. Sounds pretty much like a blocking queue to me. The syntax is something like the following.</p>
<pre class="brush: plain; title: ; notranslate">
// Create a channel of int
var channel = make(chan int) 

func send() {
  // Send 1 to the channel.
  // This operation blocks ...
  channel &lt;- 1
}

func receive() {
  // Receive from channel
  // This operation also blocks!
  message := &lt;- channel 
  fmt.Println(message) //1
}

go send()
go receive()
</pre>
<p>So ultimately I thought it should be quite easy to achieve something similar using Scala. I think this is an excellent example of the <em>scalable</em> part when it comes to Scala.<br />
Go channels are diveded into reciver and sender channels, with a bidirectional channel type. The same can be achieved using Scala traits very easily. I could also add a couple of nice syntactic sugar like adding a foreach method to a channel which allows you to use it with Scala for comprehensions.</p>
<p>Have a look at this <a href="https://gist.github.com/1002125" target="_blank" rel="nofollow">Gist</a> for the complete source code. First of all one part is a little bit unfortunate. You are not able to define <code>&lt;-</code> or <code>&lt;~</code> as a unary operator in Scala. So I thought I stick with the <code>!</code> operator which you already know from actors and it is the analog to Go&#8217;s <code>&lt;-</code>.</p>
<p>At the end of the file you will find a re-implementation of the Go <a href="https://sites.google.com/site/gopatterns/concurrency/producer-consumer" target="_blank">Producer-Consumer example</a>.</p>
<p>Something really cool is the fact that you can use Scala&#8217;s for-comprehensions which automatically exit once a channel is being closed. I think Go allows you do the same by specifying <code>range</code> when iterating over a channel. However I am not sure since I only had a brief look.</p>
<p>So is this useful? I do not know since I would probably stick with Scala actors for most of my multi-threading needs but it is still a great example of Scala&#8217;s flexibility as a language.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2011/06/01/go-channels-with-scala/" size="standard" count="true"></div></div>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2011/06/01/go-channels-with-scala/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://blog.joa-ebert.com/2011/06/01/go-channels-with-scala/</feedburner:origLink></item>
		<item>
		<title>Endless scrolling with Lift</title>
		<link>http://feedproxy.google.com/~r/je2050/~3/e0aT6VOTWCQ/</link>
		<comments>http://blog.joa-ebert.com/2011/03/07/endless-scrolling-with-lift/#comments</comments>
		<pubDate>Mon, 07 Mar 2011 12:12:31 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[misc]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=770</guid>
		<description><![CDATA[For the upcoming Audiotool 2.0 launch in collaboration with Burn I am developing our new website. The framework choice was quite obvious for me since I love Scala and really like Lift. Lift is very nice because of its excellent Ajax and Comet support. My main problem getting started with Lift was the lack of [...]]]></description>
				<content:encoded><![CDATA[<p>For the upcoming Audiotool 2.0 launch in collaboration with <a href="http://www.burn.com" target="_blank">Burn</a> I am developing our new website. The framework choice was quite obvious for me since <a href="http://blog.joa-ebert.com/2010/12/26/a-year-of-scala/">I love Scala</a> and really like <a href="http://www.liftweb.net/" target="_blank">Lift</a>. </p>
<p>Lift  is very nice because of its excellent Ajax and Comet support. My main problem getting started with Lift was the lack of documentation and real world examples. E.g. if you want a custom 404 page without a redirect your only source of information is a thread in the mailing list. Lift also comes with its own terminology and a lot of custom DSLs.</p>
<p>Cricitcs aside: I am absolutely happy that Lift exists. You simply have to start using it. The documentation has also improved a lot. <a href="http://simply.liftweb.net/" target="_blank">Simply Lift</a> and <a href="http://exploring.liftweb.net/" target="_blank">Exploring Lift</a> are available for free and the <a href="http://www.assembla.com/wiki/show/liftweb" target="_blank">Wiki</a> contains a lot of useful information too.</p>
<p>I want to give you a simple example of why I think that Lift is simply awesome and what sold me to the framework.  You probably know those endless scrolling pages.</p>
<p>Let&#8217;s see how to develop something similar with Lift and Scala. First of all we have to prepare a little template.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;div class=&quot;lift:surround?with=default;at=content&quot;&gt;
  &lt;div class=&quot;lift:endless&quot;&gt;
    &lt;ul&gt;
      &lt;li&gt;item0&lt;/li&gt;
      &lt;li&gt;item1&lt;/li&gt;
      &lt;li&gt;item2&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/div&gt;
&lt;/div&gt;
</pre>
<p>That is all the HTML we need. In fact we need even less but if you are going for <a href="http://www.assembla.com/wiki/show/liftweb/Designer_Friendly_Templates" target="_blank">designer friendly templates</a> you could extend it with your usual page chrome.</p>
<p>There are two calls to Scala code in this template. <em>lift:surround</em> will trigger the <code>SurroundSnippet</code> and insert the current template into the <em>default</em> template at the <em>content</em> position.</p>
<p>Our duty is now the implementation of <em>lift:endless</em>. Lift comes with a dynamic convention-over-configuration lookup for the so-called snippets. I am not a fan of COC so I will stick to the manual mechanism of binding <em>endless</em> to a snippet. Lift offers the DispatchSnippet in this case.</p>
<p>You will have to add this line to <code>Boot.scala</code>:</p>
<pre class="brush: scala; title: ; notranslate">LiftRules.snippetDispatch append Map(&quot;endless&quot; -&gt; EndlessSnippet)</pre>
<p>It tells Lift to invoke the <code>dispatch</code> method of the EndlessSnippet object whenever a snippet named <em>endless</em> is encountered.</p>
<p>So the only missing piece is the implementationof the EndlessSnippet and this is where Lift really shines.</p>
<pre class="brush: scala; title: ; notranslate">
import net.liftweb.common._
import net.liftweb.util._
import net.liftweb.http._
import net.liftweb.util.Helpers._
import net.liftweb.http.js.jquery.JqJsCmds
import net.liftweb.http.js.JsCmds
import net.liftweb.http.js.JE
import scala.xml.{NodeSeq, Unparsed}

object EndlessSnippet extends DispatchSnippet with Loggable {
  def dispatch = {
    // If you want to execute render only when &quot;embed.xyz&quot; is called
    // you would match on &quot;xyz&quot; here.
    case _ =&gt; render 
  }

  def render =  {
    // Generate a random identifier
    val containerId = nextFuncName

    // The page which we are currently looking at.
    var page = 0

    // Method to be called by JavaScript.
    def process(in: Any) = in match {
      case id: String if id == containerId =&gt;
        page += 1
        logger.debug(&quot;Generating page &quot;+page+&quot;.&quot;)

        // Generate new markup and append it to the list.
        JqJsCmds.AppendHtml(id, getItems(page))
      case _ =&gt;
        logger.error(&quot;Illegal data has been sent.&quot;)
        JsCmds.Noop
    }

    // Here we marry the template with our code.
    // &quot;*&quot; is a CSS selector that matches anything and #&gt; binds it to the content
    // we specify.
    // The most interesting part here is the JavaScript  which we bind to the process
    // closure. Lift does all the magic for us and calls the server-side method once the
    // user scrolls to the bottom of the page.
    &quot;*&quot; #&gt; (&lt;ul id={containerId}&gt;{getItems(page)}&lt;/ul&gt; ++ JsCmds.Script(JE.JsRaw(
&quot;&quot;&quot;$(window).scroll(function(){
  if($(window).scrollTop() == $(document).height() - $(window).height()) {&quot;&quot;&quot;+
    SHtml.jsonCall(containerId, process)._2.toJsCmd+&quot;&quot;&quot;
  }
})&quot;&quot;&quot;).cmd))
  }

  def getItems(offset: Int): NodeSeq = {
    val count = 100
    val start = offset * count
    val end = from + count

    // We generate a couple of &lt;li&gt; elements here.
    for(i &lt;- start until end) yield {
      &lt;li&gt;{&quot;item&quot;+i}&lt;/li&gt;
    }
  }
}
</pre>
<p>This little amount of code really shows the power of Lift. Simply write a closure and bind it to your JavaScript. Lift does all the plumbing for you. Then you only have to implement some logic on the server. In most cases you do not even have to write any JavaScript since Lift offers Ajax links, forms etc. already. <code>SHtml.a(...)</code> generates a link which will trigger a function on the server for instance.</p>
<p>But please beware: I am not sure if <code>SHtml.jsonCall</code> is actually the way how you should do this. There might be a better way of calling a server-side method via JavaScript.</p>
<p>There is of course more to Lift. Comet is where things get really cool and the record framework seems interesting as well. Hopefully this little excursion into Scala and Lift could quicken your appetite. Since I am usually not a frontend fan this made it interesting and fun again.</p>
<p>I will try to post a complete project in the next days as well. Before starting with the Audiotool website I wrote some test cases that might help other people getting started.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2011/03/07/endless-scrolling-with-lift/" size="standard" count="true"></div></div>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2011/03/07/endless-scrolling-with-lift/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://blog.joa-ebert.com/2011/03/07/endless-scrolling-with-lift/</feedburner:origLink></item>
		<item>
		<title>Software Transactional Memory and Audiotool</title>
		<link>http://feedproxy.google.com/~r/je2050/~3/QhapYZg2Zq0/</link>
		<comments>http://blog.joa-ebert.com/2011/02/25/stm-and-audiotool/#comments</comments>
		<pubDate>Thu, 24 Feb 2011 22:18:17 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[knowledge]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[audiotool]]></category>
		<category><![CDATA[stm]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=755</guid>
		<description><![CDATA[I have tweeted a while ago about the fact that Audiotool does heavily rely on a so called software transactional memory. In this blog post I want to discuss the implementation of our STM and why it is useful. Wikipedia defines STM as: In computer science, software transactional memory (STM) is a concurrency control mechanism [...]]]></description>
				<content:encoded><![CDATA[<p>I have tweeted a while ago about the fact that <a href="http://www.audiotool.com/" target="_blank" title="Audiotool">Audiotool</a> does heavily rely on a so called <a href="http://en.wikipedia.org/wiki/Software_transactional_memory" title="STM">software transactional memory</a>. In this blog post I want to discuss the implementation of our STM and why it is useful.</p>
<p>Wikipedia defines STM as:</p>
<blockquote><p>In computer science, software transactional memory (STM) is a concurrency control mechanism analogous to database transactions for controlling access to shared memory in concurrent computing.</p></blockquote>
<p>First of all when reading this you might think that an STM is not necessary since ActionScript does not support true concurrency and also the <a href="http://bugs.adobe.com/jira/browse/ASL-23" target="_blank">shared-nothing worker proposal</a> will not allow you concurrent memory access. While this holds true you may not forget that concurrency becomes an issue when you have just access to a single core but on multiple machines.</p>
<p>A lesser known fact about Audiotool is also that we have a built-in system for real time collaboration since its beginning. Due to conceptional issues and other prioritized features we were never able to roll it out as a full feature but the technology base is there.</p>
<p>When it comes to multiplayer gaming and network latency you will always have to figure out a system which allows you to share a certain state across multiple machines. In some games the state is synchronized across a certain server. An example is an FPS like Quake3. The Audiotool is unlike Quake3 not a FPS and different conditions have to be met. And this is the reason why I have choosen to implement an STM with very optimistic concurrency control.</p>
<p>The basic idea of my system is to use atomic transactions with commit and revert operations. Those are handled by a transaction manager which performs the basic tasks of an STM. That means: execute all transactions until an error occurs, roll back and try again. Each transaction in the Audiotool contains a guard. The guard defines whether or not one should still execute the transaction.</p>
<p><img src="/wp-content/images/stm_flow.gif" width="193" height="344" border="0" style="float: left; margin-right: 8px;"/>Here is an example of why a guard is important and how all this stuff works. You have two Audiotool instances running that share the same state. We call them <em>A</em> and <em>B</em>. <em>A</em> and <em>B</em> are connected via P2P no an arbitrary network. This means exchanging messages introduces latency and we cannot guarantee that <em>A</em> is at the same state of <em>B</em>.</p>
<p>So what happens? t<sub>0</sub> is committed by <em>A</em>, serialized and sent to <em>B</em> who is committing the same transaction. The same applies to t<sub>1</sub>. t<sub>2</sub> is initiated by <em>B</em>, serialized and sent to <em>A</em>. Everything works fine until <em>B</em> commits t<sub>4</sub>. While t<sub>4</sub> is being transferred to <em>A</em>, <em>A</em> created t<sub>5</sub> and committed it. This means <em>A</em> never saw t<sub>4</sub> when it committed t<sub>5</sub> and <em>B</em> would continue with t<sub>6</sub> ignoring t<sub>5</sub>. <em>A</em> will actually receive t<sub>4</sub> after he commited t<sub>5</sub> so the system will revert t<sub>5</sub>, commit t<sub>4</sub>, commit t<sub>5</sub> if the guard does not prevent it, and both continue at t<sub>6</sub>.</p>
<p>To explain the guard: Imagine the t<sub>5</sub> transaction includes modifications on a device in the Audiotool that is deleted by t<sub>4</sub>. In that case t<sub>5</sub> will never be executed.</p>
<p>So what does this imply? You can guess that each modification of the Audiotool state is in fact handled by a transaction and we carefully have to pick the guards. E.g. if an editor is referenced by a transaction it is part of the guard. However this introduces a second issue: references. Sharing references of objects across a network is a tricky task. I am using &#8220;boxes&#8221; to solve this issue. A box can hold a value and it is guaranteed that it will hold the same value at the same state across the network. A box can be serialized and will be shared between commit and revert states. This means if t<sub>n</sub> creates an object which is referenced by t<sub>n+1</sub> both will use the same box. This also means that I can safely revert t<sub>n+1</sub> and then t<sub>n</sub> and commit them without having to worry that both still reference the same object. And this even works across the network. And in fact we can now also identify whether or not one transaction would conflict with a different one which is a very important condition for the actual implementation.</p>
<p>Right now you might have figured out that a transaction in the Audiotool has the following properties:</p>
<ul>
<li>It is serializable so it can be transferred across the network.</li>
<li>All object references must be stored via &#8220;boxes&#8221;.</li>
<li>A guard is used to determine whether or not to commit a transaction.</li>
<li>Transactions can be committed and reverted.</li>
</ul>
<p>A lot of stuff one has to reason about. But although we do not support live collaboration at the moment we are using the STM. Why? The reason is quite simple. The STM gives us history for free. Since everything is serializable via a very lightweight protocol we can take the last 500 transactions for instance and store them as a compressed ByteArray in memory instead of each as a single object with all its references.</p>
<p>Another very nice option is testing. A serializable history means that one simply has to press a super secret shortcut to dump the whole history and send it to the responsible developer who can reason about every single step that happened which ultimately led to the error. In development mode I usually commit, revert and commit each transaction. Then I also serialize and deserialize them and do the whole thing again.</p>
<p>Since transactions are known by the system we can also write a fuzzer that executes lots of crazy stuff. Sort of Android&#8217;s monkey mode. And ultimately I personally hope that we will get to the point where we will enable live collaboration in the Audiotool of course.</p>
<p>The last feature I implemented is the automatic transformation of arbitrary transactions to a compound transaction. You can guess what this feature actually means for the user :). In fact it is very complex and I implemented it with the STM using only a couple lines of code (of course that is just half the story &#8230;).</p>
<p>If you are interested in writing your own multi user application I think this is a very nice approach since collisions do not happen very often from my experience and the optimistic concurrency in a P2P environment achieves great results in terms of overall latency and feeling. The <a href="http://www.waveprotocol.org/" target="_blank">Google Wave protocol</a> and their <a href="http://www.waveprotocol.org/whitepapers/operational-transform" target="_blank">operational transform</a> is also an interesting read.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2011/02/25/stm-and-audiotool/" size="standard" count="true"></div></div>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2011/02/25/stm-and-audiotool/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<feedburner:origLink>http://blog.joa-ebert.com/2011/02/25/stm-and-audiotool/</feedburner:origLink></item>
		<item>
		<title>Understanding Scala Implicits</title>
		<link>http://feedproxy.google.com/~r/je2050/~3/QVPZ-pmjxxk/</link>
		<comments>http://blog.joa-ebert.com/2010/12/26/understanding-scala-implicits/#comments</comments>
		<pubDate>Sun, 26 Dec 2010 21:30:54 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[misc]]></category>
		<category><![CDATA[conversion]]></category>
		<category><![CDATA[implicit]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=741</guid>
		<description><![CDATA[Many languages make use of implicit conversions. Scala is the only language I know of which makes implicit definitions a feature. It is very easy to understand an implicit conversion since most programming languages do this already for you. Here are two examples (AS3/Java): trace("Implicitly converted: "+1) System.out.println("Implicitly converted: "+1); We only have to care [...]]]></description>
				<content:encoded><![CDATA[<p>Many languages make use of implicit conversions. Scala is the only language I know of which makes implicit definitions a feature.</p>
<p>It is very easy to understand an implicit conversion since most programming languages do this already for you. Here are two examples (AS3/Java):</p>
<p><code>trace("Implicitly  converted: "+1)</code><br />
<code>System.out.println("Implicitly converted: "+1);</code></p>
<p><span id="more-741"></span></p>
<p>We only have to care about the expression <code>"Implicitly  converted: "+1</code> which will result in &#8220;Implicitly  converted: 1&#8243;. Why does this happen? We have a string on the left hand side of the expression and an integer on the right hand side. When the compiler of your choice needs to emit code for this kind of expression it will widen the type of both operands. In this case the resulting type would be String since an implicit conversion from integer to String exists in both ActionScript and Java. If no such conversion exists you would probably get a compile time error.</p>
<p>The compiler inserts this conversion for you. In this example we can make use of an explicit conversion:</p>
<p><code>trace("Explicitly converted: "+1.toString())</code><br />
<code>System.out.println("Explicitly converted: "+Integer.toString(1));</code></p>
<p>Here we specify that we really want to concatenate two strings which is of course a tedious task. We are lucky to have implicit conversions. Whenever you want to go from type A to B a compiler either inserts an implicit conversion for you or tells you that it cannot do it with an error message.</p>
<p>In certain scenarios you might want to use implicit conversions for your own types. In ActionScript I might want to go from Sprite directly to BitmapData.</p>
<p>Here is an example. Please do not do this at home. There is a of course a much better way (and less memory intensive) to do a hit test on a Sprite.</p>
<p><code>
<pre>
function hitTest(bitmapData: BitmapData, x: int, y: int): Boolean {
  return bitmapData.getPixel32(x, y) != 0x00000000
}

const sprite: Sprite = new Sprite()
hitTest(sprite, 1, 2)
</pre>
<p></code></p>
<p>Now this code would not compile of course since <code>hitTest(sprite, 1, 2)</code> is incorrect. The compiler would tell you that it expects a BitmapData as the first parameter. Let us fix the example:</p>
<p><code>
<pre>
function hitTest(bitmapData: BitmapData, x: int, y: int): Boolean {
  return bitmapData.getPixel32(x, y) != 0x00000000
}

function toBitmapData(displayObject: DisplayObject): BitmapData {
  const result: BitmapData = new BitmapData(
      displayObject.transform.pixelBounds.width,
      displayObject.transform.pixelBounds.height)

  const matrix: Matrix = displayObject.transform.matrix

  matrix.tx = matrix.ty = 0.0
  result.draw(sprite, matrix)

  return result
}

const sprite: Sprite = new Sprite()
hitTest(toBitmapData(sprite), 1, 2)
</pre>
<p></code></p>
<p>Now it works but every time we would want to go from Sprite to BitmapData we have to insert our new <code>toBitmapData</code> function.</p>
<p>And here is what makes Scala so special. You can tell the compiler that toBitmapData may be used as an implicit conversion.</p>
<p>Here is the same example in Scala without making use of implicit conversions:</p>
<p><code>
<pre>
def hitTest(bitmapData: BitmapData, x: Int, y: Int) =
  bitmapData.getPixel32(x, y) != 0x00000000L

def toBitmapData(displayObject: DisplayObject) = {
  val result = new BitmapData(
      displayObject.transform.pixelBounds.width,
      displayObject.transform.pixelBounds.height)
  val matrix = displayObject.transform.matrix

  matrix.tx = 0.0
  matrix.ty = 0.0

  result.draw(sprite, matrix)
  result
}

val sprite = new Sprite()
hitTest(toBitmapData(sprite), 1, 2)
</pre>
<p></code></p>
<p>Not so different. However we can annotate the <code>toBitmapData</code> definition as implicit and the code would look like this:</p>
<p><code>
<pre>
def hitTest(bitmapData: BitmapData, x: Int, y: Int) = ...

implicit def toBitmapData(displayObject: DisplayObject) =
  ...

val sprite = new Sprite()
hitTest(sprite, 1, 2)
</pre>
<p></code></p>
<p>So I think now it is time to take a deep breath. If you think that this is dangerous you should keep two more things in mind. First of all the compiler will only use implicit conversions that are in the current scope of your method. This means if you define an implcit conversion in class A and want to use it in B you have to import it. Also it could happen that you have two implicit conversions in the same scope. Since the compiler does not know which one it should pick it will give you an error message. This makes a lot of sense.</p>
<p>So in the end it is a great way to enable a specific implicit conversion for parts of your code. You are also able to use an import statement only in a method body like this:</p>
<p><code>
<pre>
def myComplexMethod(a: A) = {
  import ImplicitConversions.fromAtoB
  ...
}
</pre>
<p></code></p>
<p>But this is just the one part about implicit conversions. In my <a href="http://blog.joa-ebert.com/2010/12/26/a-year-of-scala/" target="_self" title="A Year Of Scala">A Year Of Scala</a> post I did mention that implicit conversions can be used to build domain specific languages.</p>
<p>Right now we get rid of our explicit casts which is nice but a true DSL needs obviously much more. For instance I might want to say <code>0xff00ff.toHexString</code> instead of <code>toHexString(0xff00ff)</code>. This can also be achieved with implicit conversions. And this is not what you might already know from Java or ActionScript.</p>
<p>Whenever we invoke a method on an object, and the object&#8217;s type does not support that method, but an implicit conversion to a different type containing the method exists, it is applied. So remember the Sprite and BitmapData example?</p>
<p>This would be illegal in ActionScript:<br />
<code>sprite.getPixel(x, y)</code></p>
<p>This would be legal:<br />
<code>toBitmapData(sprite).getPixel(x, y)</code></p>
<p>And with an implicit toBitmapData method in Scala we get:<br />
<code>sprite.getPixel(x, y)</code></p>
<p>In fact this is quite simple. So in case you did not notice: this is also statically typed <a href="http://en.wikipedia.org/wiki/Monkey_patch" target="_blank" title="Monkey Patch">monkey patching</a>. And because you can omit dots and parenthesis we get code like <code>G("vertex1" --&gt; "vertex2")</code>. Where is the implicit conversion? A string has no <code>--&gt;</code> method defined but we could define an implicit conversion to a class <code>VertexPair</code> that has the <code>--&gt;</code> method defined.</p>
<p>Last but not least there are also implicit parameters and values in Scala. In fact only an implicit value may be used as an implicit parameter.</p>
<p>If you are always carrying the same parameter around you, why not define it as implicit? An OpenGL context for instance. <code>render(float t, GL11 gl)</code> is some kind of code that might occur very often. Let us make the <code>gl</code> parameter implicit.</p>
<p><code>def render(t: Float)(implicit gl: GL11) = ...</code></p>
<p>Now if you do not have an implicit value available, you can still call this method via <code>render(1.0f)(gl)</code>. But if you declare a GL11 object once as implicit it can be passed down the chain very easy.</p>
<p><code><br />
implicit val gl = framework.getOpenGLContext()<br />
render(1.0f)<br />
render(1.5f)<br />
</code></p>
<p>Now if you call a method inside render that needs an implicit GL11 parameter as well you would not have to declare it as implicit again. But the same rules apply here. If there are two implicit GL11 typed objects available the compiler will complain.</p>
<p>I hope this makes working with implicit conversions and values a little  bit easier.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2010/12/26/understanding-scala-implicits/" size="standard" count="true"></div></div>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2010/12/26/understanding-scala-implicits/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<feedburner:origLink>http://blog.joa-ebert.com/2010/12/26/understanding-scala-implicits/</feedburner:origLink></item>
		<item>
		<title>A Year Of Scala</title>
		<link>http://feedproxy.google.com/~r/je2050/~3/-wfkllkr-wk/</link>
		<comments>http://blog.joa-ebert.com/2010/12/26/a-year-of-scala/#comments</comments>
		<pubDate>Sun, 26 Dec 2010 14:59:21 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[personal]]></category>
		<category><![CDATA[apparat]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jvm]]></category>
		<category><![CDATA[lisp]]></category>
		<category><![CDATA[ocaml]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=706</guid>
		<description><![CDATA[About a year ago I started using Scala. A programming language I felt in love with after all. The one and only programming language that started making me smile when I was happy to see how elegant I can express my ideas. I have been trying to spread the word about Scala during various Flash [...]]]></description>
				<content:encoded><![CDATA[<p>About a year ago I started using Scala. A programming language I felt in love with after all. The one and only programming language that started making me smile when I was happy to see how elegant I can express my ideas.</p>
<p>I have been trying to spread the word about Scala during various Flash conferences and always tried convincing my colleagues and friends to learn this great language. A <a href="http://nodename.com/blog/2010/12/22/haskell-liftoff/" target="_blank" title="Haskell Liftoff">blog post</a> by Alan Shaw about his experience with Haskell inspired me to write about my journey.</p>
<p><span id="more-706"></span></p>
<h3>Why Scala</h3>
<p>I was very unhappy with ActionScript and Java last year. ActionScript is a good start but needs to adapt the features of the dropped <a  href="http://www.ecmascript.org/es4/spec/overview.pdf" target="_blank" title="ECMAScript 4 Proposal">ECMAScript 4 proposal</a> to become interesting and competitive in my humble opinion. Java on the other hand is only interesting to me because of  its virtual machine. The language itself is simple and has the features you need to get the job done.</p>
<p>I got very late into the Java game and missed the bumpy early years. However I was never earning money with Java since I was doing only open source.</p>
<p>Open source is a hobby. I like doing it. So why not use a language that is fun too? I finished the first version of Apparat in 2009 using Java. But the language became more and more  annoying because of all the boilerplate code you have to write and the massive violation of the <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself" target="_blank" title="Don't repeat yourself">DRY</a> mantra. A particular example are Java&#8217;s generics. I was dealing very often with graphs in Apparat. I had a parameterized graph class <code>Graph&lt;V, E&gt;</code> and of course sometimes the vertices and edges are parameterized too. I was tired of writing code like this over and over again.</p>
<p style="text-align: left"><code>final Graph&lt;BasicBlockVertex&lt;AbstractOp&gt;, Edge&lt;BasicBlockVertex&lt;AbstractOp&gt;&gt;&gt; graph = new BasicBlockGraph&lt;BasicBlockVertex&lt;AbstractOp&gt;, Edge&lt;BasicBlockVertex&lt;AbstractOp&gt;&gt;&gt;();</code></p>
<p>So I was searching for a new language that allows me to focus on ideas. I could now talk about languages like Lisp, Clojure, OCaml, Haskell and C#; but I will just explain why I did not use C# &#8212; a language that is superior to most other languages. If Scala would not exist, I would probably do more C# work.</p>
<p>I do not think that interoperability is an issue with C# since Mono is a great project that gives you Linux and OS X support. But I used C# already for Apparat&#8217;s predecessor AS3C. So why not learn something new? This is why I went for Scala . I thought I can learn more about programming if I start using it &#8212; and boy was I right: I am learning something new each day since then.</p>
<h3>Learning Scala</h3>
<p>Most people that see Scala for the first time are immediately irritated by the syntax they do not understand. Same happened for me. When I first saw Scala I just gave it five minutes and went on to something else. The second time I came back to Scala I spent more time on the examples and tried understanding them.</p>
<p>Here is the problem: learning Scala is hard. My main issue was not the syntax but the fact that most people simply slap you with a lot of academic topics right in the face. As an autodidact you have to read a lot before you will write your first line of code if you follow that path. If you studied computer science and took a Haskell or Lisp course you will probably know about <a href="http://en.wikipedia.org/wiki/Algebraic_data_type" target="_blank" title="Algebraic Data Type">algebraic data types</a> and <a href="http://en.wikipedia.org/wiki/Monad_(functional_programming)" title="Monad" target="_blank">monads</a> already.</p>
<p>Instead I started ignoring most of the cool features and tried understanding the syntax first by writing actual code. You will find a lot of high quality blog posts on Scala very easy. When it comes to understanding Scala from an ActionScript perspective it is a little bit easier since you know anonymous functions already. Let us demistify a little bit of the syntax.</p>
<p>Take this ActionScript example.</p>
<p><code>const square: Function = function(x: int): int { return x * x }</code></p>
<p>You can remove nearly all type annotations because of Scala&#8217;s type inference. You still have to annotate method arguments. The compiler would complain if you leave those types out. This is a trade-off for readable error messages and compiler speed.</p>
<p><code>const square = function(x: int) { return x * x }</code></p>
<p>Next you can get rid of the <code>return</code> keyword in Scala. Because it is a functional language every usual statement is an expression. <code>val x = if(true) 1 else 2</code> has a value for instance and is equivalent to <code>var x: int = true ? 1 : 2</code>. What does <code>val</code> mean? It is the <code>const</code> keyword in Scala. I prefer it this way. You have <strong>var</strong>iables and <strong>val</strong>ues.</p>
<p><code>val square = function(x: int) { x * x }</code></p>
<p>This looks already much better in my opinion. And here comes the catch. Scala is a functional language. It is also an object oriented language but more on that later.  But it borrows a lot of the nice features from other languages like OCaml or Haskell.</p>
<p>Because you are working with functions so often there are multiple short-hand notations available. But the key is to drop the <code>function</code> keyword and replace it with the shorter <code>=&gt;</code>. Last but not least we do not even need the curly braces in Scala and our example finally becomes</p>
<p><code>val square = (x: Int) => x * x</code></p>
<p>You will figure out that <code>=&gt;</code> is used more often. This is another catch. Two particular things are confusing for the beginner. <code>=&gt;</code> and <code>_</code>. <code>=&gt;</code> is used in multiple places like definition of anonymous functions, types, scope definitions and self type annotations. I will probably not talk about the other two in this post.</p>
<p>It is worth noting that <code>Int =&gt; Int</code> is the type of a function that takes one parameter typed Int and returns a result typed Int.</p>
<p>So Imagine you have this definition:</p>
<p><code>val applyIntFunction = (x: Int, f: Int => Int) => f(x)</code></p>
<p>This anonymous function takes two parameters. One is typed Int and another one is a function. So we could write <code>applyIntFunction(2, square)</code>. But what if we want to increase x just by one? One option would be <code>applyIntFunction(2, x => x + 1)</code>. You can see here that Scala knows the type of my anonymous function already and I am allowed to omit it. This is not too bad. But since it is so common in functional programming to work with functions, an even shorter syntax exists. Meet the underscore.</p>
<p><code>applyIntFunction(2, _ + 1)</code></p>
<p>This is where it gets confusing at first. However you will love this feature and it is not so hard to understand. The Scala compiler expects the type <code>Int => Int</code> as the second parameter. <code>_ + 1</code> is in fact an anonymous method that takes one parameter. But we do not know anything about the type if we look at the method alone. It is always important to think about the context. <code>_ * _</code> is a method that takes two parameters for instance. This would not work in our example. What does <code>_ * _</code> do? Probably multiply two things. But again it is a question of the context and the required types.</p>
<p><code><br />
val applyTwoIntFunction = (x: Int, y: Int, f: (Int, Int) => Int) => f(x, y)<br />
applyTwoIntFunction(2, 2, _ * _)<br />
</code></p>
<p>One of my main problems with Scala was the usage of the <code>_</code> character and how it works. Fortunately a <a href="http://www.biais.org/blog/index.php/2009/09/20/75-understanding-the-_-underscore-in-scala" target="_blank" title="Understanding the underscore in Scala">great post</a> I want to highlight again already exists. It explains very well which purpose the underscore fulfills in which context.</p>
<p>So even if you think that Scala is hard to understand at first keep in mind that it is just a different dialect of expressing your ideas. If you have less to write you can do that not only faster but more concise. Once you start <i>thinking in Scala</i> it becomes of course absolutely clear that <code>_ * _</code> means multiply those two things whatever they are.</p>
<h3>A Language For Hackers</h3>
<p>Scala is a great language for hackers. Four features make it very easy to write any library that feels like real code. Namely anonymous functions, the ability to omit braces and dots, type parameters and implicit conversions. Okay, what does it mean? I already talked about anonymous functions but omitting braces and dots? In Scala the code <code>1.plus(2)</code> is identical to <code>1 plus 2</code>. Whenever you have a method with exactly one parameter and an object on the left hand side you are allowed to omit both braces and the dot. First of all this is quite cool but also I did the mistake to make extensive use of this feature. In the beginning of Apparat I was omitting nearly all dots just because I can. It does not make your code more readable and I inserted dots and braces back into the code.</p>
<p>So when does it help? When it makes sense. This sounds weird but lets think about another example. Lists are a key element of Scala and any other functional language. <code>"Hello World".toList</code> returns a list of characters. If we want to have all of them as lower case we would map that list. Even ActionScript has a predefined method for this task, called <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#map()" target="_blank" title="Array.map">Array.map</a>. Noone uses it. The explanation is that it is simply to complicated. Imagine we have a List[Char] in Scala or an Array in ActionScript and we want to convert it to an Array where all characters are lower case.</p>
<p>This is the ActionScript version:</p>
<p><code>array.map(function(x: String): String { return x.toLowerCase() })</code>. </p>
<p>This is the Scala version:</p>
<p><code>list.map(x =&gt; x.toLowerCase())</code></p>
<p>But lets keep in mind what we have learned and simplify it a little bit:</p>
<p><code>list.map(_.toLowerCase())</code></p>
<p>Remember what I said about omitting dots and braces?</p>
<p><code>list map { _.toLowerCase }</code></p>
<p>Et voilà. You can decide which one is better to read. The Scala version is short and nice. However if I would simply give you this snippet of code you do not know what it does as long as you do not know about the context. But we are dealing with language and context all day. Words have different meaning in a different context and it is not hard to guess that <code>toLowerCase</code> probably converts a character to its lower case representation.</p>
<p>Please note two more things. I left out the <code>()</code> after <code>toLowerCase</code> because it is a method without side effects. This is the case whenever your method does not modify any state in your system. Those methods are usually written in ActionScript like <code>public function get toLowerCase(): String { ... }</code>. And we omit the <code>()</code> as well.</p>
<p>One more example to convince you why this makes sense: Imagine we want to get rid of all the space characters in our now lower-case List (or Array in ActionScript).</p>
<p style="text-align: left"><code>array.map(function(x: String): String { return x.toLowerCase() }).filter(function(x: String): Boolean { return x != ' '})</code></p>
<p>vs. </p>
<p><code>list map { _.toLowerCase } filterNot { _ == ' ' }</code></p>
<p>This also explains why Scala is a great language for hackers. You can bend the language to your needs. Usually those <i>hacks</i> are categorized as domain specific languages. A language for a specific task. I have written a <a href="http://code.google.com/p/cssx-dsl/" target="_blank" title="CSS X">CSS DSL</a> using Scala for instance.</p>
<p>In order to do such things you will need implicit conversions. A very cool thing that is out of scope for this article (Update: I wrote a <a href="http://blog.joa-ebert.com/2010/12/26/understanding-scala-implicits/" title="Understanding Scala Implicits">post on implicits</a>).</p>
<h3>Conclusion</h3>
<p>Scala can do much more than you might expect. I just covered a small part of it. For me it is important to explain why I like it so much and why I believe that it is an elegant language that makes programming fun again.</p>
<p>After one year of extensive Scala use I do not regret a single minute spending confused in front of my screen. First of all I like that someone spent a good amount of time thinking about the language. It is simply great that you can distinguish between a class, something you want to instantiate multiple times, and an object, Scala&#8217;s notion of a singleton, at compile time. No need for private constructors and the other boilerplate fuzz. </p>
<p>The Scala community is filled with very intelligent and academic people who are not arrogant and always treat you with respect.</p>
<p>Speaking for myself I can only agree that Scala makes you more productive and it was a great decision to start learning it. Scala is also not a pure functional language. In my opinion a great decision although not everyone will agree. But you can always decide whether or not you want to write a loop using a simple while or to go for tail recursive functions with immutable values. It is up to you. </p>
<p>I started to use Scala also at work as well. It is very nice for smaller projects like determining the similarity between users and storing that in a database. Currently I am the only one writing Scala in our office so most projects are still either Java or ActionScript based.</p>
<p>If you are into speedcoding: Scala is your weapon of choice. The one time I was using it on stage I was finished after about 75% of the time which is great if you target ten minutes but then my IDE crashed. Tooling is a different topic but has greatly improved in the last couple of months. If you want to learn Scala why not simply start with an old experiment you wrote in Processing and convert that to Scala? Since Processing is written in Java you can call its methods from Scala without any problem. I did not mention it yet but since both languages run on the JVM you have full interoperability between them.</p>
<p>Apparat is also a great example of marrying Scala with Java. JITB is for instance written in Java and Scala. I have choosen to go for Java because I am working with Java Bytecode in Apparat and at that point the Scala compiler was not very stable regarding the bytecode it emitted. This does not mean it was broken but it changed during versions which would have made my job much harder.</p>
<p>However even if you will not use Scala on a daily basis it will make you a much better programmer. This is also true for any other functional language. I used immutable lists in my <a href="https://github.com/joa/as3-signals/" target="_blank">as3-signals fork</a> to simplify the whole dispatch logic and was able to delete a lot of unnecessary code. </p>
<p>Regarding Apparat, in the end I got rid of writing </p>
<p style="text-align: left"><code>final Graph&lt;BasicBlockVertex&lt;AbstractOp&gt;, Edge&lt;BasicBlockVertex&lt;AbstractOp&gt;&gt;&gt; graph = new BasicBlockGraph&lt;BasicBlockVertex&lt;AbstractOp&gt;, Edge&lt;BasicBlockVertex&lt;AbstractOp&gt;&gt;&gt;();</code></p>
<p>Which became </p>
<p style="text-align: left"><code>val graph = BasicBlockGraph.empty[BasicBlockVertex[AbstractOp], Edge[BasicBlockVertex[AbstractOp]]]</code></p>
<p>Oh wait, it did not. In fact it is now</p>
<p style="text-align: left"><code>def createGraph() = BasicBlockGraph.empty[BasicBlockVertex[AbstractOp], Edge[BasicBlockVertex[AbstractOp]]]<br />
...<br />
val graph = createGraph()</code></p>
<p>What does <code>def</code> mean? Go figure it out and enojy learning Scala. You will not regret it!</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2010/12/26/a-year-of-scala/" size="standard" count="true"></div></div>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2010/12/26/a-year-of-scala/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		<feedburner:origLink>http://blog.joa-ebert.com/2010/12/26/a-year-of-scala/</feedburner:origLink></item>
		<item>
		<title>Adobe MAX 2010 Opener</title>
		<link>http://feedproxy.google.com/~r/je2050/~3/N4GD4Y2OR2Q/</link>
		<comments>http://blog.joa-ebert.com/2010/10/27/adobe-max-2010-opener/#comments</comments>
		<pubDate>Tue, 26 Oct 2010 23:42:39 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[news]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[2010]]></category>
		<category><![CDATA[adobe]]></category>
		<category><![CDATA[livecoding]]></category>
		<category><![CDATA[max]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=690</guid>
		<description><![CDATA[This year I had the honor to be part of the opener show for Adobe MAX 2010. I really appreciate that the people at Adobe working on the keynote took the risk to try this out. Mike Chambers asked me already in April this year if I would like to do it. He had the [...]]]></description>
				<content:encoded><![CDATA[<div align="center"><iframe src="http://player.vimeo.com/video/16183360" width="400" height="225" frameborder="0"></iframe></div>
<p>This year I had the honor to be part of the opener show for Adobe MAX 2010. I really appreciate that the people at Adobe working on the keynote took the risk to try this out.<a href="http://blog.joa-ebert.com/wp-content/2010/10/IMG_20101022_182336.jpg" rel="lightbox[690]"><img src="http://blog.joa-ebert.com/wp-content/2010/10/IMG_20101022_182336-300x225.jpg" alt="Nokia Theatre" title="Nokia Theatre" width="300" height="225" class="alignright size-medium wp-image-691" /></a></p>
<p>Mike Chambers asked me already in April this year if I would like to do it. He had the idea of Erik Natzke generating art, me doing live coding and a DJ playing music. Eric Clark has been a fantastic supporter of Audiotool so I thought it would be really nice to have him do it. Luckily he agreed.<br />
<span id="more-690"></span><br />
We had several meetings and finalized the idea of the performance. We really wanted to connect the work from everyone of us and create one piece. Otherwise it would have been only three persons doing their stuff. But eventually we got it to a point were I was visualizing the music Eric Clark was playing using pictures that Erik Natzke has been drawing on stage.</p>
<p>I as a developer always want to know how things work. So I also want to explain the technological aspect and challenge of such a performance.</p>
<p>Eric D. Clark was using Audiotool on a touch screen and we really wanted to show how Audiotool can shine there. The idea was of course to support gestures one might intuitively expect. This was done in Germany already. We are using a custom built event handling system so I had to add gesture support there. We do currently support only zooming the desktop since the schedule was so tight. In fact the week before going to MAX we also launched <a href="http://www.burnenergydrink.com/en_GB/burnstudios/burn-studios-audiotool.html" target="_blank">a collaboration of Audiotool and Coca-Cola</a>. Everything was a little bit crazy.</p>
<p>However not as crazy as it went when we came to LA. When doing livecoding I usually prepare my final result already so I know what I want to create. You know where the little problems are and you can make the most out of the time you have. But because of the launch I did not have that much time to prepare. So I wrote one demo for me already in Germany. It was also my first time using the new 3D capabilities I was allowed to use which will be available as a public beta in 2011. Building software with a beta version of something is always fun because it can break for unknown reasons etc.</p>
<p>I also wrote a server that streams arbitrary recording devices into Flash at a very low latency. This was very important of course since I needed to access what Eric Clark was outputting. I did a version that does FFT and normal amplitudes but went only with the amplitudes since an FFT terrain looks not as interesting. It can. But then you have to do more analysis.<br />
On the flight to LA I build another program that would help me save some time during the performance. It is basically automatically compiling and launching a Flash Player. A lot of people asked me about this actually. But you can built it for yourself very easy or I can even release the source code. It is really not much to do. I also contributed this code to Flexmojos as the continuous compilation goal. In fact this was my first idea. But since I did not have internet access most of the time and I was developing this on my tiny netbook I thought I want to have something as slik as possible. <a href="http://blog.joa-ebert.com/wp-content/2010/10/IMG_20101023_214916.jpg" rel="lightbox[690]"><img src="http://blog.joa-ebert.com/wp-content/2010/10/IMG_20101023_214916-225x300.jpg" alt="" title="Eric D. Clark and the Audiotool" width="225" height="300" class="alignright size-medium wp-image-692" /></a><br />
Then there was another server involved I quickly wrote for Erik Natzkes machine. That one was also nothing special. It simply watches a folder and serves always the latest file. That way Erik only had to save an image to a certain folder with AIR and I would get it.<br />
Last but not least we also used FlashMate. My old companion when it comes to multi monitor development. FlashMate hooks into the window procedure of the Flash Player and simply repositions the window always where you left it.</p>
<p>Because of the tools I built I never had to worry about starting the compiler, moving the Flash Player window around etc. </p>
<p>The program I wrote was actually quite simple. It was a subdivided plane in 3D space and I was drawing the audio feed I got from Eric Clark onto a BitmapData. That BitmapData was used as a heightmap for the vertices of the plane. In fact each pixel was assigned to exactly one vertex. That way I could get a really nice and smooth terrain. Thanks to Molehill this was rendering even at 1920&#215;1080 without any hickups.<br />
The heightmap was also used as a lightmap to fake some kind of ambient occlusion. I know that this was rather cheap. But keep in mind that we also had a limited amount of time. Even worse: We had some cue points in the performance. Like when Serge Jespers came on stage and was giving me the audio cable. At that point everyone was expecting me to be ready to visualize the amplitudes. Otherwise the whole thing would not have made any sense.</p>
<p>However we also wanted to show even more at the end because it would have been boring to see only the terrain flight the whole time. That is the reason why I flipped the terrain and started to rotate it. We agreed to this on Saturday, two <a href="http://blog.joa-ebert.com/wp-content/2010/10/IMG_20101022_192611.jpg" rel="lightbox[690]"><img src="http://blog.joa-ebert.com/wp-content/2010/10/IMG_20101022_192611-150x150.jpg" alt="" title="Erik&#039;s Touchscreen" width="150" height="150" class="alignleft size-thumbnail wp-image-693" /></a>days before the keynote. But luckily this is a rather cheap copy and paste operation. You take the code you already have and rotate the terrain by 180° around the z-axis. The rest of the animation was really only rotating everything around the y- and z-axis.<br />
During the keynote we were also on IFB and at one point we were told that we have to stretch for five more minutes. That is the reason why the terrain was bouncing, freezing and whatever at the end.</p>
<p>I really enjoyed this whole experience. I love to have a look behind the scenes and it was an absolut pleasure to work together with everyone at the keynote. Friendly people all over the place. And a lot of hackers too.<br />
However it was stressful. It is really not easy to type and concentrate in front of such a big audience. And it is not like a Flash event where you know most people anyways. All of a sudden there is the international press and all the executives sitting front row.</p>
<p>But I really liked the whole thing. Especially the last five minutes freestyle coding. I also want to thank Erik and Eric. The artwork matched the music very well. And I love the idea of us going on stage, each with a blank canvas on its own, creating something in a limited amount of time and having it connect as one piece.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2010/10/27/adobe-max-2010-opener/" size="standard" count="true"></div></div>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2010/10/27/adobe-max-2010-opener/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		<feedburner:origLink>http://blog.joa-ebert.com/2010/10/27/adobe-max-2010-opener/</feedburner:origLink></item>
		<item>
		<title>Apparat 1.0 RC7 Is Here</title>
		<link>http://feedproxy.google.com/~r/je2050/~3/u6YQfz4UZKU/</link>
		<comments>http://blog.joa-ebert.com/2010/10/06/apparat-1-0-rc7-is-here/#comments</comments>
		<pubDate>Wed, 06 Oct 2010 12:19:03 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[Flash]]></category>
		<category><![CDATA[news]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[apparat]]></category>
		<category><![CDATA[asmifier]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jitb]]></category>
		<category><![CDATA[lwjgl]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=681</guid>
		<description><![CDATA[I wanted to make a simple bug fix release for Apparat since I solved some bugs and issues. However there are two additional features that are worth mentioning. First of all Apparat comes now with an ASMifier tool. This allows you to let Apparat generate code from an existing SWF. It will create a file [...]]]></description>
				<content:encoded><![CDATA[<p>I wanted to make a simple bug fix release for Apparat since I solved some bugs and issues. However there are two additional features that are worth mentioning. First of all Apparat comes now with an ASMifier tool. This allows you to let Apparat generate code from an existing SWF. It will create a file that contains a basic class structure with statements that you can directly use for <code>__asm</code> optimizations. You can also suppress all log output and turn Apparat into quiet mode by specifying <code>-Dapparat.quiet=true</code>.</p>
<p>Also worth mentioning: JITB ships now by default with Apparat. What does it mean? <del datetime="2010-10-06T11:43:52+00:00">Quadruple-rainbow in your face.</del> You can now run your SWF files with JITB if you follow the five golden steps to pure happiness:</p>
<ol>
<li>Download and install <a href="http://www.scala-lang.org/downloads" target="_blank" title="Scala Download">Scala 2.8.0</a></li>
<li>Type <code>scala</code> in a terminal, then type <code>println(System getProperty "java.library.path" split java.io.File.pathSeparatorChar mkString "\n")</code> and remember one of the folders</li>
<li><a href="http://sourceforge.net/projects/java-game-lib/files/Official%20Releases/LWJGL%202.5/" target="_blank" title="LWJGL Download">Download LWJGL 2.5</a> and extract somewhere</li>
<li>Copy the native libraries which are located in <code>lwjgl-2.5/native/YOUR OS/</code> into one of the folders that the Scala command showed you</li>
<li>Open a terminal, go into the Apparat installation directory and type <code>./jitb some.swf</code> to launch JITB
</ol>
<p>Now here is the problem. JITB is not complete and so it will probably fail with your SWF &#8212; In fact I can nearly gaurantee you that it will not launch your SWF. I included JITB basically because it already allows you to use GLSL shaders very easy and I know a lot of people would like to play around with that.</p>
<p>However I have created an archive of all files I showed at FOTB besides the files that came from <a href="http://www.derschmale.com/" title="DerSchmale" target="_blank">David&#8217;s laptop</a> since I do not have them on my machine. You might be interested in checking out Example12.as which is the one that uses GLSL shaders. If you want to compile your own version you will need to link apparat-ersatz.swc as an external library since it contains the <code>ContinuousFileLoader</code> and <code>GLSLShader</code> class. Happy hacking!</p>
<ul>
<li><a href="http://code.google.com/p/apparat/downloads/detail?name=jitb_examples.zip" title="jitb_examples.zip" target="_blank">Download the JITB Examples</a></li>
<li><a href="http://apparat.googlecode.com/" target="_blank" title="Apparat">Apparat on GoogleCode</a></li>
</ul>
<p><b>Update:</b> Also read <a href="http://www.derschmale.com/2010/10/07/ray-tracing-with-pixel-bender-using-jitb/" target="_blank" title="Ray tracing with Pixel Bender using JITB">Ray tracing with Pixel Bender using JITB</a> by David Laenarts for details on the FOTB demos.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2010/10/06/apparat-1-0-rc7-is-here/" size="standard" count="true"></div></div>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2010/10/06/apparat-1-0-rc7-is-here/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		<feedburner:origLink>http://blog.joa-ebert.com/2010/10/06/apparat-1-0-rc7-is-here/</feedburner:origLink></item>
		<item>
		<title>Opening The Blackbox</title>
		<link>http://feedproxy.google.com/~r/je2050/~3/j5BdPphHQCA/</link>
		<comments>http://blog.joa-ebert.com/2010/10/03/opening-the-blackbox/#comments</comments>
		<pubDate>Sun, 03 Oct 2010 17:57:00 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[experiments]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[apparat]]></category>
		<category><![CDATA[avm]]></category>
		<category><![CDATA[flashplayer]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jitb]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=674</guid>
		<description><![CDATA[The Flash Player is to many of us developers a blackbox. We use it every day in our job but do not really know much about it. Of course we do not have to understand its inner workings but it is sometimes very interesting to know more a little bit about specific implementation details. A [...]]]></description>
				<content:encoded><![CDATA[<p>The Flash Player is to many of us developers a blackbox. We use it every day in our job but do not really know much about it. Of course we do not have to understand its inner workings but it is sometimes very interesting to know more a little bit about specific implementation details.</p>
<p><span id="more-674"></span></p>
<p>A part of the Flash Player is the ActionScript Virtual Machine (AVM) which is responsible for executing the code that is bundeled in your SWF file. This piece of software called <a href="http://www.mozilla.org/projects/tamarin/" target="_blank" title="Tamarin">Tamarin</a> is open source and released under the <a href="http://www.mozilla.org/projects/tamarin/faq.html#license" target="_blank" title="Tamarin License">MPL/GPL/LGPL Triple License</a>.</p>
<p>Being able to look at the heart of the Flash Player does reveal a lot to the interesting reader. However such a virtual machine is a complex piece of software and you can be lost without any guidance and will maybe not even be able to compile it unless you are familiar with such systems. <a href="http://jpauclair.net" target="_blank" title="jpauclair">Jean-Philippe Auclair&#8217;s blog</a> contains a lot of interesting Tamarin and Flash Player releated articles if you want to know more about the VM. Of course you can also read about <a href="https://developer.mozilla.org/en/MMgc" title="MMgc" target="_blank">MMgc</a> &#8212; the garbage collection &#8212; directly at the Mozilla developer network.</p>
<p>This article is titled &#8220;Opening The Blackbox&#8221;. Although Tamarin might be some kind of blackbox to most of us the source code is available. We can dig into it and understand how it works. The Flash Player however is not completely open source and we do not know about its implementation details. Unless Adobe is opening up the source code we will not know which exact algorithm is used for <a href="http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/display/BitmapData.html#noise()" target="_blank" title="flash.display.BitmapData">BitmapData.noise</a> for instance.</p>
<blockquote><p>Fills an image with pixels representing random noise.</p></blockquote>
<p>This quote taken from the documentation does not tell you much about how to calculate this noise. In this situation I would create some algorithm that fills a BitmapData also with random noise. But until we know which algorithm is used to calculate that noise it will never be the exact same noise as the one of the Flash Player. For now we will have to live with it. There is no (legal) way to figure out the algorithm.<br />
Of course there are also other classes like ByteArray which have methods like <code>readByte</code> that do not need any extra explanation. But ByteArray also has some implementation specific details. How does it grow when you exceed its length for instance? Fortunately ByteArray is something <a href="http://hg.mozilla.org/tamarin-central/file/fbecf6c8a86f/axscript/ByteArrayGlue.cpp#l138" target="_blank" title="ByteArrayGlue.cpp">you can find</a> in the Tamarin source code. JITB uses a different algorithm however which you can find <a href="http://code.google.com/p/apparat/source/browse/apparat-playerglobal/src/main/java/flash/utils/ByteArray.java#161" target="_blank" title="ByteArray.java">here</a>.</p>
<p>But what else do we got? There are some funny things you will notice. Usually <code>Sprite(x)</code> is an explicit cast. This is true for any statement like this. However <a href="http://help.adobe.com/en_US/AS3LCR/Flash_10.0/package.html#Number()" target="_blank" title="Number()"><code>Number(x)</code></a> is a conversion with specific details how a value is converted. This is also true for some other expressions like <code>Boolean()</code>.</p>
<p>The <code>playerglobal.swc</code> contains all classes the Flash Player knows about. It should and it does with some minor differences. Of course it could be a bug on my end but some interfaces are missing. And they are suspicious since they cause/have special behaviour. Have a look at the <a href="http://code.google.com/p/apparat/source/browse/apparat-taas/src/main/scala/apparat/taas/frontend/abc/AbcFrontend.scala#32" target="_blank" title="AbcFrontend.scala">AbcFrontend</a> code. The <code>Synthetic</code> object contains part of the AST that is synthesized since those interfaces are missing in <code>playerglobal.swc</code>.</p>
<p>A lot of the Flash Player implementation details have made it into the <code>DisplayObject</code> and its subclasses. You cannot extend from <code>DisplayObject</code> and you cannot implement <code>IBitmapDataDrawable</code>. Even more interesting is the amount of classes that you cannot really use. <a href="http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/geom/Transform.html" target="_blank" title="flash.geom.Transform"><code>flash.geom.Transform</code></a> is such a class. How is <code>concatenatedMatrix</code> working if you would create your own instance of the <code>Transform</code> object?</p>
<p>Of course somewhere in the Flash Player will be some code that creates a <code>Transform</code> object. This will hold a reference to the original <code>DisplayObject</code> and concat the matrices up to the stage if you call <code>concatenatedMatrix</code>. The JITB implementation adds some special methods to the <code>Transform</code> class in such cases. Those methods are always prefixed with JITB$ if they are public. Another interesting fact is that you can modify the appearance of a <code>DisplayObject</code> by setting the matrix of the <code>Transform</code> object. This also has to change the scale, x, y and rotation values of the <code>DisplayObject</code>. There are a dozen of souch cases. Graphics would be an obvious candidate to talk about. I would advise you to take a look at <a href="http://wahlers.com.br/claus/blog/" target="_blank">Claus&#8217; blog</a> for <a href="http://wahlers.com.br/claus/blog/hacking-swf-1-shapes-in-flash/" target="_blank">everything you never wanted to know about shapes</a>.</p>
<p>Also something you probably never cared about is the way how <code>URLLoader</code> works. I do not care about the specific implementation details either. However one thing is important to keep in mind. Loaders have to work asynchronous since they do not block. This means your Flash content runs while waiting for an event like <code>Event.COMPLETE</code>. This is where it gets interesting since threads enter the game. This would be a simple view: ActionScript runs in one thread, the loader in a second thread. First of all we have to keep in mind that the ActionScript code runs in a loop which is basically only triggered by events like <code>Event.ENTER_FRAME</code> or user input. Only the code in your <code>DocumentClass</code> is the one that is initiated without an event. So how does this look like in pseudo-code?</p>
<pre>
while(NoErrorOccurred &#038;&#038; Running) {
  Dispatch Event.ENTER_FRAME to each DisplayObject
  Render DisplayList
  Dispatch Event.EXIT_FRAME to each DisplayObject
  Sleep(1000 / FrameRate - Elapsed)
}
</pre>
<p>Okay but how does an <code>Event.COMPLETE</code> make it into this loop when it comes from a different thread in which the loader runs? If the loader would simply dispatch this event when it completes the code would not run in the main thread. This means you could end up with ActionScript code running in parallel which would cause chaos and destruction. So what do you do? The current approach in JITB is to gather all events and dispatch them at the beginning of a frame. So basically the code looks now like this:</p>
<pre>
while(NoErrorOccurred &#038;&#038; Running) {
  Dispatch All Gathered Events
  Dispatch Event.ENTER_FRAME to each DisplayObject
  Render DisplayList
  Dispatch Event.EXIT_FRAME to each DisplayObject
  Sleep(1000 / FrameRate - Elapsed)
}
</pre>
<p>The implementation specific details can be found in <a href="http://code.google.com/p/apparat/source/browse/apparat-playerglobal/src/main/java/jitb/events/EventSystem.java" target="_blank" title="EventSystem.java">EventSystem.java</a> class. There are also some utility methods like <code>futureDispatch</code> to make development easier. Dynamic audio requires to dispatch an event that is filled with content. The thread in which the audio is passed to the sound card has to wait until <code>SampleDataEvent</code> is filled with new content. This also reveals a problem. The audio calculation has to wait for a complete ActionScript frame until new material is available. In fact such synchronization points are problematic for a task that requires very low latency. You can hear this when your ActionScript code takes very long to process the new audio and you get a stutter-noise or audible gap. Unfortunately there is nothing you can do about this problem at the moment besides keeping the cost of your ActionScript code as low as possible.</p>
<p>Of course everything is only my interpretation. The Flash Player might not suffer from the problems I describe here since someone might have come up with a better implementation. In fact I would doubt that the Flash Player works for dynamic audio the same way I do it currently.</p>
<p>The last blog post of this series will be more about how you can implement parts of the Flash Player API in Java so that JITB understands them and vice versa. Of course we can create our own <code>playerglobal.swc</code> as well and add new native classes like <a href="http://code.google.com/r/joaebert-sf2010-sprint/source/browse/apparat-playerglobal/src/main/java/jitb/display/GLSLShader.java" target="_blank" title="GLSLShader.java"><code>GLSLShader</code></a> which I demoed at FOTB. </p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2010/10/03/opening-the-blackbox/" size="standard" count="true"></div></div>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2010/10/03/opening-the-blackbox/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://blog.joa-ebert.com/2010/10/03/opening-the-blackbox/</feedburner:origLink></item>
		<item>
		<title>How JITB converts ActionScript to Java</title>
		<link>http://feedproxy.google.com/~r/je2050/~3/lJ4bq5M3_LI/</link>
		<comments>http://blog.joa-ebert.com/2010/10/02/how-jitb-converts-actionscript-to-java/#comments</comments>
		<pubDate>Sat, 02 Oct 2010 16:45:23 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[experiments]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[personal]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[apparat]]></category>
		<category><![CDATA[avm]]></category>
		<category><![CDATA[bytecode]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jitb]]></category>
		<category><![CDATA[jvm]]></category>
		<category><![CDATA[taas]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=670</guid>
		<description><![CDATA[One of the biggest challenges when writing a program like JITB is to convert ActionScript to Java. There are major differences between ActionScript 3.0 and Java 1.6 which JITB currently targets. ActionScript 3.0 is a dynamically typed language with function closures. Furthermore it has native XML support, scope-changes, implicit getters and setters etc. The main [...]]]></description>
				<content:encoded><![CDATA[<p>One of the biggest challenges when writing a program like JITB is to convert ActionScript to Java. There are major differences between ActionScript 3.0 and Java 1.6 which JITB currently targets.</p>
<p>ActionScript 3.0 is a dynamically typed language with function closures. Furthermore it has native XML support, scope-changes, implicit getters and setters etc. The main issue however is to convert the set of bytecodes ahead of time to statically typed Java code. JITB does not know anything about what is going on since it compiles all the code ahead of time.</p>
<p><span id="more-670"></span></p>
<h3>JITB and TAAS</h3>
<p>JITB makes use of TAAS. A three address code intermediate language. TAAS has its own set of rules and typesystem that I defined for myself. Method overloading is supported for instance. And there is no concept of array access. Code like <code>x = a[0]</code> is converted to <code>x = a.getIndex(0)</code>. In TAAS terms the name of a method is also not worth a penny since it is always using a reference based lookup.</p>
<p>What I love about TAAS is that it has a really small instruction set. Array access is just a method call like any other method call. No extra instructions added. This makes optimizations really slick and easy to develop. Since the code is statically typed you also always know which method is being called and you could construct a call graph and do whole program optimizations which is a huge bonus. Escape analysis is something that is now finally possible for me.</p>
<p>JITB uses a frontend that parses ActionScript bytecode and creates an AST which is then transformed and passed to a backend that creates Java bytecode. The class and package structure is stored in a tree form. Method bodies are always stored in a graph representation. The interesting problem is to convert ActionScript into TAAS since it is no direct mapping and some statements are not supported in the same way you get them form the ActionScript bytecode. Then the next interesting problem is to convert this code into Java bytecode which is also not a direct mapping.</p>
<p>An example for such a problem are implicit getters and setters. TAAS does not have a concept of getters and setters but understands methods. So whenever the ActionScript bytecode has a <code>GetProperty</code> instruction I try to figure out if this is a field or not. If it is a field I generate a <code>TLoad</code> instruction, if it is an implicit getter it will be converted to a <code>TCall</code> instruction. However if it cannot be determined since the class might be dynamic a <code>TCall</code> instruction will be generated which uses the special <code>TGetProperty</code> method and this will be resolved at runtime.<br />
When converting to Java a <code>TLoad</code> can be easily translated to a <code>GETFIELD</code> operation. When it is a <code>TCall</code> I first lookup whether or not it is a special native function. If it is a special function like <code>TGetProperty</code> I insert Java code like <code>object.JITB$getProperty(name)</code>. If it is a normal function I simply insert an invoke operation.</p>
<h3>Closures for Java</h3>
<p>Java 1.6 does not support closures. This means Java does not understand the concept of a reference to a function. Code like <code>addEventListener(Event.ENTER_FRAME, onEnterFrame)</code> is not possible with Java since <code>onEnterFrame</code> is a reference to the <code>onEnterFrame</code> function which is defined somewhere else in your code.</p>
<p>I took the idea from Scala and how they support closures in the JVM. Basically when code like <code>addEventListener(Event.ENTER_FRAME, onEnterFrame)</code> occurrs it will be translated to the TAAS instruction <code>TCall(TReg(0), TaasMethod(addEventListener, ...), List(TString("enterFrame"), TClosure(TaasMethod(onEnterFrame, ...))), None)</code>. This basically means that the method <code>addEventListener</code> is called on the object in register zero with two arguments of which one a closure and it has no result which is indicated by <code>None</code>.</p>
<p>This instruction is expanded to the following Java code. Please remember that it is always Java bytecode. I think it is just easier to understand if I write the corresponding Java code here.</p>
<p><code>
<pre>
this.addEventListener("enterFrame", new Function1<Event, Object>() {
  override Object call(Event arg) { callVoid(arg); return null; }
  override void callVoid(Event arg) { onEnterFrame(arg); }
});
</pre>
<p></code></p>
<p>Function1 represents a function of arity one. The AVM can call any method as either void or with an expected result. If the method has a result and you call it via <code>CallPropVoid</code> the resulting object is ignored. If however you have a method that does not have a result and you call it via <code>CallProperty</code> the <code>null</code> object will be pushed on the stack.</p>
<p>The Java code in EventDispatcher which would call closures basically now only looks like this:</p>
<p><code>
<pre>
void dispatchEvent(Event event) {
  for(Function1<Event, Object> listener : listenersFor(event.type)) 
    listener.call(event)
}
</pre>
<p></code></p>
<h3>Dynamic code in Java</h3>
<p>Since I want to target Java 1.6 I do not make use of the Java 1.7 opcodes like <code>invokedynamic</code>. Because TAAS is already statically typed we have only in very rare cases the need to make a dynamic lookup. This is done by some helper classes or methods. Every ActionScript based class extends from <code>jitb.lang.Object</code>. The <code>jitb.lang</code> package represents the ActionScript&#8217;s toplevel. The <code>Object</code> class has certain helper methods like <code>JITB$getProperty</code> and <code>JITB$setProperty</code>. Those methods throw an error by default if an object is not dynamic but they can implement the behaviour to store values in a HashMap for dynamic classes.<br />
However currently dynamic method lookup is not supported. Code like <code>a['method'+Math.random()]()</code> fails since it is impossible to know upfront which method is called. But this can be supported as well. It is just very cumbersome and annoying.</p>
<h3>Emulating the AVM in the JVM</h3>
<p>What kind of error do you expect for this kind of code: <code>var x: String = null; trace(x.toString());</code>? This creates a TypeError in ActionScript but a NullPointerException in Java. Same for things like <code>var x: A = new A(); var y: B = B(x);</code> which would result in a Java ClassCastException if A is not assignable to B.<br />
JITB offers an option which is by default turned on the get the exact same exceptions like the AVM would throw them. This means that a Java cast is converted to a call like <code>AVM.cast(x, B.class)</code> with the option turned on or the simple Java <code>CHECKCAST</code> bytecode when the option is turned off. Basically expecting something to be null in a try-catch block is very silly in my honest opinion. So to get rid of this overhead you can disable this extra step of correctness.</p>
<p>Another interesting issue is the fact thatthe AVM can throw any object. Java however expects that a throwable object extends from the Throwable class. Of course the basic <code>jitb.lang.Object</code> class could simply extend Throwable. However I do not want that overhead and at any time. Also I do not want to break how classes extend each other. If you do something like <code>throw "string"</code> it is converted to <code>throw new Throw<String>("string")</code>. Throw does extend Throwable and whenever it is catched the value is simply extracted.</p>
<h3>To box or not to box?</h3>
<p>ActionScript allows you do use int as an object with a lot of special behaviours. Same happens for values like Boolean or Number. <code>var x: int; trace(x);</code> outputs 0 but not null. But it is also possible to call <code>0.toString()</code> which indicates that the integer value <code>0</code> is treated like an object that has methods like <code>toString()</code>.<br />
In Java however you have a real <code>int</code> primitive and the <code>Integer</code> object. <code>0.toString()</code> does not compile but you would rather do <code>Integer.toString(0)</code>.</p>
<p>Of course Java is much faster when using primitive data types when appropriate. JITB does this since it handles primitive types like real primtives for Java. This means a method like <code>function add(x: int, y: int): int { return x + y}</code> is converted to <code>int add(int x, int y) { return x + y }</code>. However when you have a method that expects an Object type a primitive will be boxed into a compatible type.</p>
<p>Last but not least what happens for code like <code>0.toString()</code> or other methods? A possibility would be to emit code like <code>new jitb.lang.Number(0).toString()</code> but that does not make sense in most of the cases. Instead those calls are treated specially with a call like <code>jitb.lang.Number.JITB$toString(0)</code> and we get rid of an extra allocation.</p>
<h3>Conclusion</h3>
<p>I hope you understand a little bit better now how JITB works internally and what the main gotchas are in such an implementaiton. The journey is not over since I have to add support for anonymous methods and although I talked about things like <code>throw</code> I still have to add support for try-catch. Also a lot of other basic features are still missing but I doubt that they would cause any problems.</p>
<p>The other side of the story is the Flash Player API inside of JITB which is maybe worth a blog post like this as well since it reveals a lot of other funny and interesting gotchas.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2010/10/02/how-jitb-converts-actionscript-to-java/" size="standard" count="true"></div></div>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2010/10/02/how-jitb-converts-actionscript-to-java/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		<feedburner:origLink>http://blog.joa-ebert.com/2010/10/02/how-jitb-converts-actionscript-to-java/</feedburner:origLink></item>
		<item>
		<title>JITB’s PixelBender support</title>
		<link>http://feedproxy.google.com/~r/je2050/~3/q5yYxACwNwg/</link>
		<comments>http://blog.joa-ebert.com/2010/10/01/jitbs-pixelbender-support/#comments</comments>
		<pubDate>Fri, 01 Oct 2010 15:35:37 +0000</pubDate>
		<dc:creator>joa</dc:creator>
				<category><![CDATA[experiments]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[hydra]]></category>
		<category><![CDATA[apparat]]></category>
		<category><![CDATA[glsl]]></category>
		<category><![CDATA[jitb]]></category>
		<category><![CDATA[pixelbender]]></category>

		<guid isPermaLink="false">http://blog.joa-ebert.com/?p=664</guid>
		<description><![CDATA[I have demoed support for PixelBender shaders in JITB at the FOTB 2010 conference. It turned out that JITB can run PixelBender code really fast and well. I have demoed a Julia and Terrain raytracer which were both kindly contributed by David Lenaerts. I only showed the demos since I would have been running out [...]]]></description>
				<content:encoded><![CDATA[<p>I have demoed support for PixelBender shaders in JITB at the <a href="http://www.flashonthebeach.com/" target="_blank">FOTB 2010</a> conference. It turned out that JITB can run PixelBender code really fast and well. I have demoed a Julia and Terrain raytracer which were both kindly contributed by <a href="http://www.derschmale.com/" target="_blank">David Lenaerts</a>. I only showed the demos since I would have been running out of time. I still owe you an explanation of how it all works.<br />
<span id="more-664"></span></p>
<h3>Step #1: Parsing PixelBender data</h3>
<p>PixelBender compiles down to PBJ which is a two-address based bytecode format. Basically it contains instructions like this one which I have taken from <a href="http://www.ncannasse.fr/projects/pbj" target="_blank">Nicolas&#8217; blog</a>:</p>
<pre>  sampleNearest f2, text0[f0.rg]
  sampleNearest f3, text1[f0.rg]
  mov f4, f2
  mul f4, f3
  mov f1, f4</pre>
<p>Those PBJ files are parsed by Apparat into high level structures. This happens basically the same way I do it for ActionScript bytecode. Thanks to the work of Nicolas Cannasse this was a walk in the park.</p>
<h3>Step #2: Optimizing PixelBender bytecode</h3>
<p>The PixelBender compiler does not produce optimal code as noted by Nicolas. You can see it in the code I just posted. Or you can simply compile and empty shader and take a look at the disassembled output. Apparat performs only two very simple optimizations for PixelBender which are written especially for PBJ. Thos include copy propagation and dead code elimination. The compiler does create code which is not bad thanks to <a href="http://www.llvm.org/" target="_blank">LLVM</a> but there are unnecessary copies going on which are removed by Apparat.</p>
<h3>Step #3: Loop detection</h3>
<p>PixelBender <b>still</b> has no loops since its initial introduction in October 1st in 2007. Tomorrow it is October 1st in 2010. Go figure. So since there are no loops the only way people write loops in PixelBender is basically by copy and paste or using preprocessor directives. With JITB I want to send real shaders to the graphics card and I do want to make use of loops. So I wrote a PBJ bytecode based copy and paste detector which is based on ideas of the <a href="http://pmd.sourceforge.net/" target="_blank">PMD</a> copy and paste detector. When a segment is detected in a sequence I convert it to a loop. That way I can reduce the amount of data I have to send to the graphics card. This is very important since in the case of the demos I showed at FOTB they contained around 50.000 instructions. And my cheap graphics card was complaining that there are too many instrucitons. With the loop conversion this number drastically decreased.</p>
<h3>Step #4: Converting PixelBender bytecode to GLSL</h3>
<p>It is very easy to convert PixelBender to GLSL. The two address code format can be translated with some minor tweaks to GLSL with a very simple mapping. However this is not really optimal since you have only a two address code. When exporting to GLSL I perform one additional step which expands the two address based code to a three address based code. That way I do not emit a lot of unnecessary copies again.</p>
<p>That is basically the recipie to convert PixelBender PBJ files to GLSL shaders that perform well on current graphics card hardware. There are additional steps involved to get OpenGL shaders to work like PixelBender in Flash but they are only minor tweaks. I have no comparable metrics right now. However I will create a JITB applet version so you can have a look for yourself soon.</p>
<div class="none"><div class="g-plusone" data-href="http://blog.joa-ebert.com/2010/10/01/jitbs-pixelbender-support/" size="standard" count="true"></div></div>]]></content:encoded>
			<wfw:commentRss>http://blog.joa-ebert.com/2010/10/01/jitbs-pixelbender-support/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://blog.joa-ebert.com/2010/10/01/jitbs-pixelbender-support/</feedburner:origLink></item>
	</channel>
</rss><!-- Dynamic page generated in 0.407 seconds. --><!-- Cached page generated by WP-Super-Cache on 2013-05-19 02:03:56 --><!-- Compression = gzip -->
