Slashdot is powered by your submissions, so send in your scoop

 



Forgot your password?
typodupeerror
×
Emulation (Games) Nintendo Programming Games

A JavaScript Gameboy Emulator, Detailed In 8 Parts 62

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."
This discussion has been archived. No new comments can be posted.

A JavaScript Gameboy Emulator, Detailed In 8 Parts

Comments Filter:
  • by Anonymous Coward on Friday November 05, 2010 @09:28PM (#34144348)

    ...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!"

    • Re: (Score:3, Informative)

      by Anonymous Coward

      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/ [benfirshman.com]

      Here are some other JavaScript audio demos:

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

      • Re: (Score:3, 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.
        • Re: (Score:1, Informative)

          by Anonymous Coward

          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.

        • Re: (Score:1, Redundant)

          by Tharsman ( 1364603 )
          This.
    • by pavon ( 30274 ) on Friday November 05, 2010 @09:41PM (#34144444)

      Both sound [w3.org] and client-side data storage [w3.org] are features of HTML5.

      • Both sound [w3.org] and client-side data storage [w3.org] 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.

        • by BZ ( 40346 ) on Friday November 05, 2010 @10:50PM (#34144846)

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

        • Re: (Score:1, Informative)

          by Anonymous Coward

          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 mus

          • by tepples ( 727027 )

            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

  • I've always been curious about the inner workings of a console emulator, and this was very informative.
  • Javascript? (Score:3, Funny)

    by Tr3vin ( 1220548 ) on Friday November 05, 2010 @09:43PM (#34144452)
    Real men write their GB emulators in Minecraft.
    • Re: (Score:2, Funny)

      by Anonymous Coward
      No, *real* men write their emulators by arranging stones in the desert.
      • No, *real* men write their emulators by arranging grains of sand into brainfuck on the beach.
        • Re: (Score:2, Funny)

          by Anonymous Coward

          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 [xkcd.com]

          • Re: (Score:3, Funny)

            by RevWaldo ( 1186281 )
            Well, damn, now what am I gonna do with this infinitely long spool of magnetic tape?
            • by gmthor ( 1150907 )
              Oh cool. I've got one too. Together we could build a dual band computer. This hast to be way more powerful.
  • Sound? (Score:5, Interesting)

    by Mr. Sketch ( 111112 ) <`mister.sketch' `at' `gmail.com'> on Friday November 05, 2010 @09:44PM (#34144462)

    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 [cgarcade.com] about this while writing my NES emulator in flash [cgarcade.com].

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

    • 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.

      • 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 [slashdot.org] links to a page claiming that this is not possible: "there is no way to queue up chunks of synthesized audio for seamless playback."

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

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

    • Re:Sound? (Score:4, Informative)

      by BZ ( 40346 ) on Friday November 05, 2010 @10:40PM (#34144780)

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

      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.

      • Re: (Score:3, Interesting)

        by Mr. Sketch ( 111112 )

        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 [haxe.org] with the goal of doing a JS version at some point. However, at the time, only Chrome could even come close

  • ... why? (Score:5, Insightful)

    by Mongoose Disciple ( 722373 ) on Friday November 05, 2010 @10:22PM (#34144700)

    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.

    • Permission denied (Score:3, Interesting)

      by tepples ( 727027 )

      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.

      • Re: (Score:3, Insightful)

        by evilviper ( 135110 )

        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 n

        • by tepples ( 727027 ) <tepplesNO@SPAMgmail.com> on Saturday November 06, 2010 @10:11AM (#34146928) Homepage Journal

          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 [microsoft.com] 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.

        • Comment removed based on user account deletion
      • by xtracto ( 837672 )

        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 [portableapps.com].

        • by tepples ( 727027 )

          You might want to learn about Portable Apps [portableapps.com].

          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 [microsoft.com] 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 [slashdot.org].

    • 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...
    • by Homburg ( 213427 )

      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.

    • Re: (Score:3, 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."
  • Ode to JavaScript (Score:4, Insightful)

    by CobaltBlueDW ( 899284 ) on Friday November 05, 2010 @10:46PM (#34144818)

    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.

    • by kwerle ( 39371 )

      You, sir, are brilliant.

      • "discussing"? "retched"?

        "brilliant"?
        • Re: (Score:1, Insightful)

          by Anonymous Coward

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

          How slovenly and lazy

          • 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 woul

    • 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,
  • 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)

    • Re: (Score:3, Insightful)

      by Sycraft-fu ( 314770 )

      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

  • Vic20 in Javascript (Score:4, Informative)

    by Anonymous Coward on Saturday November 06, 2010 @12:34AM (#34145290)

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

  • by Anonymous Coward on Saturday November 06, 2010 @01:31AM (#34145426)

    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.

    • 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.

    • Comment removed based on user account deletion
  • 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.

    • 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

  • adultsikici [adultsikici.org] sikis izle [videosikisizle.com] turk porno [pornosuizle.tk] porno [liderporn.com] tarzanx [tarzanx.net] pornolar [pornolarin.net] amkamk

"If it ain't broke, don't fix it." - Bert Lantz

Working...