anqou
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
1
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
--- breaks: false tags: public-tech --- # AQBoy: Yet Another Game Boy Emulator 開発記 Go言語を使ってゲームボーイ(GB)のエミュレータ **AQBoy**を書いて、[Tobu Tobu Girl](https://tangramgames.dk/tobutobugirl/)を動かしました。 実装はいつも通り[GitHub](https://github.com/ushitora-anqou/aqboy)に上がっています。 <center> <iframe width="560" height="315" src="https://www.youtube.com/embed/Fig8WXiYEf4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </center> ## きっかけ 昨年末のアドベントカレンダーで、linoscopeさんが書いた「[OCaml でゲームボーイエミュレータを書いた話](https://qiita.com/linoscope/items/244d931aaae07df2c27e)」を読んだのが直接のきっかけです。 ちょうど年末の大掃除で、昔遊んでいた[ポケットモンスター ピカチュウ](https://www.nintendo.co.jp/n02/dmg/apsj/index.html)が実家から出てきたので、 これを動かすべくGBエミュレータの開発を始めました。 <figure> <center> <img src="https://i.imgur.com/ubLhn9o.jpg" width="500" /> <figcaption>実家の大掃除で見つけたゲームボーイアドバンスとゲームカセットと周辺機器。</figcaption> </center> </figure> ## 開発の流れ 先人に習って、まず ["The Ultimate Game Boy Talk"](https://www.youtube.com/watch?v=HyzD8pNlpwI) を見て、設計の検討をつけます。 この講演は1時間でGBの仕組みについてあらかた話してしまうというもので、 トークそのものもユーモアにとんでいて面白いのでおすすめです。特にCPUアーキテクチャの くだりが秀逸です。 <center> <iframe width="560" height="315" src="https://www.youtube.com/embed/HyzD8pNlpwI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </center> この動画だけではエミュレータを書くには不足なので、続いて詳細な資料にあたります。 - [Pan Docs](https://gbdev.io/pandocs/):GBに関する技術的詳細がまとめられています。基本的にはこれを読みながらエミュレータを書くことになります。ちなみに元々は[Wiki](https://gbdev.gg8.se/wiki/articles/Pan_Docs)でしたが、移行したようです。 - [Gameboy CPU (LR35902) instruction set](https://www.pastraiser.com/cpu/gameboy/gameboy_opcodes.html):オペコード一覧表。CPUの実装はここを見ながらすることになりますが、たまに間違っています。 - [Game Boy Programming Manual](https://web.archive.org/web/20150513170240/http://www.chrisantonellis.com:80/files/gameboy/gb-programming-manual.pdf):Nintendo in Americaが出した(?)公式の(?)仕様書。細かい処理などを確認するときに便利です。 これらを見ながら、まずCPUエミュレーションの部分から作り始めます。 基本的には、ROMから次に実行する命令のopcodeを読み込み、 その値をもとに巨大`switch`文で分岐して対応する命令を実行するだけでうまく動きます。 以前、[Cコンパイラ](https://github.com/ushitora-anqou/aqcc)や[プロセッサ](https://anqou.net/poc/2019/05/27/post-2920/)を書いた経験が幸いして、この部分ではそれほど苦労しませんでした。 ただ、現代のCPUではあまり見ない命令(DAA命令など)もあって、 そのような命令は実装に手間取りました。 巨大`switch`文を書く過程で、 Goでは`switch`の各`case`に`break`が必要ない(フォールスルーさせたいときは `fallthrough`キーワードを使う)といった仕様を知って驚いたりもしました。 <figure> <center> <img src="https://i.imgur.com/yrXx5dA.png" width="400" /> <figcaption>CPUエミュレーションの開発風景。各実行命令ごとにレジスタの値を出力させている。</figcaption> </center> </figure> CPUエミュレーションの実装には、以下が役に立ちました。 - [BGB GameBoy Emulator](https://bgb.bircd.org/):有名なGBエミュレータの一つで、デバッガがかなり充実しています。自作エミュレータの挙動が怪しいときはBGBでの挙動を参考にしました。 - [Blargg's test roms](https://gbdev.gg8.se/files/roms/blargg-gb-tests/):CPU emulationが正しく実装されているかを確認するためのROMで、`cpu_instrs`と`instr_timing`が通ることを確認しました。まだこの段階では画面表示が無いので、実行したあとのレジスタの値がエミュレータと一致するか、そもそも実行が最後まで走り切るかなどを確認しました。 - [GameBoy - Help With DAA instruction - nesdev.org](https://forums.nesdev.org/viewtopic.php?t=15944):GBにはDAAという特殊な命令があり、2進化10進数を扱うことを可能にしています。この命令の挙動はPan Docsにもあまり情報が無いのですが、このnesdev.orgの議論では、DAA命令をどのように実装するかについて記載があります。 CPUの処理中には、ROM・RAMとの入出力や、Memory-Mapped IO(MMIO)の実装のために、 Memory Management Unit(MMU)が必要になります。 そこでGoのpackage機能を使ってCPUとMMUでパッケージを分けて構成したいところですが、 CPUからMMUを参照し、MMUからCPUを参照すると、パッケージ間で循環参照に陥ってしまって、 Goプログラムがコンパイルできなくなってしまいます。そこでAQBoyでは、 CPUやMMUのインタフェースだけを保持するようなBusという新しいパッケージを作成し、 このパッケージを間に挟んで各パッケージを参照することによって解決しました。 続いてPixel Processing Unit(PPU)を作ります。PPUは画面表示を司っている部分で、 走査線(scanline)が画面の上部から下部に進みながら描画を行います。 実際の画面表示には[veandco/go-sdl2](https://github.com/veandco/go-sdl2)を使用しました。 画面が出るようになると、上記の`cpu_instrs`や`instr_timing`がどの命令が正しく実装されていないかが分かるので便利です。 <figure> <center> <img src="https://i.imgur.com/uEP9N5H.png" width="200" /> <img src="https://i.imgur.com/ybwIIiL.png" width="200" /> <img src="https://i.imgur.com/TWDJ5LT.png" width="200" /> <figcaption><code>cpu_instrs</code>や<code>instr_timing</code>での画面表示例。<code>Passed</code>はテストがパスしたことを意味し、パスしないと何が間違っているのかを表示してくれる。</figcaption> </center> </figure> PPUの詳細な動作確認には[mattcurrie/dmg-acid2](https://github.com/mattcurrie/dmg-acid2)を用いました。 このテスト用ROMは顔の表示によってPPUの挙動が正しいかどうかを判断できるように構成されており、 例えば鼻が欠けていればobject paletteの実装が間違っていることが分かります。 <figure> <center> <img src="https://i.imgur.com/vZlmIWl.png" width="200" /> <img src="https://i.imgur.com/kxtZIcG.png" width="200" /> <img src="https://i.imgur.com/9DcD1fA.png" width="200" /> <figcaption>dmg-acid2を用いたPPU開発の経過。左がPPU開発初期のもので、一番右はPPUの全ての要素を実装したあとのもの。</figcaption> </center> </figure> このあたりで、[Tobu Tobu Girl](https://tangramgames.dk/tobutobugirl/)という GBゲームのROMを読み込ませてデバッグを始めました。いくつかバグを潰すと、 次のように画面表示が比較的まともに行われるようになりました。 <figure> <center> <img src="https://i.imgur.com/hKXR6WA.gif" width="400" /> <figcaption>Tobu Tobu Girlが動作。</figcaption> </center> </figure> ゲームで遊ぶためにJoypadを実装します。GBのJoypadは単純で、 A, B, Start, Select, Up, Right, Down, Leftを適当なキーに割り当てて 入力を検知した上で、Pan Docsに書かれている通りにMMIOに追加すると動作します。 ちなみにJoypadのデバッグのためにTobu Tobu Girlで遊んでみるとむちゃくちゃ難しくて (あるいは私の操作が下手過ぎて)、いまだに一面をクリアできていません。 <figure> <center> <img src="https://i.imgur.com/13UtpyA.gif" width="400" /> <figcaption>実装したJoypadを使ってTobu Tobu Girlで遊ぶも、一面を全くクリアできない鮟鱇。</figcaption> </center> </figure> 最後に、Audio Processing Unit(APU)を作り音を出します。 The Ultimate TalkやPan DocsにはGBのAPUの構造について詳細な説明がありますが、 エミュレータを開発する上で一番問題になるのは、これをゲームエンジン(私の場合はSDL2)と どのように接続するかという部分で、ここについてはThe Ultimate Talk・Pan Docsのいずれも 示唆を与えてくれません。 このあたりはGBエミュレータ自作界隈でも知られた難関ポイントのようで、過去の個人作GBエミュレータでもAPUが搭載されていないものが多くあります。 今回の実装では、2021年3月にNight Shadeさんが公開した [Game Boy Sound Emulation | NightShade's Blog](https://nightshade256.github.io/2021/03/27/gb-sound-emulation.html) という記事を参考にしました。このサイトではGBのAPUの構造と、それをエミュレーションするための疑似コードが掲載されており、そのままコードに書き起こすことができます。 さらに、APUとゲームエンジンとを接続する方法についても説明があり、参考になりました。 最終的に、冒頭に貼ったようなエミュレータが完成しました。 <center> <iframe width="560" height="315" src="https://www.youtube.com/embed/Fig8WXiYEf4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </center> ## 参考にした実装 GBエミュレータの開発は下記のような様々な方のコードを参考にしました。 - [linoscope/CAMLBOY](https://github.com/linoscope/CAMLBOY) - linoscopeさんのOCamlでの実装。 - `Bus`で各コンポーネントをまとめるデザインはこの実装を参考にしました。OCamlではファンクタがこの構造にうまくハマっています。 - [keichi/gbr](https://github.com/keichi/gbr) - Keichi TakahashiさんのRustでの実装。 - 対応する記事である「[ゲームボーイのエミュレータを自作した話](https://keichi.dev/post/write-yourself-a-game-boy-emulator/)」も参考にしました。特にBlargg's test romsのうちcpu_instrsとinstr_timingをパスできるようにするという方針を参考にしました。 ## やり残したこと linoscopeさんの「[OCaml でゲームボーイエミュレータを書いた話](https://qiita.com/linoscope/items/244d931aaae07df2c27e)」では、 json_of_ocamlを使用してOCamlをWASMに変換し、ブラウザ上でGBエミュレータを動作させることに成功していました。 AQBoyでも、[hajimehoshi/ebiten](https://github.com/hajimehoshi/ebiten)を使用することでブラウザで動作させることができるはずなのですが、この記事の執筆時点ではまだ成功していません。 一応、Ebitenへの移植はすでに成功していて、WASMへの変換もできているのですが、 それをブラウザで動作させようとするとFPSが8程度しか出ないような状況です。 いろいろと調べた限りでは単純にAQBoyの動作が非効率的であるためのようなので、 プロファイリングを真面目に行えば動作する可能性があるのかなと思っています。 それから、冒頭で述べたように元々はポケットモンスター ピカチュウを動かすべく AQBoyの開発を始めたのですが、残念ながらまだ動かせていません。 これは理由がはっきりしていて、カセットからROMデータを吸い出すための ROM吸出し器が思ったよりも高価だったためです(Amazonで7,000円とか)。 知り合いに相談したところ自作を勧められましたが、 電子工作をほとんどやったことがなく家には半田ごても無いので、 自作するにしても色々と準備してからになるかなと思っています。 ## ところで Twitterのタイムラインに**ポケットモンスター アルセウス**のプレイ動画とか漫画とかが めっちゃ流れてきておもしろそうだなーって言っています。Nintendo Switchほしい。 <center> <iframe src="https://mstdn.anqou.net/@anqou/107752082600778551/embed" class="mastodon-embed" style="max-width: 100%; border: 0" width="400" height="230" allowfullscreen="allowfullscreen"></iframe> </center> <script src="https://mstdn.anqou.net/embed.js" async="async"></script> <hr /> ## GBエミュレータ開発こぼれ話 本文に入れられなかった話をランダムにいくつか。本文に出てこない話で、Pan Docsとかを見るとすぐに分かる内容を説明せずに書いています。 - GBに関わる開発の話(エミュレータだけではなくゲーム開発とか)は[Awesome Game Boy Development](https://gbdev.io/list.html#introduction)にある。 - [opcode表](https://www.pastraiser.com/cpu/gameboy/gameboy_opcodes.html)の間違いについて、自分が気づいたもの: - 0xe2, 0xf2のopcode sizeは1 byte - BITの(HL)のサイクルは16ではなくて12 - ZNHC flagが間違っている命令があったはず(どれか忘れた……) - `F`レジスタを書き換える場合(`POP AF`とか)、下位4bitが常に0であることに注意。 - `DAA`命令は2進化10進を普通に`ADD`や`SUB`で加算・減算した後の値を2進化10進に戻すための命令。例えば`0x99 + 0x99 -> 0x98` (i.e., $99 + 99 = 100 + 98$)を計算したいときに、`0x99 + 0x99 = 0x32`を`ADD`で計算したあとに`DAA`命令を使う。この場合`DAA`命令は(half-)carry flagを見ながらこれを0x98に補正するために0x66を足す。本文にも貼った[このスレッド](https://forums.nesdev.org/viewtopic.php?t=15944)には`DAA`命令を実装するための疑似コードもある。 - `JP (HL)`命令は`(HL)`ではなく`HL`に飛ぶ - PPUのH/W実装はFIFOバッファを用意する複雑なものだが、software emulationの場合はOAM Searchが終わった段階で一行分全て描画してしまえばよい。VRAMにアクセスできないという制約があるので、これで動作は一貫する。 - 通常のinput, update, drawというループに合わせてemulationを行うために、updateは画面描画が一回終わるまでCPU emulationを実行すると良い。具体的には$(456\times 154)$サイクルCPUを実行する。 - Objectのtransparentなpixelはcolor paletteのindexが0。colorが0ではない。 - IME=0の場合でもhalt状態が解除される場合がある。割り込みのrequest flagとenable flagが立てばHALTが終わる。ただし割り込みハンドラは動かないで、HALT命令の次のPCから実行が再開する。 - ROMに書き込みの命令を送ると、それがMBCへの通信として扱われてROM/RAMのbank switchができる。 - go-sdl2でaudioを扱う際には、bufferに波形データを詰めるようなcallback関数を登録する必要がある。このcallback関数にuserdataを渡す場合、Cgoの「Goのポインタを指すGoのポインタを関数の引数に渡してはならない」というルールに抵触しうるが、[mattn/go-pointer](https://github.com/mattn/go-pointer)を利用することで回避できる。詳細は[mattnさんの記事](https://dev.to/mattn/call-go-function-from-c-function-1n3)を参照のこと。 - PPUがdisableされたときはPPUの内部バッファの更新をしてはいけないし、enableされたときにはlyを0に戻さなければならない。このあたりの挙動は[CAMLBOY](https://github.com/linoscope/CAMLBOY/blob/ea0ac8e68c9aea216ef44fb997251f43070867b1/lib/gpu/gpu.ml#L255)が参考になる。ただしAQBoyはここまで詳細に実装していない。 - Ebitenのオーディオ処理は内部バッファがsampling rateの半分のサイズあるので、先頭から0.5秒くらい遅延してしまう。回避策は見つけられていない。 - Tobu Tobu Girlの一面は未だにクリアできていない。知り合いにライブ配信をしながらTobu Tobu Girlの一面を30分プレイしたが、[かなり良いところまで行くも](https://youtu.be/5wdwzKialPw?t=374)結局クリアできなかった。

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully