Slashdot Mirror


A JavaScript Gameboy Emulator, Detailed In 8 Parts

Two9A writes "JavaScript has shed its image of being a limited language, tied to DOM manipulation in a browser; in recent years, new engines and frameworks have given JS a reputation as a language capable of bigger things. Mix this in with the new elements of HTML5, and you have the capacity to emulate a game console or other system, with full graphical output. This series of articles looks in detail at how an emulator is written in JavaScript, using the example of the Gameboy handheld: starting at the CPU, and (as of part 8) running a copy of Tetris."

62 comments

  1. There are already tons of Game Boy emulators... by Anonymous Coward · · Score: 5, Funny

    ...but whenever I use one, I can't help but think "I sure wish this was written in Javascript, so there wouldn't be any way to save my game. Saved games are for pussies. And sure, it wouldn't support sound, but who needs that when you've got the beautiful noise of your computer fans running on full blast, thanks to its excessive CPU usage!"

    1. Re:There are already tons of Game Boy emulators... by Anonymous Coward · · Score: 3, Informative

      And sure, it wouldn't support sound, but who needs that when you've got the beautiful noise of your computer fans running on full blast, thanks to its excessive CPU usage!

      This JavaScript NES emulator supports sound: http://benfirshman.com/projects/jsnes/

      Here are some other JavaScript audio demos:

      http://hacks.mozilla.org/2010/04/beyond-html5-experiments-with-interactive-audio/
      http://hacks.mozilla.org/2010/10/audio-data-api-audio-generation-demo/

    2. Re:There are already tons of Game Boy emulators... by AmberBlackCat · · Score: 2, Informative

      While I was playing Super Mario Brothers, the emulator in the first link was too slow in Firefox but worked fairly well in Opera. It's the first time in history that javascript performance actually mattered.

    3. Re:There are already tons of Game Boy emulators... by Anonymous Coward · · Score: 1, Informative

      On my system it works best for me in the currently Firefox 4 nightly build as it has the smoothest character motion and best responsiveness. Chrome works well but is a touch sluggish and seems to lose the key input sometimes. Opera claims to have the highest framerate but the motion of the characters is choppy, so I'm not sure that the framerate count is necessarily accurate.

    4. Re:There are already tons of Game Boy emulators... by Tharsman · · Score: 0, Redundant

      This.

    5. Re:There are already tons of Game Boy emulators... by Anonymous Coward · · Score: 0

      One of the reasons I think this is interesting is because a JavaScript application will run in Safari on iOs, making emulators possible on the iPhone.

    6. Re:There are already tons of Game Boy emulators... by Anonymous Coward · · Score: 0

      http://sandbox.photonstorm.com/gameboy/index.html

      Flash version. Plays flawlessly on this computer (a low end laptop (Celeron M 1.7GHz, 1MB L2, 533MHz FSB). Javascript versions? Choppy at best.

  2. Very interesting set of articles. by Beelzebud · · Score: 1

    I've always been curious about the inner workings of a console emulator, and this was very informative.

  3. Crysis? by hezekiah957 · · Score: 0, Offtopic

    Is anybody working on a GB port of Crysis?

    1. Re:Crysis? by metalmaster · · Score: 1

      woah.....dont get ahead of yourself. We need to see if it runs linux first

  4. Your jokes are out of date. by pavon · · Score: 4, Informative

    Both sound and client-side data storage are features of HTML5.

  5. Javascript? by Tr3vin · · Score: 3, Funny

    Real men write their GB emulators in Minecraft.

    1. Re:Javascript? by Anonymous Coward · · Score: 2, Funny

      No, *real* men write their emulators by arranging stones in the desert.

    2. Re:Javascript? by Architect_sasyr · · Score: 1

      No, *real* men write their emulators by arranging grains of sand into brainfuck on the beach.

      --
      Me failed English...
      FreeBSD over Linux. If my comments seem odd, this may explain...
    3. Re:Javascript? by Anonymous Coward · · Score: 2, Funny

      No, *real* men write their emulators by arranging grains of sand into brainfuck on the beach.

      Excuse me, but real men use butterflies.
      They open their hands and let the delicate wings flap once.
      The disturbance ripples outward, changing the flow of the eddy currents in the upper atmosphere.
      These cause momentary pockets of higher-pressure air to form, which act as lenses that deflect incoming cosmic rays, focusing them to strike the drive platter and flip the desired bit...

      ...or something like that

    4. Re:Javascript? by RevWaldo · · Score: 2, Funny

      Well, damn, now what am I gonna do with this infinitely long spool of magnetic tape?

    5. Re:Javascript? by gmthor · · Score: 1

      Oh cool. I've got one too. Together we could build a dual band computer. This hast to be way more powerful.

      --
      How do I uncompress my MD5 archive?
    6. Re:Javascript? by Anonymous Coward · · Score: 0

      What... no Chuck Norris jokes?

  6. Sound? by Mr.+Sketch · · Score: 5, Interesting

    I'm curious how he plans on handling dynamically generated sound from the GB ROM. Doing CPU and Graphics are usually the easy parts of emulating, but getting smooth dynamic sound without much latency is the challenge I've had to deal with when doing web-based emulators. Most web-based systems are designed to load a static set of sounds from a server, not dynamically generate them in the code.

    Flash 10 provides some dynamic sound capability, but it has a rather large latency (~250ms). I blogged about this while writing my NES emulator in flash.

    I read through these articles hoping for some insight on dynamically generated sound, but it doesn't look like he's gotten that far.

    1. Re:Sound? by The+MAZZTer · · Score: 1

      I think the general solution is to use Javascript to generate the raw audio data, slap a WAV header on it, base 64 encode it into a data url and stick it into an audio tag set on autoplay.

      I could be wrong about that though, maybe there's a better way. I've seen a couple of SWF to JS converters that handle audio OK.

    2. Re:Sound? by GNUALMAFUERTE · · Score: 1

      http://acko.net/blog/javascript-audio-synthesis-with-html-5

      It's not perfect, but we are getting there.

      --
      WTF am I doing replying to an AC at 5 A.M on a Friday night?
    3. Re:Sound? by BZ · · Score: 3, Informative

      You might be interested in https://wiki.mozilla.org/Audio_Data_API#Writing_Audio and https://github.com/corbanbrook/dsp.js

      Not sure what the latency is, but if it's too high for uses like this, please let the people involved know? They want this to actually be useful for exactly the sort of things you're talking about.

    4. Re:Sound? by Mr.+Sketch · · Score: 2, Interesting

      That Mozilla link is along the lines of what I was thinking of for dynamic audio. Too bad it's not supported by all browsers, but it would be a start. With some proper architecture, it should be easy enough to add support for other browsers when they support a similar feature.

      Thanks!

      I should probably start looking at what it would take to port my Flash NES emulator to JavaScript. I wrote it in Haxe with the goal of doing a JS version at some point. However, at the time, only Chrome could even come close to running the JS fast enough, but now most modern browsers should be fast enough (I'll have to do some performance tests). It should just require minor tweaking to replace the flash calls with JS/HTML5 calls without having to re-do and re-work the bulk of the logic.

    5. Re:Sound? by Mr.+Sketch · · Score: 1

      Yeah, it's close, but not perfect. However, the Mozilla extensions are more along the lines of what I was thinking.

  7. ... why? by Mongoose+Disciple · · Score: 4, Insightful

    I've said it before, and I'll say it again:

    You can write damn near anything in JavaScript if you really want to, but the better question is if you should.

    And yes, that includes half (but only half!) of the stuff you'll find done in JavaScript in web apps.

    1. Re:... why? by kumanopuusan · · Score: 1

      Just write a compiler back-end that outputs JavaScript in a form that's easily optimized by whatever browser(s) you're targeting. Expose canvas, audio and local storage as libraries that are general enough to fit your planned usage. Then you can write simple front-ends that translate your preferred languages to a neat and tidy intermediate language. You could even write your compiler in Javascript, but I guess it's not necessary, since you could just bootstrap it...

      --
      Use of the words "good", "bad" or "evil" is almost invariably the result of oversimplification.
    2. Re:... why? by Homburg · · Score: 1

      The point of this doesn't seem to be to actually right a NES emulator; there are loads already, after all. Rather, the point of writing the emulator here is to explain the steps in writing an emulator. JavaScript is a fairly clear language which quite a lot of people know, so it's a good choice to use to illustrate the process.

    3. Re:... why? by AstrumPreliator · · Score: 2, Insightful

      The same reason someone would write an interpreter or compiler for an esoteric programming language such as Brainfuck or Piet. Or make a homebrew computer. It may not be the most practical thing to do with your time, but it's fun and interesting. The only reason a geek needs to do something is, "I want to."

  8. Synthesis in real time? by tepples · · Score: 2, Informative

    Both sound and client-side data storage are features of HTML5.

    I've heard of the HTML5 <audio> element. But as I understand it, it's designed for playing pre-recorded audio, not audio synthesized in real time as would be necessary for an emulator. The only reference that the page linked from "sound" makes to synthesis is in the context of text-to-speech for a textual description track. Even if you generate .wav into a data: URI, I know of no way within this spec to link multiple data: URIs to play gaplessly.

    1. Re:Synthesis in real time? by BZ · · Score: 3, Informative

      Indeed. https://wiki.mozilla.org/Audio_Data_API#Writing_Audio and https://github.com/corbanbrook/dsp.js are closer to what's needed for realtime synthesis. Hopefully it will make its way to other browsers too.

    2. Re:Synthesis in real time? by Anonymous Coward · · Score: 1, Informative

      sound_all=sound1+sound2+...soundN
      That didn't seem too hard now, did it?
      Of course, this will concat the headers as well, which you will need to not generate at this time, generate them externally to the actual data, then concat that to the front. (and likewise for the footers if there are any for .wav, would hope so...)

      And since AUDIO has a timer that you can access (well, you can with video at least), just have 2, or, you know, 8 separate AUDIOs for sound.
      This way you can alternate between 2 of them for music. Play next track 1 second before the last one to make it "seamless".
      Play sound effects on the rest of them.

      Of course, the way BZ linked to below is much easier.

    3. Re:Synthesis in real time? by tepples · · Score: 1

      sound_all=sound1+sound2+...soundN
      That didn't seem too hard now, did it?

      By the time sound1 needs to be playing, soundN isn't even generated yet.

      And since AUDIO has a timer that you can access

      How high resolution is this timer? If my users are on IE 9, Chrome, Safari, or anything else other than Firefox or SeaMonkey, how can I be assured that once one <audio> finishes, the next <audio> will begin one sample later?

      This way you can alternate between 2 of them for music. Play next track 1 second before the last one to make it "seamless".
      Play sound effects on the rest of them.

      You don't understand how Game Boy sound works. The Game Boy APU has four tone generators: two for square waves at 1/8, 1/4, or 1/2 duty, one for pseudorandom noise, and one for a 32-sample wavetable. The program can change their pitch and duty and start a volume envelope at any time.

  9. Gapless playback of rapid-fire data URIs by tepples · · Score: 1

    I think the general solution is to use Javascript to generate the raw audio data, slap a WAV header on it, base 64 encode it into a data url and stick it into an audio tag set on autoplay.

    But how does a script tell the audio tag to start one 1/60-second data URI the moment the previous 1/60-second data URI ends? GNUALMAFUERTE's post below links to a page claiming that this is not possible: "there is no way to queue up chunks of synthesized audio for seamless playback."

  10. Permission denied by tepples · · Score: 2, Interesting

    You can write damn near anything in JavaScript if you really want to, but the better question is if you should.

    If your users have access to a web browser but lack the privileges to install a native client on machines that they use, then you have no choice but to write your application in a language that runs inside the web browser. This is often the case in break rooms, public libraries, and university computer labs, where the user isn't the owner, or with locked-down appliances, where even the owner of the device isn't an administrator.

    1. Re:Permission denied by evilviper · · Score: 2, Insightful

      If your users have access to a web browser but lack the privileges to install a native client on machines that they use, then you have no choice but to write your application in a language that runs inside the web browser.

      If your users have access to emacs, but lack a web browser... ...never mind.

      Web browsers are everywhere, because they are useful applications. They weren't written in Flash, or Javascript, or anything like that. That's part of the reason they are useful to begin with.

      I agree that there need to be web interfaces for many things, because, in a pinch, it might be necessary to work that way. But that's a long way from saying you should need an septuple-core CPU, a browser that hasn't been released yet, and a super-high-speed internet connection, to check your e-mail... Google maps is popular, but that's not to say it does anything that the old plain HTML Mapquest didn't do just as well before it came along (and on 100MHz CPUs over dial-up without trouble).

      That's the question, today. Do you need some massive web interface made of hacked up javascript, or do you just need to have a little app on the server that outputs plain old HTML? Yeah, if I can't navigate your site because you use drop-down boxes for all navigation, and omitted a "Go" button in favor of script because you don't like how the single extra button clashes with the design of the site, I say screw you. Unless I've got absolutely no other choice, NoScript and I are going elsewhere. When Slashdot eliminates the "Classic interface" option, I'll be leaving here, too. I use the web for the content, not to experiment with every random idiot's ideas about interface usability. Hell, anyone who has been on the web long enough will tell you what a nightmare it was when every site was laid out differently, before the world collectively standardized on the format everyone is familiar with today.

      Games? Developers are just be stupid by not putting it in a single EXE that can be run directly. Even a seriously locked down computer will let users download and run a file. And if you're on a ridiculously locked down system which doesn't allow even that... maybe you'll have to live without playing that one game on this computer you're obviously not supposed to be playing games on...

      --
      Slashdot gets worse every day... Pipedot: News for nerds, without the corporate slant
    2. Re:Permission denied by tepples · · Score: 3, Insightful

      Web browsers are everywhere, because they are useful applications. They weren't written in Flash, or Javascript, or anything like that. That's part of the reason they are useful to begin with.

      Unlike your application, the web browser has already been approved by the appliance maker or the PC administrator.

      Do you need some massive web interface made of hacked up javascript, or do you just need to have a little app on the server that outputs plain old HTML?

      On machines with an intermittent connection to the Internet, a massive JavaScript interface using a cache manifest and localStorage can be helpful.

      Games? Developers are just be stupid by not putting it in a single EXE that can be run directly.

      This would need the code and data combined into one file, much like a self-extracting archive. That could suffice for Windows, but Mac OS X and Linux can't run Windows EXEs without CrossOver Games or some other Wine variant. JavaScript runs on any platform with a modern browser.

      Even a seriously locked down computer will let users download and run a file.

      Not always. The administrator of a PC used by the public can set Software Restriction Policies to block execution of, for example, executables located inside %USERPROFILE% (the user's home directory).

      And if you're on a ridiculously locked down system which doesn't allow even that... maybe you'll have to live without playing that one game on this computer you're obviously not supposed to be playing games on...

      Video game consoles and other set-top appliances typically can't run native binaries that are not digitally signed by the manufacturer of the appliance, but some can run web pages using JavaScript and/or SWFs using ActionScript. Yet the majority of home users routinely buy consoles instead of home theater PCs.

    3. Re:Permission denied by xtracto · · Score: 1

      If your users have access to a web browser but lack the privileges to install a native client on machines that they use, then you have no choice but to write your application in a language that runs inside the web browser

      You might want to learn about Portable Apps.

      --
      Ubuntu is an African word meaning 'I can't configure Debian'
    4. Re:Permission denied by tepples · · Score: 1

      You might want to learn about Portable Apps.

      I'm aware of them; they're Windows applications packaged to run on removable media. But these aren't very useful if your application is for a different operating system, or if your administrator has established a Software Restriction Policy against executing binaries on removable media or in the user's home directory, or against executing any binary that the administrator has not signed. For details see my reply to evilviper.

    5. Re:Permission denied by DaVince21 · · Score: 1

      Yeah, if I can't navigate your site because you use drop-down boxes for all navigation, and omitted a "Go" button in favor of script because you don't like how the single extra button clashes with the design of the site, I say screw you.

      Well, that's a design issue rather than using scripts or not. A common design rule is that scripts should always be supplemental and not actually make it impossible for people without scripts on from navigating somewhere or access some information on your site. Instead, if they have scripting turned on, it should enhance the user experience, make it easier, etc.

      Exceptions are on larger web apps where you just can't get around using JS. But for regular websites, the usage of JS (not to mention technologies like Flash) should be really carefully considered.

      --
      I am not devoid of humor.
  11. Ode to JavaScript by CobaltBlueDW · · Score: 4, Insightful

    JavaScript is truly a horrifyingly discussing,
    intrinsically retched,
    soul darkening, succubus from the abysmal depths of conceivable depravity.

    To know its stench
    is to know the crippling limitations of our future.
    To recognize its sloven decadence
    and remain indifferent
    is to burn the righteous.

    No faith,
    however moving and spectacular,
    could light a path of its continuation.
    No argument,
    however complex and equivocated,
    could elevate such a encumbering and wearisome burden.

    There is no failure so inadequate,
    or stagnation so bereft of utility
    as that of JavaScript.

    Thankyou.

    1. Re:Ode to JavaScript by kwerle · · Score: 1

      You, sir, are brilliant.

    2. Re:Ode to JavaScript by Anonymous Coward · · Score: 0

      You've forgotten about Adobe Flash *already*?!?

    3. Re:Ode to JavaScript by Anonymous Coward · · Score: 0

      Emotions have no place in evaluating a language. Maybe 5 years ago you were justified in this unsupported hatred; things have changed. "Poetry" isn't worth shit in this field.

    4. Re:Ode to JavaScript by mujadaddy · · Score: 1

      "discussing"? "retched"?

      "brilliant"?

      --
      Populus vult decipi, ergo decipiatur...
      "Force shits upon Reason's back." - Poor Richard's Almanac
    5. Re:Ode to JavaScript by Anonymous Coward · · Score: 1, Funny

      It's the geek form of religion.

    6. Re:Ode to JavaScript by Anonymous Coward · · Score: 1, Insightful

      That's what happens when you cut and paste your comments from other websites. You bring their errors with you.

      How slovenly and lazy

    7. Re:Ode to JavaScript by Anonymous Coward · · Score: 0

      Those are errors common to people who have English as a second language.

      Useful criticism would start with the content...

    8. Re:Ode to JavaScript by CobaltBlueDW · · Score: 1

      I take it as a compliment that you presumed I copied this from someone else and took it upon yourself to google it. However, if you were thorough with your investigation, you may have noticed that the poster on that blog has the EXACT same user name as myself.

      On a related note, I find it amusing how many people took my post seriously as if it wasn't completely tongue-in-cheek. Granted, I do think JavaScript is probably the 3rd or 4th worst language I've ever used, but I wouldn't have suspected anyone would have thought that that "poem" was anyone's idea of a proper critique of JavaScript's follies.

      P.S. Sorry about the spelling error, but I can't edit my previous post, so...

  12. ... Impressive. by Artful+Codger · · Score: 1

    I'm sort of a JS hater, but that IS impressive.

    If I was to be really cynical, I'd say that this proves that any ole programming language, if it survives long enough to be worked-on and added-to for a couple of decades, and given fast enough processing, can evolve. Maybe.

    (Also it's a great breakdown/tutorial of the game programming steps)

    --

    ... plans that either come to naught, or half a page of scribbled lines...
    1. Re:... Impressive. by Sycraft-fu · · Score: 2, Insightful

      That actually is the case. If you look in to it, you find that fully functional Gameboy emulators, with sound and everything, ran well on 486-Pentium class computers. They were written in C/C++ of course, often with some assembly thrown in. The Gameboy is not challenging to emulate since it is low resolution, gray scale (with very few steps), has a small memory, slow simple CPU, and so on.

      All this really demonstrates is that even if your language sucks and runs on a slow platform (webbrowser's interpreters don't count as fast) that eventually there's enough CPU power to throw at it. It isn't really a testament to Javascript, it is a testament to modern CPUs.

  13. oblig dilbert (*today's* dilbert as it happens) by Anonymous Coward · · Score: 1, Interesting
  14. Vic20 in Javascript by Anonymous Coward · · Score: 4, Informative

    And here's a Vic20 emulator in Javascript HTML5
    http://www.mdawson.net/vic20beta/vic20.php

    1. Re:Vic20 in Javascript by Anonymous Coward · · Score: 0

      And here's a Vic20 emulator in Javascript HTML5

      Now with actual link!

  15. Compile the JavaScript by Anonymous Coward · · Score: 4, Informative

    Saying that you shouldn't write this in JavaScript because of the limitations of JavaScript in web browsers is like saying people shouldn't write Apps in Java because Applets are limited. It's not JavaScript that is the problem per se, but the limitations of the Interpreter. If you want to write something like this in JavaScript, you should consider compiling the JavaScript instead.

    Using the Unity Framework ( http://unity3d.com ), you could write the emulator in JavaScript, compile it, and have a cross platform emulator that would work on Mac, PC, Wii, Iphone, Android, and PS3 with hardware accelerated 3d, support for sound, etc. Something like 20-25 of the top 100 Iphone Apps were made using Unity, and it is a pretty good platform for making 3d games.

    1. Re:Compile the JavaScript by owlstead · · Score: 1

      That is not entirely true of course, some languages are a better match for writing emulators in than other languages.

      For instance, Java does not have some common shift operations on byte and short's. It also does not have any unsigned data types, which makes it even harder.

      JavaScript of course does not even have a byte or a short, which add all kinds of "fun" for the programmer of emulators.

    2. Re:Compile the JavaScript by DaVince21 · · Score: 1

      Isn't JS JIT-compiled already? That's pretty damn close to native speeds, if I have to believe browser developers.

      --
      I am not devoid of humor.
  16. -1 Troll by rubypossum · · Score: 2

    I kind of like Javascript, I have written and maintained HUGE applications in many languages. To be honest, the worst was Java, not Javascript. Javascript is light, easy to understand, highly extensible (see JQuery or mootools) and once something is written to the standards it usually runs EVERYWHERE there is a reasonably modern web browser. Something which is not true of Flash or Java. Just look at how many people use it and write in it! Talk about a successful language! I'm fluent in Ruby, Python, Perl, Java and UNIX/Linux standard C. I've used C++, C#, AS3 and even Scheme on various professional jobs before. And I think I like Ruby best, but not by much. Javascript has a certain simple elegance that even Ruby doesn't have. It's what Java could have been. If Gosling hadn't been so strict type happy.

    --
    I have a theory that the truth is never told during the nine-to-five hours. - Hunter S. Thompson
  17. peaking my cpu ? by cfriedt · · Score: 1

    Is it just me, or does this GB emulator make your CPU peak as well? I've got some fairly older hardware.

    Also, rendering on Chrome / Linux is pretty bad, there are lots of artifacts.

    1. Re:peaking my cpu ? by owlstead · · Score: 1

      Note that JavaScript is not the most obvious language to write an emulator in. Java byte code is already a lot better, but for maximum speed you really want to go for C/C++ or a comparable language.

      JavaScript is much slower than Java and C/C++, and this is even more so if you have to do a lot of small mathematical operations on things like bytes and shorts. Take a look at cryptographic operations performed in JavaScript and compare than with other non-interpreted languages.

      Now the latest interpreters made a *lot* of progress on this particular field, and computers have become frightfully fast, but simulating a CPU will still be kind of tough, even if it is just a Z80 with a very low clock speed.

  18. a turd that won't flash by Anonymous Coward · · Score: 0

    Looking at this game I'm not sure that Flash has that much to worry about.

    It's becoming rather surreal the way html5s followers keep hopefully offering up stinkers like this.

    I can imagine that in 2019 instead of flying cars we'll have an html5 page showing us (look mum) how simple physics are possible! but no sound yet unfortunately, and sorry about the cpu usage guys.

    Give it up already.