├── .gitignore
├── runtests
├── assets
└── graphics
│ └── gb_controls.png
├── Test.hx
├── include.xml
├── test.hxml
├── retrio
├── emu
│ └── gb
│ │ ├── MBC.hx
│ │ ├── ISoundGenerator.hx
│ │ ├── Interrupt.hx
│ │ ├── mbcs
│ │ ├── MBC2.hx
│ │ ├── MBC3.hx
│ │ └── MBC1.hx
│ │ ├── GBControllerButton.hx
│ │ ├── Settings.hx
│ │ ├── RTC.hx
│ │ ├── GBController.hx
│ │ ├── ROM.hx
│ │ ├── sound
│ │ ├── Channel3.hx
│ │ ├── Channel4.hx
│ │ └── Channel1.hx
│ │ ├── Palette.hx
│ │ ├── GB.hx
│ │ ├── Memory.hx
│ │ ├── Audio.hx
│ │ ├── Video.hx
│ │ └── CPU.hx
└── ui
│ └── openfl
│ ├── GBControls.hx
│ └── GBPlugin.hx
├── project.xml
├── Main.hx
├── tests.xml
├── README.md
└── LICENSE.md
/.gitignore:
--------------------------------------------------------------------------------
1 | *.ndll
2 | bin
3 | *.log
4 | .DS_Store
5 |
--------------------------------------------------------------------------------
/runtests:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | haxe test.hxml && test/Test | tee test.log && open test_results/*.png
3 |
--------------------------------------------------------------------------------
/assets/graphics/gb_controls.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/retrio/gb/HEAD/assets/graphics/gb_controls.png
--------------------------------------------------------------------------------
/Test.hx:
--------------------------------------------------------------------------------
1 | class Test extends retrio.Test
2 | {
3 | static function main()
4 | {
5 | retrio.Test.runTests(new retrio.emu.gb.GB());
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/include.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/test.hxml:
--------------------------------------------------------------------------------
1 | -main Test
2 |
3 | -cp src
4 | -D test
5 | -lib format
6 | -lib retrio-core
7 | -lib systools
8 |
9 |
10 | --each
11 |
12 | -cpp test
13 |
14 | --next
15 |
16 | -neko test.n
17 |
--------------------------------------------------------------------------------
/retrio/emu/gb/MBC.hx:
--------------------------------------------------------------------------------
1 | package retrio.emu.gb;
2 |
3 |
4 | class MBC
5 | {
6 | public var memory:Memory;
7 | public function new() {}
8 | public function write(addr:Int, val:Int):Void {}
9 | }
10 |
--------------------------------------------------------------------------------
/retrio/emu/gb/ISoundGenerator.hx:
--------------------------------------------------------------------------------
1 | package retrio.emu.gb;
2 |
3 |
4 | interface ISoundGenerator
5 | {
6 | public var enabled(get, never):Bool;
7 |
8 | public function play(rate:Float):Int;
9 | public function lengthClock():Void;
10 | public function reset():Void;
11 | }
12 |
--------------------------------------------------------------------------------
/retrio/emu/gb/Interrupt.hx:
--------------------------------------------------------------------------------
1 | package retrio.emu.gb;
2 |
3 | import haxe.ds.Vector;
4 |
5 |
6 | @:enum
7 | abstract Interrupt(Int) from Int to Int
8 | {
9 | var Vblank = 0;
10 | var LcdStat = 1;
11 | var Timer = 2;
12 | var Serial = 3;
13 | var Joypad = 4;
14 |
15 | public static var vectors:Vector = Vector.fromArrayCopy([
16 | 0x40, 0x48, 0x50, 0x58, 0x60
17 | ]);
18 | }
19 |
--------------------------------------------------------------------------------
/retrio/emu/gb/mbcs/MBC2.hx:
--------------------------------------------------------------------------------
1 | package retrio.emu.gb.mbcs;
2 |
3 |
4 | class MBC2 extends MBC implements IState
5 | {
6 | @:state var ramEnable:Bool = false;
7 | @:state var romSelect:Bool = true;
8 |
9 | override public function write(addr:Int, val:Int):Void
10 | {
11 | switch (addr & 0xF000)
12 | {
13 | case 0x0000, 0x1000:
14 | if (addr & 0x100 == 0)
15 | ramEnable = (val & 0xf) == 0xa;
16 | case 0x2000, 0x3000:
17 | if (addr & 0x100 == 0x100)
18 | memory.romBank = val & 0xf;
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/retrio/emu/gb/GBControllerButton.hx:
--------------------------------------------------------------------------------
1 | package retrio.emu.gb;
2 |
3 |
4 | @:enum
5 | abstract GBControllerButton(Int) from Int to Int
6 | {
7 | public static var buttons = [Up,Down,Left,Right,A,B,Select,Start];
8 | public static var buttonNames:Map = [
9 | Up => "Up",
10 | Down => "Down",
11 | Left => "Left",
12 | Right => "Right",
13 | A => "A",
14 | B => "B",
15 | Select => "Select",
16 | Start => "Start",
17 | ];
18 |
19 | var A = 0;
20 | var B = 1;
21 | var Select = 2;
22 | var Start = 3;
23 | var Right = 4;
24 | var Left = 5;
25 | var Up = 6;
26 | var Down = 7;
27 | }
28 |
--------------------------------------------------------------------------------
/retrio/emu/gb/mbcs/MBC3.hx:
--------------------------------------------------------------------------------
1 | package retrio.emu.gb.mbcs;
2 |
3 |
4 | class MBC3 extends MBC implements IState
5 | {
6 | @:state var ramEnable:Bool = false;
7 | @:state var romSelect:Bool = true;
8 |
9 | override public function write(addr:Int, val:Int):Void
10 | {
11 | switch (addr & 0xF000)
12 | {
13 | case 0x0000, 0x1000:
14 | ramEnable = (val & 0xf) == 0xa;
15 | case 0x2000, 0x3000:
16 | memory.romBank = val & 0x7f;
17 | if (memory.romBank == 0) memory.romBank = 1;
18 | case 0x4000, 0x5000:
19 | if (val >= 0x8 && val <= 0xc)
20 | {
21 | memory.rtc.register = val;
22 | }
23 | else
24 | {
25 | memory.rtc.register = 0;
26 | memory.ramBank = val & 0x3;
27 | }
28 | case 0x6000, 0x7000:
29 | memory.rtc.write(val);
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/retrio/emu/gb/Settings.hx:
--------------------------------------------------------------------------------
1 | package retrio.emu.gb;
2 |
3 | import retrio.config.Setting;
4 | import retrio.config.SettingCategory;
5 |
6 |
7 | @:enum
8 | abstract Settings(String) from String to String
9 | {
10 | var GBPalette = "gbpalette";
11 |
12 | var Ch1Volume = "ch1";
13 | var Ch2Volume = "ch2";
14 | var Ch3Volume = "ch3";
15 | var Ch4Volume = "ch4";
16 |
17 | public static var settings:Array = [
18 | {
19 | id: "gb", name: 'GB', settings: [
20 | new Setting(GBPalette, "Palette (GB)", Options([for (p in Palette.paletteInfo) p.name]), "default"),
21 | ]
22 | },
23 | {
24 | id: "gbaudio", name: 'GB Audio', settings: [
25 | new Setting(Ch1Volume, "Square 1", IntValue(0,100), 100),
26 | new Setting(Ch2Volume, "Square 2", IntValue(0,100), 100),
27 | new Setting(Ch3Volume, "Noise", IntValue(0,100), 100),
28 | new Setting(Ch4Volume, "Sample", IntValue(0,100), 100),
29 | ]
30 | },
31 | ];
32 | }
33 |
--------------------------------------------------------------------------------
/retrio/emu/gb/mbcs/MBC1.hx:
--------------------------------------------------------------------------------
1 | package retrio.emu.gb.mbcs;
2 |
3 |
4 | class MBC1 extends MBC implements IState
5 | {
6 | @:state var ramEnable:Bool = false;
7 | @:state var romSelect:Bool = true;
8 |
9 | override public function write(addr:Int, val:Int):Void
10 | {
11 | switch (addr & 0xF000)
12 | {
13 | case 0x0000, 0x1000:
14 | ramEnable = (val & 0xf) == 0xa;
15 | case 0x2000, 0x3000:
16 | var lower = val & 0x1f;
17 | if (lower == 0) lower = 1;
18 | memory.romBank = (memory.romBank & 0xe0) | lower;
19 | case 0x4000, 0x5000:
20 | if (romSelect)
21 | {
22 | memory.romBank = (memory.romBank & 0x1f) | ((val & 0x3) << 5);
23 | }
24 | else
25 | {
26 | memory.ramBank = val & 0x3;
27 | }
28 | case 0x6000, 0x7000:
29 | romSelect = (val & 1) == 0;
30 | if (romSelect)
31 | {
32 | memory.ramBank = 0;
33 | }
34 | else
35 | {
36 | memory.romBank &= 0x1f;
37 | }
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/retrio/emu/gb/RTC.hx:
--------------------------------------------------------------------------------
1 | package retrio.emu.gb;
2 |
3 |
4 | class RTC implements IState
5 | {
6 | @:state public var register:Int = 0; // RTC register selected or 0 if none
7 |
8 | @:state var rtcTime:Date = Date.now(); // latched RTC time
9 | @:state var rtcLatch:Bool = false;
10 |
11 | public function new() {}
12 |
13 | public inline function read():Int
14 | {
15 | switch (register)
16 | {
17 | case 0x8: return rtcTime.getSeconds();
18 | case 0x9: return rtcTime.getMinutes();
19 | case 0xa: return rtcTime.getHours();
20 | case 0xb:
21 | return Std.int((Date.now().getTime() - rtcTime.getTime()) / 86400) & 0xff;
22 | case 0xc:
23 | var dayCounter = Std.int((Date.now().getTime() - rtcTime.getTime()) / 86400);
24 | return ((dayCounter >> 8) & 1) | (dayCounter > 511 ? 0x80 : 0);
25 | default: return 0xff;
26 | }
27 | }
28 |
29 | public inline function write(value:Int):Void
30 | {
31 | if (rtcLatch)
32 | {
33 | if (value == 1)
34 | {
35 | rtcTime = Date.now();
36 | }
37 | else rtcLatch = false;
38 | }
39 | else
40 | {
41 | rtcLatch = value == 0;
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/retrio/emu/gb/GBController.hx:
--------------------------------------------------------------------------------
1 | package retrio.emu.gb;
2 |
3 |
4 | class GBController
5 | {
6 | public var controller(default, set):IController;
7 | function set_controller(c:IController)
8 | {
9 | if (c != null) c.inputHandler = this.handleInput;
10 | return controller = c;
11 | }
12 |
13 | public var directionsEnabled:Bool = false;
14 | public var buttonsEnabled:Bool = false;
15 | public var changed:Bool = false;
16 |
17 | public function new() {}
18 |
19 | inline function pressed(btn:Int)
20 | {
21 | return controller == null ? false : controller.pressed(btn);
22 | }
23 |
24 | public inline function buttons()
25 | {
26 | return
27 | (directionsEnabled ?
28 | ((pressed(GBControllerButton.Right) ? 0 : 0x1) |
29 | (pressed(GBControllerButton.Left) ? 0 : 0x2) |
30 | (pressed(GBControllerButton.Up) ? 0 : 0x4) |
31 | (pressed(GBControllerButton.Down) ? 0 : 0x8))
32 | : 0x1f) &
33 | (buttonsEnabled ?
34 | ((pressed(GBControllerButton.A) ? 0 : 0x1) |
35 | (pressed(GBControllerButton.B) ? 0 : 0x2) |
36 | (pressed(GBControllerButton.Select) ? 0 : 0x4) |
37 | (pressed(GBControllerButton.Start) ? 0 : 0x8))
38 | : 0x2f);
39 | }
40 |
41 | function handleInput(e:Dynamic)
42 | {
43 | changed = true;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/Main.hx:
--------------------------------------------------------------------------------
1 | import retrio.io.FileWrapper;
2 | import retrio.ui.openfl.GBPlugin;
3 | import retrio.ui.openfl.Shell;
4 | import retrio.ui.openfl.controllers.KeyboardController;
5 | import retrio.emu.gb.GBControllerButton;
6 |
7 |
8 | class Main extends retrio.ui.openfl.Shell
9 | {
10 | function new()
11 | {
12 | super(retrio.io.IO.defaultIO);
13 |
14 | #if (cpp && profile)
15 | cpp.vm.Profiler.start();
16 | }
17 |
18 | var _profiling:Bool = true;
19 | var _f = 0;
20 | override public function update(e:Dynamic)
21 | {
22 | super.update(e);
23 |
24 | if (_profiling)
25 | {
26 | _f++;
27 | trace(_f);
28 | if (_f >= 60*15)
29 | {
30 | trace("DONE");
31 | cpp.vm.Profiler.stop();
32 | _profiling = false;
33 | }
34 | }
35 | #end
36 | }
37 |
38 | static function main()
39 | {
40 | var m = new Main();
41 | }
42 |
43 | override function onStage(e:Dynamic)
44 | {
45 | super.onStage(e);
46 |
47 | KeyboardController.init();
48 | loadPlugin("gb");
49 |
50 | if (plugin.controllers[0] == null)
51 | {
52 | var controller = new KeyboardController();
53 | var keyDefaults = retrio.ui.openfl.GBControls.defaultBindings[KeyboardController.name];
54 | for (btn in keyDefaults.keys())
55 | controller.define(keyDefaults[btn], btn);
56 | addController(controller, 0);
57 | }
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/retrio/ui/openfl/GBControls.hx:
--------------------------------------------------------------------------------
1 | package retrio.ui.openfl;
2 |
3 | import retrio.config.SettingCategory;
4 | import retrio.config.CustomSetting;
5 | import retrio.emu.gb.GBControllerButton;
6 | import retrio.ui.haxeui.ControllerSettingsPage;
7 | import retrio.ui.openfl.controllers.*;
8 |
9 |
10 | class GBControls
11 | {
12 | public static var controllerImg:String = "graphics/gb_controls.png";
13 |
14 | // String because Class can't be used as a map key
15 | public static var defaultBindings:Map> = [
16 | #if (flash || desktop)
17 | KeyboardController.name => [
18 | GBControllerButton.Up => 87,
19 | GBControllerButton.Down => 83,
20 | GBControllerButton.Left => 65,
21 | GBControllerButton.Right => 68,
22 | GBControllerButton.A => 76,
23 | GBControllerButton.B => 75,
24 | GBControllerButton.Select => 9,
25 | GBControllerButton.Start => 13,
26 | ],
27 | #end
28 | ];
29 |
30 | public static function settings(plugin:GBPlugin):Array
31 | {
32 | return [
33 | {id: "controls", name: "Controls", custom: new CustomSetting({
34 | render:ControllerSettingsPage.render.bind(
35 | plugin,
36 | controllerImg,
37 | GBControllerButton.buttons,
38 | GBControllerButton.buttonNames,
39 | ControllerInfo.controllerTypes
40 | ),
41 | save:ControllerSettingsPage.save.bind(plugin),
42 | serialize:ControllerSettingsPage.serialize.bind(plugin),
43 | unserialize:ControllerSettingsPage.unserialize.bind(plugin, ControllerInfo.controllerTypes),
44 | })},
45 | ];
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/tests.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Cross-platform Game Boy emulator.
2 |
3 | This is a work in progress; see the issues page for known issues.
4 |
5 |
6 | Installation
7 | ------------
8 |
9 | To build, you'll need to install the Retrio core library:
10 |
11 | git clone https://github.com/retrio/core
12 | haxelib dev retrio-core core
13 |
14 | Other dependencies:
15 |
16 | * OpenFL
17 | * systools
18 |
19 | Once retrio-core is installed, run `openfl test flash` to start the emulator.
20 |
21 |
22 | Tests
23 | -----
24 |
25 | Retrio emulators include automated unit tests utilizing special testing ROMs.
26 | These can be executed with `./runtests`. Each test will run a specific test ROM,
27 | comparing a hash of the screen contents with what the screen should look like on
28 | success, until the screen stops changing or the success state is reached.
29 |
30 | To add new tests, add the ROM to the assets/roms/test directory and add an entry
31 | in tests.xml. Run the test suite; because your new test doesn't have a success
32 | hash yet, its status will be inconclusive. Check the image that is generated in
33 | test_results for that test and, if it was successful, copy and paste the hash
34 | for your test from stdout into tests.xml.
35 |
36 |
37 | Copyright
38 | ---------
39 |
40 | Copyright 2015 Ben Morris.
41 |
42 | This program is free software: you can redistribute it and/or modify it under
43 | the terms of the GNU General Public License as published by the Free Software
44 | Foundation, either version 3 of the License, or (at your option) any later
45 | version.
46 |
47 | This program is distributed in the hope that it will be useful, but WITHOUT ANY
48 | WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
49 | PARTICULAR PURPOSE. See the GNU General Public License for more details.
50 |
51 | You should have received a copy of the GNU General Public License along with
52 | this program. If not, see .
53 |
--------------------------------------------------------------------------------
/retrio/emu/gb/ROM.hx:
--------------------------------------------------------------------------------
1 | package retrio.emu.gb;
2 |
3 | import haxe.ds.Vector;
4 | import retrio.io.FileWrapper;
5 |
6 |
7 | class ROM implements IState
8 | {
9 | @:state public var name:String;
10 | public var gbc:Bool;
11 | public var sgb:Bool;
12 | public var cartType:Int;
13 | public var japan:Bool;
14 | public var version:Int;
15 | public var checksum:Int;
16 | public var globalChecksum:Int;
17 | public var hasSram:Bool;
18 |
19 | @:state public var romSize:Int;
20 | @:state public var ramSize:Int;
21 | @:state public var romBankCount:Int;
22 | @:state public var ramBankCount:Int;
23 |
24 | public var data:FileWrapper;
25 | public var fixedRom:ByteString;
26 |
27 | public function new(file:FileWrapper)
28 | {
29 | // read fixed ROM bank
30 | data = file;
31 |
32 | fixedRom = new ByteString(0x4000);
33 | fixedRom.readFrom(data);
34 |
35 | name = "";
36 | for (i in 0x134 ... 0x144)
37 | {
38 | var c = fixedRom[i];
39 | if (c > 0) name += String.fromCharCode(c);
40 | }
41 |
42 | sgb = fixedRom.get(0x146) != 0;
43 |
44 | cartType = fixedRom[0x147];
45 | hasSram = switch(cartType)
46 | {
47 | case 0x03, 0x06, 0x09, 0x0d, 0x0f, 0x10, 0x13, 0x17,
48 | 0x1b, 0x1e, 0xff:
49 | true;
50 | default:
51 | false;
52 | }
53 |
54 | // read additional ROM banks
55 | var romSizeByte = fixedRom[0x148];
56 | if (romSizeByte < 8)
57 | {
58 | romSize = 0x8000 * Std.int(Math.pow(2, romSizeByte));
59 | romBankCount = Std.int(romSize / 0x4000);
60 | }
61 | else
62 | {
63 | switch(romSizeByte)
64 | {
65 | case 0x52:
66 | romBankCount = 72;
67 | case 0x53:
68 | romBankCount = 80;
69 | case 0x54:
70 | romBankCount = 96;
71 | default:
72 | throw "Unrecognized rom size byte: " + StringTools.hex(romSizeByte);
73 | }
74 | romSize = romBankCount * 0x4000;
75 | }
76 |
77 | var ramSizeByte = fixedRom[0x149];
78 | ramSize = switch(ramSizeByte)
79 | {
80 | case 1: 0x2000;
81 | case 2: 0x4000;
82 | case 3: 0x8000;
83 | case 4: 0x20000;
84 | case 5: 0x10000;
85 | default: 0;
86 | }
87 | ramBankCount = Std.int(Math.max(Math.ceil(ramSize/0x2000), 1));
88 |
89 | japan = fixedRom[0x14a] == 0;
90 | version = fixedRom[0x14c];
91 | checksum = fixedRom[0x14d];
92 |
93 | globalChecksum = (fixedRom[0x14e] << 8) | fixedRom[0x14f];
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/retrio/emu/gb/sound/Channel3.hx:
--------------------------------------------------------------------------------
1 | package retrio.emu.gb.sound;
2 |
3 |
4 | class Channel3 implements ISoundGenerator implements IState
5 | {
6 | public var enabled(get, never):Bool;
7 | inline function get_enabled()
8 | {
9 | return (lengthCounter > 0 || repeat) && dac && canPlay && outputLevel > 0;
10 | }
11 | @:state public var canPlay:Bool = false;
12 | @:state public var dac:Bool = false;
13 |
14 | @:state public var repeat:Bool = true;
15 | @:state public var length(default, set):Int = 0;
16 | function set_length(l:Int)
17 | {
18 | lengthCounter = 0x100-l;
19 | return length = l;
20 | }
21 | @:state public var lengthCounter:Int = 0;
22 |
23 | @:state public var wavData:ByteString;
24 |
25 | @:state public var frequency(default, set):Int = 0;
26 | inline function set_frequency(f:Int)
27 | {
28 | cycleLengthNumerator = Std.int(Audio.NATIVE_SAMPLE_RATE/64) * (0x800 - f);
29 | cycleLengthDenominator = Std.int(0x10000/64);
30 | sampleLength = Std.int(cycleLengthNumerator / 32);
31 | return frequency = f;
32 | }
33 |
34 | @:state public var outputLevel:Int;
35 |
36 | @:state var cycleLengthNumerator:Int = 1;
37 | @:state var cycleLengthDenominator:Int = 1;
38 | @:state var cyclePos:Float = 0;
39 | @:state var sampleLength:Int = 1;
40 |
41 | public function new()
42 | {
43 | // memory region FF30-FF3F; contains 16 bytes, but each is made up of
44 | // two 4-bit samples
45 | wavData = new ByteString(32);
46 | }
47 |
48 | public inline function setOutput(value:Int)
49 | {
50 | outputLevel = (value & 0x60) >> 5;
51 | dac = value & 0xf8 > 0;
52 | }
53 |
54 | public inline function lengthClock():Void
55 | {
56 | if (lengthCounter > 0)
57 | {
58 | --lengthCounter;
59 | }
60 | }
61 |
62 | public function reset():Void
63 | {
64 | if (lengthCounter == 0) lengthCounter = 0x100;
65 | cyclePos = 0;
66 | }
67 |
68 | public inline function play(rate:Float):Int
69 | {
70 | var val = 0;
71 | cyclePos += (cycleLengthDenominator * Audio.NATIVE_SAMPLE_RATIO) * rate;
72 | if (cyclePos >= cycleLengthNumerator) cyclePos -= cycleLengthNumerator;
73 |
74 | if (enabled)
75 | {
76 | var val1 = wavData[Math.floor(cyclePos / sampleLength) & 0x1f];
77 | var val2 = wavData[Math.ceil(cyclePos / sampleLength) & 0x1f];
78 | var t = (cyclePos / sampleLength) % 1;
79 | val = Std.int(Math.round(Util.lerp(val1, val2, t)));
80 | if (outputLevel > 1) val >>= (outputLevel - 1);
81 | }
82 |
83 | return val;
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/retrio/emu/gb/Palette.hx:
--------------------------------------------------------------------------------
1 | package retrio.emu.gb;
2 |
3 | import haxe.ds.Vector;
4 |
5 |
6 | typedef PaletteInfo =
7 | {
8 | name:String,
9 | colors:Array,
10 | }
11 |
12 | class Palette
13 | {
14 | public static var paletteMap:Map>;
15 | public static var paletteInfo:Array = [
16 | {colors: [0xffffff, 0xc0c0c0, 0x606060, 0x000000], name: "default"},
17 | {colors: [0x9cba29, 0x8cab26, 0x326132, 0x113711], name: "classic green"},
18 | {colors: [0xe3e6c9, 0xc3c4a5, 0x8e8b61, 0x6c6c4e], name: "pocket"},
19 | {colors: [0xfff77b, 0xb5ae4a, 0x6b6931, 0x212010], name: "yellow"},
20 | {colors: [0xf3f3f3, 0xa5a5a5, 0x525252, 0x262626], name: "soft"},
21 | {colors: [0xe7d79c, 0xb5a66b, 0x7b7163, 0x393829], name: "tan"},
22 | {colors: [0xf3f3f3, 0xffad63, 0x833100, 0x262626], name: "orange"},
23 | {colors: [0xf3f3f3, 0x7bff30, 0x008300, 0x262626], name: "lime"},
24 | {colors: [0xf3f3f3, 0xff8584, 0x833100, 0x262626], name: "cherry"},
25 | {colors: [0xf3f3f3, 0xfe9494, 0x9394fe, 0x262626], name: "sunset"},
26 | {colors: [0xf3f3f3, 0x65a49b, 0x0000fe, 0x262626], name: "seaside"},
27 | {colors: [0xf3f3f3, 0x51ff00, 0xff4200, 0x262626], name: "watermelon"},
28 | {colors: [0xf3f3f3, 0xff8584, 0x943a3a, 0x262626], name: "salmon"},
29 | {colors: [0x262626, 0x008486, 0xffde00, 0xf3f3f3], name: "negative"},
30 | {colors: [0x000000, 0x480000, 0x900000, 0xf00000], name: "virtual reality"},
31 | ];
32 |
33 | static var palettes:Vector> = getColors();
34 |
35 | static function getColors():Vector>
36 | {
37 | var palettes = new Vector(paletteInfo.length);
38 | paletteMap = new Map();
39 |
40 | for (i in 0 ... paletteInfo.length)
41 | {
42 | var info = paletteInfo[i];
43 | var pal = Vector.fromArrayCopy([for (color in info.colors) convert(color)]);
44 | palettes[i] = paletteMap[info.name] = pal;
45 | }
46 |
47 | return palettes;
48 | }
49 |
50 | static function convert(c:Int):Int
51 | {
52 | #if (flash || legacy)
53 | var r = (c & 0xff0000) >> 16;
54 | var g = (c & 0xff00) >> 8;
55 | var b = (c & 0xff);
56 |
57 | // store colors as little-endian for flash.Memory
58 | return (0xff) | ((Std.int(r) & 0xff) << 8) | ((Std.int(g) & 0xff) << 16) | ((Std.int(b) & 0xff) << 24);
59 | #else
60 | // store colors as big-endian for flash.Memory
61 | return (0xff000000) | c;
62 | #end
63 | }
64 |
65 | public var palette:Vector;
66 |
67 | public function new()
68 | {
69 | palette = paletteMap['pocket'];
70 | }
71 |
72 | public function swapPalettes(name:String)
73 | {
74 | palette = paletteMap.exists(name) ? paletteMap[name] : palettes[0];
75 | }
76 |
77 | public inline function getColor(i:Int) return palette[i];
78 | }
79 |
--------------------------------------------------------------------------------
/retrio/emu/gb/sound/Channel4.hx:
--------------------------------------------------------------------------------
1 | package retrio.emu.gb.sound;
2 |
3 | import haxe.ds.Vector;
4 |
5 |
6 | class Channel4 implements ISoundGenerator implements IState
7 | {
8 | static var randomValues:Vector;
9 |
10 | public var enabled(get, never):Bool;
11 | inline function get_enabled()
12 | {
13 | return (lengthCounter > 0 || repeat) && dac && amplitude > 0;
14 | }
15 | @:state public var dac:Bool = false;
16 |
17 | @:state public var repeat:Bool = true;
18 | @:state public var length(default, set):Int = 0;
19 | function set_length(l:Int)
20 | {
21 | lengthCounter = 0x40-l;
22 | return length = l;
23 | }
24 | @:state public var lengthCounter:Int = 0;
25 |
26 | @:state public var frequency(default, set):Int = 0;
27 | inline function set_frequency(f:Int)
28 | {
29 | cycleLengthNumerator = Std.int(Audio.NATIVE_SAMPLE_RATE/64 * (f == 0 ? 0.5 : f)) << (shiftClockFrequency + 1);
30 | cycleLengthDenominator = Std.int(0x80000/64);
31 | return frequency = f;
32 | }
33 |
34 | @:state public var envelopeType:Bool = false;
35 | @:state public var envelopeTime:Int = 0;
36 | @:state public var envelopeVolume:Int = 0;
37 | @:state public var envelopeCounter:Int = 0;
38 | @:state var envelopeOn:Bool = false;
39 |
40 | @:state public var shiftClockFrequency:Int = 0;
41 | @:state public var counterStep:Bool = false;
42 |
43 | @:state var amplitude:Int = 0;
44 | @:state var cycleLengthNumerator:Int = 1;
45 | @:state var cycleLengthDenominator:Int = 1;
46 | @:state var cyclePos:Float = 0;
47 | @:state var noisePos:Int = 0;
48 | @:state var counterFlip:Bool = false;
49 |
50 | public function new()
51 | {
52 | randomValues = new Vector(0x10000);
53 | for (i in 0 ... randomValues.length)
54 | {
55 | randomValues[i] = Math.random() > 0.5;
56 | }
57 | }
58 |
59 | public function setEnvelope(value:Int):Void
60 | {
61 | envelopeTime = (value & 0x7);
62 | envelopeCounter = envelopeTime;
63 | envelopeType = Util.getbit(value, 3);
64 | envelopeVolume = (value & 0xf0) >> 4;
65 | envelopeOn = envelopeTime > 0;
66 | dac = value & 0xf8 > 0;
67 | }
68 |
69 | public function setPolynomial(value:Int):Void
70 | {
71 | shiftClockFrequency = (value & 0xf0) >> 4;
72 | counterStep = Util.getbit(value, 3);
73 | frequency = (value & 0x7);
74 | }
75 |
76 | public function reset():Void
77 | {
78 | amplitude = envelopeVolume;
79 | envelopeCounter = envelopeTime;
80 | if (lengthCounter == 0) lengthCounter = 0x40;
81 | cyclePos = 0;
82 | }
83 |
84 | public inline function lengthClock():Void
85 | {
86 | if (lengthCounter > 0)
87 | {
88 | --lengthCounter;
89 | }
90 | }
91 |
92 | public inline function envelopeClock():Void
93 | {
94 | if (envelopeOn && envelopeTime > 0)
95 | {
96 | if (--envelopeCounter == 0)
97 | {
98 | if (envelopeType)
99 | {
100 | if (++amplitude >= 0xf)
101 | {
102 | amplitude = 0xf;
103 | envelopeOn = false;
104 | }
105 | else envelopeCounter = envelopeTime;
106 | }
107 | else
108 | {
109 | if (--amplitude <= 0)
110 | {
111 | amplitude = 0;
112 | envelopeOn = false;
113 | }
114 | else envelopeCounter = envelopeTime;
115 | }
116 | }
117 | }
118 | }
119 |
120 | public inline function play(rate:Float):Int
121 | {
122 | var val = 0;
123 |
124 | if (enabled)
125 | {
126 | cyclePos += (cycleLengthDenominator * Audio.NATIVE_SAMPLE_RATIO) * rate;
127 | if (cyclePos >= cycleLengthNumerator)
128 | {
129 | cyclePos -= cycleLengthNumerator;
130 | noisePos++;
131 | if (counterStep && (noisePos & 7 == 0))
132 | {
133 | if (counterFlip)
134 | noisePos -= 8;
135 | counterFlip = !counterFlip;
136 | }
137 | noisePos %= randomValues.length;
138 | }
139 | val = (randomValues[noisePos]) ? amplitude : -amplitude;
140 | }
141 |
142 | return val;
143 | }
144 | }
145 |
--------------------------------------------------------------------------------
/retrio/emu/gb/GB.hx:
--------------------------------------------------------------------------------
1 | package retrio.emu.gb;
2 |
3 | import haxe.io.BytesInput;
4 | import retrio.io.FileWrapper;
5 | import retrio.io.IEnvironment;
6 | import retrio.io.IScreenBuffer;
7 |
8 |
9 | class GB implements IEmulator implements IState
10 | {
11 | @:stateVersion static var stateVersion = 1;
12 | @:stateChildren static var stateChildren = ['cpu', 'memory', 'rom', 'video', 'audio'];
13 |
14 | public static inline var WIDTH:Int = 160;
15 | public static inline var HEIGHT:Int = 144;
16 | // minimum # of frames to wait between saves
17 | public static inline var SRAM_SAVE_FRAMES = 60;
18 |
19 | public var width:Int = WIDTH;
20 | public var height:Int = HEIGHT;
21 |
22 | public var io:IEnvironment;
23 | public var extensions:Array = ["*.gb"];
24 | public var screenBuffer(default, set):IScreenBuffer;
25 | function set_screenBuffer(screenBuffer:IScreenBuffer)
26 | {
27 | return this.screenBuffer = screenBuffer;
28 | }
29 |
30 | // hardware components
31 | public var cpu:CPU;
32 | public var memory:Memory;
33 | public var rom:ROM;
34 | public var video:Video;
35 | public var audio:Audio;
36 | public var palette:Palette = new Palette();
37 |
38 | public var maxControllers:Int = 1;
39 | public var controller:GBController;
40 |
41 | var _saveCounter:Int = 0;
42 | @:state var romName:String;
43 | @:state var useSram:Bool = true;
44 |
45 | public function new()
46 | {
47 | controller = new GBController();
48 | }
49 |
50 | public function loadGame(gameData:FileWrapper, ?useSram:Bool=true)
51 | {
52 | rom = new ROM(gameData);
53 | memory = new Memory(rom);
54 |
55 | romName = gameData.name;
56 | this.useSram = useSram;
57 |
58 | reset();
59 | }
60 |
61 | public function reset():Void
62 | {
63 | cpu = new CPU();
64 | video = new Video();
65 | audio = new Audio();
66 |
67 | memory.init(cpu, video, audio, controller);
68 | video.init(this, cpu, memory);
69 | audio.init(cpu, memory);
70 | cpu.init(memory, video, audio);
71 | memory.writeInitialState();
72 |
73 | if (useSram) loadSram();
74 | }
75 |
76 | public function frame(rate:Float)
77 | {
78 | audio.newFrame(rate);
79 | cpu.runFrame();
80 |
81 | if (memory.sramDirty)
82 | {
83 | if (_saveCounter < SRAM_SAVE_FRAMES)
84 | {
85 | ++_saveCounter;
86 | }
87 | else
88 | {
89 | saveSram();
90 | }
91 | }
92 | else _saveCounter = 0;
93 | }
94 |
95 | public function addController(controller:IController, port:Int)
96 | {
97 | this.controller.controller = controller;
98 | }
99 |
100 | public function removeController(port:Int)
101 | {
102 | controller.controller = null;
103 | }
104 |
105 | public inline function getColor(c:Int)
106 | {
107 | return palette.getColor(c);
108 | }
109 |
110 | public function savePersistentState(slot:SaveSlot):Void
111 | {
112 | if (io != null)
113 | {
114 | var state = saveState();
115 | var file = io.writeFile();
116 | file.writeBytes(state);
117 | file.save(romName + ".st" + slot);
118 | }
119 | }
120 |
121 | public function loadPersistentState(slot:SaveSlot):Void
122 | {
123 | if (io != null)
124 | {
125 | var stateFile = io.readFile(romName + ".st" + slot);
126 | if (stateFile == null) throw "State " + slot + " does not exist";
127 | var input = new BytesInput(stateFile.readAll());
128 | loadState(input);
129 | }
130 | }
131 |
132 | function saveSram()
133 | {
134 | if (useSram && rom.hasSram && memory.sramDirty && io != null)
135 | {
136 | var file = io.writeFile();
137 | file.writeVector(memory.ramBanks);
138 | file.save(romName + ".srm");
139 | memory.sramDirty = false;
140 | _saveCounter = 0;
141 | }
142 | }
143 |
144 | function loadSram()
145 | {
146 | if (useSram && io.fileExists(romName + ".srm"))
147 | {
148 | var file = io.readFile(romName + ".srm");
149 | if (file != null)
150 | {
151 | for (bank in memory.ramBanks)
152 | {
153 | bank.readFrom(file);
154 | }
155 | memory.sramDirty = false;
156 | }
157 | }
158 | }
159 | }
160 |
--------------------------------------------------------------------------------
/retrio/ui/openfl/GBPlugin.hx:
--------------------------------------------------------------------------------
1 | package retrio.ui.openfl;
2 |
3 | import haxe.ds.Vector;
4 | import flash.Lib;
5 | import flash.Memory;
6 | import flash.display.Sprite;
7 | import flash.display.Bitmap;
8 | import flash.display.BitmapData;
9 | import flash.events.Event;
10 | import flash.events.TimerEvent;
11 | import flash.geom.Rectangle;
12 | import flash.geom.Matrix;
13 | import flash.utils.ByteArray;
14 | import retrio.config.GlobalSettings;
15 | import retrio.emu.gb.GB;
16 | import retrio.emu.gb.Settings;
17 | import retrio.emu.gb.Palette;
18 |
19 |
20 | @:access(retrio.emu.gb.GB)
21 | class GBPlugin extends EmulatorPlugin
22 | {
23 | public static var _name:String = "gb";
24 |
25 | static inline var AUDIO_BUFFER_SIZE:Int = 0x800;
26 | static var _registered = Shell.registerPlugin(_name, new GBPlugin());
27 |
28 | var _stage(get, never):flash.display.Stage;
29 | inline function get__stage() return Lib.current.stage;
30 |
31 | var gb:GB;
32 |
33 | var frameCount = 0;
34 | var screenDirty:Bool = false;
35 |
36 | public function new()
37 | {
38 | super();
39 |
40 | controllers = new Vector(1);
41 |
42 | this.emu = this.gb = new GB();
43 | screenBuffer = new BitmapScreenBuffer(GB.WIDTH, GB.HEIGHT);
44 |
45 | this.settings = GlobalSettings.settings.concat(
46 | retrio.emu.gb.Settings.settings
47 | ).concat(
48 | GBControls.settings(this)
49 | );
50 | extensions = gb.extensions;
51 |
52 | if (Std.is(screenBuffer, Bitmap)) addChildAt(cast(screenBuffer, Bitmap), 0);
53 | }
54 |
55 | override public function resize(width:Int, height:Int)
56 | {
57 | if (width == 0 || height == 0)
58 | return;
59 |
60 | screenBuffer.resize(width, height);
61 | initialized = true;
62 | }
63 |
64 | override public function frame()
65 | {
66 | if (!initialized) return;
67 |
68 | if (running)
69 | {
70 | super.frame();
71 | gb.frame(frameRate);
72 |
73 | if (!gb.video.finished) return;
74 |
75 | if (frameSkip > 0)
76 | {
77 | frameCount = (frameCount + 1) % (frameSkip + 1);
78 | if (frameCount > 0) return;
79 | }
80 | }
81 |
82 | if (running || screenDirty)
83 | {
84 | screenBuffer.render();
85 | screenDirty = false;
86 | }
87 | }
88 |
89 | override public function activate()
90 | {
91 | super.activate();
92 | }
93 |
94 | override public function deactivate()
95 | {
96 | super.deactivate();
97 | gb.audio.buffer1.clear();
98 | gb.audio.buffer2.clear();
99 | gb.saveSram();
100 | }
101 |
102 | var _buffering:Bool = true;
103 | override public function getSamples(e:Dynamic)
104 | {
105 | gb.audio.catchUp();
106 |
107 | var l:Int;
108 | if (_buffering)
109 | {
110 | l = Std.int(Math.max(0, AUDIO_BUFFER_SIZE * 2 - gb.audio.buffer1.length));
111 | if (l <= 0) _buffering = false;
112 | else l = AUDIO_BUFFER_SIZE;
113 | }
114 | else
115 | {
116 | // not enough samples; buffer until more arrive
117 | l = Std.int(Math.max(0, AUDIO_BUFFER_SIZE - gb.audio.buffer1.length));
118 | if (l > 0)
119 | {
120 | _buffering = true;
121 | }
122 | }
123 |
124 | for (i in 0 ... l)
125 | {
126 | e.data.writeDouble(0);
127 | }
128 |
129 | for (i in l ... AUDIO_BUFFER_SIZE)
130 | {
131 | e.data.writeFloat(volume * Util.clamp(gb.audio.buffer2.pop(), -0xf, 0xf) / 0xf);
132 | e.data.writeFloat(volume * Util.clamp(gb.audio.buffer1.pop(), -0xf, 0xf) / 0xf);
133 | }
134 | }
135 |
136 | override public function setSetting(id:String, value:Dynamic):Void
137 | {
138 | switch (id)
139 | {
140 | case Settings.GBPalette:
141 | gb.palette.swapPalettes(Std.string(value));
142 | screenDirty = true;
143 |
144 | case Settings.Ch1Volume:
145 | if (gb != null && gb.audio != null) gb.audio.ch1vol = cast(value, Int) / 100;
146 | case Settings.Ch2Volume:
147 | if (gb != null && gb.audio != null) gb.audio.ch2vol = cast(value, Int) / 100;
148 | case Settings.Ch3Volume:
149 | if (gb != null && gb.audio != null) gb.audio.ch3vol = cast(value, Int) / 100;
150 | case Settings.Ch4Volume:
151 | if (gb != null && gb.audio != null) gb.audio.ch4vol = cast(value, Int) / 100;
152 |
153 | default:
154 | super.setSetting(id, value);
155 | }
156 | }
157 | }
158 |
--------------------------------------------------------------------------------
/retrio/emu/gb/sound/Channel1.hx:
--------------------------------------------------------------------------------
1 | package retrio.emu.gb.sound;
2 |
3 | import haxe.ds.Vector;
4 |
5 |
6 | class Channel1 implements ISoundGenerator implements IState
7 | {
8 | static var dutyLookup:Vector> = Vector.fromArrayCopy([
9 | Vector.fromArrayCopy([ true, false, false, false, false, false, false, false, ]),
10 | Vector.fromArrayCopy([ false, false, false, false, true, true, false, false, ]),
11 | Vector.fromArrayCopy([ true, true, true, true, false, false, false, false, ]),
12 | Vector.fromArrayCopy([ true, true, true, true, true, true, false, false, ]),
13 | ]);
14 |
15 | @:state public var ch2:Bool = false;
16 |
17 | public var enabled(get, never):Bool;
18 | inline function get_enabled()
19 | {
20 | return (repeat || lengthCounter > 0) && !sweepFault && dac && (amplitude > 0 || (envelopeType && envelopeTime > 0));
21 | }
22 | @:state public var dac:Bool = false;
23 |
24 | @:state public var length:Int = 0;
25 | inline function set_length(l:Int)
26 | {
27 | lengthCounter = 0x40 - l;
28 | return length = l;
29 | }
30 | @:state public var lengthCounter:Int = 0;
31 |
32 | @:state public var duty(default, set):Int = 0;
33 | function set_duty(i:Int)
34 | {
35 | cachedDuty = dutyLookup[i];
36 | return duty = i;
37 | }
38 | var cachedDuty:Vector = dutyLookup[0];
39 |
40 | @:state public var sweepDecrease:Bool = false;
41 | @:state public var sweepDiv:Int = 0;
42 | @:state public var sweepTime:Int = 0;
43 | @:state public var sweepCounter:Int = 0;
44 | @:state var swept:Bool = false;
45 | @:state var sweepFault:Bool = false;
46 | @:state var shadowFrequency:Int = 0;
47 |
48 | @:state public var envelopeType:Bool = false;
49 | @:state public var envelopeTime:Int = 0;
50 | @:state public var envelopeVolume:Int = 0;
51 | @:state public var envelopeCounter:Int = 0;
52 | @:state var envelopeOn:Bool = false;
53 |
54 | @:state public var repeat:Bool = true;
55 | @:state public var baseFrequency(default, set):Int = 0;
56 | inline function set_baseFrequency(f:Int)
57 | {
58 | return baseFrequency = frequency = f;
59 | }
60 | @:state public var frequency(default, set):Int = 0;
61 | inline function set_frequency(f:Int)
62 | {
63 | sweepFault = false;
64 | cycleLengthNumerator = Std.int(Audio.NATIVE_SAMPLE_RATE/64) * (0x800 - f);
65 | cycleLengthDenominator = Std.int(0x20000/64);
66 | dutyLength = Std.int(cycleLengthNumerator / 8);
67 | return frequency = f;
68 | }
69 |
70 | @:state var cycleLengthNumerator:Int = 1;
71 | @:state var cycleLengthDenominator:Int = 1;
72 | @:state var cyclePos:Float = 0;
73 | @:state var dutyLength:Int = 1;
74 | @:state public var amplitude:Int = 0;
75 |
76 | public function new() {}
77 |
78 | public function setSweep(value:Int):Void
79 | {
80 | sweepDiv = value & 0x7;
81 | if (sweepDecrease && !Util.getbit(value, 3)) sweepFault = true;
82 | else sweepFault = false;
83 | sweepDecrease = Util.getbit(value, 3);
84 | sweepTime = (value & 0x70) >> 4;
85 | sweepCounter = sweepTime;
86 | }
87 |
88 | public var sweepRegister(get, never):Int;
89 | inline function get_sweepRegister()
90 | {
91 | return (sweepDiv) | (sweepDecrease ? 0x8 : 0) | (sweepTime << 4);
92 | }
93 |
94 | public function setDuty(value:Int):Void
95 | {
96 | length = value & 0x3f;
97 | duty = (value & 0xc0) >> 6;
98 | }
99 |
100 | public var dutyRegister(get, never):Int;
101 | inline function get_dutyRegister()
102 | {
103 | return (length) | (duty << 6);
104 | }
105 |
106 | public function setEnvelope(value:Int):Void
107 | {
108 | envelopeTime = (value & 0x7);
109 | envelopeCounter = envelopeTime;
110 | envelopeType = Util.getbit(value, 3);
111 | envelopeVolume = (value & 0xf0) >> 4;
112 | envelopeOn = envelopeTime > 0;
113 | dac = value & 0xf8 > 0;
114 | }
115 |
116 | public var envelopeRegister(get, never):Int;
117 | inline function get_envelopeRegister()
118 | {
119 | return (envelopeTime) | (envelopeType ? 0x8 : 0) | (envelopeVolume << 4);
120 | }
121 |
122 | public function reset():Void
123 | {
124 | amplitude = envelopeVolume;
125 | envelopeCounter = envelopeTime;
126 | envelopeOn = envelopeTime > 0;
127 | sweepCounter = sweepTime;
128 | swept = sweepFault = false;
129 | if (lengthCounter == 0) lengthCounter = 0x40;
130 | cyclePos = 0;
131 | frequency = baseFrequency;
132 | shadowFrequency = frequency;
133 | sweepDummy();
134 | }
135 |
136 | public inline function lengthClock():Void
137 | {
138 | if (lengthCounter > 0)
139 | {
140 | --lengthCounter;
141 | }
142 | }
143 |
144 | public inline function sweepClock():Void
145 | {
146 | if (--sweepCounter == 0)
147 | {
148 | if (sweepDiv > 0)
149 | {
150 | if (sweepDecrease)
151 | {
152 | shadowFrequency -= shadowFrequency >> sweepDiv;
153 | frequency = (shadowFrequency) & 0x7ff;
154 | }
155 | else
156 | {
157 | shadowFrequency += shadowFrequency >> sweepDiv;
158 | if (shadowFrequency + (shadowFrequency >> sweepDiv) > 0x7ff)
159 | {
160 | // overflow
161 | sweepFault = true;
162 | }
163 | else
164 | {
165 | frequency = shadowFrequency;
166 | }
167 | }
168 | swept = true;
169 | }
170 | sweepCounter = sweepTime;
171 | }
172 | }
173 |
174 | inline function sweepDummy():Void
175 | {
176 | if (sweepDiv > 0)
177 | {
178 | if (!sweepDecrease)
179 | {
180 | shadowFrequency += shadowFrequency >> sweepDiv;
181 | if (shadowFrequency + (shadowFrequency >> sweepDiv) > 0x7ff)
182 | {
183 | // overflow
184 | sweepFault = true;
185 | }
186 | }
187 | swept = true;
188 | }
189 | }
190 |
191 | public inline function envelopeClock():Void
192 | {
193 | if (envelopeOn && envelopeTime > 0)
194 | {
195 | if (--envelopeCounter == 0)
196 | {
197 | if (envelopeType)
198 | {
199 | if (++amplitude >= 0xf)
200 | {
201 | amplitude = 0xf;
202 | envelopeOn = false;
203 | }
204 | else envelopeCounter = envelopeTime;
205 | }
206 | else
207 | {
208 | if (--amplitude <= 0)
209 | {
210 | amplitude = 0;
211 | envelopeOn = false;
212 | }
213 | else envelopeCounter = envelopeTime;
214 | }
215 | }
216 | }
217 | }
218 |
219 | public inline function play(rate:Float):Int
220 | {
221 | var val = 0;
222 | if (enabled)
223 | {
224 | cyclePos += (cycleLengthDenominator * Audio.NATIVE_SAMPLE_RATIO) * rate;
225 | if (cyclePos >= cycleLengthNumerator) cyclePos -= cycleLengthNumerator;
226 | val = (cachedDuty[Std.int(cyclePos / dutyLength) & 0x7]) ? amplitude : -amplitude;
227 | }
228 |
229 | return val;
230 | }
231 | }
232 |
--------------------------------------------------------------------------------
/retrio/emu/gb/Memory.hx:
--------------------------------------------------------------------------------
1 | package retrio.emu.gb;
2 |
3 | import haxe.ds.Vector;
4 | import retrio.emu.gb.mbcs.*;
5 |
6 |
7 | class Memory implements IState
8 | {
9 | @:stateChildren static var stateChildren = ['mbc', 'rtc'];
10 |
11 | public var rom:ROM;
12 | public var mbc:MBC;
13 | public var cpu:CPU;
14 | public var video:Video;
15 | public var audio:Audio;
16 | public var rtc:RTC;
17 | public var controller:GBController;
18 |
19 | public var ram:ByteString; // pointer to external RAM
20 | public var wram1:ByteString; // pointer to fixed work RAM
21 | public var wram2:ByteString; // pointer to switchable work RAM
22 | @:state public var hram:ByteString; // HRAM
23 |
24 | public var romBanks:Vector;
25 | @:state public var ramBanks:Vector;
26 | @:state public var wramBanks:Vector;
27 |
28 | @:state public var romBank(default, set):Byte;
29 | inline function set_romBank(b:Byte)
30 | {
31 | rom2 = romBanks[b % romBanks.length];
32 | return romBank = b;
33 | }
34 |
35 | @:state public var ramBank(default, set):Byte;
36 | inline function set_ramBank(b:Byte)
37 | {
38 | ram = ramBanks[b % ramBanks.length];
39 | return ramBank = b;
40 | }
41 |
42 | @:state public var wram1Bank(default, set):Byte;
43 | inline function set_wram1Bank(b:Byte)
44 | {
45 | wram1 = wramBanks[b % wramBanks.length];
46 | return wram1Bank = b;
47 | }
48 | @:state public var wram2Bank(default, set):Byte;
49 | inline function set_wram2Bank(b:Byte)
50 | {
51 | wram2 = wramBanks[b % wramBanks.length];
52 | return wram2Bank = b;
53 | }
54 |
55 | public var rom1:ByteString; // pointer to fixed ROM bank
56 | public var rom2:ByteString; // pointer to switchable ROM bank
57 |
58 | public var sramDirty:Bool = false;
59 |
60 | @:state var joypadButtons:Bool = false;
61 |
62 | public function new(rom:ROM)
63 | {
64 | rom1 = rom.fixedRom;
65 |
66 | // initial memory allocation
67 | hram = new ByteString(0x200);
68 |
69 | wramBanks = new Vector(8);
70 | for (i in 0 ... 8)
71 | {
72 | wramBanks[i] = new ByteString(0x1000);
73 | }
74 |
75 | // MBC
76 | mbc = switch (rom.cartType)
77 | {
78 | case 0x00, 0x08, 0x09:
79 | // no MBC; base class doesn't actually do anything
80 | new MBC();
81 | case 0x01, 0x02, 0x03:
82 | new MBC1();
83 | case 0x05, 0x06:
84 | new MBC2();
85 | case 0xf, 0x10, 0x11, 0x12, 0x13:
86 | new MBC3();
87 | // TODO: MBC5
88 | default:
89 | throw "Cart type " + StringTools.hex(rom.cartType) + " not supported";
90 | }
91 | mbc.memory = this;
92 |
93 | // additional ROM banks
94 | romBanks = new Vector(rom.romBankCount);
95 | romBanks[0] = rom1;
96 | for (i in 1 ... rom.romBankCount)
97 | {
98 | romBanks[i] = new ByteString(0x4000);
99 | romBanks[i].readFrom(rom.data);
100 | }
101 |
102 | // set up RAM
103 | ramBanks = new Vector(rom.ramBankCount);
104 | for (i in 0 ... rom.ramBankCount)
105 | {
106 | ramBanks[i] = new ByteString(0x2000);
107 | }
108 |
109 | // real time clock
110 | rtc = new RTC();
111 | }
112 |
113 | public function init(cpu:CPU, video:Video, audio:Audio, controller:GBController)
114 | {
115 | this.cpu = cpu;
116 | this.video = video;
117 | this.audio = audio;
118 | this.controller = controller;
119 |
120 | hram.fillWith(0);
121 |
122 | for (i in 0 ... wramBanks.length) wramBanks[i].fillWith(0);
123 | for (i in 0 ... ramBanks.length) ramBanks[i].fillWith(0);
124 |
125 | romBank = 1;
126 | wram1Bank = 0;
127 | wram2Bank = 1;
128 | ramBank = 0;
129 | }
130 |
131 | public function writeInitialState()
132 | {
133 | for (key in _regs.keys())
134 | write(key, _regs[key]);
135 | }
136 |
137 | public function read(addr:Int):Int
138 | {
139 | switch (addr & 0xf000)
140 | {
141 | case 0x0000, 0x1000, 0x2000, 0x3000:
142 | return rom1[addr];
143 | case 0x4000, 0x5000, 0x6000, 0x7000:
144 | return rom2[addr-0x4000];
145 | case 0x8000, 0x9000:
146 | return video.vramRead(addr);
147 | case 0xa000, 0xb000:
148 | return (rtc.register > 0) ? rtc.read() : ram[addr-0xa000];
149 | case 0xc000:
150 | return wram1[addr-0xc000];
151 | case 0xd000:
152 | return wram2[addr-0xd000];
153 | case 0xe000:
154 | return wram1[addr-0xe000];
155 | case 0xf000:
156 | if (addr < 0xfe00)
157 | {
158 | return wram2[addr-0xf000];
159 | }
160 | else if (addr < 0xfea0)
161 | {
162 | return video.oamRead(addr);
163 | }
164 | else if (addr < 0xff00)
165 | {
166 | // unused memory region
167 | return 0xff;
168 | }
169 | else if (addr < 0xff40)
170 | {
171 | return ioRead(addr);
172 | }
173 | else if (addr < 0xff80)
174 | {
175 | return video.ioRead(addr);
176 | }
177 | else if (addr < 0xffff)
178 | {
179 | return hram[addr - 0xff80];
180 | }
181 | else
182 | {
183 | return cpu.interruptsEnabledFlag;
184 | }
185 |
186 | default:
187 | return 0xff;
188 | }
189 | }
190 |
191 | public function write(addr:Int, value:Int):Void
192 | {
193 | switch (addr & 0xf000)
194 | {
195 | case 0x0000, 0x1000, 0x2000, 0x3000,
196 | 0x4000, 0x5000, 0x6000, 0x7000:
197 | mbc.write(addr, value);
198 |
199 | case 0x8000, 0x9000:
200 | video.vramWrite(addr, value);
201 | case 0xa000, 0xb000:
202 | if (rtc.register > 0) rtc.write(value);
203 | else
204 | {
205 | var a = addr-0xa000;
206 | sramDirty = sramDirty || ram[a] != value;
207 | ram.set(a, value);
208 | }
209 | case 0xc000:
210 | wram1.set(addr-0xc000, value);
211 | case 0xd000:
212 | wram2.set(addr-0xd000, value);
213 | case 0xe000:
214 | wram1.set(addr-0xe000, value);
215 | case 0xf000:
216 | if (addr < 0xfe00)
217 | {
218 | wram2.set(addr-0xf000, value);
219 | }
220 | else if (addr < 0xfea0)
221 | {
222 | video.oamWrite(addr, value);
223 | }
224 | else if (addr < 0xff00)
225 | {
226 | // writing here does nothing
227 | }
228 | else if (addr < 0xff40)
229 | {
230 | ioWrite(addr, value);
231 | }
232 | else if (addr < 0xff80)
233 | {
234 | video.ioWrite(addr, value);
235 | }
236 | else if (addr < 0xffff)
237 | {
238 | hram.set(addr - 0xff80, value);
239 | }
240 | else
241 | {
242 | cpu.interruptsEnabledFlag = value;
243 | }
244 |
245 | default: {}
246 | }
247 | }
248 |
249 | inline function ioRead(addr:Int):Int
250 | {
251 | switch (addr)
252 | {
253 | case 0xff00:
254 | return controller == null ? 0 : controller.buttons();
255 | case 0xff04:
256 | var result = (cpu.divTicks >> 8) & 0xff;
257 | //cpu.divTicks &= 0xff;
258 | return result;
259 | case 0xff05: return cpu.timerValue;
260 | case 0xff06: return cpu.timerMod;
261 | case 0xff07:
262 | return (switch (cpu.tacClocks)
263 | {
264 | case 0x10: 1;
265 | case 0x40: 2;
266 | case 0x100: 3;
267 | default: 0;
268 | }) | (cpu.timerEnabled ? 0x4 : 0);
269 | case 0xff0f: return 0xe0 | cpu.interruptsRequestedFlag;
270 | default: return audio.read(addr);
271 | }
272 | }
273 |
274 | inline function ioWrite(addr:Int, value:Int):Void
275 | {
276 | switch(addr)
277 | {
278 | case 0xff00:
279 | if (controller != null)
280 | {
281 | controller.directionsEnabled = !Util.getbit(value, 4);
282 | controller.buttonsEnabled = !Util.getbit(value, 5);
283 | }
284 | case 0xff04: cpu.divTicks = 0;
285 | case 0xff05: cpu.timerValue = value;
286 | case 0xff06: cpu.timerMod = value;
287 | case 0xff07:
288 | cpu.tacClocks = switch (value & 0x3)
289 | {
290 | case 1: 0x10;
291 | case 2: 0x40;
292 | case 3: 0x100;
293 | default: 0x400;
294 | }
295 | cpu.timerEnabled = Util.getbit(value, 2);
296 | case 0xff0f: cpu.interruptsRequestedFlag = value;
297 |
298 | default: return audio.write(addr, value);
299 | }
300 | }
301 |
302 | static var _regs:Map = [
303 | 0xff05 => 0x00,
304 | 0xff06 => 0x00,
305 | 0xff07 => 0x00,
306 | 0xff10 => 0x80,
307 | 0xff11 => 0xbf,
308 | 0xff12 => 0xf3,
309 | 0xff14 => 0xbf,
310 | 0xff16 => 0x3f,
311 | 0xff17 => 0x00,
312 | 0xff19 => 0xbf,
313 | 0xff1a => 0x7f,
314 | 0xff1b => 0xff,
315 | 0xff1c => 0x9f,
316 | 0xff1e => 0xbf,
317 | 0xff20 => 0xff,
318 | 0xff21 => 0x00,
319 | 0xff22 => 0x00,
320 | 0xff23 => 0xbf,
321 | 0xff24 => 0x77,
322 | 0xff25 => 0xf3,
323 | 0xff26 => 0xf0,
324 | 0xff40 => 0x91,
325 | 0xff42 => 0x00,
326 | 0xff43 => 0x00,
327 | 0xff45 => 0x00,
328 | 0xff47 => 0xfc,
329 | 0xff48 => 0xff,
330 | 0xff49 => 0xff,
331 | 0xff4a => 0x00,
332 | 0xff4b => 0x00,
333 | 0xffff => 0x00,
334 | ];
335 | }
336 |
--------------------------------------------------------------------------------
/retrio/emu/gb/Audio.hx:
--------------------------------------------------------------------------------
1 | package retrio.emu.gb;
2 |
3 | import haxe.io.Bytes;
4 | import haxe.ds.Vector;
5 | import retrio.audio.SoundBuffer;
6 | import retrio.audio.LowPassFilter;
7 | import retrio.emu.gb.sound.*;
8 |
9 |
10 | @:build(retrio.macro.Optimizer.build())
11 | class Audio implements IState
12 | {
13 | @:stateChildren static var stateChildren = ['ch1', 'ch2', 'ch3', 'ch4'];
14 |
15 | // currently OpenFL on native, like Flash, does not support non-44100 sample rates
16 | public static inline var SAMPLE_RATE:Int = 44100;//#if flash 44100 #else 48000 #end;
17 | public static inline var NATIVE_SAMPLE_RATE:Int = (456*154*60);
18 | public static inline var NATIVE_SAMPLE_RATIO:Int = 4;
19 | static inline var SEQUENCER_RATE = 8230; // 456*154*60/8/64
20 | static inline var BUFFER_LENGTH:Int = 0x8000;
21 | static inline var MAX_VOLUME:Int = 16;
22 | static inline var FILTER_ORDER = 63;
23 |
24 | public var cpu:CPU;
25 | public var memory:Memory;
26 |
27 | public var buffer1:SoundBuffer; // right output
28 | public var buffer2:SoundBuffer; // left output
29 |
30 | public var ch1vol:Float = 1;
31 | public var ch2vol:Float = 1;
32 | public var ch3vol:Float = 1;
33 | public var ch4vol:Float = 1;
34 |
35 | var playRate:Float = 1;
36 |
37 | var cycleSkip:Int = NATIVE_SAMPLE_RATIO;
38 |
39 | @:state var vol1:Int = 0;
40 | @:state var vol2:Int = 0;
41 |
42 | @:state var soundEnabled:Bool = false;
43 |
44 | var ch1:Channel1;
45 | var ch2:Channel1; // channel 2 is channel 1 without sweep
46 | var ch3:Channel3;
47 | var ch4:Channel4;
48 | @:state var channelsOn1:Vector = new Vector(4);
49 | @:state var channelsOn2:Vector = new Vector(4);
50 |
51 | @:state var cycles:Int = 0;
52 | var sampleCounter:Int = 0;
53 | var sampleSync:Float = 0;
54 | var sampleStepSize:Float = SAMPLE_RATE * NATIVE_SAMPLE_RATIO;
55 |
56 | // sample data for interpolation
57 | var s1:Float = 0;
58 | var s2:Float = 0;
59 | var s1prev:Float = 0;
60 | var s2prev:Float = 0;
61 | var t:Null = null;
62 |
63 | var filter1:LowPassFilter;
64 | var filter2:LowPassFilter;
65 |
66 | public function new()
67 | {
68 | buffer1 = new SoundBuffer(BUFFER_LENGTH);
69 | buffer2 = new SoundBuffer(BUFFER_LENGTH);
70 |
71 | ch1 = new Channel1();
72 | ch2 = new Channel1();
73 | ch2.ch2 = true;
74 | ch3 = new Channel3();
75 | ch4 = new Channel4();
76 |
77 | for (i in 0 ... channelsOn1.length) channelsOn1[i] = false;
78 | for (i in 0 ... channelsOn2.length) channelsOn2[i] = false;
79 |
80 | filter1 = new LowPassFilter(Std.int(NATIVE_SAMPLE_RATE / NATIVE_SAMPLE_RATIO), SAMPLE_RATE, FILTER_ORDER);
81 | filter2 = new LowPassFilter(Std.int(NATIVE_SAMPLE_RATE / NATIVE_SAMPLE_RATIO), SAMPLE_RATE, FILTER_ORDER);
82 | }
83 |
84 | public function init(cpu:CPU, memory:Memory)
85 | {
86 | this.cpu = cpu;
87 | this.memory = memory;
88 | }
89 |
90 | public function newFrame(rate:Float)
91 | {
92 | playRate = 60/rate;
93 | sampleStepSize = SAMPLE_RATE * NATIVE_SAMPLE_RATIO * playRate;
94 | }
95 |
96 | public inline function read(addr:Int):Int
97 | {
98 | catchUp();
99 |
100 | switch (addr)
101 | {
102 | case 0xff10:
103 | return ch1.sweepRegister;
104 |
105 | case 0xff11:
106 | return ch1.dutyRegister;
107 |
108 | case 0xff12:
109 | return ch1.envelopeRegister;
110 |
111 | case 0xff13:
112 | return ch1.frequency & 0xff;
113 |
114 | case 0xff14:
115 | return ((ch1.frequency & 0x700) >> 8) |
116 | (ch1.repeat ? 0 : 0x40);
117 |
118 | case 0xff16:
119 | return ch2.dutyRegister;
120 |
121 | case 0xff17:
122 | return ch2.envelopeRegister;
123 |
124 | case 0xff18:
125 | return ch2.frequency & 0xff;
126 |
127 | case 0xff19:
128 | return ((ch2.frequency & 0x700) >> 8) |
129 | (ch2.repeat ? 0 : 0x40);
130 |
131 | case 0xff24:
132 | return (vol1 - 1) | ((vol2 - 1) << 4);
133 |
134 | case 0xff25:
135 | return (channelsOn1[0] ? 0x1 : 0) |
136 | (channelsOn1[1] ? 0x2 : 0) |
137 | (channelsOn1[2] ? 0x4 : 0) |
138 | (channelsOn1[3] ? 0x8 : 0) |
139 | (channelsOn2[0] ? 0x10 : 0) |
140 | (channelsOn2[1] ? 0x20 : 0) |
141 | (channelsOn2[2] ? 0x40 : 0) |
142 | (channelsOn2[3] ? 0x80 : 0);
143 |
144 | case 0xff26:
145 | return (ch1.enabled ? 0x1 : 0) |
146 | (ch2.enabled ? 0x2 : 0) |
147 | (ch3.enabled ? 0x4 : 0) |
148 | (ch4.enabled ? 0x8 : 0) |
149 | (soundEnabled ? 0x80 : 0);
150 |
151 | case 0xff30, 0xff31, 0xff32, 0xff33, 0xff34, 0xff35, 0xff36, 0xff37,
152 | 0xff38, 0xff39, 0xff3a, 0xff3b, 0xff3c, 0xff3d, 0xff3e, 0xff3f:
153 | var a:Int = (addr - 0xff30) * 2;
154 | return (ch3.wavData[a] << 4) | (ch3.wavData[a+1]);
155 |
156 | default:
157 | return 0;
158 | }
159 | }
160 |
161 | public function write(addr:Int, value:Int):Void
162 | {
163 | catchUp();
164 |
165 | switch (addr)
166 | {
167 | case 0xff10:
168 | if (soundEnabled)
169 | ch1.setSweep(value);
170 |
171 | case 0xff11:
172 | ch1.setDuty(value);
173 |
174 | case 0xff12:
175 | if (soundEnabled)
176 | ch1.setEnvelope(value);
177 |
178 | case 0xff13:
179 | if (soundEnabled)
180 | ch1.baseFrequency = (ch1.baseFrequency & 0x700) | value;
181 |
182 | case 0xff14:
183 | if (soundEnabled)
184 | {
185 | ch1.baseFrequency = (ch1.baseFrequency & 0xff) | ((value & 0x7) << 8);
186 | ch1.repeat = !Util.getbit(value, 6);
187 | if (Util.getbit(value, 7))
188 | {
189 | ch1.reset();
190 | }
191 | }
192 |
193 | case 0xff16:
194 | ch2.setDuty(value);
195 |
196 | case 0xff17:
197 | if (soundEnabled)
198 | ch2.setEnvelope(value);
199 |
200 | case 0xff18:
201 | if (soundEnabled)
202 | ch2.baseFrequency = (ch2.baseFrequency & 0x700) | value;
203 |
204 | case 0xff19:
205 | if (soundEnabled)
206 | {
207 | ch2.baseFrequency = (ch2.baseFrequency & 0xff) | ((value & 0x7) << 8);
208 | ch2.repeat = !Util.getbit(value, 6);
209 | if (Util.getbit(value, 7))
210 | {
211 | ch2.reset();
212 | }
213 | }
214 |
215 | case 0xff1a:
216 | if (soundEnabled)
217 | ch3.canPlay = Util.getbit(value, 7);
218 |
219 | case 0xff1b:
220 | ch3.length = value;
221 |
222 | case 0xff1c:
223 | if (soundEnabled)
224 | ch3.setOutput(value);
225 |
226 | case 0xff1d:
227 | if (soundEnabled)
228 | ch3.frequency = (ch3.frequency & 0x700) | value;
229 |
230 | case 0xff1e:
231 | if (soundEnabled)
232 | {
233 | ch3.frequency = (ch3.frequency & 0xff) | ((value & 0x7) << 8);
234 | ch3.repeat = !Util.getbit(value, 6);
235 | if (Util.getbit(value, 7))
236 | {
237 | ch3.reset();
238 | }
239 | }
240 |
241 | case 0xff20:
242 | ch4.length = value & 0x3f;
243 |
244 | case 0xff21:
245 | if (soundEnabled)
246 | ch4.setEnvelope(value);
247 |
248 | case 0xff22:
249 | if (soundEnabled)
250 | ch4.setPolynomial(value);
251 |
252 | case 0xff23:
253 | if (soundEnabled)
254 | {
255 | ch4.repeat = !Util.getbit(value, 6);
256 | if (Util.getbit(value, 7))
257 | {
258 | ch4.reset();
259 | }
260 | }
261 |
262 | case 0xff24:
263 | vol1 = (value & 0x7) + 1;
264 | vol2 = ((value >> 4) & 0x7) + 1;
265 |
266 | case 0xff25:
267 | if (soundEnabled)
268 | {
269 | channelsOn1[0] = Util.getbit(value, 0);
270 | channelsOn1[1] = Util.getbit(value, 1);
271 | channelsOn1[2] = Util.getbit(value, 2);
272 | channelsOn1[3] = Util.getbit(value, 3);
273 |
274 | channelsOn2[0] = Util.getbit(value, 4);
275 | channelsOn2[1] = Util.getbit(value, 5);
276 | channelsOn2[2] = Util.getbit(value, 6);
277 | channelsOn2[3] = Util.getbit(value, 7);
278 | }
279 |
280 | case 0xff26:
281 | soundEnabled = Util.getbit(value, 7);
282 |
283 | case 0xff30, 0xff31, 0xff32, 0xff33, 0xff34, 0xff35, 0xff36, 0xff37,
284 | 0xff38, 0xff39, 0xff3a, 0xff3b, 0xff3c, 0xff3d, 0xff3e, 0xff3f:
285 | var a:Int = (addr - 0xff30) * 2;
286 | ch3.wavData[a] = (value & 0xf0) >> 4;
287 | ch3.wavData[a+1] = (value & 0xf);
288 |
289 | default: {}
290 | }
291 | }
292 |
293 | public function catchUp()
294 | {
295 | while (cpu.apuCycles > 0)
296 | {
297 | /*--cpu.apuCycles;
298 | runCycle();
299 | generateSample();*/
300 | var runTo = Std.int(Math.min(predict(), cpu.apuCycles));
301 | cpu.apuCycles -= runTo;
302 | for (i in 0 ... runTo) generateSample();
303 | subCycles -= runTo;
304 | while (subCycles < 0)
305 | {
306 | subCycles += SEQUENCER_RATE;
307 | runCycle();
308 | }
309 | }
310 | }
311 |
312 | inline function predict()
313 | {
314 | return Std.int(Math.max(subCycles, 1));
315 | }
316 |
317 | var subCycles:Int = SEQUENCER_RATE;
318 | inline function runCycle()
319 | {
320 | switch (cycles++)
321 | {
322 | case 0:
323 | lengthClock();
324 | case 2:
325 | lengthClock();
326 | sweepClock();
327 | case 4:
328 | lengthClock();
329 | case 6:
330 | lengthClock();
331 | sweepClock();
332 | case 7:
333 | envelopeClock();
334 | cycles = 0;
335 | }
336 | }
337 |
338 | inline function lengthClock()
339 | {
340 | ch1.lengthClock();
341 | ch2.lengthClock();
342 | ch3.lengthClock();
343 | ch4.lengthClock();
344 | }
345 |
346 | inline function sweepClock()
347 | {
348 | ch1.sweepClock();
349 | }
350 |
351 | inline function envelopeClock()
352 | {
353 | ch1.envelopeClock();
354 | ch2.envelopeClock();
355 | ch4.envelopeClock();
356 | }
357 |
358 | var _samples:Vector = new Vector(4);
359 | inline function generateSample()
360 | {
361 | if (++sampleCounter >= cycleSkip)
362 | {
363 | sampleCounter -= cycleSkip;
364 | sampleSync += sampleStepSize;
365 |
366 | if (soundEnabled)
367 | {
368 | getSoundOut1();
369 | getSoundOut2();
370 | }
371 | else
372 | {
373 | s1 = s2 = 0;
374 | }
375 |
376 | filter1.addSample(s1);
377 | filter2.addSample(s2);
378 |
379 | if (NATIVE_SAMPLE_RATE - sampleSync < sampleStepSize)
380 | {
381 | if (t == null)
382 | {
383 | s1prev = filter1.getSample();
384 | s2prev = filter2.getSample();
385 | t = (NATIVE_SAMPLE_RATE - sampleSync) / sampleStepSize;
386 | }
387 | else
388 | {
389 | buffer1.push(Util.lerp(s1prev, filter1.getSample(), t) / MAX_VOLUME);
390 | buffer2.push(Util.lerp(s2prev, filter2.getSample(), t) / MAX_VOLUME);
391 |
392 | sampleSync -= NATIVE_SAMPLE_RATE;
393 | t = null;
394 | }
395 | }
396 | }
397 | }
398 |
399 | inline function getSoundOut1()
400 | {
401 | s1 = 0;
402 |
403 | if (channelsOn1[0])
404 | {
405 | s1 += _samples[0] = ch1.play(playRate) * ch1vol;
406 | }
407 | if (channelsOn1[1])
408 | {
409 | s1 += _samples[1] = ch2.play(playRate) * ch2vol;
410 | }
411 | if (channelsOn1[2])
412 | {
413 | s1 += _samples[2] = ch3.play(playRate) * ch3vol;
414 | }
415 | if (channelsOn1[3])
416 | {
417 | s1 += _samples[3] = ch4.play(playRate) * ch4vol;
418 | }
419 |
420 | s1 *= vol1;
421 | }
422 |
423 | inline function getSoundOut2()
424 | {
425 | s2 = 0;
426 |
427 | if (channelsOn2[0])
428 | {
429 | s2 += channelsOn1[0] ? _samples[0] : (ch1.play(playRate) * ch1vol);
430 | }
431 | if (channelsOn2[1])
432 | {
433 | s2 += channelsOn1[1] ? _samples[1] : (ch2.play(playRate) * ch2vol);
434 | }
435 | if (channelsOn2[2])
436 | {
437 | s2 += channelsOn1[2] ? _samples[2] : (ch3.play(playRate) * ch3vol);
438 | }
439 | if (channelsOn2[3])
440 | {
441 | s2 += channelsOn1[3] ? _samples[3] : (ch4.play(playRate) * ch4vol);
442 | }
443 |
444 | s2 *= vol2;
445 | }
446 | }
447 |
--------------------------------------------------------------------------------
/retrio/emu/gb/Video.hx:
--------------------------------------------------------------------------------
1 | package retrio.emu.gb;
2 |
3 | import haxe.ds.Vector;
4 | import retrio.io.IScreenBuffer;
5 |
6 |
7 | @:enum
8 | abstract VideoMode(Int) from Int to Int
9 | {
10 | var Hblank = 0;
11 | var Vblank = 1;
12 | var Oam = 2;
13 | var Vram = 3;
14 | }
15 |
16 |
17 | typedef SpriteInfo = {
18 | var x:Int;
19 | var y:Int;
20 | var tile:Int;
21 | var palette:Bool; // true = second palette
22 | var xflip:Bool; // true = flipped
23 | var yflip:Bool; // true = flipped
24 | var behindBg:Bool; // false = above BG
25 | }
26 |
27 |
28 | @:build(retrio.macro.Optimizer.build())
29 | class Video implements IState
30 | {
31 | public var gb:GB;
32 | public var cpu:CPU;
33 | public var memory:Memory;
34 | var screenBuffer(get, never):IScreenBuffer;
35 | inline function get_screenBuffer() return gb.screenBuffer;
36 |
37 | @:state public var oam:ByteString; // object attribute memory
38 | @:state public var vram:ByteString; // video RAM
39 |
40 | @:state public var frameCount:Int = 0;
41 | @:state public var scanline:Int = 153;
42 | @:state public var cycles:Int = 396;
43 | @:state public var stolenCycles:Int = 0;
44 | @:state public var finished:Bool = false;
45 |
46 | @:state public var lcdDisplay:Bool = true;
47 |
48 | @:state var bgDisplay:Bool = false;
49 | @:state var objDisplay:Bool = false;
50 | @:state var tallSprites:Bool = false;
51 | @:state var bgTileAddr:Int = 0x9800;
52 | @:state var tileDataAddr:Int = 0x8800;
53 | @:state var windowDisplay:Bool = false;
54 | @:state var windowTileAddr:Int = 0x9800;
55 |
56 | @:state public var hblankInterrupt:Bool = false;
57 | @:state public var vblankInterrupt:Bool = false;
58 | @:state public var oamInterrupt:Bool = false;
59 | @:state public var coincidenceInterrupt:Bool = false;
60 | @:state public var coincidenceScanline:Int = 0;
61 |
62 | var mode:VideoMode = Oam;
63 |
64 | @:state var bgPalette:Vector = Vector.fromArrayCopy([0, 1, 2, 3]);
65 | @:state var sp1Palette:Vector = Vector.fromArrayCopy([0, 1, 2, 3]);
66 | @:state var sp2Palette:Vector = Vector.fromArrayCopy([0, 1, 2, 3]);
67 |
68 | @:state var tileBuffer:ByteString;
69 | var spriteInfo:Vector = new Vector(40);
70 |
71 | // compact binary serializer for spriteinfo
72 | @:state var spriteInfoSerialized(get, set):haxe.io.Bytes;
73 | inline function get_spriteInfoSerialized():haxe.io.Bytes
74 | {
75 | var b = new haxe.io.BytesOutput();
76 | for (s in spriteInfo)
77 | {
78 | b.writeByte(s.x);
79 | b.writeByte(s.y);
80 | b.writeByte(s.tile);
81 | var meta = (s.palette ? 0x1 : 0) | (s.xflip ? 0x2 : 0) | (s.yflip ? 0x4 : 0) | (s.behindBg ? 0x8 : 0);
82 | b.writeByte(meta);
83 | }
84 | return b.getBytes();
85 | }
86 | inline function set_spriteInfoSerialized(b:haxe.io.Bytes)
87 | {
88 | var i = new haxe.io.BytesInput(b);
89 | for (s in spriteInfo)
90 | {
91 | s.x = i.readByte();
92 | s.y = i.readByte();
93 | s.tile = i.readByte();
94 | var meta = i.readByte();
95 | s.palette = Util.getbit(meta, 0);
96 | s.xflip = Util.getbit(meta, 1);
97 | s.yflip = Util.getbit(meta, 2);
98 | s.behindBg = Util.getbit(meta, 3);
99 | }
100 | return b;
101 | }
102 |
103 | @:state var scrollX:Int = 0;
104 | @:state var scrollY:Int = 0;
105 | @:state var windowX:Int = 0;
106 | @:state var windowY:Int = 0;
107 |
108 | @:state var dmaAddress:Int = 0;
109 |
110 | public function new()
111 | {
112 | oam = new ByteString(0xa0);
113 | oam.fillWith(0);
114 |
115 | vram = new ByteString(0x2000);
116 | vram.fillWith(0);
117 |
118 | tileBuffer = new ByteString(0x8000);
119 | tileBuffer.fillWith(0);
120 |
121 | for (i in 0 ... 40) spriteInfo[i] = {x:0, y:0, tile:0, palette:false, xflip:false, yflip:false, behindBg:false};
122 | }
123 |
124 | public function init(gb:GB, cpu:CPU, memory:Memory)
125 | {
126 | this.gb = gb;
127 | this.cpu = cpu;
128 | this.memory = memory;
129 | }
130 |
131 | public inline function ioRead(addr:Int):Int
132 | {
133 | catchUp();
134 |
135 | switch(addr)
136 | {
137 | case 0xff40:
138 | // LCD control
139 | return (bgDisplay ? 0x1 : 0) |
140 | (objDisplay ? 0x2 : 0) |
141 | (tallSprites ? 0x4 : 0) |
142 | (bgTileAddr == 0x9c00 ? 0x8 : 0) |
143 | (tileDataAddr == 0x8000 ? 0x10 : 0) |
144 | (windowDisplay ? 0x20 : 0) |
145 | (windowTileAddr == 0x9c00 ? 0x40 : 0) |
146 | (lcdDisplay ? 0x80 : 0);
147 |
148 | case 0xff41:
149 | // LCDC status
150 | return Std.int(mode) |
151 | (scanline == coincidenceScanline ? 0x4 : 0) |
152 | (hblankInterrupt ? 0x8 : 0) |
153 | (vblankInterrupt ? 0x10 : 0) |
154 | (oamInterrupt ? 0x20 : 0) |
155 | (coincidenceInterrupt ? 0x40 : 0);
156 |
157 | // scroll
158 | case 0xff42: return scrollY;
159 | case 0xff43: return scrollX;
160 |
161 | // scanline
162 | case 0xff44: return scanline % 153;
163 | case 0xff45: return coincidenceScanline;
164 |
165 | // DMA
166 | case 0xff46: return dmaAddress;
167 |
168 | // palettes
169 | case 0xff47: return getPalette(bgPalette);
170 | case 0xff48: return getPalette(sp1Palette);
171 | case 0xff49: return getPalette(sp2Palette);
172 |
173 | // window
174 | case 0xff4a: return windowY;
175 | case 0xff4b: return windowX + 7;
176 |
177 | default:
178 | return memory.hram.get(addr - 0xfe00);
179 | }
180 | }
181 |
182 | public inline function ioWrite(addr:Int, value:Int):Void
183 | {
184 | catchUp();
185 |
186 | switch(addr)
187 | {
188 | case 0xff40:
189 | bgDisplay = Util.getbit(value, 0);
190 | objDisplay = Util.getbit(value, 1);
191 | tallSprites = Util.getbit(value, 2);
192 | bgTileAddr = Util.getbit(value, 3) ? 0x9c00 : 0x9800;
193 | tileDataAddr = Util.getbit(value, 4) ? 0x8000 : 0x8800;
194 | windowDisplay = Util.getbit(value, 5);
195 | windowTileAddr = Util.getbit(value, 6) ? 0x9c00 : 0x9800;
196 | lcdDisplay = Util.getbit(value, 7);
197 | if (!lcdDisplay)
198 | {
199 | scanline = cycles = 0;
200 | }
201 |
202 | case 0xff41:
203 | // ignore first three bits
204 | hblankInterrupt = Util.getbit(value, 3);
205 | vblankInterrupt = Util.getbit(value, 4);
206 | oamInterrupt = Util.getbit(value, 5);
207 | coincidenceInterrupt = Util.getbit(value, 6);
208 |
209 | // scroll
210 | case 0xff42: scrollY = value;
211 | case 0xff43: scrollX = value;
212 |
213 | // scanline
214 | case 0xff44: scanline = 0;
215 | case 0xff45: coincidenceScanline = value;
216 |
217 | // DMA
218 | case 0xff46:
219 | if (value > 0x7f && value < 0xe0)
220 | {
221 | dmaAddress = value;
222 | dma();
223 | }
224 |
225 | // palettes
226 | case 0xff47: setPalette(bgPalette, value);
227 | case 0xff48: setPalette(sp1Palette, value);
228 | case 0xff49: setPalette(sp2Palette, value);
229 |
230 | // window
231 | case 0xff4a: windowY = value;
232 | case 0xff4b: windowX = value - 7;
233 |
234 | // destination VRAM
235 | case 0xff4f: // TODO
236 |
237 | // GBC
238 | case 0xff68: // TODO
239 | case 0xff69: // TODO
240 | case 0xff6a: // TODO
241 |
242 | default: {}
243 | }
244 | }
245 |
246 | public inline function oamRead(addr:Int)
247 | {
248 | return oam.get(addr - 0xfe00);
249 | }
250 |
251 | public inline function oamWrite(addr:Int, value:Int)
252 | {
253 | oam.set(addr - 0xfe00, value);
254 |
255 | // update sprite info cache
256 | var obj = (addr - 0xfe00) >> 2;
257 | if (obj < 40)
258 | {
259 | var sprite = spriteInfo[obj];
260 |
261 | switch (addr & 3)
262 | {
263 | case 0:
264 | sprite.y = value - 16;
265 | case 1:
266 | sprite.x = value - 8;
267 | case 2:
268 | sprite.tile = value;
269 | default:
270 | sprite.palette = Util.getbit(value, 4);
271 | sprite.xflip = Util.getbit(value, 5);
272 | sprite.yflip = Util.getbit(value, 6);
273 | sprite.behindBg = Util.getbit(value, 7);
274 | }
275 | }
276 | }
277 |
278 | inline function getPalette(pal:Vector)
279 | {
280 | return pal[0] | (pal[1] << 2) | (pal[2] << 4) | (pal[3] << 6);
281 | }
282 |
283 | inline function setPalette(pal:Vector, value:Int)
284 | {
285 | pal[0] = value & 0x3;
286 | pal[1] = (value >> 2) & 0x3;
287 | pal[2] = (value >> 4) & 0x3;
288 | pal[3] = (value >> 6) & 0x3;
289 | }
290 |
291 | inline function dma()
292 | {
293 | var startAddr = dmaAddress << 8;
294 | @unroll for (i in 0 ... 160)
295 | {
296 | oamWrite(0xfe00 + i, memory.read(startAddr + i));
297 | }
298 | }
299 |
300 | public function catchUp()
301 | {
302 | if (lcdDisplay)
303 | {
304 | while (cpu.cycles > 0)
305 | {
306 | --cpu.cycles;
307 | stolenCycles += cpu.cycles;
308 | advance();
309 | runCycle();
310 | }
311 | }
312 | else
313 | {
314 | stolenCycles = cpu.cycles;
315 | cpu.cycles = 0;
316 | }
317 | }
318 |
319 | inline function advance()
320 | {
321 | if (++cycles > 455)
322 | {
323 | cycles = 0;
324 | if (++scanline > 153)
325 | {
326 | scanline = 0;
327 | ++frameCount;
328 | finished = true;
329 | }
330 | if (lcdDisplay && coincidenceInterrupt && scanline == coincidenceScanline)
331 | {
332 | cpu.irq(Interrupt.LcdStat);
333 | }
334 | }
335 | }
336 |
337 | inline function runCycle()
338 | {
339 | if (scanline < 144)
340 | {
341 | switch (cycles)
342 | {
343 | case 0:
344 | mode = Oam;
345 | if (oamInterrupt) cpu.irq(Interrupt.LcdStat);
346 |
347 | case 80:
348 | mode = Vram;
349 |
350 | case 252:
351 | renderScanline();
352 | if (hblankInterrupt) cpu.irq(Interrupt.LcdStat);
353 | mode = Hblank;
354 |
355 | default: {}
356 | }
357 | }
358 | else if (scanline == 144 && cycles == 0)
359 | {
360 | cpu.irq(Interrupt.Vblank);
361 | if (vblankInterrupt) cpu.irq(Interrupt.LcdStat);
362 | mode = Vblank;
363 | }
364 | }
365 |
366 | var _bg:Vector = new Vector(160);
367 | var _spritePriority:Vector = new Vector(160);
368 | inline function renderScanline()
369 | {
370 | if (!windowDisplay || (scanline < windowY || windowX > 0))
371 | {
372 | // background tiles
373 | var mapOffset = bgTileAddr + (((scanline + scrollY) & 0xf8) << 2);
374 | var lineOffset = scrollX >> 3;
375 | var y = (scanline + scrollY) & 0x7;
376 | var x = scrollX & 0x7;
377 | var bufferOffset = 160 * scanline;
378 |
379 | var tile = vram[(mapOffset + lineOffset) & 0x1fff] & 0x1ff;
380 | if (tileDataAddr == 0x8800 && tile < 0x80) tile += 0x100;
381 |
382 | var value:Int, color:Int;
383 | var pixelEnd:Int = (windowDisplay && scanline >= windowY) ? Std.int(Math.min(160, Math.max(windowX, 0))) : 160;
384 | for (i in 0 ... pixelEnd)
385 | {
386 | value = bgDisplay ? tileBuffer[(tile << 6) + (y << 3) + (x)] : 0;
387 | _bg[i] = value == 0;
388 | color = bgPalette[value];
389 | pset(bufferOffset++, color);
390 | if (++x == 8)
391 | {
392 | x = 0;
393 | lineOffset = (lineOffset + 1) & 0x1f;
394 | tile = vram[(mapOffset + lineOffset) & 0x1fff] & 0x1ff;
395 | if (tileDataAddr == 0x8800 && tile < 0x80) tile += 0x100;
396 | }
397 | }
398 | }
399 | if (windowDisplay && scanline >= windowY)
400 | {
401 | // window
402 | var mapOffset = windowTileAddr + (((scanline - windowY) & 0xf8) << 2);
403 | var lineOffset = 0;
404 | var y = scanline & 0x7;
405 | var x = 0;
406 | var pixelStart = Std.int(Math.min(160, Math.max(windowX, 0)));
407 | var bufferOffset = 160 * scanline + pixelStart;
408 |
409 | var tile = (vram[(mapOffset + lineOffset) & 0x1fff] & 0x1ff);
410 | if (tile < 0x80) tile += 0x100;
411 |
412 | var value:Int, color:Int;
413 | for (i in pixelStart ... 160)
414 | {
415 | value = tileBuffer[(tile << 6) + (y << 3) + (x)];
416 | _bg[i] = value == 0;
417 | color = bgPalette[value];
418 | pset(bufferOffset++, color);
419 | if (++x == 8)
420 | {
421 | x = 0;
422 | lineOffset = (lineOffset + 1);
423 | tile = (vram[(mapOffset + lineOffset) & 0x1fff] & 0x1ff);
424 | if (tile < 0x80) tile += 0x100;
425 | }
426 | }
427 | }
428 | if (!(bgDisplay || windowDisplay))
429 | {
430 | var bufferOffset = 160 * scanline;
431 | // nothing is visible
432 | for (i in 0 ... 160)
433 | {
434 | pset(bufferOffset + i, bgPalette[0]);
435 | _bg[i] = false;
436 | }
437 | }
438 |
439 | // sprites
440 | if (objDisplay)
441 | {
442 | var height = tallSprites ? 16 : 8;
443 | // when sprites overlap, the one further to the left takes priority
444 | // TODO: in color mode, this isn't the case
445 | for (i in 0 ... 160)
446 | {
447 | _spritePriority[i] = 0xff;
448 | }
449 | var spriteCount:Int = 0;
450 | for (sprite in spriteInfo)
451 | {
452 | var x = sprite.x, y = sprite.y;
453 | if (y <= scanline && y+height > scanline)
454 | {
455 | var pal = sprite.palette ? sp2Palette : sp1Palette;
456 | var bufferOffset = 160 * scanline + x;
457 | var tileRow = (sprite.tile << 6) + ((sprite.yflip ? (height - 1 - (scanline - y)) : (scanline - y)) << 3);
458 |
459 | var displayed:Bool = false;
460 | var value:Int, color:Int;
461 | @unroll for (xi in 0 ... 8)
462 | {
463 | if (x + xi >= 0 && x + xi < 160 && (!sprite.behindBg || _bg[x+xi]) && x < _spritePriority[x + xi])
464 | {
465 | value = tileBuffer[tileRow + (sprite.xflip ? (7-xi) : (xi))];
466 | if (value > 0)
467 | {
468 | displayed = true;
469 | color = pal[value];
470 | pset(bufferOffset+xi, color);
471 | _spritePriority[x + xi] = x;
472 | }
473 | }
474 | }
475 | if (displayed) if (++spriteCount >= 10) break;
476 | }
477 | }
478 | }
479 | }
480 |
481 | public inline function vramRead(addr:Int):Int
482 | {
483 | catchUp();
484 | return vram[addr & 0x1fff];
485 | }
486 |
487 | public inline function vramWrite(addr:Int, value:Int):Void
488 | {
489 | catchUp();
490 |
491 | vram.set(addr & 0x1fff, value);
492 | updateTile(addr, value);
493 | }
494 |
495 | inline function updateTile(addr:Int, value:Int)
496 | {
497 | addr &= 0x1ffe;
498 | var tile = (addr >> 4) & 0x1ff;
499 | var y = (addr >> 1) & 7;
500 |
501 | @unroll for (x in 0 ... 8)
502 | {
503 | tileBuffer.set(
504 | (tile << 6) + (y << 3) + x,
505 | (Util.getbit(vram[addr], 7-x) ? 1 : 0) +
506 | (Util.getbit(vram[addr+1], 7-x) ? 2 : 0)
507 | );
508 | }
509 | }
510 |
511 | inline function pset(addr:Int, value:Int)
512 | {
513 | screenBuffer.pset(addr, gb.getColor(value));
514 | }
515 | }
516 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | ==========================
3 | Version 3, 29 June 2007
4 | ==========================
5 |
6 | > Copyright (C) 2007 Free Software Foundation, Inc.
7 | Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
8 |
9 | # Preamble
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | # TERMS AND CONDITIONS
72 |
73 | ## 0. Definitions.
74 |
75 | _"This License"_ refers to version 3 of the GNU General Public License.
76 |
77 | _"Copyright"_ also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | _"The Program"_ refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as _"you"_. _"Licensees"_ and
82 | "recipients" may be individuals or organizations.
83 |
84 | To _"modify"_ a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a _"modified version"_ of the
87 | earlier work or a work _"based on"_ the earlier work.
88 |
89 | A _"covered work"_ means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To _"propagate"_ a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To _"convey"_ a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | ## 1. Source Code.
113 |
114 | The _"source code"_ for a work means the preferred form of the work
115 | for making modifications to it. _"Object code"_ means any non-source
116 | form of a work.
117 |
118 | A _"Standard Interface"_ means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The _"System Libraries"_ of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The _"Corresponding Source"_ for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | ## 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | ## 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | ## 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | ## 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | ## 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A _"User Product"_ is either (1) a _"consumer product"_, which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | _"Installation Information"_ for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | ## 7. Additional Terms.
344 |
345 | _"Additional permissions"_ are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | ## 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | ## 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | ## 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An _"entity transaction"_ is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | ## 11. Patents.
472 |
473 | A _"contributor"_ is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's _"essential patent claims"_ are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | ## 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | ## 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | ## 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | ## 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | ## 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | ## 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | # END OF TERMS AND CONDITIONS
622 | --------------------------------------------------------------------------
623 |
624 |
625 | # How to Apply These Terms to Your New Programs
626 |
627 | If you develop a new program, and you want it to be of the greatest
628 | possible use to the public, the best way to achieve this is to make it
629 | free software which everyone can redistribute and change under these terms.
630 |
631 | To do so, attach the following notices to the program. It is safest
632 | to attach them to the start of each source file to most effectively
633 | state the exclusion of warranty; and each file should have at least
634 | the "copyright" line and a pointer to where the full notice is found.
635 |
636 |
637 | Copyright (C)
638 |
639 | This program is free software: you can redistribute it and/or modify
640 | it under the terms of the GNU General Public License as published by
641 | the Free Software Foundation, either version 3 of the License, or
642 | (at your option) any later version.
643 |
644 | This program is distributed in the hope that it will be useful,
645 | but WITHOUT ANY WARRANTY; without even the implied warranty of
646 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
647 | GNU General Public License for more details.
648 |
649 | You should have received a copy of the GNU General Public License
650 | along with this program. If not, see .
651 |
652 | Also add information on how to contact you by electronic and paper mail.
653 |
654 | If the program does terminal interaction, make it output a short
655 | notice like this when it starts in an interactive mode:
656 |
657 | Copyright (C)
658 | This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.
659 | This is free software, and you are welcome to redistribute it
660 | under certain conditions; type 'show c' for details.
661 |
662 | The hypothetical commands _'show w'_ and _'show c'_ should show the appropriate
663 | parts of the General Public License. Of course, your program's commands
664 | might be different; for a GUI interface, you would use an "about box".
665 |
666 | You should also get your employer (if you work as a programmer) or school,
667 | if any, to sign a "copyright disclaimer" for the program, if necessary.
668 | For more information on this, and how to apply and follow the GNU GPL, see
669 | .
670 |
671 | The GNU General Public License does not permit incorporating your program
672 | into proprietary programs. If your program is a subroutine library, you
673 | may consider it more useful to permit linking proprietary applications with
674 | the library. If this is what you want to do, use the GNU Lesser General
675 | Public License instead of this License. But first, please read
676 | .
677 |
--------------------------------------------------------------------------------
/retrio/emu/gb/CPU.hx:
--------------------------------------------------------------------------------
1 | package retrio.emu.gb;
2 |
3 | import haxe.ds.Vector;
4 |
5 |
6 | @:build(retrio.macro.Optimizer.build())
7 | class CPU implements IState
8 | {
9 | public var memory:Memory;
10 | public var video:Video;
11 | public var audio:Audio;
12 |
13 | @:state public var cycleCount:Int = 0;
14 | @:state public var cycles:Int = 0;
15 | @:state public var apuCycles:Int = 0;
16 |
17 | // timers
18 | @:state public var divTicks:Int = 0;
19 | @:state public var timerValue:Int = 0;
20 | @:state public var timerTicks:Int = 0;
21 | @:state public var tacClocks:Int = 0x400;
22 | @:state public var timerMod:Int = 0;
23 | @:state public var timerEnabled:Bool = false;
24 |
25 | @:state public var halted:Bool = false;
26 |
27 | @:state var ticks:Int = 0;
28 | @:state var timerPostpone:Bool = true;
29 |
30 | #if cputrace
31 | var log:String;
32 | #end
33 |
34 | @:state var a:Byte = 0x01;
35 | @:state var b:Byte = 0x00;
36 | @:state var c:Byte = 0x13;
37 | @:state var d:Byte = 0x00;
38 | @:state var e:Byte = 0xd8;
39 | @:state var h:Byte = 0x01;
40 | @:state var l:Byte = 0x4d;
41 |
42 | // don't need @:state due to being contained in f
43 | var cf:Bool = true; // carry flag
44 | var hf:Bool = true; // half carry flag
45 | var sf:Bool = false; // subtract flag
46 | var zf:Bool = true; // zero flag
47 |
48 | @:state var f(get, set):Byte;
49 | inline function get_f() return (zf ? 0x80 : 0) | (sf ? 0x40 : 0) | (hf ? 0x20 : 0) | (cf ? 0x10 : 0);
50 | inline function set_f(byte:Int)
51 | {
52 | cf = Util.getbit(byte, 4);
53 | hf = Util.getbit(byte, 5);
54 | sf = Util.getbit(byte, 6);
55 | zf = Util.getbit(byte, 7);
56 | return byte;
57 | }
58 |
59 | var bc(get, set):Int;
60 | inline function get_bc() return (b << 8) | c;
61 | inline function set_bc(byte:Int)
62 | {
63 | b = (byte & 0xff00) >> 8;
64 | c = byte & 0xff;
65 | return byte;
66 | }
67 | var de(get, set):Int;
68 | inline function get_de() return (d << 8) | e;
69 | inline function set_de(byte:Int)
70 | {
71 | d = (byte & 0xff00) >> 8;
72 | e = byte & 0xff;
73 | return byte;
74 | }
75 | var hl(get, set):Int;
76 | inline function get_hl() return (h << 8) | l;
77 | inline function set_hl(byte:Int)
78 | {
79 | h = (byte & 0xff00) >> 8;
80 | l = byte & 0xff;
81 | return byte;
82 | }
83 | var af(get, set):Int;
84 | inline function get_af() return (a << 8) | f;
85 | inline function set_af(byte:Int)
86 | {
87 | a = (byte & 0xff00) >> 8;
88 | f = byte & 0xff;
89 | return byte;
90 | }
91 |
92 | @:state var sp:Int = 0xfffe;
93 | @:state var pc:Int = 0x100;
94 |
95 | @:state var ime:Bool = true; // interrupt master enable
96 | @:state var interruptsRequested:Vector;
97 | @:state var interruptsEnabled:Vector;
98 |
99 | public var interruptsEnabledFlag(get, set):Int;
100 | inline function get_interruptsEnabledFlag()
101 | {
102 | return (interruptsEnabled[0] ? 0x1 : 0) |
103 | (interruptsEnabled[1] ? 0x2 : 0) |
104 | (interruptsEnabled[2] ? 0x4 : 0) |
105 | (interruptsEnabled[3] ? 0x8 : 0) |
106 | (interruptsEnabled[4] ? 0x10 : 0);
107 | }
108 | inline function set_interruptsEnabledFlag(v:Int)
109 | {
110 | @unroll for (i in 0 ... 5) interruptsEnabled[i] = Util.getbit(v, i);
111 | return v;
112 | }
113 |
114 | public var interruptsRequestedFlag(get, set):Int;
115 | inline function get_interruptsRequestedFlag()
116 | {
117 | return (interruptsRequested[0] ? 0x1 : 0) |
118 | (interruptsRequested[1] ? 0x2 : 0) |
119 | (interruptsRequested[2] ? 0x4 : 0) |
120 | (interruptsRequested[3] ? 0x8 : 0) |
121 | (interruptsRequested[4] ? 0x10 : 0);
122 | }
123 | inline function set_interruptsRequestedFlag(v:Int)
124 | {
125 | @unroll for (i in 0 ... 5) interruptsRequested[i] = Util.getbit(v, i);
126 | return v;
127 | }
128 |
129 | public function new()
130 | {
131 | interruptsEnabled = new Vector(5);
132 | for (i in 0 ... interruptsEnabled.length) interruptsEnabled[i] = false;
133 | interruptsRequested = new Vector(5);
134 | for (i in 0 ... interruptsRequested.length) interruptsRequested[i] = false;
135 | interruptsRequested[Interrupt.Vblank] = true;
136 | }
137 |
138 | public function init(memory:Memory, video:Video, audio:Audio)
139 | {
140 | this.memory = memory;
141 | this.video = video;
142 | this.audio = audio;
143 | }
144 |
145 | public function irq(interruptType:Interrupt)
146 | {
147 | interruptsRequested[interruptType] = true;
148 | }
149 |
150 | public function runFrame()
151 | {
152 | video.stolenCycles = 0;
153 | video.finished = false;
154 | var total:Int = 0;
155 |
156 | while (!video.finished)
157 | {
158 | runCycle();
159 |
160 | var projScanline = video.scanline + ((video.cycles + cycles) / 456);
161 | if (halted || projScanline > video.scanline)
162 | {
163 | video.catchUp();
164 | }
165 |
166 | if (ime)
167 | {
168 | var interrupted = false;
169 | @unroll for (i in 0 ... 5)
170 | {
171 | if (!interrupted && interruptsEnabled[i] && interruptsRequested[i])
172 | {
173 | interrupt(i);
174 | interrupted = true;
175 | }
176 | }
177 | }
178 | }
179 |
180 | var controller = memory.controller;
181 | if (controller != null && controller.changed)
182 | {
183 | controller.changed = false;
184 | irq(Joypad);
185 | }
186 |
187 | audio.catchUp();
188 | }
189 |
190 | inline function runCycle()
191 | {
192 | #if cputrace
193 | log = StringTools.hex(cycleCount, 8).toLowerCase();
194 | log += " L" + StringTools.hex(video.scanline % 153, 2).toLowerCase();
195 | log += " PC:" + StringTools.hex(pc, 4).toLowerCase();
196 | #end
197 | var op = readpc();
198 | #if cputrace
199 | log += " OP:" + StringTools.hex(op, 2).toLowerCase();
200 | log += " AF:" + StringTools.hex(af, 4).toLowerCase();
201 | log += " BC:" + StringTools.hex(bc, 4).toLowerCase();
202 | log += " DE:" + StringTools.hex(de, 4).toLowerCase();
203 | log += " HL:" + StringTools.hex(hl, 4).toLowerCase();
204 | log += " SP:" + StringTools.hex(sp, 4).toLowerCase();
205 | #end
206 |
207 | runOp(op);
208 |
209 | tick(ticks);
210 |
211 | #if cputrace
212 | #if sys
213 | Sys.println(log);
214 | #else
215 | trace(log);
216 | #end
217 | #end
218 | }
219 |
220 | inline function runOp(op:Int)
221 | {
222 | ticks = tickValues[op];
223 |
224 | switch (op)
225 | {
226 | case 0x00: // NOP
227 | case 0x01: // LD BC,nn
228 | bc = read16pc();
229 | case 0x02: // LD (BC),A
230 | write(bc, a);
231 | case 0x03: // INC BC
232 | bc++;
233 | case 0x04: // INC B
234 | b = inc(b);
235 | case 0x05: // DEC B
236 | b = dec(b);
237 | case 0x06: // LD B,n
238 | b = readpc();
239 | case 0x07: // RLCA
240 | cf = a > 0x7f;
241 | a = (a << 1 & 0xff) | (a >> 7);
242 | zf = sf = hf = false;
243 | case 0x08: // LD (nn),SP
244 | write16(read16pc(), sp);
245 | case 0x09: // ADD HL,BC
246 | hl = add16(hl, bc);
247 | case 0x0a: // LD A,(BC)
248 | a = read(bc);
249 | case 0x0b: // DEC BC
250 | bc--;
251 | case 0x0c: // INC C
252 | c = inc(c);
253 | case 0x0d: // DEC C
254 | c = dec(c);
255 | case 0x0e: // LD C,n
256 | c = readpc();
257 | case 0x0f: // RRCA
258 | a = (a >> 1) | ((a & 1) << 7);
259 | cf = a > 0x7f;
260 | zf = sf = hf = false;
261 | case 0x10: // STOP
262 | // TODO
263 | case 0x11: // LD DE,nn
264 | de = read16pc();
265 | case 0x12: // LD (DE),A
266 | write(de, a);
267 | case 0x13: // INC DE
268 | de++;
269 | case 0x14: // INC D
270 | d = inc(d);
271 | case 0x15: // DEC D
272 | d = dec(d);
273 | case 0x16: // LD D,n
274 | d = readpc();
275 | case 0x17: // RLA
276 | var carry = cf ? 1 : 0;
277 | cf = a > 0x7f;
278 | a = ((a << 1) & 0xff) | carry;
279 | zf = sf = hf = false;
280 | case 0x18: // JR n
281 | var inc = signed(readpc());
282 | pc += inc;
283 | case 0x19: // ADD HL,DE
284 | hl = add16(hl, de);
285 | case 0x1a: // LD A,(DE)
286 | a = read(de);
287 | case 0x1b: // DEC DE
288 | de--;
289 | case 0x1c: // INC E
290 | e = inc(e);
291 | case 0x1d: // DEC E
292 | e = dec(e);
293 | case 0x1e: // LD E,n
294 | e = readpc();
295 | case 0x1f: // RRA
296 | var carry = cf ? 0x80 : 0;
297 | cf = Util.getbit(a, 0);
298 | a = (a >> 1) | carry;
299 | zf = sf = hf = false;
300 | case 0x20: // JR NZ,n
301 | if (!zf)
302 | {
303 | var inc = signed(readpc());
304 | pc += inc;
305 | ticks += 4;
306 | }
307 | else ++pc;
308 | case 0x21: // LD HL,nn
309 | hl = read16pc();
310 | case 0x22: // LDI (HL),A
311 | write(hl++, a);
312 | case 0x23: // INC HL
313 | hl++;
314 | case 0x24: // INC H
315 | h = inc(h);
316 | case 0x25: // DEC H
317 | h = dec(h);
318 | case 0x26: // LD H,n
319 | h = readpc();
320 | case 0x27: // DAA
321 | var tmp:Int = cf ? 0x60 : 0;
322 |
323 | if (hf) tmp |= 0x06;
324 | if (!sf)
325 | {
326 | if (a & 0xf > 0x9)
327 | tmp |= 0x06;
328 | if (a > 0x99)
329 | tmp |= 0x60;
330 | a += tmp;
331 | cf = tmp > 0x5f;
332 | } else a -= tmp;
333 |
334 | a &= 0xff;
335 |
336 | zf = a == 0;
337 | hf = false;
338 |
339 | case 0x28: // JR Z,n
340 | if (zf)
341 | {
342 | var inc = signed(readpc());
343 | pc += inc;
344 | ticks += 4;
345 | }
346 | else ++pc;
347 | case 0x29: // ADD HL,HL
348 | hl = add16(hl, hl);
349 | case 0x2a: // LDI A,(HL)
350 | a = read(hl++);
351 | case 0x2b: // DEC HL
352 | hl--;
353 | case 0x2c: // INC L
354 | l = inc(l);
355 | case 0x2d: // DEC L
356 | l = dec(l);
357 | case 0x2e: // LD L,n
358 | l = readpc();
359 | case 0x2f: // CPL
360 | a ^= 0xff;
361 | sf = hf = true;
362 | case 0x30: // JR NC,n
363 | if (!cf)
364 | {
365 | var inc = signed(readpc());
366 | pc += inc;
367 | ticks += 4;
368 | }
369 | else ++pc;
370 | case 0x31: // LD SP,nn
371 | sp = read16pc();
372 | case 0x32: // LDD (HL),A
373 | write(hl--, a);
374 | case 0x33: // INC SP
375 | sp = (sp + 1) & 0xffff;
376 | case 0x34: // INC (HL)
377 | var tmp = (read(hl) + 1) & 0xff;
378 | zf = tmp == 0;
379 | hf = (tmp & 0xf) == 0;
380 | sf = false;
381 | write(hl, tmp);
382 | case 0x35: // DEC (HL)
383 | var tmp = (read(hl) - 1) & 0xff;
384 | zf = tmp == 0;
385 | hf = (tmp & 0xf) == 0xf;
386 | sf = true;
387 | write(hl, tmp);
388 | case 0x36: // LD (HL),n
389 | write(hl, readpc());
390 | case 0x37: // SCF
391 | cf = true;
392 | sf = hf = false;
393 | case 0x38: // JR C,n
394 | if (cf)
395 | {
396 | var inc = signed(readpc());
397 | pc += inc;
398 | ticks += 4;
399 | }
400 | else ++pc;
401 | case 0x39: // ADD HL,SP
402 | hl = add16(hl, sp);
403 | case 0x3a: // LDD A,(HL)
404 | a = read(hl--);
405 | case 0x3b: // DEC SP
406 | sp = (sp - 1) & 0xffff;
407 | case 0x3c: // INC A
408 | a = inc(a);
409 | case 0x3d: // DEC A
410 | a = dec(a);
411 | case 0x3e: // LD A,n
412 | a = readpc();
413 | case 0x3f: // CCF
414 | cf = !cf;
415 | sf = hf = false;
416 | case 0x40: // LD B,B
417 | case 0x41: // LD B,C
418 | b = c;
419 | case 0x42: // LD B,D
420 | b = d;
421 | case 0x43: // LD B,E
422 | b = e;
423 | case 0x44: // LD B,H
424 | b = h;
425 | case 0x45: // LD B,L
426 | b = l;
427 | case 0x46: // LD B,(HL)
428 | b = read(hl);
429 | case 0x47: // LD B,A
430 | b = a;
431 | case 0x48: // LD C,B
432 | c = b;
433 | case 0x49: // LD C,C
434 | case 0x4a: // LD C,D
435 | c = d;
436 | case 0x4b: // LD C,E
437 | c = e;
438 | case 0x4c: // LD C,H
439 | c = h;
440 | case 0x4d: // LD C,L
441 | c = l;
442 | case 0x4e: // LD C,(HL)
443 | c = read(hl);
444 | case 0x4f: // LD C,A
445 | c = a;
446 | case 0x50: // LD D,B
447 | d = b;
448 | case 0x51: // LD D,C
449 | d = c;
450 | case 0x52: // LD D,D
451 | case 0x53: // LD D,E
452 | d = e;
453 | case 0x54: // LD D,H
454 | d = h;
455 | case 0x55: // LD D,L
456 | d = l;
457 | case 0x56: // LD D,(HL)
458 | d = read(hl);
459 | case 0x57: // LD D,A
460 | d = a;
461 | case 0x58: // LD E,B
462 | e = b;
463 | case 0x59: // LD E,C
464 | e = c;
465 | case 0x5a: // LD E,D
466 | e = d;
467 | case 0x5b: // LD E,E
468 | case 0x5c: // LD E,H
469 | e = h;
470 | case 0x5d: // LD E,L
471 | e = l;
472 | case 0x5e: // LD E,(HL)
473 | e = read(hl);
474 | case 0x5f: // LD E,A
475 | e = a;
476 | case 0x60: // LD H,B
477 | h = b;
478 | case 0x61: // LD H,C
479 | h = c;
480 | case 0x62: // LD H,D
481 | h = d;
482 | case 0x63: // LD H,E
483 | h = e;
484 | case 0x64: // LD H,H
485 | case 0x65: // LD H,L
486 | h = l;
487 | case 0x66: // LD H,(HL)
488 | h = read(hl);
489 | case 0x67: // LD H,A
490 | h = a;
491 | case 0x68: // LD L,B
492 | l = b;
493 | case 0x69: // LD L,C
494 | l = c;
495 | case 0x6a: // LD L,D
496 | l = d;
497 | case 0x6b: // LD L,E
498 | l = e;
499 | case 0x6c: // LD L,H
500 | l = h;
501 | case 0x6d: // LD L,L
502 | case 0x6e: // LD L,(HL)
503 | l = read(hl);
504 | case 0x6f: // LD L,A
505 | l = a;
506 | case 0x70: // LD (HL),B
507 | write(hl, b);
508 | case 0x71: // LD (HL),C
509 | write(hl, c);
510 | case 0x72: // LD (HL),D
511 | write(hl, d);
512 | case 0x73: // LD (HL),E
513 | write(hl, e);
514 | case 0x74: // LD (HL),H
515 | write(hl, h);
516 | case 0x75: // LD (HL),L
517 | write(hl, l);
518 | case 0x76: // HALT
519 | halted = true;
520 | predictHalt();
521 | case 0x77: // LD (HL),A
522 | write(hl, a);
523 | case 0x78: // LD A,B
524 | a = b;
525 | case 0x79: // LD A,C
526 | a = c;
527 | case 0x7a: // LD A,D
528 | a = d;
529 | case 0x7b: // LD A,E
530 | a = e;
531 | case 0x7c: // LD A,H
532 | a = h;
533 | case 0x7d: // LD A,L
534 | a = l;
535 | case 0x7e: // LD A,(HL)
536 | a = read(hl);
537 | case 0x7f: // LD A,A
538 | case 0x80: // ADD A,B
539 | a = add(a, b);
540 | case 0x81: // ADD A,C
541 | a = add(a, c);
542 | case 0x82: // ADD A,D
543 | a = add(a, d);
544 | case 0x83: // ADD A,E
545 | a = add(a, e);
546 | case 0x84: // ADD A,H
547 | a = add(a, h);
548 | case 0x85: // ADD A,L
549 | a = add(a, l);
550 | case 0x86: // ADD A,(HL)
551 | a = add(a, read(hl));
552 | case 0x87: // ADD A,A
553 | a = add(a, a);
554 | case 0x88: // ADC A,B
555 | adc(b);
556 | case 0x89: // ADC A,C
557 | adc(c);
558 | case 0x8a: // ADC A,D
559 | adc(d);
560 | case 0x8b: // ADC A,E
561 | adc(e);
562 | case 0x8c: // ADC A,H
563 | adc(h);
564 | case 0x8d: // ADC A,L
565 | adc(l);
566 | case 0x8e: // ADC A,(HL)
567 | adc(read(hl));
568 | case 0x8f: // ADC A,A
569 | adc(a);
570 | case 0x90: // SUB A,B
571 | a = sub(a, b);
572 | case 0x91: // SUB A,C
573 | a = sub(a, c);
574 | case 0x92: // SUB A,D
575 | a = sub(a, d);
576 | case 0x93: // SUB A,E
577 | a = sub(a, e);
578 | case 0x94: // SUB A,H
579 | a = sub(a, h);
580 | case 0x95: // SUB A,L
581 | a = sub(a, l);
582 | case 0x96: // SUB A,(HL)
583 | a = sub(a, read(hl));
584 | case 0x97: // SUB A,A
585 | a = 0;
586 | hf = cf = false;
587 | zf = sf = true;
588 | case 0x98: // SBC A,B
589 | sbc(b);
590 | case 0x99: // SBC A,C
591 | sbc(c);
592 | case 0x9a: // SBC A,D
593 | sbc(d);
594 | case 0x9b: // SBC A,E
595 | sbc(e);
596 | case 0x9c: // SBC A,H
597 | sbc(h);
598 | case 0x9d: // SBC A,L
599 | sbc(l);
600 | case 0x9e: // SBC A,(HL)
601 | sbc(read(hl));
602 | case 0x9f: // SBC A,A
603 | if (cf)
604 | {
605 | zf = false;
606 | sf = hf = cf = true;
607 | a = 0xff;
608 | }
609 | else
610 | {
611 | hf = cf = false;
612 | zf = sf = true;
613 | a = 0;
614 | }
615 | case 0xa0: // AND B
616 | and(b);
617 | case 0xa1: // AND C
618 | and(c);
619 | case 0xa2: // AND D
620 | and(d);
621 | case 0xa3: // AND E
622 | and(e);
623 | case 0xa4: // AND H
624 | and(h);
625 | case 0xa5: // AND L
626 | and(l);
627 | case 0xa6: // AND (HL)
628 | and(read(hl));
629 | case 0xa7: // AND A
630 | zf = (a == 0);
631 | hf = true;
632 | sf = cf = false;
633 | case 0xa8: // XOR B
634 | xor(b);
635 | case 0xa9: // XOR C
636 | xor(c);
637 | case 0xaa: // XOR D
638 | xor(d);
639 | case 0xab: // XOR E
640 | xor(e);
641 | case 0xac: // XOR H
642 | xor(h);
643 | case 0xad: // XOR L
644 | xor(l);
645 | case 0xae: // XOR (HL)
646 | xor(read(hl));
647 | case 0xaf: // XOR A
648 | a = 0;
649 | zf = true;
650 | sf = hf = cf = false;
651 | case 0xb0: // OR B
652 | or(b);
653 | case 0xb1: // OR C
654 | or(c);
655 | case 0xb2: // OR D
656 | or(d);
657 | case 0xb3: // OR E
658 | or(e);
659 | case 0xb4: // OR H
660 | or(h);
661 | case 0xb5: // OR L
662 | or(l);
663 | case 0xb6: // OR (HL)
664 | or(read(hl));
665 | case 0xb7: // OR A
666 | zf = a == 0;
667 | cf = sf = hf = false;
668 | case 0xb8: // CMP B
669 | cmp(b);
670 | case 0xb9: // CMP C
671 | cmp(c);
672 | case 0xba: // CMP D
673 | cmp(d);
674 | case 0xbb: // CMP E
675 | cmp(e);
676 | case 0xbc: // CMP H
677 | cmp(h);
678 | case 0xbd: // CMP L
679 | cmp(l);
680 | case 0xbe: // CMP (HL)
681 | cmp(read(hl));
682 | case 0xbf: // CMP A
683 | cf = hf = false;
684 | zf = sf = true;
685 | case 0xc0: // RET !FZ
686 | if (!zf)
687 | {
688 | pc = popStack();
689 | ticks += 12;
690 | }
691 | case 0xc1: // POP BC
692 | bc = popStack();
693 | case 0xc2: // JP !FZ,nn
694 | if (!zf)
695 | {
696 | pc = read16pc();
697 | ticks += 4;
698 | }
699 | else
700 | {
701 | pc += 2;
702 | }
703 | case 0xc3: // JP nn
704 | pc = read16pc();
705 | case 0xc4: // CALL !FZ,nn
706 | if (!zf)
707 | {
708 | call();
709 | ticks += 12;
710 | }
711 | else
712 | {
713 | pc += 2;
714 | }
715 | case 0xc5: // PUSH BC
716 | pushStack(bc);
717 | case 0xc6: // ADD,n
718 | a = add(a, readpc());
719 | case 0xc7: // RST 0
720 | pushStack(pc);
721 | pc = 0;
722 | case 0xc8: // RET FZ
723 | if (zf)
724 | {
725 | pc = popStack();
726 | ticks += 12;
727 | }
728 | case 0xc9: // RET
729 | pc = popStack();
730 | case 0xca: // JP FZ,nn
731 | if (zf)
732 | {
733 | pc = read16pc();
734 | ticks += 4;
735 | }
736 | else
737 | {
738 | pc += 2;
739 | }
740 | case 0xcb: // secondary op set
741 | secondaryOp(readpc());
742 | case 0xcc: // CALL FZ,nn
743 | if (zf)
744 | {
745 | call();
746 | ticks += 12;
747 | }
748 | else
749 | {
750 | pc += 2;
751 | }
752 | case 0xcd: // CALL nn
753 | call();
754 | case 0xce: // ADC A,n
755 | adc(readpc());
756 | case 0xcf: // RST 0x8
757 | rst(0x8);
758 | case 0xd0: // RET !FC
759 | if (!cf)
760 | {
761 | pc = popStack();
762 | ticks += 12;
763 | }
764 | case 0xd1: // POP DE
765 | de = popStack();
766 | case 0xd2: // JP !FC,nn
767 | if (!cf)
768 | {
769 | pc = read16pc();
770 | ticks += 4;
771 | }
772 | else
773 | {
774 | pc += 2;
775 | }
776 | // 0xd3 is illegal
777 | case 0xd4: // CALL !FC,nn
778 | if (!cf)
779 | {
780 | call();
781 | ticks += 12;
782 | }
783 | else
784 | {
785 | pc += 2;
786 | }
787 | case 0xd5: // PUSH DE
788 | pushStack(de);
789 | case 0xd6: // SUB A,n
790 | a = sub(a, readpc());
791 | case 0xd7: // RST 0x10
792 | rst(0x10);
793 | case 0xd8: // RET FC
794 | if (cf)
795 | {
796 | pc = popStack();
797 | ticks += 12;
798 | }
799 | case 0xd9: // RETI
800 | pc = popStack();
801 | ime = true;
802 | case 0xda: // JP FC,nn
803 | if (cf)
804 | {
805 | pc = read16pc();
806 | ticks += 4;
807 | }
808 | else
809 | {
810 | pc += 2;
811 | }
812 | // 0xdb is illegal
813 | case 0xdc: // CALL FC,nn
814 | if (cf)
815 | {
816 | call();
817 | ticks += 12;
818 | }
819 | else
820 | {
821 | pc += 2;
822 | }
823 | // 0xdd is illegal
824 | case 0xde: // SBC A,n
825 | sbc(readpc());
826 | case 0xdf: // RST 0x18
827 | rst(0x18);
828 | case 0xe0: // LDH (n),A
829 | write(0xff00 | readpc(), a);
830 | case 0xe1: // POP HL
831 | hl = popStack();
832 | case 0xe2: // LD (0xFF00+C),A
833 | write(0xFF00 | c, a);
834 | // 0xe3 is illegal
835 | // 0xe4 is illegal
836 | case 0xe5: // PUSH HL
837 | pushStack(hl);
838 | case 0xe6: // AND n
839 | and(readpc());
840 | case 0xe7: // RST 0x20
841 | rst(0x20);
842 | case 0xe8: // ADD SP,n
843 | var val = signed(readpc());
844 | var sum = (sp + val) & 0xffff;
845 | val = sp ^ val ^ sum;
846 | sp = sum;
847 | cf = Util.getbit(val, 8);
848 | hf = Util.getbit(val, 4);
849 | zf = sf = false;
850 | case 0xe9: // JP, (HL)
851 | pc = hl;
852 | case 0xea: // LD n,A
853 | write(read16pc(), a);
854 | // 0xeb is illegal
855 | // 0xec is illegal
856 | // 0xed is illegal
857 | case 0xee:
858 | xor(readpc());
859 | case 0xef: // RST 0x28
860 | rst(0x28);
861 | case 0xf0: // LDH A,(n)
862 | a = read(0xff00 | readpc());
863 | case 0xf1: // POP AF
864 | af = popStack();
865 | case 0xf2: // LD A,(0xFF00+C)
866 | a = read(0xFF00 | c);
867 | case 0xf3: // DI
868 | ime = false;
869 | // 0xf4 is illegal
870 | case 0xf5: // PUSH AF
871 | pushStack(af);
872 | case 0xf6: // OR n
873 | or(readpc());
874 | case 0xf7: // RST 0x30
875 | rst(0x30);
876 | case 0xf8: // LDHL SP,n
877 | var tmp = signed(readpc());
878 | hl = (sp + tmp) & 0xffff;
879 | zf = sf = false;
880 | tmp = sp ^ tmp ^ hl;
881 | cf = tmp & 0x100 == 0x100;
882 | hf = tmp & 0x10 == 0x10;
883 | case 0xf9: // LD SP,HL
884 | sp = hl;
885 | case 0xfa: // LD A,(nn)
886 | a = read(read16pc());
887 | case 0xfb: // EI
888 | ime = true;
889 | // 0xfc is illegal
890 | // 0xfd is illegal
891 | case 0xfe: // CMP n
892 | cmp(readpc());
893 | case 0xff: // RST 0x38
894 | rst(0x38);
895 |
896 | default:
897 | throw "Unrecognized opcode: " + StringTools.hex(op);
898 |
899 | }
900 |
901 | pc &= 0xffff;
902 | }
903 |
904 | inline function secondaryOp(op:Int)
905 | {
906 | ticks = tickValues2[op];
907 |
908 | switch (op)
909 | {
910 | case 0x00: // RLC B
911 | b = rlc(b);
912 | case 0x01: // RLC C
913 | c = rlc(c);
914 | case 0x02: // RLC D
915 | d = rlc(d);
916 | case 0x03: // RLC E
917 | e = rlc(e);
918 | case 0x04: // RLC H
919 | h = rlc(h);
920 | case 0x05: // RLC L
921 | l = rlc(l);
922 | case 0x06: // RLC (HL)
923 | write(hl, rlc(read(hl)));
924 | case 0x07: // RLC A
925 | a = rlc(a);
926 | case 0x08: // RRC B
927 | b = rrc(b);
928 | case 0x09: // RRC C
929 | c = rrc(c);
930 | case 0x0a: // RRC D
931 | d = rrc(d);
932 | case 0x0b: // RRC E
933 | e = rrc(e);
934 | case 0x0c: // RRC H
935 | h = rrc(h);
936 | case 0x0d: // RRC L
937 | l = rrc(l);
938 | case 0x0e: // RRC (HL)
939 | write(hl, rrc(read(hl)));
940 | case 0x0f: // RRC A
941 | a = rrc(a);
942 | case 0x10: // RL B
943 | b = rl(b);
944 | case 0x11: // RL C
945 | c = rl(c);
946 | case 0x12: // RL D
947 | d = rl(d);
948 | case 0x13: // RL E
949 | e = rl(e);
950 | case 0x14: // RL H
951 | h = rl(h);
952 | case 0x15: // RL L
953 | l = rl(l);
954 | case 0x16: // RL (HL)
955 | write(hl, rl(read(hl)));
956 | case 0x17: // RL A
957 | a = rl(a);
958 | case 0x18: // RR B
959 | b = rr(b);
960 | case 0x19: // RR C
961 | c = rr(c);
962 | case 0x1a: // RR D
963 | d = rr(d);
964 | case 0x1b: // RR E
965 | e = rr(e);
966 | case 0x1c: // RR H
967 | h = rr(h);
968 | case 0x1d: // RR L
969 | l = rr(l);
970 | case 0x1e: // RR (HL)
971 | write(hl, rr(read(hl)));
972 | case 0x1f: // RR A
973 | a = rr(a);
974 |
975 | case 0x20: // SLA B
976 | b = sla(b);
977 | case 0x21: // SLA C
978 | c = sla(c);
979 | case 0x22: // SLA D
980 | d = sla(d);
981 | case 0x23: // SLA E
982 | e = sla(e);
983 | case 0x24: // SLA H
984 | h = sla(h);
985 | case 0x25: // SLA L
986 | l = sla(l);
987 | case 0x26: // SLA (HL)
988 | write(hl, sla(read(hl)));
989 | case 0x27: // SLA A
990 | a = sla(a);
991 | case 0x28: // SRA B
992 | b = sra(b);
993 | case 0x29: // SRA C
994 | c = sra(c);
995 | case 0x2a: // SRA D
996 | d = sra(d);
997 | case 0x2b: // SRA E
998 | e = sra(e);
999 | case 0x2c: // SRA H
1000 | h = sra(h);
1001 | case 0x2d: // SRA L
1002 | l = sra(l);
1003 | case 0x2e: // SRA (HL)
1004 | write(hl, sra(read(hl)));
1005 | case 0x2f: // SRA A
1006 | a = sra(a);
1007 | case 0x30: // SWAP B
1008 | b = swap(b);
1009 | case 0x31: // SWAP C
1010 | c = swap(c);
1011 | case 0x32: // SWAP D
1012 | d = swap(d);
1013 | case 0x33: // SWAP E
1014 | e = swap(e);
1015 | case 0x34: // SWAP H
1016 | h = swap(h);
1017 | case 0x35: // SWAP L
1018 | l = swap(l);
1019 | case 0x36: // SWAP (HL)
1020 | write(hl, swap(read(hl)));
1021 | case 0x37: // SWAP A
1022 | a = swap(a);
1023 | case 0x38: // SRL B
1024 | b = srl(b);
1025 | case 0x39: // SRL C
1026 | c = srl(c);
1027 | case 0x3a: // SRL D
1028 | d = srl(d);
1029 | case 0x3b: // SRL E
1030 | e = srl(e);
1031 | case 0x3c: // SRL H
1032 | h = srl(h);
1033 | case 0x3d: // SRL L
1034 | l = srl(l);
1035 | case 0x3e: // SRL (HL)
1036 | write(hl, srl(read(hl)));
1037 | case 0x3f: // SRL A
1038 | a = srl(a);
1039 | case 0x40: // BIT 0,B
1040 | bit(b, 0);
1041 | case 0x41: // BIT 0,C
1042 | bit(c, 0);
1043 | case 0x42: // BIT 0,D
1044 | bit(d, 0);
1045 | case 0x43: // BIT 0,E
1046 | bit(e, 0);
1047 | case 0x44: // BIT 0,H
1048 | bit(h, 0);
1049 | case 0x45: // BIT 0,L
1050 | bit(l, 0);
1051 | case 0x46: // BIT 0,(HL)
1052 | bit(read(hl), 0);
1053 | case 0x47: // BIT 0,A
1054 | bit(a, 0);
1055 | case 0x48: // BIT 1,B
1056 | bit(b, 1);
1057 | case 0x49: // BIT 1,C
1058 | bit(c, 1);
1059 | case 0x4a: // BIT 1,D
1060 | bit(d, 1);
1061 | case 0x4b: // BIT 1,E
1062 | bit(e, 1);
1063 | case 0x4c: // BIT 1,H
1064 | bit(h, 1);
1065 | case 0x4d: // BIT 1,L
1066 | bit(l, 1);
1067 | case 0x4e: // BIT 1,(HL)
1068 | bit(read(hl), 1);
1069 | case 0x4f: // BIT 1,A
1070 | bit(a, 1);
1071 | case 0x50: // BIT 2,B
1072 | bit(b, 2);
1073 | case 0x51: // BIT 2,C
1074 | bit(c, 2);
1075 | case 0x52: // BIT 2,D
1076 | bit(d, 2);
1077 | case 0x53: // BIT 2,E
1078 | bit(e, 2);
1079 | case 0x54: // BIT 2,H
1080 | bit(h, 2);
1081 | case 0x55: // BIT 2,L
1082 | bit(l, 2);
1083 | case 0x56: // BIT 2,(HL)
1084 | bit(read(hl), 2);
1085 | case 0x57: // BIT 2,A
1086 | bit(a, 2);
1087 | case 0x58: // BIT 3,B
1088 | bit(b, 3);
1089 | case 0x59: // BIT 3,C
1090 | bit(c, 3);
1091 | case 0x5a: // BIT 3,D
1092 | bit(d, 3);
1093 | case 0x5b: // BIT 3,E
1094 | bit(e, 3);
1095 | case 0x5c: // BIT 3,H
1096 | bit(h, 3);
1097 | case 0x5d: // BIT 3,L
1098 | bit(l, 3);
1099 | case 0x5e: // BIT 3,(HL)
1100 | bit(read(hl), 3);
1101 | case 0x5f: // BIT 3,A
1102 | bit(a, 3);
1103 | case 0x60: // BIT 4,B
1104 | bit(b, 4);
1105 | case 0x61: // BIT 4,C
1106 | bit(c, 4);
1107 | case 0x62: // BIT 4,D
1108 | bit(d, 4);
1109 | case 0x63: // BIT 4,E
1110 | bit(e, 4);
1111 | case 0x64: // BIT 4,H
1112 | bit(h, 4);
1113 | case 0x65: // BIT 4,L
1114 | bit(l, 4);
1115 | case 0x66: // BIT 4,(HL)
1116 | bit(read(hl), 4);
1117 | case 0x67: // BIT 4,A
1118 | bit(a, 4);
1119 | case 0x68: // BIT 5,B
1120 | bit(b, 5);
1121 | case 0x69: // BIT 5,C
1122 | bit(c, 5);
1123 | case 0x6a: // BIT 5,D
1124 | bit(d, 5);
1125 | case 0x6b: // BIT 5,E
1126 | bit(e, 5);
1127 | case 0x6c: // BIT 5,H
1128 | bit(h, 5);
1129 | case 0x6d: // BIT 5,L
1130 | bit(l, 5);
1131 | case 0x6e: // BIT 5,(HL)
1132 | bit(read(hl), 5);
1133 | case 0x6f: // BIT 5,A
1134 | bit(a, 5);
1135 | case 0x70: // BIT 6,B
1136 | bit(b, 6);
1137 | case 0x71: // BIT 6,C
1138 | bit(c, 6);
1139 | case 0x72: // BIT 6,D
1140 | bit(d, 6);
1141 | case 0x73: // BIT 6,E
1142 | bit(e, 6);
1143 | case 0x74: // BIT 6,H
1144 | bit(h, 6);
1145 | case 0x75: // BIT 6,L
1146 | bit(l, 6);
1147 | case 0x76: // BIT 6,(HL)
1148 | bit(read(hl), 6);
1149 | case 0x77: // BIT 6,A
1150 | bit(a, 6);
1151 | case 0x78: // BIT 7,B
1152 | bit(b, 7);
1153 | case 0x79: // BIT 7,C
1154 | bit(c, 7);
1155 | case 0x7a: // BIT 7,D
1156 | bit(d, 7);
1157 | case 0x7b: // BIT 7,E
1158 | bit(e, 7);
1159 | case 0x7c: // BIT 7,H
1160 | bit(h, 7);
1161 | case 0x7d: // BIT 7,L
1162 | bit(l, 7);
1163 | case 0x7e: // BIT 7,(HL)
1164 | bit(read(hl), 7);
1165 | case 0x7f: // BIT 7,A
1166 | bit(a, 7);
1167 | case 0x80: // RES 0,B
1168 | b = res(b, 0);
1169 | case 0x81: // RES 0,C
1170 | c = res(c, 0);
1171 | case 0x82: // RES 0,D
1172 | d = res(d, 0);
1173 | case 0x83: // RES 0,E
1174 | e = res(e, 0);
1175 | case 0x84: // RES 0,H
1176 | h = res(h, 0);
1177 | case 0x85: // RES 0,L
1178 | l = res(l, 0);
1179 | case 0x86: // RES 0,(HL)
1180 | write(hl, res(read(hl), 0));
1181 | case 0x87: // RES 0,A
1182 | a = res(a, 0);
1183 | case 0x88: // RES 1,B
1184 | b = res(b, 1);
1185 | case 0x89: // RES 1,C
1186 | c = res(c, 1);
1187 | case 0x8a: // RES 1,D
1188 | d = res(d, 1);
1189 | case 0x8b: // RES 1,E
1190 | e = res(e, 1);
1191 | case 0x8c: // RES 1,H
1192 | h = res(h, 1);
1193 | case 0x8d: // RES 1,L
1194 | l = res(l, 1);
1195 | case 0x8e: // RES 1,(HL)
1196 | write(hl, res(read(hl), 1));
1197 | case 0x8f: // RES 1,A
1198 | a = res(a, 1);
1199 | case 0x90: // RES 2,B
1200 | b = res(b, 2);
1201 | case 0x91: // RES 2,C
1202 | c = res(c, 2);
1203 | case 0x92: // RES 2,D
1204 | d = res(d, 2);
1205 | case 0x93: // RES 2,E
1206 | e = res(e, 2);
1207 | case 0x94: // RES 2,H
1208 | h = res(h, 2);
1209 | case 0x95: // RES 2,L
1210 | l = res(l, 2);
1211 | case 0x96: // RES 2,(HL)
1212 | write(hl, res(read(hl), 2));
1213 | case 0x97: // RES 2,A
1214 | a = res(a, 2);
1215 | case 0x98: // RES 3,B
1216 | b = res(b, 3);
1217 | case 0x99: // RES 3,C
1218 | c = res(c, 3);
1219 | case 0x9a: // RES 3,D
1220 | d = res(d, 3);
1221 | case 0x9b: // RES 3,E
1222 | e = res(e, 3);
1223 | case 0x9c: // RES 3,H
1224 | h = res(h, 3);
1225 | case 0x9d: // RES 3,L
1226 | l = res(l, 3);
1227 | case 0x9e: // RES 3,(HL)
1228 | write(hl, res(read(hl), 3));
1229 | case 0x9f: // RES 3,A
1230 | a = res(a, 3);
1231 | case 0xa0: // RES 4,B
1232 | b = res(b, 4);
1233 | case 0xa1: // RES 4,C
1234 | c = res(c, 4);
1235 | case 0xa2: // RES 4,D
1236 | d = res(d, 4);
1237 | case 0xa3: // RES 4,E
1238 | e = res(e, 4);
1239 | case 0xa4: // RES 4,H
1240 | h = res(h, 4);
1241 | case 0xa5: // RES 4,L
1242 | l = res(l, 4);
1243 | case 0xa6: // RES 4,(HL)
1244 | write(hl, res(read(hl), 4));
1245 | case 0xa7: // RES 4,A
1246 | a = res(a, 4);
1247 | case 0xa8: // RES 5,B
1248 | b = res(b, 5);
1249 | case 0xa9: // RES 5,C
1250 | c = res(c, 5);
1251 | case 0xaa: // RES 5,D
1252 | d = res(d, 5);
1253 | case 0xab: // RES 5,E
1254 | e = res(e, 5);
1255 | case 0xac: // RES 5,H
1256 | h = res(h, 5);
1257 | case 0xad: // RES 5,L
1258 | l = res(l, 5);
1259 | case 0xae: // RES 5,(HL)
1260 | write(hl, res(read(hl), 5));
1261 | case 0xaf: // RES 5,A
1262 | a = res(a, 5);
1263 | case 0xb0: // RES 6,B
1264 | b = res(b, 6);
1265 | case 0xb1: // RES 6,C
1266 | c = res(c, 6);
1267 | case 0xb2: // RES 6,D
1268 | d = res(d, 6);
1269 | case 0xb3: // RES 6,E
1270 | e = res(e, 6);
1271 | case 0xb4: // RES 6,H
1272 | h = res(h, 6);
1273 | case 0xb5: // RES 6,L
1274 | l = res(l, 6);
1275 | case 0xb6: // RES 6,(HL)
1276 | write(hl, res(read(hl), 6));
1277 | case 0xb7: // RES 6,A
1278 | a = res(a, 6);
1279 | case 0xb8: // RES 7,B
1280 | b = res(b, 7);
1281 | case 0xb9: // RES 7,C
1282 | c = res(c, 7);
1283 | case 0xba: // RES 7,D
1284 | d = res(d, 7);
1285 | case 0xbb: // RES 7,E
1286 | e = res(e, 7);
1287 | case 0xbc: // RES 7,H
1288 | h = res(h, 7);
1289 | case 0xbd: // RES 7,L
1290 | l = res(l, 7);
1291 | case 0xbe: // RES 7,(HL)
1292 | write(hl, res(read(hl), 7));
1293 | case 0xbf: // RES 7,A
1294 | a = res(a, 7);
1295 | case 0xc0: // SET 0,B
1296 | b = set(b, 0);
1297 | case 0xc1: // SET 0,C
1298 | c = set(c, 0);
1299 | case 0xc2: // SET 0,D
1300 | d = set(d, 0);
1301 | case 0xc3: // SET 0,E
1302 | e = set(e, 0);
1303 | case 0xc4: // SET 0,H
1304 | h = set(h, 0);
1305 | case 0xc5: // SET 0,L
1306 | l = set(l, 0);
1307 | case 0xc6: // SET 0,(HL)
1308 | write(hl, set(read(hl), 0));
1309 | case 0xc7: // SET 0,A
1310 | a = set(a, 0);
1311 | case 0xc8: // SET 1,B
1312 | b = set(b, 1);
1313 | case 0xc9: // SET 1,C
1314 | c = set(c, 1);
1315 | case 0xca: // SET 1,D
1316 | d = set(d, 1);
1317 | case 0xcb: // SET 1,E
1318 | e = set(e, 1);
1319 | case 0xcc: // SET 1,H
1320 | h = set(h, 1);
1321 | case 0xcd: // SET 1,L
1322 | l = set(l, 1);
1323 | case 0xce: // SET 1,(HL)
1324 | write(hl, set(read(hl), 1));
1325 | case 0xcf: // SET 1,A
1326 | a = set(a, 1);
1327 | case 0xd0: // SET 2,B
1328 | b = set(b, 2);
1329 | case 0xd1: // SET 2,C
1330 | c = set(c, 2);
1331 | case 0xd2: // SET 2,D
1332 | d = set(d, 2);
1333 | case 0xd3: // SET 2,E
1334 | e = set(e, 2);
1335 | case 0xd4: // SET 2,H
1336 | h = set(h, 2);
1337 | case 0xd5: // SET 2,L
1338 | l = set(l, 2);
1339 | case 0xd6: // SET 2,(HL)
1340 | write(hl, set(read(hl), 2));
1341 | case 0xd7: // SET 2,A
1342 | a = set(a, 2);
1343 | case 0xd8: // SET 3,B
1344 | b = set(b, 3);
1345 | case 0xd9: // SET 3,C
1346 | c = set(c, 3);
1347 | case 0xda: // SET 3,D
1348 | d = set(d, 3);
1349 | case 0xdb: // SET 3,E
1350 | e = set(e, 3);
1351 | case 0xdc: // SET 3,H
1352 | h = set(h, 3);
1353 | case 0xdd: // SET 3,L
1354 | l = set(l, 3);
1355 | case 0xde: // SET 3,(HL)
1356 | write(hl, set(read(hl), 3));
1357 | case 0xdf: // SET 3,A
1358 | a = set(a, 3);
1359 | case 0xe0: // SET 4,B
1360 | b = set(b, 4);
1361 | case 0xe1: // SET 4,C
1362 | c = set(c, 4);
1363 | case 0xe2: // SET 4,D
1364 | d = set(d, 4);
1365 | case 0xe3: // SET 4,E
1366 | e = set(e, 4);
1367 | case 0xe4: // SET 4,H
1368 | h = set(h, 4);
1369 | case 0xe5: // SET 4,L
1370 | l = set(l, 4);
1371 | case 0xe6: // SET 4,(HL)
1372 | write(hl, set(read(hl), 4));
1373 | case 0xe7: // SET 4,A
1374 | a = set(a, 4);
1375 | case 0xe8: // SET 5,B
1376 | b = set(b, 5);
1377 | case 0xe9: // SET 5,C
1378 | c = set(c, 5);
1379 | case 0xea: // SET 5,D
1380 | d = set(d, 5);
1381 | case 0xeb: // SET 5,E
1382 | e = set(e, 5);
1383 | case 0xec: // SET 5,H
1384 | h = set(h, 5);
1385 | case 0xed: // SET 5,L
1386 | l = set(l, 5);
1387 | case 0xee: // SET 5,(HL)
1388 | write(hl, set(read(hl), 5));
1389 | case 0xef: // SET 5,A
1390 | a = set(a, 5);
1391 | case 0xf0: // SET 6,B
1392 | b = set(b, 6);
1393 | case 0xf1: // SET 6,C
1394 | c = set(c, 6);
1395 | case 0xf2: // SET 6,D
1396 | d = set(d, 6);
1397 | case 0xf3: // SET 6,E
1398 | e = set(e, 6);
1399 | case 0xf4: // SET 6,H
1400 | h = set(h, 6);
1401 | case 0xf5: // SET 6,L
1402 | l = set(l, 6);
1403 | case 0xf6: // SET 6,(HL)
1404 | write(hl, set(read(hl), 6));
1405 | case 0xf7: // SET 6,A
1406 | a = set(a, 6);
1407 | case 0xf8: // SET 7,B
1408 | b = set(b, 7);
1409 | case 0xf9: // SET 7,C
1410 | c = set(c, 7);
1411 | case 0xfa: // SET 7,D
1412 | d = set(d, 7);
1413 | case 0xfb: // SET 7,E
1414 | e = set(e, 7);
1415 | case 0xfc: // SET 7,H
1416 | h = set(h, 7);
1417 | case 0xfd: // SET 7,L
1418 | l = set(l, 7);
1419 | case 0xfe: // SET 7,(HL)
1420 | write(hl, set(read(hl), 7));
1421 | case 0xff: // SET 7,A
1422 | a = set(a, 7);
1423 | }
1424 | }
1425 |
1426 | inline function add(op1:Int, op2:Int)
1427 | {
1428 | var sum = op1 + op2;
1429 | hf = (op1 & 0xf) > (sum & 0xf);
1430 | cf = sum > 0xff;
1431 | sf = false;
1432 | sum &= 0xff;
1433 | zf = sum == 0;
1434 | return sum;
1435 | }
1436 |
1437 | inline function add16(op1:Int, op2:Int)
1438 | {
1439 | var sum = op1 + op2;
1440 | hf = (op1 & 0xfff) > (sum & 0xfff);
1441 | cf = sum > 0xffff;
1442 | sf = false;
1443 | sum &= 0xffff;
1444 | //zf = sum == 0;
1445 | return sum;
1446 | }
1447 |
1448 | inline function adc(op:Int)
1449 | {
1450 | var carry = cf ? 1 : 0;
1451 | var sum = a + op + carry;
1452 | hf = ((a & 0xf) + (op & 0xf) + carry > 0xf);
1453 | cf = sum > 0xff;
1454 | a = sum & 0xff;
1455 | zf = a == 0;
1456 | sf = false;
1457 | }
1458 |
1459 | //00 - 88 = 78
1460 | //hf should be false
1461 | inline function sub(op1:Int, op2:Int)
1462 | {
1463 | var sum = op1 - op2;
1464 | cf = sum < 0;
1465 | hf = (op1 & 0xf) < (op2 & 0xf);
1466 | zf = sum == 0;
1467 | sf = true;
1468 | return sum & 0xff;
1469 | }
1470 |
1471 | inline function sbc(op:Int)
1472 | {
1473 | var carry = cf ? 1 : 0;
1474 | var sum = a - op - carry;
1475 | hf = (a & 0xf) - (op & 0xf) - carry < 0;
1476 | cf = sum < 0;
1477 | a = sum & 0xff;
1478 | zf = a == 0;
1479 | sf = true;
1480 | }
1481 |
1482 | inline function inc(val:Int)
1483 | {
1484 | val = (val + 1) & 0xff;
1485 | zf = (val == 0);
1486 | hf = (val & 0xf) == 0;
1487 | sf = false;
1488 | return val & 0xff;
1489 | }
1490 |
1491 | inline function dec(val:Int)
1492 | {
1493 | val = (val - 1) & 0xff;
1494 | zf = val == 0;
1495 | hf = val & 0xf == 0xf;
1496 | sf = true;
1497 | return val & 0xff;
1498 | }
1499 |
1500 | inline function and(val:Int)
1501 | {
1502 | a &= val;
1503 | zf = (a == 0);
1504 | hf = true;
1505 | sf = cf = false;
1506 | }
1507 |
1508 | inline function xor(val:Int)
1509 | {
1510 | a ^= val;
1511 | zf = (a == 0);
1512 | sf = hf = cf = false;
1513 | }
1514 |
1515 | inline function or(val:Int)
1516 | {
1517 | a |= val;
1518 | zf = a == 0;
1519 | sf = cf = hf = false;
1520 | }
1521 |
1522 | inline function cmp(val:Int)
1523 | {
1524 | var diff = a - val;
1525 | hf = (diff & 0xf) > (a & 0xf);
1526 | cf = diff < 0;
1527 | zf = diff == 0;
1528 | sf = true;
1529 | }
1530 |
1531 | inline function call()
1532 | {
1533 | var newPc = read16pc();
1534 | pushStack(pc);
1535 | pc = newPc;
1536 | }
1537 |
1538 | inline function rst(addr:Int)
1539 | {
1540 | pushStack(pc);
1541 | pc = addr;
1542 | }
1543 |
1544 | inline function rlc(val:Int)
1545 | {
1546 | cf = val > 0x7f;
1547 | val = (val << 1 & 0xff) | (cf ? 1 : 0);
1548 | zf = val == 0;
1549 | sf = hf = false;
1550 | return val & 0xff;
1551 | }
1552 |
1553 | inline function rrc(val:Int)
1554 | {
1555 | cf = (val & 1) == 1;
1556 | val = (val >> 1 & 0xff) | (cf ? 0x80 : 0);
1557 | zf = val == 0;
1558 | sf = hf = false;
1559 | return val & 0xff;
1560 | }
1561 |
1562 | inline function rl(val:Int)
1563 | {
1564 | var newCf = val > 0x7f;
1565 | val = ((val << 1) & 0xff) | (cf ? 1 : 0);
1566 | cf = newCf;
1567 | hf = sf = false;
1568 | zf = val == 0;
1569 | return val & 0xff;
1570 | }
1571 |
1572 | inline function rr(val:Int)
1573 | {
1574 | var newCf = (val & 1) == 1;
1575 | val = ((val >> 1) & 0xff) | (cf ? 0x80 : 0);
1576 | cf = newCf;
1577 | hf = sf = false;
1578 | zf = val == 0;
1579 | return val & 0xff;
1580 | }
1581 |
1582 | inline function sla(val:Int)
1583 | {
1584 | cf = val > 0x7f;
1585 | val = (val << 1) & 0xff;
1586 | hf = sf = false;
1587 | zf = val == 0;
1588 | return val;
1589 | }
1590 |
1591 | inline function sra(val:Int)
1592 | {
1593 | cf = (val & 1) == 1;
1594 | val = (val & 0x80) | (val >> 1);
1595 | hf = sf = false;
1596 | zf = val == 0;
1597 | return val & 0xff;
1598 | }
1599 |
1600 | inline function swap(val:Int)
1601 | {
1602 | val = ((val & 0xf) << 4) | (val >> 4);
1603 | zf = val == 0;
1604 | cf = hf = sf = false;
1605 | return val & 0xff;
1606 | }
1607 |
1608 | inline function srl(val:Int)
1609 | {
1610 | cf = (val & 1) == 1;
1611 | val >>= 1;
1612 | hf = sf = false;
1613 | zf = val == 0;
1614 | return val & 0xff;
1615 | }
1616 |
1617 | inline function bit(val:Int, n:Int)
1618 | {
1619 | hf = true;
1620 | sf = false;
1621 | zf = !Util.getbit(val, n);
1622 | }
1623 |
1624 | inline function res(val:Int, n:Int)
1625 | {
1626 | return Util.setbit(val, n, false);
1627 | }
1628 |
1629 | inline function set(val:Int, n:Int)
1630 | {
1631 | return Util.setbit(val, n, true);
1632 | }
1633 |
1634 | inline function readpc()
1635 | {
1636 | return read((pc++) & 0xffff);
1637 | }
1638 |
1639 | inline function read16pc()
1640 | {
1641 | var val = read16(pc);
1642 | pc += 2;
1643 | return val;
1644 | }
1645 |
1646 | inline function read(addr:Int)
1647 | {
1648 | return memory.read(addr) & 0xff;
1649 | }
1650 |
1651 | inline function read16(addr:Int)
1652 | {
1653 | return read(addr) | (read(addr+1) << 8);
1654 | }
1655 |
1656 | inline function write(addr:Int, value:Int)
1657 | {
1658 | memory.write(addr, value & 0xff);
1659 | }
1660 |
1661 | inline function write16(addr:Int, value:Int)
1662 | {
1663 | write(addr, value);
1664 | write(addr+1, value >> 8);
1665 | }
1666 |
1667 | inline function pushStack(val:Int)
1668 | {
1669 | write((--sp) & 0xffff, val >> 8);
1670 | write((--sp) & 0xffff, val & 0xff);
1671 | sp &= 0xffff;
1672 | }
1673 |
1674 | inline function popStack()
1675 | {
1676 | return (read(sp++) | (read(sp++) << 8)) & 0xffff;
1677 | }
1678 |
1679 | inline function signed(n:Int)
1680 | {
1681 | return (n ^ 0x80) - 0x80;
1682 | }
1683 |
1684 | inline function interrupt(i:Int)
1685 | {
1686 | interruptsRequested[i] = false;
1687 | ime = false;
1688 | pushStack(pc);
1689 | pc = Interrupt.vectors[i];
1690 | tick(20);
1691 | halted = false;
1692 | }
1693 |
1694 | inline function bestPrediction(oldPrediction:Int, newPrediction:Int):Int
1695 | {
1696 | return (oldPrediction == -1 || newPrediction < oldPrediction) ? newPrediction : oldPrediction;
1697 | }
1698 |
1699 | inline function predictHalt()
1700 | {
1701 | // figure out which interrupt will break out of halt first,
1702 | // then wait for it
1703 | var awake:Int = -1;
1704 |
1705 | if (video.lcdDisplay)
1706 | {
1707 | // end of frame, wake up to yield control
1708 | awake = 456 * (154 - video.scanline) - video.cycles;
1709 |
1710 | if (interruptsEnabled[Interrupt.Vblank])
1711 | {
1712 | awake = 456 * (144 - video.scanline) - video.cycles;
1713 | }
1714 | if (interruptsEnabled[Interrupt.LcdStat])
1715 | {
1716 | if (video.hblankInterrupt)
1717 | {
1718 | var next = 252 - video.cycles;
1719 | if (next < 0) next += 456;
1720 | awake = bestPrediction(awake, next);
1721 | }
1722 | if (video.oamInterrupt)
1723 | {
1724 | awake = bestPrediction(awake, 456 - video.cycles);
1725 | }
1726 | if (video.coincidenceInterrupt)
1727 | {
1728 | var next = (video.coincidenceScanline - video.scanline) * 456 - video.cycles;
1729 | if (next < 0) next += (154 * 456);
1730 | awake = bestPrediction(awake, next);
1731 | }
1732 | }
1733 | }
1734 | if (timerEnabled)
1735 | {
1736 | var next = (0x100 - timerValue) * tacClocks - timerTicks;
1737 | awake = bestPrediction(awake, next);
1738 | }
1739 | // TODO: serial
1740 |
1741 | if (awake > cycles)
1742 | {
1743 | tick(awake - cycles);
1744 | }
1745 |
1746 | halted = false;
1747 | }
1748 |
1749 | inline function tick(ticks:Int)
1750 | {
1751 | cycleCount += ticks;
1752 | if (cycleCount > 536870912) cycleCount -= 536870912;
1753 | cycles += ticks;
1754 | apuCycles += ticks;
1755 | divTicks = (divTicks + ticks) & 0xffff;
1756 | if (timerEnabled)
1757 | {
1758 | if (timerPostpone) timerPostpone = false;
1759 | else tickTimer(ticks);
1760 | }
1761 | else timerPostpone = true;
1762 | }
1763 |
1764 | inline function tickTimer(ticks:Int)
1765 | {
1766 | timerTicks += ticks;
1767 | while (timerTicks >= tacClocks)
1768 | {
1769 | timerTicks -= tacClocks;
1770 | if (++timerValue == 0x100)
1771 | {
1772 | timerValue = timerMod;
1773 | irq(Interrupt.Timer);
1774 | }
1775 | }
1776 | }
1777 |
1778 | static var tickValues:Vector = Vector.fromArrayCopy([
1779 | /* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F*/
1780 | 4, 12, 8, 8, 4, 4, 8, 4, 20, 8, 8, 8, 4, 4, 8, 4, //0
1781 | 0, 12, 8, 8, 4, 4, 8, 4, 12, 8, 8, 8, 4, 4, 8, 4, //1
1782 | 8, 12, 8, 8, 4, 4, 8, 4, 8, 8, 8, 8, 4, 4, 8, 4, //2
1783 | 8, 12, 8, 8, 12, 12, 12, 4, 8, 8, 8, 8, 4, 4, 8, 4, //3
1784 | 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, //4
1785 | 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, //5
1786 | 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, //6
1787 | 8, 8, 8, 8, 8, 8, 0, 8, 4, 4, 4, 4, 4, 4, 8, 4, //7
1788 | 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, //8
1789 | 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, //9
1790 | 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, //A
1791 | 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 4, 8, 4, //B
1792 | 8, 12, 12, 16, 12, 16, 8, 16, 8, 16, 12, 0, 12, 24, 8, 16, //C
1793 | 8, 12, 12, 0, 12, 16, 8, 16, 8, 16, 12, 0, 12, 0, 8, 16, //D
1794 | 12, 12, 8, 0, 0, 16, 8, 16, 16, 4, 16, 0, 0, 0, 8, 16, //E
1795 | 12, 12, 8, 4, 0, 16, 8, 16, 12, 8, 16, 4, 0, 0, 8, 16 //F
1796 | ]);
1797 | static var tickValues2:Vector = Vector.fromArrayCopy([
1798 | /* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F*/
1799 | 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8, //0
1800 | 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8, //1
1801 | 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8, //2
1802 | 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8, //3
1803 | 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, //4
1804 | 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, //5
1805 | 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, //6
1806 | 8, 8, 8, 8, 8, 8, 12, 8, 8, 8, 8, 8, 8, 8, 12, 8, //7
1807 | 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8, //8
1808 | 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8, //9
1809 | 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8, //A
1810 | 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8, //B
1811 | 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8, //C
1812 | 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8, //D
1813 | 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8, //E
1814 | 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 16, 8 //F
1815 | ]);
1816 | }
1817 |
--------------------------------------------------------------------------------