Compare commits

...

293 Commits
v068 ... v091

Author SHA1 Message Date
Tim Allen
7f404e6edb Update to v091 release.
byuu says:

A few issues crept up in the last release, this should take care of
them.

First, it seems that the 32-bit runtime on 64-bit versions of Windows
have 64-bit time functions; whereas true 32-bit Windows does not. This
was causing a DLL error when attempting to load bsnes v090.

Second, when there were more than 2,000 files in the same folder on
Windows, it was lagging the file browser. With OV2's help, I've fixed
that and it'll now load the list instantly.

Lastly, I've included the missing video shaders this time.
2012-08-11 12:18:19 +10:00
Tim Allen
47dffcae85 Update to v090 release.
byuu says:

Most notably, this release adds Nintendo DS emulation. The Nintendo DS
module was written entirely by Cydrak, so please give him all of the
credit for it. I for one am extremely grateful to be allowed to use his
module in bsnes.

The Nintendo DS emulator's standalone name is dasShiny. You will need
the Nintendo DS firmware, which I cannot provide, in order to use it. It
also cannot (currently?) detect the save type used by NDS games. As
such, manifest.xml files must be created manually for this purpose. The
long-term plan is to create a database of save types for each game.
Also, you will need an analog input device for the touch screen for now
(joypad axes work well.)

There have also been a lot of changes from my end: a unified
manifest.xml format across all systems, major improvements to SPC7110
emulation, enhancements to RTC emulation, MSU1 enhancements, icons in
the file browser list, improvements to SNES coprocessor memory mapping,
cleanups and improvements in the libraries used to build bsnes, etc.

I've also included kaijuu (which allows launching game folders directly
with bsnes) and purify (which allows opening images that are compressed,
have copier headers, and have wrong extensions); both of which are fully
GUI-based.

This release only loads game folders, not files. Use purify to load ROM
files in bsnes.

Note that this will likely be the last release for a long time, and that
I will probably rename the emulator for the next release, due to how
many additional systems it now supports.
2012-08-08 00:08:37 +10:00
Tim Allen
be625cc0fb Update to v089r18 release.
byuu says:

Changelog:
- fixed bsnes to let config files and system folders to be in the same
  folder as the executable
- fixed RawInput driver to compile again without linear_vector
- fixed phoenix/Windows to compile again without linear_vector
- fixed old vs new name warnings on MinGW w64 (technically the warnings
  were erroneous, but I worked around them anyway)
- added memory export hotkey (SNES driver only; mainly for FEoEZ
  translation)
- restored WRAM randomization for v090 stability (we can discuss that
  idea for v091+)
- fixed SuperFX / SA-1 "0x" prefix in the header generation (drop it
  into the latest purify if you want)
- added nall/Makefile uname support for UnxUtils (was breaking
  compilation with full UnxUtils in your path otherwise)
2012-08-07 23:28:00 +10:00
Tim Allen
4cb8b51606 Update to purify v00r07 release.
byuu says:

This update uses the latest manifest.xml mappings. It also adds a new
"Update Manifests" button that can be used to quickly regenerate all
manifests (sans Famicom games ... since I strip the iNES header, that
information is gone. We can't support Famicom manifest.xml updates until
we have a database.) This is different than the before wrapping of the
functionality on the convert games button. You can also trigger this on
the command-line with "purify synchronize"

g6672D, great catch. This was fixed, thank you.

[g6672D's bug was: "SA-1 and SuperFX are missing the "0x" for
program.rom/save.rwm size." - Ed.]
2012-07-23 22:53:28 +10:00
Tim Allen
87cb164f7c Update to v089r17 release.
byuu says:

This implements the spec from the XML part 3 thread:

    http://board.byuu.org/viewtopic.php?f=16&t=2998

It's also propagated the changes to nall and purify, so you can test
this one.

This is basically it, after years of effort I feel I finally have
a fully consistent and logical XML board format.
The only things left to change will be: modifications if emulation turns
out to be incorrect (eg we missed some MMIO mirrors, or mirrored too
much), and new additions.

And of course, I'm giving it a bit of time for good arguments against
the format.

Other than that, this release removes linear_vector and pointer_vector,
as vector is better than linear_vector and I've never used
pointer_vector.
vector also gets move(), which is a way to use move-semantics across
types. It lets you steal the underlying memory pool, effectively
destroying the vector without a copy.
This works really nicely with the move for read() functions to return
vector<uint8> instead of taking (uint8_t*&, unsigned&) parameters.
2012-07-22 22:27:18 +10:00
Tim Allen
c1318961d8 Update to v089r16 release.
byuu says:

Changelog:
- eliminated <mmio>, <mcu> tags [they are merged to their parent nodes
  now]
- added <ram name= size=> tag to EpsonRTC, SharpRTC
- added <firmware> tag to DSP-n, ST-01n, ST-018, Cx4
- interface->path(0) now returns the system folder, which can be used
  for storage now
- as a fun proof-of-concept, I've simulated SNES warm power cycles by
  saving and loading work RAM (same effect if you instantly swapped
  carts)
  - long-term, I'm not sure how I want to do this. The power menu option
    makes no sense with warm RAM
  - I like the idea of decaying RAM based on timestamp from last play;
    and power can just force the timestamp to 0 (which will corrupt all
    RAM)
- Interface::firmware is gone. The cores now load firmware inside their
  boot up routines
- you now get a message on the screen if the emulator can't find
  firmware, should help with "I just get a black screen" messages

I'd like to start preparing for a v090 release. I think we're almost
there now. Have to update nall/cartridge and purify to handle XML
changes first.
2012-07-22 22:27:14 +10:00
Tim Allen
791e64951b Update to v089r15 release.
byuu says:

Changelog:
- SuperFX has its own ROM and RAM
- Cx4 has its own ROM
- SPC7110 has its own ProgramROM, DataROM and RAM
- OBC1 has its own RAM
- BsxCartridge has its own ROM, RAM and PSRAM
- mapping changes to accommodate the above
2012-07-09 21:40:23 +10:00
Tim Allen
27af50099f Update to v089r14 release.
byuu says:

Changelog:
- NSS emulation improvement (DIP is 8-bits, not 16-bits; can be remapped
  via XML now like all the other chips)
- SA-1 memory map improvements (IRAM and BWRAM can be saved; ROM, IRAM
  and BWRAM are separate from Cartridge::ROM, RAM; no MCU)
- S-DD1 memory map improvements (ROM, RAM inside mapping; no MCU)
- SPC7110 memory map improvements (ROM, RAM inside mapping; no MCU; not
  finished yet [have to handle 8mbit expansion somehow now)

I have tried multiple times now to get the SuperFX core to use internal
ROM and RAM (separate from Cartridge::ROM, RAM) to no avail.
Not sure what the hell is going on there. Trace logs of 430MB are not
enticing ...

So right now: SuperFX, SPC7110 and BS-X cheat by mapping stuff to
Cartridge::ROM, RAM still. They need to not do that.
2012-07-08 12:57:34 +10:00
Tim Allen
fbd52c7e5f Update to v089r13 release.
[also, replace the old purify tool with the new tool by the same name.
There were some previous releases outside the WIP thread, but this is
the first one that actually works with a WIP release. -Ed.]

byuu says:

Fixes up loading issues with recent purify changes, and purify also
works on BS/ST file types now and should be a bit more crash-resistant.
2012-06-25 22:49:39 +10:00
Tim Allen
36795e8061 Update to v089r12 release.
byuu says:

Changelog:
- Game Boy XML uses <cartridge><board type="MBC3"/> instead of
  <cartridge mapper="MBC3">
- if you run bsnes with a filename argument, it will invoke "purify
  filename" and exit immediately
  - this chains: purify will turn the file into a game folder, and then
    invoke bsnes with the game folder name
    - net result: you can drag a ZIP file onto bsnes or associate SMC
      headered ROMs with bsnes and they'll just work
- new nall: unified usage of - vs _ vs nothing on filenames; fancier
  lstring; fancier image (constructor for creating from filename or from
  memory); etc
- new phoenix: images in ListView, GTK+ merges the check box into the
  first column like the other targets do, etc
- browser list now uses icons to differentiate system folders from game
  folders (the game folder icon sucks, I'm open to suggestions though,
  as long as it's available on Debian Squeeze in /usr/share/icons, no
  custom stuff please)
2012-06-18 20:13:51 +10:00
Tim Allen
ec8350794a Update to v089r11 release.
byuu says:

Changelog:
- SPC7110 $480b (and its settings in $4805-6 + $4807) is now fully
  emulated
- decompressor restructured and commented accordingly

The final parts remaining for the SPC7110 core, all within the
decompression engine:
- need to detect when 15+ input bytes are read for one output byte and
  simulate a crash somehow (don't have to perfectly simulate corrupted
  data stream)
- need to emulate time required to decompress data (doesn't have to be
  perfect, just something other than instantaneous)
- need to determine what $480c status flags d6-d0 are for, as best we
  can anyway
2012-06-06 19:57:53 +10:00
Tim Allen
4545e7c62d Update to v089r10 release.
byuu says:

Changelog:
- Cydrak merged all three SPC7110 decompression routines into one, cuts
  the size in half
- fixed masking of $4803.d7 and $4813.d7
- data port out of bounds accesses emulated correctly for app SPC7110
  boards
- all(?) data port $4810 reload cases now supported
- basic timing for $4805-6 seeking; reworked delay timing to work better
  as well
- fixed $480c.d7 flag (1 = ready, not busy)
- AbsoluteInput returns -32768 if presentation window lacks focus and
  you don't always allow input
2012-05-31 22:27:46 +10:00
Tim Allen
3302398907 Update to v089r09 release.
byuu says:

Changelog:
- SPC7110 data port emulation greatly improved
- SPC7110 $480b.d1 emulated (but $4805-4806 does not work right for mode
  2 decompression yet)
- MSU1 audio output will be muted when the S-DSP FLG ($6c).d6 (mute)
  flag is set
- MSU1 will read filenames from manifest now (defaults to msu1.rom and
  track-#.pcm if missing ... for now)
- bugfixes with MSU1 load state and track seek (and $4804 was wrapping
  into $4805 to change the track#)
- Link coprocessor removed (it was meant for ST018 HLE, which never
  happened)

Notes for things I forgot but need to address:
- $4813 needs to be uint7 for the set_data_offset() to not allow reading
  A23 as set ever (or we can mask)
- AbsoluteInput when window doesn't have focus should return -32768, not
  0
- need to support input ID lists that aren't linear (0-7), but arbitrary
  (0,1,6,7 or whatever)
2012-05-29 22:20:46 +10:00
Tim Allen
189e707594 Update to v089r08 release.
byuu says:

Changelog:
- Super Game Boy, BS-X Satellaview and Sufami Turbo cartridges all load
  manifests that specify their file names, and they all work
- Sufami Turbo can now properly handle carts without RAM, or empty slots
  entirely
- Emulator::Interface structures no longer specify any file names, ever
- exposed "capability.(cheats,states)" now. So far, this just means the
  GBA doesn't show the cheat editor, since it doesn't support cheat
  codes yet
- as such, state manager and cheat editor windows auto-hide (may be
  a tiny bit inconvenient, but it makes not having to sync them or deal
  with input when no cart is loaded easier)
- added "AbsoluteInput" type, which returns mouse coordinates from
  -32767,-32767 (top left) to +32767,+32767 (bottom right) or
  -32768,-32768 (offscreen)

AbsoluteInput is just something I'm toying with. Idea is to support eg
Super Scope or Justifier, or possibly some future Famicom controllers
that are absolute-indexed. The coordinates are scaled, so the bigger
your window, the more precise they are. But obviously you can't get more
precise than the emulated system, so 1x scale will behave the same
anyway. I haven't hooked it up yet, need to mess with the idea of custom
cursors via phoenix for that first. Also not sure if it will feel
smoother or not ... if you resize the window, your mouse will seem to
move slower. Still, not having to capture the mouse for SS/JS may be
nicer yet. But we'll see ... just experimenting for now.
2012-05-28 09:50:50 +10:00
Tim Allen
9a8a54c75e Update to v089r07 release.
byuu says:

Not even purify makes compatible images for this WIP.
Unless you want to figure it out yourself, I'd suggest waiting for an
updated tool before using subsequent WIPs.

Changelog:
- MSU1 initializes data port + audio track to 0
- MSU1 implements audio track error flag on $2000.d3
- manifest.xml now controls file names for cartridge folders ... mostly

Regressions:
- Super Game Boy support is broken
- Sufami Turbo support is broken

So, basically Emulator::Interface() now has:

    void load(const string &manifest);
    void save();

The first one will analyze the manifest, and call all the ROM + RAM
loadRequest() commands necessary to run the game.
The second one will call saveRequest() commands on all writable and
non-volatile storage (basically if it's a RAM type and has a filename
specified, it gets saved to disk.)
save() shrinks the size of Emulator::Interface() by hiding information
one is unlikely to care about. It also makes it much easier to save.
The core auto-calls this when you unload a game as well. So the only
time you ever have to worry about it is if you want to save RAM files
mid-game (in case you want to do periodic backups in case of a crash.)
2012-05-26 18:18:42 +10:00
Tim Allen
d418eda97c Update to v089r06 release.
[Yes, the release number is re-used. -Ed.]

byuu says:

I had some bugs in r07 that I couldn't track down, DKJM2's clock was
getting all out of sync.
So I just reverted to r05, blew away both RTCs entirely, and wrote them
cleanly from scratch (obviously looking off the old code.) A bit
extreme, but it worked.
I believe I found the error in the process, day and month were resetting
the counter to 0 instead of 1, it wasn't handling leap year, etc.
While I was at it, I fixed the day-of-week calculation. The SharpRTC
epoch is actually 1000-01-01, and not 1900-01-01.
I'm sure you guys will be really happy that if it ever becomes 1000AD
again and you're playing a ROM hack that uses the SharpRTC and relies on
its weekday value that it will show the correct day now ...
Kind of a pain to compute, but nothing compared to the seventh circle of
hell that was my IBM dBase III Julian<>Gregorian conversion functions :/
Also found a few bugs in the Epson code this way. And I moved the round
seconds actions and flag clear to +125us after flag set.

So, if you had the old r06 or r07, please delete those.

Unfortunately, this took all of my energy today, so the file names
inside manifest changes will have to be in the next WIP.

EDIT: ran a diff against old r07 and new r06.
- added if(days == 31) case twice in EpsonRTC::tick_day()
- forgot weekday = 0; in SharpRTC::load()
- need to move the cartridge+cheat objects up in sfc/Makefile again
- System::init() needs assert(interface != nullptr /* not 0 */)
2012-05-25 09:26:06 +10:00
Tim Allen
5dbd5f4d0f Update to v089r07 release.
byuu says:

Changelog:
- EpsonRTC emulation improved further (stop/pause blocks IRQs, verified
  secondhi >= 3 triggers 30-second adjust (even on invalid BCD),
  second-changed flag is mirrored to minute+hour+day+month+weekday,
  improved busy timing, etc.)
- SharpRTC rewritten, works like EpsonRTC now in that it has its own
  timing thread and ticks with the emulation
- won't attempt to read from an unopen file stream now (I think this is
  what was crashing Sufami Turbo without SRAM?)
- added Tools -> Synchronize Time option below load/save state options.
  Only appears when you play a game with an emulated RTC chip

Just realized that I used 125ms for the 30-second adjust instead of
125us, so I'll fix that in the next WIP.
Aside from that, this is as good as the emulation is going to get.
There's still a couple of absolutely psychopathic edge cases that are
just too damn difficult to simulate.
So that leaves us with data port control + decompression status
registers to investigate before SPC7110 will be finished.
2012-05-23 21:27:45 +10:00
Tim Allen
d6001a2df4 Update to v089r06 release.
byuu says:

Changelog:
- renamed SRTC -> SharpRTC
- renamed RTC4513 -> EpsonRTC (consistent with DSP naming schema)
- full emulation of invalid BCD values for EpsonRTC
- fixed EpsonRTC IRQ mask

Remaining SPC7110 tasks:
- RTC: test 30-second adjust with all values from 00-7f
- RTC: hold is supposed to tick the clock one second after being
  released?
- RTC: wait times are too long (need to use >32KHz oscillation to
  simulate it properly)
- Data Port: test $4818 more thoroughly (not too important)
- Decompression: test $480c more thoroughly (very important)
- Decompression: perform some tests on DMA transferring data, especially
  with $4807 set

Write-offs, at least for now:
- Decompression: emulation of the crash/glitch behavior seen on the real
  chip when fed invalid data
- Decompression: I can find no use of $4808
- ALU: Booth cycles for MUL/DIV (this could actually be rather important
  if the game reads simpler values quickly [some shoddy games did this
  with the CPU ALU])
- RTC: delay after hold release for $4841 accesses
- RTC: 125uS delay after 30-second adjust that will screw with registers
  in odd ways if your read or write too soon
- RTC: psychotic behavior of reading too early returning port address
  - 1
2012-05-22 22:10:00 +10:00
Tim Allen
bd61432322 Update to v089r05 release.
byuu says:

I split the RTC-4513 code from the SPC7110 code (and obviously in the
XML mapping as well), since they are separate chips on the FEoEZ PCB.
In this way, you can use just the RTC-4513 in homebrew now if you want.
It's a bit nicer than the Sharp RTC from Dai Kaijuu Monogatari II.
This was needed anyway, it has an internal oscillator that's not
divisible by the SNES clock used by the SPC7110; and both the RTC and
decompression code need to be running their own threads anyway.

In the process, I rewrote the way variables are stored to use named
integers rather than a block of memory. Makes the code a lot easier on
the eyes, and more importantly, will make emulating bad BCD values
a whole lot easier.
2012-05-21 20:56:48 +10:00
Tim Allen
0611fefefa Update to v089r04 release.
byuu says:

Changelog: (SPC7110)
- emulated $480b.d0 + $4807 deinterleave mode
- cleaned up decompression core (I'd still like to wipe out those static
  variables, those are bad for save states.)
- improved emulation of data port ($481a only increments, never reads)
- improved emulation of RTC (block appropriate bits in the hour register
  based on 12/24h mode select; $4840 modes != 1 all disable the chip;
  added MDR; etc.)
2012-05-19 16:28:54 +10:00
Tim Allen
6ac7b733bd Update to v089r03 release.
byuu says:

Substantial improvements to SPC7110 emulation. Added all of the findings
from http://byuu.org/temp/spc7110-mmio.txt that I understood.

I also completely rewrote the RTC. We only had about ~40% of the chip
emulated before. Turns out there's cool stuff like spare RAM, calendar
disable, 12-hour mode, IRQs, IRQ masking, duty cycles, etc. So I went
ahead and emulated all of it. The upper bits on hour+ don't work as
nocash described though, not sure what doc he was reading. The Epson
RTC-4513 manual I have doesn't explain any of the registers.
The new RTC core also ticks seconds based on the emulated clock, and not
on the system clock. This is going to suck for people wanting to keep
the in-game clock synced with their computer, who also abuse fast
forward and save states. Fast forward makes the clock run faster, and
save states will jump the clock to the time it was at when you took the
save state. (It will keep track of the number of seconds between
unloading the game and loading it again, so time passes normally there.)
This is required, however, and how I'm going to rearrange all of the
RTCs for all systems. Any other method can be detected by the game, and
is thus not faithful emulation. To help with this, I'll probably make an
RTC time tool so that you can adjust the time when the emulator isn't
running, but I don't intend to bundle that into bsnes.
New state format bit-packs the RTCRAM values, and it also uses a 64-bit
timestamp. So it's 16 bytes now instead of 20 bytes. S-RTC will drop
from 16 to 12 when it's done.
The RTC busy flag timing needs to be refined with more hardware tests,
there's a slim chance of the game hanging on save at the moment.

The SPC7110 ALU delays are emulated now, too. They may not be perfectly
accurate, but they get the basic gist down.
The only hack that needs to be removed now is the decompression busy
flag. That's ... not going to be fun.

I also redid the mouse emulation. I was polling the mouse position
multiple times per latch. So it should be a bit more precise now,
I hope.
I read it regardless of latch state, dunno if that's good or not.
2012-05-16 10:27:34 +10:00
Tim Allen
a1e4c67a05 Update to v089r02 release.
(r01 was not posted to the WIP thread)

byuu says:

r01 changelog:
- major improvements to SPC7110 MCU (memory controller unit)
- revised SPC7110 memory map to reflect aforementioned improvements
- added "Toggle Tracer" hotkey to target-ethos (only works for SFC so
  far, I plan to use this as a lightweight laevateinn for FEoEZ)

r02 changelog:
- quick fix: SRAM is mapped to 00-3f|80-bf:6000-7fff
- quick fix: $4830.d7 is SRAM chip enable, not SRAM write enable. Reads
  return 0x00 when this bit is clear
2012-05-14 23:32:55 +10:00
Tim Allen
73ebe093b8 Update to v089 release.
byuu says:

Changelog to v089:
- fix SA-1 Mini Yonku Shining Scorpion
- load from command-line
- remove SNES::Cartridge::NVRAM
- fix SGB save RAM
- update cheats.xml
- already mapped inputs cancel input assign

BS-X wasn't broken after all. I forgot that I ran purify on my BS-X
images, and that the BS Zelda ZIP I have has the disable ROM bit set.
Whoops.
2012-05-12 12:34:35 +10:00
Tim Allen
c3f9d421da Update to v088r16 release.
byuu says:

Changelog:
- fixed BGnxOFS to not cache when MOSAIC is not in effect [fixes Air
  Strike Patrol "Good Luck" text]
- added GameBoy::Interface::Hook for SGB bindings [SGB works again]
- do not create bsnes/ folder unless it is absolutely needed (eg you
  create a save state or state manager archive)
- SuperFX works [needed to call system.init() in Interface::Interface()]

Last chance for any bug reports, at this point I pretty much consider
ethos to be finished. It's shipping without BS-X BIOS game loading
support. Sorry, I can't figure that one out.
2012-05-10 09:35:29 +10:00
Tim Allen
689fc49047 Update to v088r15 release.
byuu says:

Changelog:
- default placement of presentation window optimized for 1024x768
  displays or larger (sorry if yours is smaller, move the window
  yourself.)
- Direct3D waits until a previous Vblank ends before waiting for the
  next Vblank to begin (fixes video timing analysis, and ---really---
  fast computers.)
- Window::setVisible(false) clears modality, but also fixed in Browser
  code as well (fixes loading images on Windows hanging)
- Browser won't consume full CPU resources (but timing analysis will,
  I don't want stalls to affect the results.)
- closing settings window while analyzing stops analysis
- you can load the SGB BIOS without a game (why the hell you would want
  to ...)
- escape closes the Browser window (it won't close other dialogs, it has
  to be hooked up per-window)
- just for fun, joypad hat up/down moves in Browser file list, any
  joypad button loads selected game [not very useful, lacks repeat, and
  there aren't GUI load file open buttons]
- Super Scope and Justifier crosshairs render correctly (probably
  doesn't belong in the core, but it's not something I suspect people
  want to do themselves ...)
- you can load GB, SGB, GB, SGB ... without problems (not happy with how
  I did this, but I don't want to add an Interface::setInterface()
  function yet)
- PAL timing works as I want now (if you want 50fps on a 60hz monitor,
  you must not use sync video) [needed to update the DSP frequency when
  toggling video/audio sync]
- not going to save input port selection for now (lot of work), but it
  will properly keep your port setting across cartridge loads at least
  [just goes to controller on emulator restart]
- SFC overscan on and off both work as expected now (off centers image,
  on shows entire image)
- laevateinn compiles properly now
- ethos goes to ~/.config/bsnes now that target-ui is dead [honestly,
  I recommend deleting the old folder and starting over]
- Emulator::Interface callbacks converted to virtual binding structure
  that GUI inherits from (simplifies binding callbacks)
    - this breaks Super Game Boy for a bit, I need to rethink
      system-specific bindings without direct inheritance

Timing analysis works spectacularly well on Windows, too. You won't get
your 100% perfect rate (unless maybe you leave the analysis running
overnight?), but it'll get really freaking close this way.
2012-05-08 09:29:03 +10:00
Tim Allen
cb97d98ad2 Update to v088r14 release.
byuu says:

Changelog:
- added NSS DIP switch settings window (when loading NSS carts with
  appropriate manifest.xml file)
- added video shader selection (they go in ~/.config/bsnes/Video
  Shaders/ now)
- added driver selection
- added timing settings (not only allows video/audio settings, also has
  code to dynamically compute the values for you ... and it actually
  works pretty good!)
- moved "None" controller device to bottom of list (it is the least
  likely to be used, after all)
- added Interface::path() to support MSU1, USART, Link
- input and hotkey mappings remember list position after assignment
- and more!

target-ethos now has all of the functionality of target-ui, and more.
Final code size for the port is 101.2KB (ethos) vs 167.6KB (ui).
A ~67% reduction in code size, yet it does even more! And you can add or
remove an entire system with only three lines of code (Makefile include,
header include, interface append.)

The only problem left is that the BS-X BIOS won't load the BS Zelda no
Densetsu file.
I can't figure out why it's not working, would appreciate any
assistance, but otherwise I'm probably just going to leave it broken for
v089, sorry.

So the show stoppers for a new release at this point are:
- fix laevateinn to compile with the new interface changes (shouldn't be
  too hard, it'll still use the old, direct interface.)
- clean up Emulator::Interface as much as possible (trim down
  Information, mediaRequest should use an alternate struct designed to
  load firmware / slots separately)
- enhance purify to strip SNES ROM headers, and it really needs a GUI
  interface
- it would be highly desirable to make a launcher that can create
  a cartridge folder from an existing ROM set (* ethos will need to
  accept command-line arguments for this.)
- probably need to remember which controller was selected in each port
  for each system across runs
- need to fix the cursor for Super Scope / Justifier games (move from
  19-bit to 32-bit colors broke it)
- have to refactor that cache.(hv)offset thing to fix ASP
2012-05-07 09:27:42 +10:00
Tim Allen
3cb04b101b Update to v088r13 release.
byuu says:

Changelog:
- fixed Super Game Boy input
- Sufami Turbo prompts to load second slot now (you can cancel to leave
  it empty)
- NEC/Hitachi/ARM DSP firmware is loaded; NEC RAM is saved
- folders are grouped properly: Sufami Turbo save RAM saves to its slot
  folder, etc.
- title shows properly (SGB shows GB game name only, BS-X slotted shows
  game name and optional slot name, etc.)
    - above extends to saving cheats and such in their correct folders
      as well
- added cheat editor and cheat database
    - and hooked up the requisite SGB mode loads and can use GB cheats,
      because that's kinda cool
- added state manager
- input settings, cheat editor and state manager all have erase (one)
  and reset (all) buttons now
- lots of cleanup and restructuring on Emulator::Interface; *almost*
  finished with it now

Remaining:
- BS-X BIOS won't show the data pack
- need XML mapping information window
- need NSS DIP switch settings window
- need video shaders
- need driver selection
- need to hide controllers that have no inputs from the input mapping
  list (tempted to just remove "None" as a controller option ...)

ethos is currently 88KB of code, ui is 167KB. We're missing about 5-10KB
of code in ethos to complete it, so the rewrite nearly cut the GUI code
size in half, while support all of the same functionality and allowing
the easy addition and removal of entire systems.
2012-05-06 16:34:46 +10:00
Tim Allen
5d273c5265 Update to v088r12 release.
byuu says:

Changelog:
- all hotkeys from target-ui now exist in target-ethos
- controller port menus now show up when you load a system (hidden if
  there are no options to choose from)
- tools menu auto-hides with no game open ... not much point to it then
- since we aren't using RawInput's multi-KB/MS support anyway, input and
  hotkey mappings remove KB0:: and turn MS0:: into Mouse::, makes it
  a lot easier to read
- added mute audio, sync video, sync audio, mask overscan
- added video settings: saturation, gamma, luminance, overscan
  horizontal, overscan vertical
- added audio settings: frequency, latency, resampler, volume
- added input settings: when focus is lost [ ] pause emulator [ ] allow
  input
- pausing and autopausing works
- status messages hooked up (show a message in status bar for a few
  seconds, then revert to normal status text)
- sub systems (SGB, BSX, ST) sorted below primary systems list
- added geometry settings cache
- Emulator::Interface cleanups and simplifications
- save states go into (cart foldername.extension/bsnes/state-#.bsa) now.
  Idea is to put emulator-specific data in their own subfolders

Caveats / Missing:
- SGB input does not work
- Sufami Turbo second slot doesn't work yet
- BS-X BIOS won't show the data pack
- need XML mapping information window
- need cheat editor and cheat database
- need state manager
- need video shaders
- need driver selection
- need NSS DIP switch settings
- need to hide controllers that have no inputs from the input mapping
  list

So for video settings, I used to have contrast/brightness/gamma.
Contrast was just a multiplier on intensity of each channel, and
brightness was an addition or subtraction against each channel. They
kind of overlapped and weren't that effective. The new setup has
saturation, gamma and luminance.

Saturation of 100% is normal. If you lower it, color information goes
away. 0% = grayscale. If you raise it, color intensity increases (and
clamps.) This is wonderful for GBA games, since they are oversaturated
to fucking death. Of course we'll want to normalize that inside the
core, so the same sat. value works on all systems, but for now it's
nice. If you raise saturation above 100%, it basically acts like
contrast used to. It's just that lowering it fades to grayscale rather
than black.

Adding doesn't really work well for brightness, it throws off the
relative distance between channels and looks like shit.  So now we have
luminance, which takes over the old contrast <100% role, and just fades
the pixels toward black. Obviously, luminance > 100% would be the same
as saturation > 100%, so that isn't allowed, it caps at 100% now.
Gamma's the same old function. Gamma curve on the lower-half of the
color range.
Effects are applied in the order they appear in the GUI: color ->
saturate -> gammify -> luminate -> output.
2012-05-04 22:47:41 +10:00
Tim Allen
8703d57030 Update to v088r11 release.
byuu says:

Changelog:
- phoenix has added Window::setModal(bool modal = true);
- file dialog is now modal. This allows emulation cores to request data
  and get it immediately before continuing the loading process
- save data is hooked up for most systems, still need to handle
  subsystem slot saves (Sufami Turbo, basically.)
- toggle fullscreen key binding added (Alt+Enter for now. I think F11 is
  probably better though, Enter is often mapped to game start button.)
- video scaling is in (center, scale, stretch), works the same in
  windowed and fullscreen mode (stretch hides resize window option), all
  in the settings menu now
- enough structure to map all saved paths for the browser and to load
  BS-X slotted carts, BS-X carts, single Sufami Turbo carts

Caveats / Missing:
- Super Game Boy input doesn't work yet (due to change in callback
  binding)
- doesn't load secondary Sufami Turbo slot yet
- BS-X BIOS isn't show the data pack games to load for some reason (ugh,
  I hate the shit out of debugging BS-X stuff ...)
- need mute audio, sync audio+video toggle, save/load state menu and
  quick keys, XML mapping information window
- need cheat editor and cheat database
- need state manager
- need to sort subsystems below main systems in load menu (basically
  just see if media.slot.size() > 0)
- need video shaders (will probably leave off filters for the time being
  ... due to that 24/30-bit thing)
- need video adjustments (contrast etc, overscan masks)
- need audio adjustments (frequency, latency, resampler, volume,
  per-system frequency)
- need driver selection and input focus policy (driver crash detection
  would be nice too)
- need NSS DIP switch settings (that one will be really fun)
- need to save and load window geometry settings
- need to hook up controller selection (won't be fun), create a map to
  hide controllers with no inputs to reassign
2012-05-03 22:36:47 +10:00
Tim Allen
9ad8b7eaac Update to v088r10 release.
byuu says:

ethos is going to be absolutely amazing. You guys are in for a treat :D
I'm impressing the hell out of myself with how well-structured this code
is, it's allowing me to do amazing new things.

Just a small sampling of what's in store (and already implemented):

The file browser will display folders as "[ folder name ]", and
cartridge folders as "Game Name" (no extension, no /) [icons would be
nicer, but well ... phoenix.]
Folders are sorted above cartridge folders.
Cartridge folders for other systems do not show up in the list.
Not only are unique paths stored for each image type, your position in
the list is saved across runs.
Some voodoo was added to GTK+ so that all targets even scroll directly
to that item when you open the list. Load->System->Enter restarts your
last game.
That sounds really simple and obvious, but it makes an -incredible-
difference. Didn't realize it until I tried an implementation of it,
wow.

The input mapping list now lets you bind as many hotkeys as you want to
any given input.
So SFC::Port1::Joypad::B = Keyboard::Z or Joypad::Button1 ... no need to
remap everything to switch between keyboard and joypad. Either one
activates the key.
There is a separate Hotkeys tab now. This should hopefully end the
confusion about how to remap hotkeys that users experience.
Hotkeys are different, too. Instead of OR logic, they use AND logic.
So Fullscreen = Keyboard::Alt and Keyboard::Enter. Both must be pressed
to enter the key. This lets you easily implement "super" modifier keys.

The actual codebase has new features the old UI never had, and has about
~50% of the old functionality (so far, of course), yet is only ~25% as
much code.
The entire GUI no longer needs to pull in all the headers for each
emulated system. It just needs a small interface header file.
Then bind the entire system with exactly **two** lines of code.
Everything is dynamically generated for you after that.
2012-05-01 22:27:50 +10:00
Tim Allen
76553756a2 Update to v088r09 release.
byuu says:

Lots of work on ethos, nothing more.
Settings window is in, InputManager pulls all the inputs from all cores
and binds them to ruby inputs, main window adds menu and dynamically
maps in all systems and cartridge slots and options and such, file
browser's back in, RAM is loaded and saved, etc. It's barely usable, but
you have to set up your inputs from the config file by hand for now.
2012-05-01 22:27:50 +10:00
Tim Allen
4fd20f0ae0 Update to v088r08 release.
byuu says:

From this WIP, I'm starting on the impossible task of
a declarative-based GUI, which I'm calling Ethos.
base/ becomes emulator/, and we add emulator/interface.hpp, which is
a base API that all emulation cores must implement in full.
(Right now, it's kind of a hybrid to work with the old GUI and the new
GUI at the same time, of course.)
Unlike the old interfaces, the new base class also provides all general
usability hooks: loading and saving files and states, cheat codes, etc.
The new interface also contains information and vector structs to
describe all possible loading methods, controller bindings, etc; and
gives names for them all.
The actual GUI in fact should not include eg <gba/gba.hpp> anymore.
Should speed up GUI compilation.

So the idea going forward is that ethos will build a list of emulators
right when the application starts up.
Once you've appended an emulator to that list, you're done. No more GUI
changes are needed to support that system.
The GUI will have code to parse the emulator interfaces list, and build
all the requisite GUI options dynamically, declarative style.

Ultimately, once the project is finished, the new GUI should look ~99%
identical to the current GUI. But it'll probably be a whole lot smaller.
2012-05-01 22:27:48 +10:00
Tim Allen
bb4db22a7d Update to v088r07 release.
byuu says:

(r05 and r06 were save points between large core modifications)

I would really appreciate extensive regression testing (especially
around SuperFX, Cx4, ST018, DSP-n, ST-01n, NES, GB) at this point.
The most critical core changes should be completed now. And it was an
unbelievable amount of restructuring.

Changelog:
- SuperFX core moved to Processor::GSU
- SNES::CPU core moved to Processor::R65816
- SNES::SMP core moved to Processor::SPC700
- NES::CPU core renamed to Processor::R6502
- use filestream to load RAM files from interface
- save states store SHA256 instead of CRC32 (CRC32 usage removed
  entirely from bsnes)
- nes/ -> fc/ and NES -> FC
- snes/ -> sfc/ and SNES -> SFC
- SuperFamicom::MappedRAM::copy uses stream instead of data+size
- Linux port uses gcc-4.7 (still using only gcc-4.6 subset, so you can
  make a gcc-4.6 symlink for now if you like.)
- all profiles and all targets compile and work properly

All eight instruction set cores have been moved to processor/ now.
Consistency's a wonderful thing.
The last remnants of NES/SNES are now limited to target-ui code; and the
nall/(system) folder names.
I'm building with gcc-4.7 on my Linux box now because the resultant
binaries are up to 20% faster (seriously) than gcc-4.6.
2012-05-01 22:02:14 +10:00
Tim Allen
67c13f749f Update to v088r04 release.
byuu says:

This will hopefully be a short-lived WIP, I just want to save
a breakpoint before I attempt something else.
NES, GB, GBC and GBA all load via const stream& now.
NES CPU core moved to Processor::RP2A03.
2012-04-28 16:35:51 +10:00
Tim Allen
616372e96b Update to v088r03 release.
byuu says:

static vector<uint8_t> file::read(const string &filename); replaces:
static bool file::read(const string &filename, uint8_t *&data, unsigned
&size); This allows automatic deletion of the underlying data.

Added vectorstream, which is obviously a vector<uint8_t> wrapper for
a data stream.  Plan is for all data accesses inside my emulation cores
to take stream objects, especially MSU1.  This lets you feed the core
anything: memorystream, filestream, zipstream, gzipstream, httpstream,
etc.  There will still be exceptions for link and serial, those need
actual library files on disk. But those aren't official hardware devices
anyway.

So to help with speed a bit, I'm rethinking the video rendering path.

Previous system:
- core outputs system-native samples (SNES = 19-bit LRGB, NES = 9-bit
  emphasis+palette, DMG = 2-bit grayscale, etc.)
- interfaceSystem transforms samples to 30-bit via lookup table inside
  the emulation core
- interfaceSystem masks off overscan areas, if enabled
- interfaceUI runs filter to produce new target buffer, if enabled
- interfaceUI transforms 30-bit video to native display depth (24-bit or
  30-bit), and applies color-adjustments (gamma, etc) at the same time

New system:
- all cores now generate an internal palette, and call
  Interface::videoColor(uint32_t source, uint16_t red, uint16_t green,
  uint16_t blue) to get native display color post-adjusted (gamma, etc
  applied already.)
- all cores output to uint32_t* buffer now (output video.palette[color]
  instead of just color)
- interfaceUI runs filter to produce new target buffer, if enabled
- interfaceUI memcpy()'s buffer to the video card

videoColor() is pretty neat. source is the raw pixel (as per the
old-format, 19-bit SNES, 9-bit NES, etc), and you can create a color
from that if you really want to. Or return that value to get a buffer
just like v088 and below.  red, green, blue are 16-bits per channel,
because why the hell not, right? Just lop off all the bits you don't
want. If you have more bits on your display than that, fuck you :P

The last step is extremely difficult to avoid. Video cards can and do
have pitches that differ from the width of the texture.  Trying to make
the core account for this would be really awful. And even if we did
that, the emulation routine would need to write directly to a video card
RAM buffer.  Some APIs require you to lock the video buffer while
writing, so this would leave the video buffer locked for a long time.
Probably not catastrophic, but still awful.  And lastly, if the
emulation core tried writing directly to the display texture, software
filters would no longer be possible (unless you -really- jump through
hooks and divert to a memory buffer when a filter is enabled, but ...
fuck.)

Anyway, the point of all that work was to eliminate an extra video copy,
and the need for a really painful 30-bit to 24-bit conversion (three
shifts, three masks, three array indexes.) So this basically reverts us,
performance-wise, to where we were pre-30 bit support.

[...]

The downside to this is that we're going to need a filter for each
output depth. Since the array type is uint32_t*, and I don't intend to
support higher or lower depths, we really only need 24+30-bit versions
of each filter.  Kinda shitty, but oh well.
2012-04-27 22:12:53 +10:00
Tim Allen
bba597fc6f Update to v088r02 release.
byuu says:

Basically, the current implementation of nall/array is deprecated now.
The old method was for non-reference types, it acted like a vector for
POD types (raw memory allocation instead of placement new construction.)
And for reference types, it acted like an unordered set. Yeah, not good.

As of right now, nall/array is no longer used. The vector type usage was
replaced with actual vectors.
I've created nall/set, which now contains the specialization for
reference types.
nall/set basically acts much like std::unordered_set. No auto-sort, only
one of each type is allowed, automatic growth.
This will be the same both for reference and non-reference types ...
however, the non-reference type wasn't implemented just yet.
Future plans for nall/array are for it to be a statically allocated
block of memory, ala array<type, size>, which is meant for RAII memory
usage.
Have to work on the specifics, eg the size as a template parameter may
be problematic. I'd like to return allocated chunks of memory (eg
file::read) in this container so that I don't have to manually free the
data anymore.

I also removed nall/moduloarray, and moved that into the SNES DSP class,
since that's the only thing that uses it.
2012-04-26 20:56:15 +10:00
Tim Allen
abe639ea91 Update to v088r01 release.
byuu says:

- GB::CPU::Core -> Processor::LR35902
- Processor::LR35902 -> jump table to switch table
- GB::LCD -> GB::PPU
- static frequency for DMG (no multiplication on clock ticks)
- GB::PPU::interface->videoRefresh() moved outside scheduler (use host
  thread)
- namespace NES  -> Famicom
- namespace SNES -> SuperFamicom
- namespace GB   -> GameBoy
- namespace GBA  -> GameBoyAdvance
- removed boot.rom writeout in GB::System
2012-04-26 20:51:13 +10:00
Tim Allen
77bb5b7891 Update to v088 release.
byuu says:

Changes to v088:
- OBJ mosaic Y fix
- Laevateinn compilation
- Remove filebrowser extra code
- Fix -march=native on Windows
- Fix purify mkdir
- GBA sound volume
- Add .gbb
- free firmware memory after file load
- Add GBA game to profile list (Yoshi's Island should work)
2012-04-24 23:17:52 +10:00
Tim Allen
4b2944c39b Update to v087r30 release.
byuu says:

Changelog:
- DMA channel masks added (some are 27-bit source/target and some are
  14-bit length -- hooray, varuint_t class.)
- No more state.pending flags. Instead, we set dma.pending flag when we
  want a transfer (fixes GBA Video - Pokemon audio) [Cydrak]
- fixed OBJ Vmosaic [Cydrak, krom]
- OBJ cannot read <=0x13fff in BG modes 3-5 (fixes the garbled tile at
  the top-left of some games)
- DMA timing should be much closer to hardware now, but probably not
  perfect
- PPU frame blending uses blargg's bit-perfect, rounded method (slower,
  but what can you do?)
- GBA carts really unload now
- added nall/gba/cartridge.hpp: used when there is no manifest. Scans
  ROMs for library tags, and selects the first valid one found
- added EEPROM auto-detection when EEPROM size=0. Forces disk/save state
  size to 8192 (otherwise states could crash between pre and post
  detect.)
    - detects first read after a set read address command when the size
      is zero, and sets all subsequent bit-lengths to that value, prints
      detected size to terminal
- added nall/nes/cartridge.hpp: moves iNES detection out of emulation
  core.

Important to note: long-term goal is to remove all
nall/(system)/cartridge.hpp detections from the core and replace with
databases. All in good time.
Anyway, the GBA workarounds should work for ~98.5% of the library, if my
pre-scanning was correct (~40 games with odd tags. I reject ones without
numeric versions now, too.)

I think we're basically at a point where we can release a new version
now. Compatibility should be relatively high (at least for a first
release), and fixes are only going to affect one or two games at a time.
I'd like to start doing some major cleaning house internally (rename
NES->Famicom, SNES->SuperFamicom and such.) Would be much wiser to do
that on a .01 WIP to minimize regressions.

The main problems with a release now:
- speed is pretty bad, haven't really optimized much yet (not sure how
  much we can improve it yet, this usually isn't easy)
- sound isn't -great-, but the GBA audio sucks anyway :P
- couple of known bugs (Sonic X video, etc.)
2012-04-22 20:49:19 +10:00
Tim Allen
4c29e6fbab Update to v087r29 release.
byuu says:

Changelog:
- revised NES XML tag nesting
- program.rom is going to refer to PRG+CHR combined. Split is going to
  have to use different file names
- slot loader is gone (good riddance!)
- "Cartridge -> Load Game Boy Advance Cartridge ..." has become "Load ->
  Game Boy Advance ..."
- Load Satellaview Slotted Cartridge is gone. If you load an SNES
  cartridge and it sees <bsx><slot>, it asks if you want to load a BS-X
  data pack
- If you load a Sufami Turbo cartridge with <cartridge linkable="true">,
  it asks if you want to link in another Sufami Turbo cartridge
- if you try and load the same exact Sufami Turbo cartridge in both
  slots, it yells at you for being an idiot :P
2012-04-20 22:48:09 +10:00
Tim Allen
a454e9d927 Update to v087r28 release.
byuu says:

Be sure to run make install, and move required images to their appropriate system profile folders.
I still have no warnings in place if those images aren't present.

Changelog:
- OBJ mosaic should hopefully be emulated correctly now (thanks to krom
  and Cydrak for testing the hardware behavior)
- emulated dummy serial registers, fixes Sonic Advance (you may still
  need to specify 512KB FlashROM with an appropriate ID, I used
  Panaonic's)
- GBA core exits scheduler (PPU thread) and calls
  interface->videoRefresh() from main thread (not required, just nice)
- SRAM, FRAM, EEPROM and FlashROM initialized to 0xFF if it does not
  exist (probably not needed, but FlashROM likes to reset to 0xFF
  anyway)
- GBA manifest.xml for file-mode will now use "gamename.xml" instead of
  "gamename.gba.xml"
- started renaming "NES" to "Famicom" and "SNES" to "Super Famicom" in
  the GUI (may or may not change source code in the long-term)
- removed target-libsnes/
- added profile/

Profiles are the major new feature. So far we have:

    Famicom.sys/{nothing (yet?)}
    Super Famicom.sys/{ipl.rom}
    Game Boy.sys/{boot.rom}
    Game Boy Color.sys/{boot.rom}
    Game Boy Advance.sys/{bios.rom[not included]}
    Super Game Boy.sfc/{boot.rom,program.rom[not included]}
    BS-X Satellaview.sfc/{program.rom,bsx.ram,bsx.pram}
    Sufami Turbo.sfc/{program.rom}

The SGB, BSX and ST cartridges ask you to load GB, BS or ST cartridges
directly now. No slot loader for them.  So the obvious downsides: you
can't quickly pick between different SGB BIOSes, but why would you want
to? Just use SGB2/JP.  It's still possible, so I'll sacrifice a little
complexity for a rare case to make it a lot easier for the more common
case.  ST cartridges currently won't let you load the secondary slot.
BS-X Town cart is the only useful game to load with nothing in the slot,
but only barely, since games are all seeded on flash and not on PSRAM
images. We can revisit a way to boot the BIOS directly if and when we
get the satellite uplink emulated and data can be downloaded onto the
PSRAM :P BS-X slotted cartridges still require the secondary slot.

My plan for BS-X slotted cartridges is to require a manifest.xml to
specify that it has the BS-X slot present.  Otherwise, we have to load
the ROM into the SNES cartridge class, and parse its header before we
can find out if it has one. Screw that.  If it's in the XML, I can tell
before loading the ROM if I need to present you with an optional slot
loading dialog.  I will probably do something similar for Sufami Turbo.
Not all games even work with a secondary slot, so why ask you to load
a second slot for them? Let the XML request a second slot. A complete
Sufami Turbo ROM set will be trivial anyway.  Not sure how I want to do
the sub dialog yet. We want basic file loading, but we don't want it to
look like the dialog 'didn't do anything' if it pops back open
immediately again. Maybe change the background color of the dialog to
a darker gray? Tacky, but it'd give you the visual cue without the need
for some subtle text changes.
2012-04-18 23:58:04 +10:00
Tim Allen
d2241f1931 Update to v087r27 release.
byuu says:

Changelog:
- serialize processor.pc.data, not processor.pc
- call CPU processor.setMode() in ARM serialize
- serialize BIOS.mdr
- support SRAM > 32KB
- EEPROM, FlashROM serialize
- EEPROM lose nall/bitarray.hpp
- noise line feed after envelope
- space out PSR read
- ST018 needs byte reads fixed (don't align) [fixes HNMS2]
- flush sram/eeprom/flashrom to 0 on cartridge load
- APU/PPU dont sync back to CPU if syncing for state
- fixed APU sync problems in GB/GBC core that could possibly wreck save
  states as well

Quite a lot of little problems there. I believe GBA save states are
fixed now.
2012-04-17 22:16:54 +10:00
Tim Allen
0cd0dcd811 Update to v087r26 release.
byuu says:

Changelog:
- fixed FIFO[1] reset behavior (fixes audio in Sword of Mana)
- added FlashROM emulation (both sizes)
- GBA parses RAM settings from manifest.xml now
- save RAM is written to disk now
- added save state support (it's currently broken, though)
- fixed ROM/RAM access timings
- open bus should mostly work (we don't do the PC+12 stuff yet)
- emulated the undocumented memory control register (mirror IWRAM,
  disable I+EWRAM, EWRAM wait state count)
- emulated keypad interrupts
- emulated STOP (freezes video, audio, DMA and timers; only breaks on
  keypad IRQs)
- probably a lot more, it was a long night ...

Show stoppers, missing things, broken things, etc:
- ST018 is still completely broken
- GBC audio sequencer apparently needs work
- GBA audio FIFO buffer seems too quiet
- PHI / ROM prefetch needs to be emulated (no idea on how to do this,
  especially PHI)
- SOUNDBIAS 64/128/256khz modes should output at that resolution
  (really, we need to simulate PWM properly, no idea on how to do this)
- object mosaic top-left coordinates are wrong (minor, fixing will
  actually make the effect look worse)
- need to emulate PPU greenswap and color palette distortion (no idea on
  how do this)
- need GBA save type database (I would also LIKE to blacklist
  / patch-out trainers, but that's a discussion for another day.)
- some ARM ops advance the prefetch buffer, so you can read PC+12 in
  some cases
2012-04-16 22:19:39 +10:00
Tim Allen
1c18812f47 Update to v087r25 release.
byuu says:

(r24 was a point release during merging of changes.)

This release is almost entirely Cydrak's direct work:
- Added ARM::sequential() and some WAITCNT timings
- Added Bus::io(uint32 pc), intended for prefetch timing
- Added ARM::load() with data rotation (fixed Mother 3 graphics)
- Added ARM::store() for data mirroring
- LDM, STM, and instruction fetch still use read/write()
- ARM::vector() no longer unmasks FIQs
- Set THUMB shifter flags via bit(), consistent with ARM
- Replace shifter loops with conditional tests

My changes:
- fixed sprite clipping on left-edge of screen
- added first system folder, GBA.system
- sudo make install is now make install
- make install will create GBA.system for you in your home folder

Windows users, take data/GBA.system and put it in the same folder as
bsnes.exe, and give it a BIOS named bios.rom
Or place it in your home folder (%APPDATA%/bsnes)
Also note that this is highly experimental, I'll probably be changing
things a lot before release.

EDIT: I botched the cartridge timing change. Will fix in r26. It'll
still run a bit too fast for now, unfortunately.
2012-04-15 16:49:56 +10:00
Tim Allen
28885db586 Update to v087r23 release.
byuu says:

Changelog:
- fixed cascading timers and readouts (speed hit from 320fps to 240fps;
  would be 155fps with r20 timers) (fixes Spyro)
- OBJ mode 3 acts like OBJ mode 2 now (may not be correct, but nobody
  has info on it)
- added background + object vertical+horizontal mosaic in all modes
  (linear+affine+bitmap)
- object mosaic uses sprite (0,0) for start coordinates, not screen
  (0,0) (again, nobody seems to have info on it)
- BIOS cannot be read by r(15)>=0x02000000; returns last BIOS read
  instead (I can't believe games rely on this to work ... fixes SMA
  Mario Bros.)

Mosaic is what concerns me the most, I've no idea if I'm doing it
correctly. But anything is probably better than nothing, so there's
that. I don't really notice the effect in Metroid Fusion. So either it's
broken, or it's really subtle.
2012-04-14 17:26:45 +10:00
Tim Allen
d423ae0a29 Update to v087r22 release.
byuu says:

Changelog:
- fixed below pixel green channel on color blending
- added semi-transparent objects [Exophase's method]
- added full support for windows (both inputs, OBJ windows, and output, with optional color effect disable)
- EEPROM uses nall::bitarray now to be friendlier to saving memory to disk
- removed incomplete mosaic support for now (too broken, untested)
- improved sprite priority. Hopefully it's right now.

Just about everything should look great now. It took 25 days, but we
finally have the BIOS rendering correctly.

In order to do OBJ windows, I had to drop my above/below buffers
entirely. I went with the nuclear option.  There's separate layers for
all BGs and objects. I build the OBJ window table during object
rendering.  So as a result, after rendering I go back and apply windows
(and the object window that now exists.) After that, I have to do
a painful Z-buffer select of the top two most important pixels.  Since
I now know the layers, the blending enable tests are a lot nicer, at
least.  But this obviously has quite a speed hit: 390fps to 325fps for
Mr. Driller 2 title screen.

TONC says that "bad" window coordinates do really insane things. GBAtek
says it's a simple y2 < y1 || y2 > 160 ? 160 : y2; x2 < x1 || x2 > 240
? 240 : x2; I like the GBAtek version more, so I went with that. I sure
hope it's right ... but my guess is the hardware does this with
a counter that wraps around or something.  Also, say you have two OBJ
mode 2 sprites that overlap each other, but with different priorities.
The lower (more important) priority sprite has a clear pixel, but the
higher priority sprite has a set pixel. Do we set the "inside OBJ
window" flag to true here? Eg does the value OR, or does it hold the
most important sprite's pixel value? Cydrak suspects it's OR-based,
I concur from what I can see.

Mosaic, I am at a loss. I really need a lot more information in order to
implement it.  For backgrounds, does it apply to the Vcounter of the
entire screen? Or does it apply post-scroll? Or does it even apply after
every adjust in affine/bitmap modes?  I'm betting the hcounter
background mosaic starts at the leftmost edge of the screen, and repeats
previous pixels to apply the effect. Like SNES, very simple.  For
sprites, the SNES didn't have this. Does the mosaic grid start at (0,0)
of the screen, or at (0,0) of each sprite? The latter will look a lot
nicer, but be a lot more complex. Is mosaic on affine objects any
different than mosaic of linear(tiled) objects?

With that out of the way, we still have to fix the CPU memory access
timing, add the rest of the CPU penalty cycles, the memory rotation
/ alignment / extend behavior needs to be fixed, the shifter desperately
needs to be moved from loops to single shift operations, and I need to
add flash memory support.
2012-04-13 21:50:53 +10:00
Tim Allen
303a0a67d0 Update to v087r21 release.
byuu says:

Timer speedup added. Boosts Mr. Driller 2 title from 170fps to 400fps.
Other games still benefit, but not as amazingly. I don't dip below
160fps ever here.
Reverted the memory speed to 2 for everything for now, to fix
Castlevania slowdown. We obviously need to add the N/S stuff before we
do that.
Added linear BG and linear OBJ mosaic-Y. Did not add mosaic-X, or any
mosaic to the affine/bitmap modes, because I'm not sure when to apply
the compensation.
Rewrote layer stuff. It now has two layers (above and below), and it
performs the four blending modes as needed.
Didn't add semi-transparent sprites because the docs are too confusing.
Added a blur filter directly into the PPU for now. This obviously
violates my interface, but F-Zero needed it for HUD display. We can
remove it when we have an official release with a blur filter available.
The filter still doesn't warp colors like a real GBA, because I don't
know the formula.
2012-04-10 21:41:35 +10:00
Tim Allen
01b4cb9919 Update to v087r20 release.
byuu says:

Changelog:
- HALT waits 16 cycles before testing IRQs instead of 1 (probably less
  precise, but provides a massive speedup) [we will need to work on this
  later]
- MMIO regs for CPU/PPU simplified by combining array accesses
- custom VRAM/PRAM/OAM read/write functions that emulate 8->16-bit
  writes
- 16-bit PRAM data (decent speedup)
- emulated memory access speed (but don't handle non-sequential
  penalties or PPU access penalties yet) [amazingly, doesn't help speed
  at all]
- misc. code cleanups

For this WIP, FPS for Mr. Driller 2 went from 88fps to 172fps.
Compatibility should be unchanged. Timers are still an interesting
avenue to increase performance, but will be very tough to handle the
16MHz timers with eg a period of 65535 (overflow every single tick.) And
that's basically the last major speed boost we'll be able to get.
Blending and windowing is going to hurt performance, but it remains to
be seen how much.
2012-04-09 16:41:27 +10:00
Tim Allen
17b5bae86a Update to v087r19 release.
byuu says:

Changelog:
- added FIFO buffer emulation (with DMA and all that jazz) [Cydrak]
- fixed timers and vcounter assign [Cydrak]
- emulated EEPROM (you have to change size manually for 14-bit mode, we
  need a database badly now) [SMA runs now]
- removed OAM array, now decoding directly to struct Object {} [128] and
  ObjectParam {} [32] (faster this way)
- check forceblank (still doesn't remove all garble between transitions,
  though??)
- lots of other stuff

Delete your settings.cfg, or manually change frequencyGBA to 32768, or
bad things will happen (this may change back to 256KHz-4MHz later.)

15 of 16 games are fully playable now, and look and sound great.
The major missing detail right now is PPU blending support, and we
really need to optimize the hell out of the code.
2012-04-09 16:19:32 +10:00
Tim Allen
6189c93f3d Update to v087r18 release.
byuu says:

Merged Cydrak's r17c changes:
- BG affine mode added
- BG bitmap mode added
- OBJ affine mode added
- fixed IRQ bug in THUMB mode (fixed almost every game)
- timers added (broke almost every game, whee.)

Cydrak is absolutely amazingly awesome and patient. This really wouldn't
be happening without him.

Also fixed some things from my end, including greatly improved sprite
priorities, and a much better priority sorter. Mr. Driller looks a lot
better now.
2012-04-07 18:17:49 +10:00
Tim Allen
1de484262c Update to v087r17 release.
byuu says:

Emulated GBC sound plus the new extensions to it.
I am kind of surprised by how little developers utilized the GBC audio
portion.
Mr. Driller now has sound effects, and Pinobee no Daibouken has BGM.
I still have yet to emulate the GBA extra sound channels and PWM. Need
to emulate timers and DMA 2 refresh mode before I can do that.

Also, I moved both GBC and GBA audio to use length = data; if(++length
== 0); rather than length = 64 - data; if(--length == 0); so that
I could return literal values for register reads.
I thought there was a good reason we used the latter version, but
I can't hear any audible difference even in GBC games, so oh well.
Lastly, I think the pattern[++offset] in the wave channel was a bug in
the DMG/GBC only. I really, really hope it doesn't apply to the GBA,
because that will make bank selection a serious pain in the ass.
2012-04-06 14:29:50 +10:00
Tim Allen
b8d0ec29b2 Update to v087r16 release.
byuu says:

Fixed the r15 mask per Cydrak.
Added DMA support (immediate + Vblank + Hblank + HDMA) with IRQ support.
Basically only missing FIFO reload mode for the APU on channel 2.
Added background linear renderer (tilemap mode.)
Added really inefficient pixel priority selector, so that all BGs+OBJ
could be visible onscreen at the same time.

As a result of the above:
* Mr. Driller is our first fully playable game
* Bakunetsu Dodge Ball Fighters is also fully playable
* Pinobee no Daibouken is also fully playable

Most games (15 of 16 tested) are now showing *something*, many things
look really really good in fact.

Absolutely essential missing components:
- APU
- CPU timers and their interrupts
- DMA FIFO mode
- OBJ affine mode
- BG affine mode
- BG bitmap mode
- PPU windows (BG and OBJ)
- PPU mosaic
- PPU blending modes
- SRAM / EEPROM (going to rely on a database, not heuristics. Homebrew
  will require a manifest file.)
2012-04-04 09:50:40 +10:00
Tim Allen
79a47d133a Update to v087r15 release.
byuu says:

Added linear (eg non-affine) sprite rendering, 4bpp and 8bpp with hflip
and vflip. Nothing else.
You can now see the Nintendo logo and Gameboy text at the end of the BIOS.
It's a start =)
2012-04-03 10:47:28 +10:00
Tim Allen
c8bb4949b1 Update to v087r14 release.
byuu says:

Fixed aforementioned issues.

[From a previous post:
- mul was using r(d) instead of r(n) for accumulate.
- mull didn't remove c/v clear.
- APU register mask was broken, so SOUNDBIAS was reading out wrong.
- APU was only mapping 0x088 and not 0x089 as well.
- Halfword reads in CPU+PPU+APU were all reading from the low address
  each time.]

All CPU+PPU registers are now hooked up (not that they do anything.)
SOUNDBIAS for APU was hooked up, got tired of working on it for the rest :P
I recall from the GB APU that you can't just assign values for the APU
MMIO regs. They do odd reload things as well.
Also, was using MMIO read code like this:

    return (
       (flaga << 0)
    || (flagb << 1)
    || (flagc << 2)
    );

Logical or doesn't work so well with building flags :P
Bad habit from how I split multiple conditionals across several lines.

So ... r14 is basically what r13 should have been yesterday, delaying my
schedule by yet another day :(
2012-04-01 11:41:15 +10:00
Tim Allen
f587cb0dcc Update to v087r13 release.
byuu says:

Contains all of Cydrak's fixes, sans PPU.
On the PPU front, I've hooked up 100% of read and write registers.
All three DISPSTAT IRQs (Vblank, Hblank, Vcoincidence) are connected now
as well.
Super Mario Advance now runs without *appearing* to crash, although it's
hard to tell since I have no video or sound :P
ARM Wrestler is known to run, as is the BIOS.
2012-03-31 19:17:36 +11:00
Tim Allen
ea086fe33f Update to v087r12 release.
byuu says:

Enough to get through the BIOS and into cartridge ROM.
I am a bit annoyed that I was basically told that the GBA PPU wasn't
that bad. Sprites are a clusterfuck, easily worse than Mode7, docs don't
even begin to explain them in enough detail.
This is going to be fun.
2012-03-31 19:14:31 +11:00
Tim Allen
c66cc73374 Update to v087r11 release.
byuu says:

Added all of the above fixes and changes. [A lot of individual fixes for
the ARM core from Cydrak - Ed.] Also new is pipeline_decode() to fetch
data, and IME/IE/IF support, and an ARM::processor.irqline flag that
triggers IRQs at 0x18. Only Vblank is hooked up, which is what SWI 4 was
waiting on previously.
I'm sure my interrupt support is horribly broken and wrong. I was never
able to really figure out IE/IF on the Game Boy, so there's no question
this is even worse.
It's now going crazy and writing 0 to IE forever now after the Vblank
IRQ triggers.
2012-03-29 22:58:10 +11:00
Tim Allen
5a1dcf5079 Update to v087r10 release.
byuu says:

Changelog:
- fixed THUMB hi immediate reads (immediate * 4)
- cartridge is properly mirrored to 32MB (eg 12mbit repeats as
  lo8+hi4+hi4+lo8+hi4+hi4) [so it's a bit slower than a standard memcpy
  fill]
- added ARM - load/store halfword register offset
- added ARM - load/store halfword immediate offset
- added ARM - load signed halfword/byte register offset
- added ARM - load signed halfword/byte immediate offset
- added decode() function to make opcode bit testing a lot clearer
  (didn't apply it to the debugger yet)

All ARMv4M and all THUMBv4 instructions should now be implemented.
Although I'm not sure if my implementations of the new instructions are
correct.
2012-03-27 22:02:57 +11:00
Tim Allen
e16dd58184 Update to v087r09 release.
byuu says:

Split apart necdsp: core is now in processor/upd96050 (wish I had
a better name for it, but there's no family name that is maskable.)
I would like to support the uPD7720 in the core as well, just for
completeness' sake, but I'll have to modify the decoder to drop one bit
from each mode.
So ... I'll do that later. Worst part is even if I do, I won't be able
to test it :(

Added all of Cydrak's changes. I also simplified LDMIA/STMIA and
PUSH/POP by merging the outer loops.
Probably infinitesimally slower, but less code is nicer. Maybe GCC
optimization will expand it, who knows.
2012-03-26 21:13:02 +11:00
Tim Allen
395e5a5639 Update to v087r08 release.
byuu says:

Added some more ARM opcodes, hooked up MMIO. Bind it with mmio[(addr
000-3ff)] = this; inside CPU/PPU/APU, goes to read(), write().
Also moved the Hitachi HG51B core to processor/, and split it apart from
the snes/chip/hitachidsp implementation.
This one actually worked really well. Very clean split between MMIO/DMA
and the processor core. I may move a more generic DMA function inside
the core, not sure yet.

I still believe the HG51B169 to be a variant of the HG51BS family, but
given they're meant to be incredibly flexible microcontrollers, it's
possible that each variant gets its own instruction set.
So, who knows. We'll worry about it if we ever find another HG51B DSP,
I guess.

GBA BIOS is constantly reading from 04000300, but it never writes. If
I return prng()&1, I can get it to proceed until it hits a bad opcode
(stc opcode, which the GBA lacks a coprocessor so ... bad codepath.)
Without it, it just reads that register forever and keeps resetting the
system, or something ...

I guess we're going to have to try and get ARMwrestler working, because
the BIOS seems to need too much emulation code to do anything at all.
2012-03-24 18:52:36 +11:00
Tim Allen
ec939065bd Update to v087r07 release.
There was a "v087r07pre" release that I unfortunately missed.

byuu says (about v087r07pre):

Creates the bsnes/processor folder. This has a shared ARM core there
which both the GBA and ST018 inherit.
There are going to be separate decoders, and revision-specific checks,
to support the differences between v3+.
In the future, I also want to move the other processor cores here:
- GBZ80 (GB, GBC)
- 65816 (SNES CPU, SA-1)
- NEC uPD (7725, 96050, maybe 7720 just for fun)
- Hitachi HG51B169
- SuperFX
- SPC700
- 65(C?)02

Basically, the GBA/ST018 forces my hand to start coding a bit more like
a multi-system emulator.

Right now, the ST018 is broken. Hence the pre. Apparently the GBA core
being used now has some bugs. So this'll be a nice way to stress-test
the GBA core a bit before we make it to ARMwrestler.

byuu says (about v087r07):

Both snes/chip/armdsp and gba/cpu use processor/arm now.
Fixed THUMB to execute the BL prefix and suffix separately. I can now
get the GBA BIOS stuck in some kind of infinite loop. Hooray ...
I guess?
2012-03-23 21:43:39 +11:00
Tim Allen
77578cd0a4 Update to v087r06 release.
byuu says:

I believe I've implemented every THUMB instruction now, although I'm
sure there are dozens of bugs in the implementation.

It seems that the last jump taken is ending up being off-by-two. It's
probably due to not masking/adjusting PC correctly at certain points.

I don't know if any other bugs are being hit prior to this or not.
I don't implement any I/O registers yet, and the BIOS seems to be poking
at a few of them along the way, so ... who knows.
I could also be reading the log wrong, but it looks to me like there's
some PSR setting the mode flag register to 0, which is supposed to be an
undefined behavior mode ... perhaps mrs has no effect on the m/t bits,
and it just affects the i/f bits?
2012-03-22 22:47:25 +11:00
Tim Allen
04087a74b0 Update to v087r05 release.
byuu says:

Implemented all of the ARMv3 instructions, and the bx rm instruction as
well. Already hit THUMB mode right at the start of the BIOS, sigh.
Implemented the first THUMB instruction to get that rolling. Also tried
to support the S flag to LDM/STM, but not sure how successful I was.
2012-03-21 22:08:16 +11:00
Tim Allen
6701403745 Update to v087r04 release.
byuu says:

GBA stuff re-added. Only thing missing that was there before is the ARM
branch opcode.
Since we're going to be staring at it for a very long time, I added
a more interesting test video pattern.

Went from 6fps to 912fps. Amazing what being able to divide can do for
a frame rate.
2012-03-19 22:19:53 +11:00
Tim Allen
95c62f92ac Update to v087r03 release.
byuu says:

Fixing the PPU stepping increased FPS to 250. Promising, at least, since
the ARM core is still severely overclocked.
However, I reverted back to r02. This one patches gameboy/ and GameBoy::
to gb/ and GB:: and that's it.
Sorry, I just couldn't shake this bad feeling about the code. There were
some poorly hacked-together constructs. I'd rather just redo two days of
work than feel bad about the codebase for the next several years. Going
to attempt the GBA bridge again. Third time's a charm, I suppose (there
was a pre-r03 WIP I abandoned as well.)
This isn't unprecedented, GB core took a few attempts like this as well.
2012-03-19 21:27:40 +11:00
Tim Allen
0f54be93b7 Update to v087r04 release.
byuu says:

Changelog:
- gameboy/ -> gb/
- GameBoy -> GB
- basic memory map for GBA
- enough code to execute the first BIOS instruction (b 0x68)

I have the code resetting r(15) to 0 on an exception just as a test.
Since that flushes the pipeline, that means we're basically executing "b
0x68" at 8MHz, and nothing else.
... and I am getting __6 motherfucking FPS__ at 4.4GHz on an i7.

Something is seriously, horribly, unfuckingbelievably wrong here, and
I can't figure out what it is.
My *fully complete* ARM core on the ST018 is even less efficient and
runs at 21.47MHz, and yet I get 60fps even after emulating the SNES
CPU+PPU @ 10+MHz each as well.

... I'm stuck. I can't proceed until we figure out what in the holy fuck
is going on here. So ... if anyone can help, please do. If we can't fix
this, the GBA emulation is dead.
I was able to profile on Windows, and I've included that in this WIP
under out/log.txt.
But it looks normal to me. But yeah, there's NO. FUCKING. WAY. This code
should be running this slowly.
2012-03-18 23:35:53 +11:00
Tim Allen
8db134843f Update to v087r03 release.
byuu says:

I wanted to keep this a secret, but unlike other recent additions, this
will easily take several weeks, maybe months, to show anything.
Assuming I can even pull it off. Nothing technically overwhelming here,
I'm more worried about the near-impossibility of debugging the CPU.
2012-03-18 12:04:22 +11:00
Tim Allen
06e83c6154 Update to v087r02 release.
byuu says:

Changelog:
- extended USART with quit(), readable(), writable() [both emulation and
  hardware]
    - quit() returns true on hardware when Ctrl+C (SIGINT) is generated
      (breaks main loop); no effect under emulation yet (hard to
      simulate)
    - readable() returns true when data is ready to be read
      (non-blocking support for read())
    - writable() returns true when data can be written (non-blocking
      support for write()) [always true under emulation, since we have
      no buffer size limit]
2012-03-10 23:47:19 +11:00
Tim Allen
cbfbec4dc3 Update to v087r01 release.
byuu says:

Changelog:
- fixes ARM core unaligned memory reads (fixes HNMS2 AI, hopefully completely,
  we'll see though) [Cydrak]
- ARM 40000010 writes are now connected to d2 rather than the timer
- ARM bus_readbyte() removed (would love to do the same for writebyte if
  we can ... then we can drop back to bus_read + bus_write only)
- USART with IObit set acts as a regular gamepad now (don't have this
  hooked up with real hardware, but oh well, it's technically possible
  so there's that)
- OpenGL/GLX will use 30-bit when you have a 30-bit display; no need for
  config file video.depth anymore
2012-03-10 23:37:36 +11:00
Tim Allen
386ac87d21 Update to v087 release.
byuu says:

This release adds ST018 emulation. As this was the final unsupported
SNES coprocessor, this means that bsnes v087 is the first SNES emulator
to be able to claim 100% known compatibility with all officially
released games. And it does this with absolutely no hacks.

Again, I really have to stress the word known. No emulator is perfect.
No emulator ever really can be perfect for a system of this complexity.
The concept doesn't even really exist, since every SNES behaves subtly
different. What I mean by this, is that every single game ever
officially sold has been tested, and zero bugs (of any severity level)
are currently known.

It is of course extremely likely that bugs will be found in this
release, as well as in future releases. But this will always be
a problem for every emulator ever made: there is no way to test every
possible codepath of every single game to guarantee perfection. I will,
of course, continue to do my best to fix newfound bugs so long as I'm
around.

I'd really like to thank Cydrak and LostTemplar for their assistance in
emulating the ST018. I could not have done it without their help.

The ST018 ROM, like the other coprocessor ROMs, is copyrighted. This
means I am unable to distribute the image.

Changelog (since v086):
- emulated the 21.47MHz ST018 (ARMv3) coprocessor used by Hayazashi
  Nidan Morita Shougi 2
- fixed PPU TM/TS edge case; fixes bottom scanline of text boxes in
  Moryo Senki Madara 2
- fixed saving and loading of Super Game Boy save RAM
- NEC uPD7725,96050 ROMs now stored in little-endian format for
  consistency
- cartridge folder concept has been reworked to use fixed file names
- added emulation of serial USART interface (replaces asynchronous UART
  support previously)
2012-03-08 00:29:38 +11:00
Tim Allen
533aa97011 Update to v086r16 release.
byuu says:

Cydrak, I moved the step from the opcode decoder and opcodes themselves
into bus_(read,write)(byte,word), to minimize code.
If that's not feasible for some reason, please let me know and I'll
change it back to your latest WIP.
This has your carry flag fix, the timer skeleton (doesn't really work
yet), the Booth two-bit steps, and the carry flag clear thing inside
multiply ops.
Also added the aforementioned reset delay and reset bit stuff, and fixed
the steps to 21MHz for instructions and 64KHz for reset pulse.
I wasn't sure about the shifter extra cycles. I only saw it inside one
of the four (or was it three?) opcodes that have shifter functions.
Shouldn't it be in all of them?

The game does indeed appear to be fully playable now, but the AI doesn't
exactly match my real cartridge.
This could be for any number of reasons: ARM CPU bug, timer behavior
bug, oscillator differences between my real hardware and the emulator,
etc.
However ... the AI is 100% predictable every time, both under emulation
and on real hardware.

- For the first step, move 九-1 to 八-1.
- The opponent moves 三-3 to 四-3.
- Now move 七-1 to 六-1.
- The opponent moves 二-2 to 八-8.
  However, on my real SNES, the opponent moves 一-3 to 二-4.
2012-03-08 00:03:15 +11:00
Tim Allen
d118b70b30 Update to v086r15 release.
byuu says:

Most importantly ... I'm now using "st018.rom" which is the program ROM
+ data ROM in one "firmware" file. Since all three Seta DSPs have the
ST01N stamp, unlike some of the arcade variants, I'm just going to go
with ST01N from now on instead of ST-001N. I was using the latter as
that's what Overload called them.

Moving on ...
The memory map should match real hardware now, and I even match the open
bus read results.
I also return the funky 0x40404001 for 60000000-7fffffff, for whatever
that's worth.
The CPU-side registers are also mirrored correctly, as they were in the
last WIP, so we should be good there.
I also simulate the reset pulse now, and a 0->!0 transition of $3804
will destroy the ARM CPU thread.
It will wait until the value is set back to zero to resume execution.
At startup, the ARM CPU will sleep for a while, thus simulating the
reset delay behavior.
Still need to figure out the exact cycle length, but that's really not
important for emulation.

Note in registers.hpp, the |4 in status() is basically what allows the
CPU program to keep going, and hit the checkmate condition.
If we remove that, the CPU deadlocks. Still need to figure out how and
when d4 is set on $3804 reads.
I can run any test program on both real hardware and in my emulator and
compare results, so by all means ... if you can come up with a test,
I'll run it.
2012-03-02 22:07:17 +11:00
Tim Allen
aa8ac7bbb8 Update to v086r14 release.
byuu says:

Attempted to fix the bugs pointed out by Cydrak for the shifter carry
and subtraction flags. No way to know if I was successful.
The memory map should exactly match real hardware now.
Also simplified bus reading/writing: we can get fancy when it works,
I suppose.
Reduced some of the code repetition to try and minimize the chances for
bugs.
I hopefully fixed up register-based ror shifting to what the docs were
saying.
And lastly, the disassembler should handle every opcode in every mode
now.
ldr rn,[pc,n] adds (pc,n) [absolute address] after opcode. I didn't want
to actually read from ROM here (in case it ever touches I/O or
something), but I suppose we could try anyway.
At startup, it will write out "disassembly.txt" which is a disassembly
of the entire program ROM.
If anyone wants to look for disassembly errors, I'll go ahead and fix
them. Just note that I won't do common substitutions like mov pc,lr ==
ret.

At this point, we can make two moves and then the game tells us that
we've won.
So ... I'm back to thinking the problem is with bugs in the ARM core,
and that our bidirectional communication is strong enough to play the
game.
Although that's not perfect. The game definitely looks at d4 (and
possibly others later), but my hardware tests can't get anything but
d0/d3 set.
2012-03-01 23:23:05 +11:00
Tim Allen
ad71e18e02 Update to v086r13 release.
byuu says:

That's my best implementation of the shifter carry. It's horribly
inefficient and possibly wrong (especially on ROR by register, but that
doesn't ever appear to be used in this program), but oh well. It's the
best I can do.

Game is basically getting stuck after a board upload and issuing another
command. It's sitting in a loop waiting on $3804.d0 to be set, meaning
the ARM is never writing anything for the CPU to read. There's some
chance that my $3804/r40000000 flags are wrong. Short of guessing
though, I'm not sure how we can get more info on how those work.

... I really can't debug this any better than I have. If no one else
sees anything, then we're going to have to give up and wait for MESS to
create opcode logs for us to compare against.
2012-02-29 23:59:48 +11:00
Tim Allen
a00c7cb639 Update to v086r12 release.
byuu says:

Attract demonstration game is fully playable.
2012-02-29 23:56:21 +11:00
Tim Allen
112520cf45 Update to v086r11 release.
byuu says:

More ARM work. Can get in-game, and upload the board (0xaa) successfully.
Bug in checkmate command makes the CPU really difficult to defeat :P
2012-02-28 22:21:18 +11:00
Tim Allen
11d6f09359 Update to v086r10 release.
byuu says:

More ARM work. ARM core now begins to act upon initial 0xf1 command, but
hangs.
2012-02-28 22:10:02 +11:00
Tim Allen
3ed42af8a1 Update to v086r09 release.
byuu says:

A lot more work on the ARMv3 core.
2012-02-27 11:18:50 +11:00
Tim Allen
482b4119f6 Update to v086r08 release.
byuu says:

Contains the fledgling beginnings of an ARM CPU core, which can execute
the first three and a half instructions of the ST-0018.
It's a start, I guess.
2012-02-26 18:59:44 +11:00
Tim Allen
f1d6325bcd Update to v086r07 release.
byuu says:

USART improvements. The clock pulse from reading data() drives both
reading and writing.
Also added a usart_init() to bind the initializer functions, so all you
need now is:
extern "C" usartproc void usart_main() { ... }
And inside, you use usart_read(), usart_write(), etc.
So we can add all the new functions we want (eg I'd like to have
usart_readable() to check if data is available) without changing the
entry point signature.

blargg enhanced his Teensy driver to ignore frame error reads, as well.
2012-02-25 20:12:08 +11:00
Tim Allen
e48671694e Update to v086r06 release.
byuu says:

It is done. bsnes can now emulate sending and receiving data via USART.
As such, the UART code has been removed.
The final UART code can be downloaded here: http://byuu.org/snes/uart/
I won't maintain it going forward, because nobody ever used it, and
USART is superior in every way.

I've also verified both sending and receiving on the real SNES now :D
It's so easy ... a caveman with electrical engineering and computer
programming experience can do it.
2012-02-25 20:03:11 +11:00
Tim Allen
338f13e57b Update to v086r05 release.
byuu says:

USART implements reading and writing, but I don't yet have code to test
SNES reading yet.
So ... obviously I need to do that next.

Went ahead and required nall::function, so the modules will have to be
C++11. I don't see anyone else making these, and it avoids the annoyance
of deducing the correct controller port based on dynamic casting the
active thread.
Apparently a library can have a main() function to no ill effect, so
there's no need for USART_HARDWARE. Same exact code with different flags
will make the binary and the library.
2012-02-25 19:52:42 +11:00
Tim Allen
6cbc312f11 Update to v086r04 release.
byuu says:

There will probably be a series of small WIPs as I experiment here.

snes/controller/serial is now snes/controller/uart. Asynchronous serial
communications, typically capped at 57,600 baud.
snes/controller/usart is new. It aims to emulate the SNES connected to
a Teensy++ board, and can easily handle 524,288 baud.
And much more importantly, it's synchronous, so there are no timing
issues anymore. Just bit-bang as fast as you can.

Right now, the USART code is just enough for SNES->PC to transfer data
to ... well, nothing yet.

Unless anyone is actually using the UART stuff, I'll be removing it once
the USART is totally up and running.
No sense maintaining code that is 10x slower, more error prone, and used
by nobody.

Note: this is all thanks to blargg being absolutely amazing.
2012-02-25 19:49:27 +11:00
Tim Allen
7a96321e78 Update to v086r03 release.
byuu says:

Cart unload save path was using the new game rather than the old game.
Caused by trying to allow a failed cartridge load to not unload the
current game.
But that's so uncommon that it's not worth worrying about. It'll always
unload before trying to load a new game now.

Removed the TM/TS disable speedup, to fix Madara 2's text boxes.
This actually did cause a slight performance penalty on games that
disable layers via TM/TS. Zelda 3 inside Link's house is a good example.
It knocked the FPS from 98.5 to 94.5. So to counter that, I removed
conditionals from tiledata loading and decoding, and used fall through
switches.
This boosted us back to 97.0. The -march=native flag apparently works
better with SB now, so that was added, putting us up to 99.0fps.
So it should be the same speed in the worst case, and slightly faster in
the best case.

Bumped the pre-render time to 68 clocks from 60 clocks. Adjusted sprite
tile fetch time from 22 to 14 to compensate.
This should give us perfectly stable Dai Kaijuu Monogatari 2 battles.
2012-02-18 18:49:52 +11:00
Tim Allen
6cfb9e89e7 Update to v086r02 release.
byuu says:

Fixed Super Game Boy RAM saving and loading. It plainly wasn't hooked up
at all. Was apparently hard-coded before it became a multi-emulator.
I also fixed a crashing issue when loading Satellaview-slotted or
Satellaview games without specifying the sub-cart, wasn't setting
has_bsx_slot = true, so the raw memory wasn't being allocated internally
when it wasn't mapped in. Of course a better fix would be to just not
physically map the ranges if the things aren't present. Kind of a lazy
hack to map blank cartridges there, but oh well.  Oh, fixed title
displays as well; and did the best I could for now with regards to
multi-file path saving.
2012-02-16 23:48:05 +11:00
Tim Allen
a37ce1cb2f Update to v086r01 release.
byuu says:

The goals for v087 are to have a unified cartridge-folder concept, as
well as a more functional SNES debugger.

Starting with the cartridge folders. What I have so far:

Code:
NES:
- program.rom
- character.rom
- program.ram
- …

SNES:
- program.rom
- program.rtc
- data.rom (SPC7110)
- { dsp1.rom, dsp1b.rom, cx4.rom, … }
- msu1.rom
- track-#.pcm

Game Boy, Game Boy Color:
- program.rom
- program.ram
- program.rtc

Sub-cartridges (BS-X, Sufami Turbo, …) are stored as separate folders
Folder names must be UTF-8 based, with all-lowercase extensions
File names must be all-lowercase

SNES:
- "program.ram" (.srm, .sts)
- "msu1.rom" (name.msu)
- "track-#.pcm" (name-#.pcm)
- "upd96050.ram" -> "name.ram"
- "bsx.ram" (.bss)
- "bsx.psram" (.bsp)
- "serial.so" -> "libserial.so" (broken)

Need:
- Super Game Boy (not even sure how this loads and saves memory, it's
  obviously broken)

And I need to think of some way of handling multi-cart loaded games.
Eg Satellaview-slotted and Sufami Turbo. It was { base + slot ( + slot
... } }, but this gets trickier with folders and fixed names.
Actual markup for the NES needs to change as well.
2012-02-16 01:01:22 +11:00
Tim Allen
10fd29e7bb Update to v086 release.
byuu says:

The main focus of this release is Laevateinn, which is the new bsnes
debugger. Unlike previous debuggers, Laevateinn is a standalone
application with its own GUI entirely focused on debugging.

Changelog:
- created ui-debugger target (Laevateinn)
- fixed multitap ports 2-4 [quequotion]
- fixed ui-libsnes target compilation
- fixed a crashing issue with NSS XML markup
- improved cartridge-folder loading support
- NES can now load .fc (headerless NES) or .prg+.chr (split NES) images
- fixed cursor being visible in fullscreen mode when using
  Linux/Metacity window manager [ncbncb]
- show normal cursor when using Linux/SDL video driver [ncbncb]
- added menu accelerators
- fixed a bug in performance profile SMP incw/decw instructions
- SNES core can now optionally be built without Game Boy emulation core
- added 2012-02-04 cheats.xml database [mightymo]
2012-02-13 22:44:02 +11:00
Tim Allen
0370229444 Update to v085r09 release.
byuu says:

Added VRAM viewer (mouse over to get tile# and VRAM address), CPU+SMP
register editors, settings.cfg to cache path+sync audio+mute audio
settings (Windows Vista+ ignore my request for the default folder
because they are fucking stupid, so they always default to your home
folder. I'm going to have to recommend using a batch file to start
laevateinn there. Sorry, blame Microsoft for being fuck-ups),
geometry.cfg to remember where you placed windows and what size you made
them (a bug in Qt prevents me from making some windows fixed-size for
now, but that'll change when I can work around the Qt issue), usage map
invalidation if the ROM was modified after the usage files, that empty
line insertion thing creaothceann wanted on emulation resume, all chips
now synchronize immediately rather than just-in-time, which is important
for a debugger.

Going to postpone the properties viewer until after v086.

So this is pretty much ready for release. Please bug-test. I don't care
so much about little frills like "oh the memory editor window should
default to a little bigger", you can work around that by resizing it.
I care about things like, "VRAM write breakpoints don't work at all."

If we miss any bugs and it gets released, not the end of the world, but
you'll be waiting a while for the next release to address any missed
bugs now.
2012-02-12 20:58:04 +11:00
Tim Allen
82afd511fc Update to v085r08 release.
byuu says:

Changelog:
- follow the Laevateinn topic to get most of it
- also added NMI, IRQ step buttons to CPU debugger
- also added trace masking + trace mask reset
- also added memory export
- cartridge loading is entirely folder-based now

FitzRoy, I'll go ahead and make a second compromise with you for v086:
I'll match the following:

    /path/to/SNES.sfc/*.sfc
    /path/to/NES.fc/*.prg, *.chr (split format)
    /path/to/NES.fc/*.fc (merged format)
    /path/to/GB.gb/*.gb
    /path/to/GBC.gbc/*.gbc

Condition will be that there can only be one of each file. If there's
more than one, it'll abort. That lets me name my ROMs as
"Game.fc/Game.fc", and you can name yours as "Game.fc/cartridge.prg,
cartridge.chr". Or whatever you want.
We'll just go with that, see what fares out as the most popular, and
then restrict it back to that method.
The folder must have the .fc, etc extension though. That will be how we
avoid false-positive folder matches.

[Editor's note - the Laevateinn topic mentions these changes for
v085r08:

    Added SMP/PPU breakpoints, SMP debugger, SMP stepping / tracing,
    memory editing on APU-bus / VRAM / OAM / CGRAM, save state menu,
    WRAM mirroring on breakpoints, protected MMIO memory regions
    (otherwise, viewing $002100 could crash your game.)

    Major missing components:
    - trace mask
    - trace mask clear / usage map clear
    - window geometry caching / sizing improvements
    - VRAM viewer
    - properties viewer
    - working memory export button

    The rest will most likely appear after v086 is released.
]
2012-02-12 16:35:40 +11:00
Tim Allen
ad3eafd735 Update to v085r07 release.
byuu says:

Changelog:
- stuff

[Editor's note - pretty much just more debugger implementation]
2012-02-12 16:07:24 +11:00
Tim Allen
4bc5f66aa5 Update to v085r06 release.
byuu says:

Lots of debugger enhancements. Memory editor works for CPU-bus only,
breakpoint editor does nothing yet.
Tracing works, writes to 001-999 files sequentially. Stepping works,
too. But only on the CPU.
Added "privileged", which becomes "public" if DEBUGGER is defined,
"private" otherwise.
Meant so the debugger can stab deeply into the cores for state
manipulation. Interface is guaranteed to be unstable and dependent upon
the accuracy core.
The about screen logo adds 100KB onto the source download (won't affect
regular bsnes binaries), but too bad. I want some visual flair this
time.
2012-02-09 23:53:55 +11:00
Tim Allen
730e6ae4cc Update to v085r04 release.
byuu says:

Changelog:
- added base/ folder
- base/base.hpp defines the version number for all UI targets, all the
  varint-types, and a hook() class for debugger functions (see below)
- fixed compatibility profile compilation
- removed within<> template from the SNES target
- the SNES core can be built without Game Boy support now, if you so
  choose (my SNES debugger is not going to support debugging the GBZ80,
  sorry.)
- added ui-debugger; not at all useful right now, will be a long while
  to get something usable ready

So hook is a class wrapper around nall::function. It allows you to
invoke potentially empty functions (and as such, the return type must
have a trivial constructor.)
It also doesn't actually perform the test+invocation when DEBUGGER
(options=debugger) is not defined. So you should have no overhead in
regular builds.
The core classes now have a subclass with all the debugging hooks, so
you'll see eg:

    void CPU::op_step() {
      debugger.op_exec(regs.pc);
      (this->*opcode_table[op_read()])();
    }

Clear what it's doing, clear what it's for. A whole lot less work than
inheriting the whole CPU core and virtualizing the functions we want to
hook.
All the logic for what to do inside these callbacks will be handled by
individual debuggers, so they can have all the functionality they want.
2012-02-06 23:03:45 +11:00
Tim Allen
892bb3ab01 Update to v085r03 release.
byuu says:

Changelog:
- fixed cursor being visible under Metacity window manager (hopefully
  doesn't cause regression with other WMs)
- show normal cursor when using SDL video driver
- added menu accelerators (meh, why not?)
- removed debugvirtual, ChipDebugger and chip/debugger functionality
  entirely
- alt/smp disassembler moved up
- fixed alt/smp incw/decw instructions (unsigned->uint16 for internal
  variables)

My plan going forward for a debugger is not to hardcode functionality
that causes the 10-15% slowdown right into the emulator itself.
Instead, I'm going to make a callback class, which will be a specialized
version of nall::function:
- can call function even if not assigned (results in no-op, return type
  must have a trivial default constructor)
- if compiled without #define DEBUGGER, the entire thing turns into
  a huge no-op; and will be eliminated entirely when compiled
- strategically place the functions: cb_step, cb_read, cb_write, etc.

From here, the ui-debugger GUI will bind the callbacks, implement
breakpoint checking, usage table generation, etc itself.
I'll probably have to add some breakout commands to exit the emulation
core prior to a frame event in some cases as well.

I didn't initially want any debugger-related stuff in the base cores,
but the #if debugger sCPUDebugger #else sCPU #endif stuff was already
more of a burden than this will be.
2012-02-04 20:23:53 +11:00
Tim Allen
e4e50308d2 Update to v085r02 release.
byuu says:

Fixed NSS XML crashing issue.
Improved folder-loading support.
NES can now load game.fc/game.fc, or game.fc/game.prg+game.chr.
Both types should have no iNES header at all.
And both types require an XML file (until we have a built-in database.)
2012-01-26 17:50:09 +11:00
Tim Allen
cc518dcc3c Update to v085r01 release.
byuu says:

Changelog:
- updated bsnes to use the newest versions of nall and phoenix
- fixed ui-libsnes compilation (testing would be a good idea, especially
  the cheat codes. I just copy-pasted that from the regular UI.)
- fixed multitap controllers 2-4 [quequotion]
2012-01-15 19:29:57 +11:00
Tim Allen
ba081d309e Update to v085 release.
byuu says:

A new release for the new year.

Changelog:
fixed auto joypad polling edge case; fixes Ys 5 controls
fixed Justifier polling code; Lethal Enforcers should be fully
responsive once again
rewrote SNES S-SMP processor core (~20% code reduction)
fixed Game Boy 8x16 sprite mode; fixed some sprites in Zelda: Link's
Awakening
treat Game Boy HuC1 RAM enable flag as writable flag instead; fixes
Pokemon Card GB
created far faster XML parser; bsnes can now load XML files once again
updated to mightymo's most recent cheat code database
internal color calculations now performed at 30-bits per pixel
gamma slider now acts as fine-tuned gamma ramp option
Linux OpenGL driver will output at 30bpp on capable displays
Linux port defaults to GTK+ now instead of Qt (both are still available)
2012-01-04 00:10:46 +11:00
Tim Allen
1bf9265b7c Update to v084r08 release.
byuu says:

Okay, everything can now load XML again, including board layouts for all
three systems. New is the ability to load external Game Boy layouts (not
really that useful, but it's there.)
I'd like to aim for a v085 release soon. I've included a binary, so I'd
appreciate testing. I had to redo all of the XML mappings for every
system (I like consistency), so basically the following things need to
be tested:
* load one of every type of game for every system (every NES board type,
* every Game Boy MBC type, every SNES chip and layout type.)
* test cheat codes and the cheat database
* test pixel shaders for OpenGL and Direct3D (sepia for the win)
* test anything else for v085 release
2011-12-31 20:24:58 +11:00
Tim Allen
f947d84309 Update to v084r07 release.
byuu says:

Added the new super-fast XML parser. So far, the shaders, cheat files,
and cheat database have been updated to allow XML mode once again. Which
is sure to please Screwtape =)
So it's down to just the cartridge mapping files now, which are always
a major pain.

I still think BML is better for parsing simplicity, memory usage, disk
size, lack of red tape and speed (but horrendously bad for ease of
creating files manually), but since the base API is identical, there's
no reason not to support both. Especially since the pixel shaders have
kind of taken on a life of their own.
2011-12-30 17:41:29 +11:00
Tim Allen
0bd21185b8 Update to v084r06 release.
byuu says:

Changelog:
- fixed sprite tile masking for 8x16 mode (fixes Zelda: DX sprites)
- HuC1 flag sets RAM writable, not RAM enable (fixes Pokemon Card)
- removed within<> template, didn't turn out to be all that useful

I would be almost certain no games would break by allowing reads when it
is disabled, no game would rely on that behavior.
I prefer to be overly restrictive. Better to not allow valid behavior
than to allow invalid behavior. The latter is what gives us a dozen
broken SNES translations.
2011-12-26 21:49:48 +11:00
Tim Allen
6227974bf6 Update to v084r05 release.
(note: before the post announcing this release, there had been
a discussion of a performance optimisation that made the Super Scope
emulation a lot faster, but caused problems for the Justifier perpheral)

byuu says:

Spent a good two hours trying things to no avail.
I was trying to allow the CPU to run ahead, and sync on accesses to
$4016/4017/4201/4213, but that doesn't work because the controllers have
access to strobe IObit at will.
The codebase is really starting to get difficult to work with. I am
guessing because the days of massive development are long over, and the
code is starting to age.
Jonas' fix works 98% of the time, but there's still a few missed shots
here and there. So that's not going to work either.
So ... I give up. I've disabled the speed hack, so that it works 100% of
the time.
Did the same for the Super Scope: it may not have the same problem, but
I like consistency and don't feel like taking the chance.
This doesn't affect the mouse, since the mouse does not latch the
counters to indicate its X/Y position.
Speed hit is 92->82fps (accuracy profile), but only for Super Scope and
Justifier games.
But ... at least it works now. Slow and working is better than fast and
broken.

I appreciate the help in researching the issue, Jonas and krom.

Also pulled in phoenix/Makefile, which simplifies ui/Makefile.
Linux port defaults to GTK+ now. I can't get QGtkStyle to look good on
Debian.
2011-12-18 14:19:45 +11:00
Tim Allen
ea95eaca3c Update to v084r04 release.
byuu says:

Fixed the Ys 5 input bug in the auto joypad polling code. Can't
guarantee it's hardware-accurate (I have no way to extensively test it),
but I can guarantee it is closer to being correct now.
Also uses updated version of phoenix.

The justifier input is indeed all fucked up now. Seems like it stops
updating input after firing for a few frames.
I really don't want to debug that code anymore ... anyone want to make
$10 by fixing it? :P
2011-12-12 21:59:53 +11:00
Tim Allen
ad0805b168 Update to v084r03 release.
(r02 was not posted to the WIP thread)

byuu says:

Internally, all color is processed with 30-bit precision. The filters
also operate at 30-bit depth.
There's a new config file setting, video.depth, which defaults to 24.
This causes the final output to downsample to 24-bit, as most will
require.
If you set it to 30-bit, the downsampling will not occur, and bsnes will
ask ruby for a 30-bit surface. If you don't have one available, you're
going to get bad colors. Or maybe even a crash with OpenGL.
I don't yet have detection code to make sure you have an appropriate
visual in place.

30-bit mode will really only work if you are running Linux, running Xorg
at Depth 30, use the OpenGL or XShm driver, have an nVidia Quadro or AMD
FireGL card with the official drivers, and have a 30-bit capable
monitor.
Lots of planning and work for very little gain here, but it's nice that
it's finally finished.

Oh, I had to change the contrast/brightness formulas a tiny bit, but
they still work and look nice.
2011-12-03 14:22:54 +11:00
Tim Allen
2cc077e12b Update to v084r01 release.
I rewrote the S-SMP processor core (implementation of the 256 opcodes),
utilizing my new 6502-like syntax. It matches what bass v05r01 uses.
Took 10 hours.
Due to being able to group the "mov reg,mem" opcodes together with
"adc/sbc/ora/and/eor/cmp" sets, the total code size was reduced from
55.7KB to 42.5KB for identical accuracy and speed.
I also dropped the trick I was using to pass register variables as
template arguments, and instead just use a switch table to pass them as
function arguments. Makes the table a lot easier to read.

Passes all of my S-SMP tests, and all of blargg's
arithmetic/cycle-timing S-SMP tests. Runs Zelda 3 great as well. Didn't
test further.
This does have the potential to cause some regressions if I've messed
anything up, and none of the above tests caught it, so as always,
testing would be appreciated.

Anyway, yeah. By writing the actual processor with this new mnemonic
set, it confirms the parallels I've made.
My guess is that Sony really did clone the 6502, but was worried about
legal implications or something and changed the mnemonics last-minute.

(Note to self: need to re-enable snes.random before v085 official.)

EDIT: oh yeah, I also commented out the ALSA snd_pcm_drain() inside
term(). Without it, there is a tiny pop when the driver is
re-initialized. But with it, the entire emulator would lock up for five
whole seconds waiting on that call to complete. I'll take the pop any
day over that.
2011-11-17 23:05:35 +11:00
Tim Allen
ae6c3c377d Update to v084 ninja bug-fix.
byuu says:

Hiding the viewport is necessary on Windows to prevent it from
overlapping the status bar. I've changed it to set the size to 1,1 when
nothing is loaded.
That still puts a 1x1 pixel over the status bar when you resize the
window to 1xHeight, but ... you know, don't do that.
Also corrected the mask overscan option for NES/SNES.

Silently updated the bsnes_v084-source.tar.bz2 archive with those fixes,
there were only 48 downloads.
2011-11-08 22:58:50 +11:00
Tim Allen
01750e9c83 Update to v084 release.
byuu says:

This release adds preliminary Game Boy Color emulation. Due to lack of
technical information, this is undoubtedly the least stable module
I provide at this time; but improvements should continue as it is
developed.

This release also polishes the NES emulation and user interface code.

Changelog (since v083):
- added preliminary Game Boy Color emulation
- NES: added MMC6, VRC1, VRC2, VRC3 emulation
- NES: fixed MMC5 banking and added split-screen support [Cydrak]
- NES: pass all of blargg's ppu_vbl_nmi tests, pass more sprite tests
- NES: palette is now generated algorithmically [Bisqwit]
- SNES: fixed SA-1 IRQ regression caused by code refactoring
- Game Boy: rewrote audio channel mixing code; sound output is greatly
  improved as a result
- Game Boy: uses DMG boot ROM instead of SGB boot ROM
- Game Boy: fixed potential bug when loading save states
- phoenix: fixed ListView focus issue [X-Fi6]
- phoenix: fixed dialog message parsing [X-Fi6]
- ui: video output is truly 24-bit now; SNES luma=0 edge case emulated
- ui: audio frequency, latency, resampler are now user configurable
- ui: gamma ramp is dynamically adjustable
- ui: all filters ported to 24-bit mode (speed hit to HQ2x)
- ui: added turbo button mappings for all generic controllers
- ui: fixed audio volume on unmute via menu [Ver Greeneyes]
- ui: shrink window option does nothing when no cartridge is loaded
- ui: re-added compositor disable, driver verification from v082
2011-11-08 00:04:58 +11:00
Tim Allen
891f1ab7af Update to v083r10 release.
byuu says:

Changelog:
- NES: added VRC1, VRC2, VRC3, MMC6 emulation
- shrink window doesn't do anything when no cartridge is loaded
- phoenix Horizontal,VerticalLayout use const Size& instead of unsigned
  width,height [for consistency]

So, all official NES ASICs are supported now. Just need sound output for
MMC5+VRC7 to complete them; and then some board re-arrangement stuff for
VRC2+MMC3.

Note that MMC6 uses the same mapper ID as MMC3, and VRC2 uses the same
ID as VRC4, so you have to make a BML board mapping or toggle which type
is chosen in the source file to use these two chips.

Side note: NES overscan clamping is obviously still assuming 16-bit, as
only half the lines are erased. Need to fix that.
2011-11-04 22:57:54 +11:00
Tim Allen
bf78e66027 Update to v083r09 release.
byuu says:

Added frequency, latency, resampler selection to the audio settings
panel (I really only wanted it there for resampler selection ... having
three options matches the driver selection style though, so whatever.)
The linear/hermite sampler will double the framerate when running Game
Boy games, and sounds the same. Same framerate and sound quality on
SNES. But it will cause buzzing in many NES titles.
Also re-added the composition { never, fullscreen, always } modes.
I think that option is clutter, but it's just impossible to get good
audio+video on Windows 7 without it ...
Lastly, HQ2x was ported over, but not very well. I just convert source
pixels from RGB888 to RGB555, and output pixels in the opposite
direction.
Need someone good to port the diff() and blend functions over to RGB888
in a way that's not terribly slow.
2011-10-31 20:55:48 +11:00
Tim Allen
483f9f8f20 Update to v083r08 release.
byuu says:

Fixed SA-1 IRQ regression for Super Mario RPG
Added turbo B,A to NES+GB; B,A,X,Y to SNES (please don't ask for turbo
L,R; you never use those keys rapidly.)
Re-added video color adjustments, which are now done in full 8-bit
colorspace for more precision

Gamma ramp option is gone. It's now the gamma option, which now only
affects the lower-half of the colors.
A value of 1.0 gives you the original, washed out colors. 1.75 is what
the gamma ramp checkbox used to do (roughly).
The new default is 1.5, which still prevents color washout, but isn't as
overly dark as before.

I wanted to make the core/interface stuff abstract the complexity of
setting up a new C++ class, but it really didn't make anything easier.
It was all one-line stubs to internal functions, and there was just too
many platform-specific things that needed to be captured, so I did away
with that. Made a base class for the ui/interface stuff to get rid of
a lot of switch(mode()) stuff, still a work in progress.
2011-10-29 18:32:20 +11:00
Tim Allen
f3feaa3e86 Update to v083r07 release.
byuu says:

Game Boy: audio should sound a lot better, eg Zelda: DX first opening
scene
Game Boy Color: now uses cothread Processor::frequency to dynamically
clock GB-CPU to 8MHz. Proper OAM DMA and timer speed. Fixes SMT: DC - WB
audio.
Added the break; statements to phoenix/windows/platform message loop
Added audio latency/frequency to config file only
2011-10-28 20:51:43 +11:00
Tim Allen
aaffd000a4 Update to v083r06 release.
byuu says:

All cores: Video classes have internal->{RGB30,24,16,15} palette
generation support
All cores: video output is now RGB24, all filters except HQ2x were
updated to reflect this (HQ2x will be very hard)
NES: MMC5 CHR mapping fixes (Bandit Kings, RTK2, Uchuu Keibitai SDF)
[Cydrak]
NES: MMC5 vertical split screen support (Uchuu Keibitai SDF) [Cydrak]
Game Boy + Game Boy Color: fixed a potential freezing bug when loading
save states (re-create cothreads on state load; was implied when using
SGB mode.)
Game Boy Color: fixed freezing bug with Zelda: LA opening (SVBK is
readable.)
Game Boy Color: more accurate colors (better than GiiBii, probably worse
than KiGB)
SNES: luminance of zero is no longer pure black, as on real hardware.
This is possible thanks to using RGB888 output now.

The current major problems I'd like to solve:
- Zelda: Link's Awakening music when Link first wakes up in the house is
  atrociously bad
- Shin Megami Tensei: Devil Children - White Book (Shiro no Sho) plays
  music at 50% speed; yet Black Book (Kuro no Sho) does not ... one of
  my favorite games, so it'd be great to fix it
2011-10-28 00:30:19 +11:00
Tim Allen
118a393c4c Update to v083r05 release.
(r04 was not posted to the WIP thread)

byuu says:

NES: passes ppu_sprite_overflow tests 01, 02, 05.
Game Boy: uses DMG BIOS (the one with the slow title scroll) or SGB
BIOS, based upon how you load the game.
Game Boy Color: Everything except the IR port is emulated. I don't have
any plans to allow linking two instances of bsnes. And that's frankly
never going to happen over netplay anyway, due to latency requirements
of the serial/IR ports.
The new DMA stuff is possibly incorrect, my test games don't seem to use
it.
Zelda: DX usually resets or crashes on the intro right before the beach
scene. I'm not sure why. Skip the intro and the game plays fine.

This is the best I can do when the most up-to-date GB/C reference
document is over ten years old and half-assed (pandocs.)
I could really use some help from anyone who understands the system.
Probably the worst part of my emulation at the moment is the interrupt
system.
Lots of things real hardware doesn't allow (DMA outside HRAM, CGB DMA to
invalid addresses, etc) isn't blocked yet.
LCD renderer is still scanline-based, which is just terrible. Doesn't
seem to be any good docs on cycle-level operation. I only know that it's
incredibly pathological and variable.
2011-10-27 11:00:17 +11:00
Tim Allen
6b708de893 Update to v083r03 release.
byuu says:

Lots of phoenix issues fixed, especially for Windows and GTK+.
NES emulation passes all ten ppu_vbl_nmi tests from blargg.
Sprite timing is nowhere near accurate yet (always consumes four clocks
per sprite), but oh well.
2011-10-24 22:35:34 +11:00
Tim Allen
db5e2107b4 Update to v083r02 release.
byuu says:

It seems impossible to pass blargg's NES ppu_vbl_nmi test 03 and 07 at
the same time. Wrote up a description of the problem here:
http://nesdev.parodius.com/bbs/viewtopic.php?p=85156#85156
2011-10-18 21:05:29 +11:00
Tim Allen
13ac6104e3 Update to v083r01 release.
byuu says:

This adds Bisqwit's NES palette generation code:

    http://nesdev.parodius.com/bbs/viewtopic.php?p=85060#85060

I set the saturation to 2.0 to closer match the existing "bright"
palette, although it still has a greater contrast range (some colors are
darker.) The gamma ramp option works now. Like SNES, best to also set
gamma to 0.8 afterward.  Once I think of a good way to expose the
saturation/hue settings, I'll do so.

I've also merged in the updated nall. Adds Cygwin uname check, and
replaces linear_vector with vector in lstring and the GUI.
2011-10-16 20:44:48 +11:00
Tim Allen
7fa8ad755d Update to v083 release.
byuu says:

This release adds preliminary Nintendo / Famicom emulation. It's only
a week or two old, so a lot of work still needs to be done before it can
compete with the most popular NES emulators.

It's important to clarify: bsnes is primarily an SNES emulator. That
will always be its forte and my core focus. I have added Game Boy
support previously for Super Game Boy emulation, and I've added NES
support mostly for something fun to work on to break up the monotony of
working on one system for seven years now. Obviously, I'd like the
emulation to be accurate and highly compatible, but I simply cannot
afford to invest the same amount of time and money into any other
systems.

Still, either way the NES and GB emulation serve as fun side-diversions,
and allow for a unified emulator interface with all of bsnes' unique
features applied to all systems. My personal favorite feature is
mightymo's extended built-in cheat code database that now also includes
NES and Game Boy codes. And it even works in Super Game Boy mode now,
too!

I'm also not worried about speed at all: so long as NES/GB are faster
than SNES/compatibility, it's fine by me. Note that due to the NES audio
running at 1.78MHz, and Game Boy audio at 4MHz stereo, a more
sophisticated audio resampler was needed: Ryphecha (Mednafen author) has
graciously written a first-rate resampler: it is a band-limited
Kaiser-windowed polyphase sinc resampler. It is combined with two
highpass filters to remove DC bias. The filter itself is SSE optimized,
but even still, approximately 50% of CPU usage for NES/GB emulation goes
to the audio filtering alone. However, you now have the best sound
possible for NES and Game Boy emulation as a result.

The GUI has also been heavily re-structured to accommodate multiple
emulators from the same interface. As such, it's quite likely a few bugs
are still lurking here and there. Please report them and I'll iron them
out for the next release.

Changelog:
- license is now GPLv3
- re-structured GUI as a multi-system emulator
- added NES emulation [byuu, Ryphecha]
- added NES ICs: MMC1, MMC2, MMC3, MMC4, MMC5, VRC4, VRC6+audio, VRC7,
  Sunsoft-5B+audio, Bandai-LZ93D50
- added NES boards: AxROM, BNROM, CNROM, ExROM, FxROM, GxROM, NROM,
  PxROM, SxROM, TxROM, UxROM
- Game Boy emulation improvements [Jonas Quinn]
- SNES core outputs full 19-bit color (4-bit luma included) for more
  accurate color reproduction (~5% speed hit)
- audio resampler is now a band-limited polyphase resampler [Ryphecha]
- cheat database includes NES+GB codes as well [mightymo, tukuyomi]
- lots of other changes
2011-10-14 21:05:25 +11:00
Tim Allen
ef85f7ccb0 Update to v082r33 release.
byuu says:

Added MMC2, MMC4, VRC4, VRC7 (no audio.)
Split NES audio code up into individual modules.
Fixed libsnes to compile: Themaister, can you please test to make sure
it works? I don't have a libsnes client on my work PC to test it.
Added about / license information to bottom of advanced settings screen
for now (better than nothing, I guess.)
Blocked PPU reads/writes while rendering for now, easier than coming up
with a bus address locking thing :/

I can't seem to fix MMC5 graphics during the intro to Uchuu Keibitai.
Without that, trying to implement vertical-split screen mode doesn't
make sense.

So as far as special audio chips go ...
* VRC6 is completed
* Sunsoft 5B has everything the only game to use it uses, but there are
  more unused channels I'd like to support anyway (they aren't
  documented, though.)
* MMC5 audio unsupported for now
* VRC7 audio unsupported, probably for a long time (hardest audio driver
  of all. More complex than core NES APU.)
* audio PCM games (Moero Pro Yakyuu!) I probably won't ever support
  (they require external WAV packs.)
2011-10-12 23:03:58 +11:00
Tim Allen
b8d607d16b Update to v082r32 release.
byuu says:

Added delay to MMC1 register writes, to fix Bill & Ted's Godawful
Adventure.
Fixed up MMC5 RAM+fill mode, and added EXRAM mode support (8x8
tiles/attributes.)
Just Breed is fully playable now.

MMC5 is a total pain in the ass, the documentation on it is just
terrible. I basically just tried seven hundred variations until
something worked.
I still need to add MMC5 vertical split screen (for one single game's
attract screen, ugh), and the extra sound channels.
Would like to rework the NES APU first. Since the pulse channels are
identical sans sweep, it'd be nice to just inherit those and mask out
the sweep register bit writes.
So that probably won't make it into the first release, at least.

Still, overall I think it'll be an impressive showing of complex mappers
for a first release: MMC3, MMC5, VRC6 and 5B. The latter two with full
audio. The only other really, really hard bit is the VRC7 audio,
supposedly.
2011-10-08 18:34:16 +11:00
Tim Allen
4c47cc203f Update to v082r31 release.
byuu says:

Enable Overscan->Mask Overscan [best I'm doing]
Video settings -> Overscan mask: (horizontal, vertical: 0-16 on each
side) [only works on NES+SNES]
BPS patching works for NES+SNES+GB; note that long-term I want BPS to
only patch headerless PRG+CHR files, but we'll need a database
/ completed board mapping system first.
MMC1 splits the board/chip markups a bit better. My attempts to emulate
the extra CHR bits per hardware fail repeatedly. Docs do not explain how
it works at all.
Emulated enough of the MMC5 to play Castlevania 3.

The MMC5 is easily the most complicated mapper the NES has to offer, and
of course, has the most pitifully vague and difficult documentation of
any mapper around.
It seems the only way anyone is able to emulate this chip is
empirically.
Everyone else apparently hooks the MMC5 right into the PPU core, which
I of course cannot do. So I had to come up with my own (probably wrong)
way to synchronize the PPU simply by observing CHR bus accesses.

I must say, I over-estimated how well fleshed out the NES hardware
documentation was. Shit hits the fan right after MMC3.
It's miles beyond the GB scene, but I find myself wanting for someone
with the technical writing ability of anomie.
I can't find anything at all on how we're supposed to support the $2007
port reads/writes without it extra-clocking the PPU's bus, which could
throw off mapper timing.
Absolutely nothing at all on the subject anywhere, something everybody
is required to do for all cycle-based emulators and ... nada.

Anyway, I'd like to refine the MMC5 a bit, getting Just Breed playable
even without sound would be really nice (it's a fun game.)
Then we need to get libsnes building again (ugh, getting worn out in
backporting changes to it.)
Once v083 is public, we can start discussing a new API for multiple
emulators.
2011-10-06 20:53:16 +11:00
Tim Allen
4cbaf4e4ec Update to v082r30 release.
byuu says:

cheats.xml -> cheats.bml, includes NES+SNES+GB codes now. Absolutely
awesome, thanks to mightymo and tukuyomi.

I also added Sunsoft-FME7/5B (with sound) emulation. Really only useful
for playing the Japanese release of Gimmick!
Fun game, but balls to the wall hard.
2011-10-05 20:37:00 +11:00
Tim Allen
21f9fe4cd5 Update to v082r29 release.
byuu says:

I doubt anyone is going to like these changes, but oh well.

The base height output for NES+SNES is now always 256x240. The Enable
Overscan option blanks out borders around the screen. This eliminates
the need for an overscan software filter. For NES, it's 16px from the
top and bottom, and 8px from the left and right. Anything less and you
get scrolling artifacts in countless games. For the SNES, it's only 16px
from the top and bottom. Main point is that most NTSC SNES games are
224-height games, so you'll have black borders. Oh well, hack the source
if you want. Game Boy overscan option does nothing.

Everything except for the cheats.xml file now uses BML markup. I need to
write a converter for cheats.xml still. Cut the SNES board parsing code
in half, 30KB->16KB. Much cleaner now.
Took the opportunity to fix a mistake I made back with the XML spec: all
numbers are integers, but can be prefixed with 0x to become hexadecimal.
Before, offset/size values defaulted to hex-mode even without a prefix,
unlike frequency/etc values.

The XML shaders have gone in their own direction anyway, with most being
multi-pass and incompatible with bsnes. So that said, please don't
extend the BML functionality from your end. But f eel free to add to the
XML spec, since other emulators now use that as well. And don't
misunderstand, I love the work that's being done there. It's pretty
awesome to see multi-pass shader capabilities, and the RAM watching
stuff is just amazing.
If there are any really awesome single-pass shaders that people would
like, I can convert it from XML and include it with future releases.
On that topic, I removed the watercolor/hdr-tv ones from the binary
packages (still in the source archive) ... they are neat, but not very
useful for actual gaming.
If we had more than one, I'd remove the Direct3D sepia one. Not going to
use shaders from a certain bipolar manic, because I'd never hear the end
of it if I did :/

Oh, one change I think people will like: MSU1 no longer requires
a memory map specification, so MSU1 authors won't have to keep updating
to my newer revisions of board markups. Basically, if there's not
a board with an msu1 section, it'll check if "gamename.msu" exists. If
it does, MSU1 gets mapped to 00-3f,80-bf:2000-2007. If all you want is
music, make a blank, zero-byte gamename.msu file.
2011-10-04 22:55:39 +11:00
Tim Allen
b629a46779 Update to v082r28 release.
byuu says:

Was mostly working on BML. Still working on the spec.
Added NES-BNROM, NES-GNROM/NES-MHROM boards. I don't even know why. The
latter games do not work very well without Zapper support.
2011-10-02 21:05:45 +11:00
Tim Allen
ba2e6b5789 Update to v082r27 release.
byuu says:

Finished porting over all mappers to board/chip disambiguations. Had to
nearly rewrite the MMC1 code to do it, but all variants should be
supported.
iNES1 is too stupid to express them all, so you'll need a board markup
if you want to play the >8KB PRG RAM games.
For whatever reason, they call VRC6's memory WRAM, and MMC1's PRG RAM.
I am calling them all PRG RAM, since it's the same damn thing.
Board spec is not going to be stable until I have a hell of a lot more
mappers implemented, so be wary of that.
Anyway, at this time, all games can be loaded sans iNES header, if you
have the board markup. I'd also like to have a board database for all
commercial titles.
I'm treating *.fc as PRG-ROM(+CHR-ROM). Will work on loading the split
files later possibly.
2011-10-01 22:06:48 +10:00
Tim Allen
7115047d85 Update to v082r26 release.
byuu says:

.cht files now use BML-formatted data. I'm still going to request the
cheats.xml file as-is, and will write my own converter for embedding
during releases.
This is where parsing 2MB markup files in 10ms is really going to be
nice. Had to use an evil hack before for actually searching for games.

This has the start of the board/chip separation from mappers for NES,
and it has a barebones iNES->board markup converter.
You can specify your own board markup and bypass the need for an iNES
header, so in other words it will load No-Intro style games with
a proper board file.
Long-term, we'll have an internal database for commercial boards, and
probably folder.fc/prg.rom{,chr.rom} loading support.

Since they can't co-exist, the mappers are currently disabled, and I've
only ported the easy ones. So no MMC1/MMC3/VRC6 in this release. I need
to make them into chips first.
2011-10-01 21:16:57 +10:00
Tim Allen
e8b1af0917 Update to v082r25 release.
byuu says:

Ryphecha fixed Gun Nac, it was some sort of problem with blank sprite
address fetching messing with the MMC3
I've started on an XML parser for iNES-free loading, but it's pretty
barebones right now. Only NROM-256 loads, and you have to make it
a compile-time thing (so other games work for now.)
Updated nall with nullptr stuff.
nall/detect is now nall/intrinsic and has both #defines + static
constants that can be used to detect the platform (allows for run-time
platform checks where practical.)
ruby has a Makefile now, that makes using it in other projects a lot
easier
2011-09-29 22:08:22 +10:00
Tim Allen
1d4f778176 Update to v082r24 release.
byuu says:

Upgraded to GCC 4.6.1.
Removed nall/foreach and nall/concept, upgraded iterator support on all
of my containers, and replaced everything with range-for.
Fixed up Qt geometry a good bit, should at least create windows now without bouncing around.
Added some initial nullptr / constexpr changes.
Some other minor cleanups ... removing foreach() took about 6-8 hours
alone.
2011-09-27 21:55:02 +10:00
Tim Allen
875ed46d79 Update to v082r23 release.
byuu says:

Ryphecha fixed the FF1 glitch, added two highpass filters to NES audio
output (still working on a lowpass), and fixed VRC6 audio issues.
I reduced the complexity of all eight supported mapping modes, and
standardized them; and added in an overscan filter (not in archive) for
chopping off all the NES edge garbage (8 pixels on the left and right,
16 on the top and bottom.)
It's extreme, but anything less shows junk. I may make this part of the
menu option, just clip off more on NES mode than SNES mode.
2011-09-26 21:38:57 +10:00
Tim Allen
046e478d86 Update to v082r22 release.
byuu says:

Mappers are now optionally threaded.
Fixed up MMC3 emulation, SMB3 and MM3-6 are all fully playable. However,
many unusual variants of this chip are not supported still.
Added UNROM+UOROM for Contra and MM1, allowing all six MM games to play
now.
Added VRC6 with sound emulation, because I wanted to get audio mixing in
place.

Chose VRC6 because it has Esper Dream 2, which is an absolutely amazing
game that everyone should play :D
The game didn't use sawtooth, and I didn't test any other VRC6 games, so
hopefully that is emulated passably well enough.
2011-09-26 21:27:06 +10:00
Tim Allen
82a17ac0f5 Update to v082r21 release.
byuu says:

2-6% speed hit in SNES core for outputting 19-bit (rounded to 32-bit ...
sigh) video, so that luma non-linearity can eventually be emulated
properly.
Now using sinc audio resampler, massive speed hit of course to NES+GB
only, but it's required to get rid of aliasing (buzzing) present in
many, many games otherwise.
Fixed fast forward and none/blur select.
Finally fixed texture clearing for changing pixel shaders and video
filters.
Some realllly basic NES MMC3, extremely broken so don't bug me about it.
Other stuff, probably.
2011-09-24 19:51:08 +10:00
Tim Allen
979aa640af Update to v082r20 release.
byuu says:

NES now has save state support.
NES A/B buttons were indeed swapped, so that's fixed now.
nall/dsp now puts resamplers into separate classes, so that each can
have their own state information.
opengl.hpp uses GL_RGBA internal format and doesn't regenerate textures
on resize. No speedup, no fix to junk on resize, so I will be very
unhappy if this breaks things for anyone.
GLSL shaders use <fragment filter="nearest/point"> as you guys wanted.
ui-snes was removed.
2011-09-23 21:13:57 +10:00
Tim Allen
98ec338285 Update snesfilter to release 20110920.
This was released beside bsnes v082r19. byuu didn't mention it in the
v082r19 release notes, but in a previous post mentioned that a number of
filters stopped working when bsnes switched to using RGB555 for all its
internal data.
2011-09-22 10:03:11 +10:00
Tim Allen
5b4dcbfdfe Update to v082r19 release.
byuu says:

This will be the last release with the ui-snes folder (it's broken now
anyway.)
Re-added cheat code database searching + add window. It hashes
NES+SNES+GB images now and will look them up in the database.
Re-added filter support, all filters now output at RGB555. Stacking is
possible, but I don't currently allow it.
Removed mouse capture + test options from tools menu.
Removed smooth video output from settings menu.
There are now two built-in "shaders": "None" (point filtering) and
"Blur" (linear filtering).
OpenGL shaders can now use <shader language="GLSL" filter="point"> (or
"linear") to specify their filtering mode.
Individual emulator versions are gone, and names are hidden from the
GUI: you just see bsnes v082.19 now. A new release bumps all core
versions.

I cannot for the life of me get the video to clear properly when
toggling the shaders. Say you set pixellate2x filter, then turn on
curvature shader, then turn off the filter, you get junk at the bottom
right.
I have tried clearing and flipping the OpenGL surface 64x in a row ...
I don't know where the hell it's getting the data from. If anyone can
make a small patch to fix that, I'd greatly appreciate it.
2011-09-22 10:00:21 +10:00
Tim Allen
101c9507b1 Update to v082r18 release.
byuu says:

There we go, the GUI is nearly feature-complete once again.

All cores now output their native video format (NES={emphasis}{palette},
SNES=BGR555, GameBoy={ bright, normal, darker, darkest }), and are
transformed to RGB555 data that is passed to the video renderer.
The video renderer then uses its internal palette to apply
brightness/contrast/gamma/ramp adjustments and outputs in RGB888 color
space.
This does add in another rendering pass, unfortunately, but it's
a necessary one for universal support.
The plan is to adapt all filters to take RGB555 input, and output RGB555
data as well. By doing this, it will be possible to stack filters.
However, it's a bit complicated: I need to plan how the stacking should
occur (eg we never want to apply scanlines before HQ2x, etc.)
Added input frequency adjustments for all three systems. I can easily
get perfect video/audio sync on all three now, hooray.
Long-term, it seems like we only really need one, and we can do
a video/audio delta to get an adjusted value. But for now, this gets the
job done.
Added audio volume adjust. I left out the balance for now, since it's
obviously impossible to balance the NES' single channel audio (I can
duplicate the channel, and do twice the filtering work, but ... why?)
I replaced NTSC/PAL TV mode selection with an "Enable Overscan"
checkbox. On, you get 240 lines on NES+SNES. Off, you get 224 lines on
NES+SNES.
Also added aspect correction box back. I don't do that gross PAL
distortion shit anymore, sorry PAL people. I just scale up the
54/47*(240/224) aspect correction for overscan off mode.
All memory is loaded and saved now, for all three systems (hooray, now
you can actually play Zelda 1&2.)
Added all of the old bsnes hotkeys, with the exception of capture
screenshot. May add again later. May come up with something a bit
different for extra features.
Re-added the NSS DIP switch setting window. Since geometry is saved,
I didn't want to auto-hide rows, so now you'll see all eight possible
DIPs, and the ones not used are grayed out.
Ultimately, nobody will notice since we only have DIPs for ActRaiser
NSS, and nobody's probably even using the XML file for that anyway.
Whatever, it's nice to have anyway.
Took FitzRoy's advice and single-item combo boxes on the input selection
are disabled, so the user doesn't waste time checking them.
I wanted to leave text so that you know there's not a problem. Qt
disabled radio box items look almost exactly like enabled ones.
Fixed lots of issues in phoenix and extended it a bit. But I was still
having trouble with radio box grouping, so I said fuck it and made the
panels show/hide based instead of append/remove based.
That's all for stuff off the checklist, I did a bunch of other things
I don't recall.

So yeah, I'd say the GUI is 100% usable now. This is my opinion on how
multi-platform GUIs should be done =)

Oh, I figure I should mention, but the NES core is GPLv3, and all future
SNES+GB releases will be as well. It's a move against Microsoft's Metro
store.
2011-09-21 00:04:43 +10:00
Tim Allen
69ed35db99 Update to v082r17 release.
byuu says:

Adds BS-X/Slotted/SufamiTurbo/SGB cartridge loading. Calling it
Satellaview as I'm more partial to that at the moment.
FileBrowser now remembers your folders per filter type like before, and
will keep your place in the list if you don't switch away.
I wanted there to be ONE slot loader, so the loader will show a grayed
out secondary slot on non-ST loading, but it's more consistent to only
have one window instead of two for geometry placement.
Removed help menu. Will try and work it in somewhere unobtrusive later
on I suppose.
Added timed messages and the usual "no cart loaded / paused" messages
and such.
2011-09-19 22:34:18 +10:00
Tim Allen
5c2d16828c Update to v082r16 release.
byuu says:

Binary output is once again called bsnes. No versioning on the title
without a system cartridge loaded. Still saving config files to
.config/batch for now.
Finally fixed NES APU frame IRQ clearing on $4015 reads.
Added mouse button/axis binding through buttons on the input capture
window.
Added advanced settings window with driver selection and focus policy
settings. Will show your default driver properly if none are selected
now, unlike old bsnes.
That exposed a small bug where phoenix isn't removing widgets on
Layout::remove, worked around it for now by hiding the panels. Damn,
sick of working on phoenix.
Added all missing input controllers, which can all now be mapped, and
bound them to the main menu, and added NES support for selecting "no
connected controller."
Added mouse capture and the requisite tools menu option for it.
Added WindowManager class that keeps track of both position and size now
(eg full geometry), so now you can resize your windows and save the
settings, unlike old bsnes.
WindowManager has more stringent geometry checks. The *client area* (not
the window border) can't be below 0,0 or above the width/height of three
30" monitors. If you have 4+ 30" monitors, then fuck you :P
settings.cfg is now also saved, captures all currently available
settings. Right now, there's only one path for the file browser to
remember. I will probably make this per-system later.
FileBrowser has been made a bit more friendly. The bottom left tells you
what type of files the list is filtered by (so you see "*.sfc" for
SNES), and the bottom right has an open button that can enter folders or
load files.
Added video shader support.
Fixed nall/dsp variadic-channel support, was only outputting the left
channel.
2011-09-19 22:25:56 +10:00
Tim Allen
382ae1e61e Update to v082r15 release.
byuu says:

7.5 hours of power coding. Das Keyboard definitely helped (but didn't
eliminate) RSI, neato.

Okay, the NES resampler was using 315 / 88.8 by mistake, so the output
rate was wrong, causing way more video/audio stuttering than necessary.
STILL forgot the NES APU frame IRQ clear thing on $4015 reads, blah. Why
do I always remember things right after uploading the WIPs?
Recreated the input manager with a new design, works much nicer than the
old one, a whole lot less duplicated code.
Recreated the input settings window to work with the new multi-system
emulation.
All input settings are saved to their own configuration file, input.cfg.
Going to batch folder for now.

Okay, so the new input settings window ... basically there are now three
drop-downs, and I'm not even trying to label them anymore.
They are primary, secondary, tertiary selectors for the listed group
below. Examples:
"NES -> Controller Port 1 -> Gamepad"
"SNES -> Controller Port 2 -> Super Scope"
"User Interface -> Hotkeys -> Save States"

I am aware that "Clear" gets disabled when assigning. I will work on
that later, being lazy for now and disabling the entire window. Have to
add the mouse binders back, too.
Escape and modifiers are both mappable as individual keys now. If you
want to clear, click the damn clear button :P

Oh, and all input goes to all windows for now. That'll be fixed too when
input focus stuff is re-added.
2011-09-17 16:42:17 +10:00
Tim Allen
7619805266 Update to v082r14 release.
byuu says:

Emulates DMC channel (sound effect when Link gets hit in Zelda 1, for
instance), fixes up bugs in rectangle/sweep and triangle channels, adds
DMC/frame APU IRQs, adds proper stalling for DMC ROM reads (should even
be cycle accurate, but has one extra cycle when triggered during OAM
DMA, I think), but forgets the frame IRQ acknowledge clear on $4015 read
(will fix next WIP.) All sound courtesy of Ryphecha.

Made template configuration settings window (empty for now.) Simplified
SNES cheat.cpp code. Some other stuff.

Further developed RSI.
2011-09-16 21:44:07 +10:00
Tim Allen
e3c7bbfb63 Update to v082r13 release.
byuu says:

I've updated the {System}::Interface classes to encapsulate all common
functionality, so they are C++ equivalents of libsnes now.
The idea being, use the interface class and you'll never have to reach
into core objects (unless you really want to.)
Not guaranteeing as stable an API as I do with libsnes for that, though.
C++ doesn't make for nice dynamic libraries, anyway.

Added back the state manager, and it now works for both SNES and Game
Boy. NES save states aren't in yet.
Anyway, this should give you a pretty good feel for what the combined UI
is going to be like: same as before, everything works the same. Only
difference is the dynamic system menu and cartridge menu with more load
options. The settings window will be mostly the same as well, but will
obviously have options that only apply to some systems.
2011-09-16 21:30:45 +10:00
Tim Allen
5f099b8ad0 Update to v082r12 release.
byuu says:

Merged Ryphecha's APU emulation, so NES has sound output now. We are
still missing the DMC memory fetch, so there will be missing sound
effects here and there.
2011-09-15 22:33:26 +10:00
Tim Allen
cb3460a673 Update to v082r11 release.
byuu says:

Emulates grayscale and color emphasis modes, improves sprite timing and
PPU bus fetching behavior with the PPU disabled.
2011-09-15 22:27:34 +10:00
Tim Allen
278cf8462c Update to v082r10 release.
byuu says:

Emulated the Game Genie for the NES and Game Boy, and wrote a new cheat
editor that doesn't reach into specific emulation cores so that it would
work.
Before you ask: yes, long-term I'd like Super Game Boy mode to accept
Game Boy codes. But that's not high on the priority list.
Renamed the mappers toward board names, LZ...->BandaiFCG,
LS161...->AOROM, added CNROM emulation (Adventure Island, Gradius, etc.)
Added the tools menu load/save state stuff, but note that the NES
doesn't have save state support yet (waiting for the interface to
stabilize a bit more first.)

Note: this will be the last release to have the ui-gameboy folder, it's
been deleted locally from my end, as the new multi-GUI does all that it
does and more now.
2011-09-15 22:23:13 +10:00
Tim Allen
7f4381b505 Update to v082r09 release.
byuu says:

Skip this build if you can, it's CPU+PPU timing improvements that should
not visibly affect anything.
2011-09-15 22:14:07 +10:00
Tim Allen
c668d10ac7 Update to v082r08 release.
byuu says:

Fixed up the PPU to be as close to cycle-perfect as possible. Fixed RMW
to write twice instead of read twice. Ryphecha added AOROM and fixed up
MMC1. Have CNROM too, but I need to rethink the mapper/board
distinction. Apparently the same logic IC is used in both AOROM and
CNROM, and it's just a matter of routing the pins to it. I need to
consider how crazy it'd be to emulate the logic IC and have boards
simply reroute pins to it. If it's too much work, we'll just treat
mappers as board + logic IC combinations. We'll see.
2011-09-12 20:30:44 +10:00
Tim Allen
7fc78dae07 Update to v082r07 release.
byuu says:

Wrote a cycle-based PPU renderer, ~95% hardware accurate for BGs, not so
much for sprites yet. Mednafen has been helping out a lot.
2011-09-12 20:17:12 +10:00
Tim Allen
4ca051a22f Update to v082r06 release.
byuu says:

Emulated MMC1, currently defaults to B2 configuration. Fixed a whole
bunch of timing things, render things, nametable mirroring things, etc.
Zelda and Mega Man II are fully playable, but they have odd vertical
scrolling issues that make it a not so fun experience.
Not sure what the problem is there, yet. The Y scroll register writes
seem to be wonky ... I don't know.

Keeping the Cartridge menu always visible now, so it's faster to load
carts, but I am still hiding the non-loaded system menus.
2011-09-12 19:44:22 +10:00
Tim Allen
8618334356 Update to v082r05 release.
byuu says:

Okay, I fixed up many outstanding phoenix issues.
* Windows/GTK+ fixed by using processEvents instead of main(); Windows can run unthrottled, and GTK+ shows the window contents now
* fixed keyboard beeping once and for all on Windows: I now whitelist tabbable controls
* fixed main menubar setVisible calls
* Qt and GTK+ now allow you to resize windows smaller than they initially were

Both Qt and GTK+ still fuck up the geometry a bit when toggling fullscreen mode. I have tried, and tried, and tried and tried and tried to fix it all. Nothing works. I give up.
Easier to destroy and recreate the fucking window than figure out how to resize it on Linux (and no, I can't do that. ruby would not like the handle changing.)

As for the GUI:
* file browser is back in, still need remember place and open folder code; that needs to be extended to handle multiple systems now
* shrink window command added to tools menu.
2011-09-09 14:16:25 +10:00
Tim Allen
ec7e4087fb Update to v082r04 release.
byuu says:

So, here's the deal. I now have three emulators. I don't think the
NES/GB ones are at all useful, but I do want them to be eventually. And
having them have those pathetic little GUIs like ui-gameboy, and keeping
everything in separate project folders, just doesn't work well for me.
I kind of "got around" the issue with the Game Boy, by only allowing SGB
mode emulation. But there is no "Super Nintendo" ... er ... wait ...
uhmm ... well, you know what I mean anyway.

So, my idea is to write a multi-emulator GUI, and keep the projects
together. The GUI is not going to change much. The way I envision this
working:

At startup, you have a menubar with: "Cartridge, Settings, Tools, Help".
Cartridge has "Load NES Cartridge", "Load SNES Cartridge", etc.
When you load something, Cartridge is replaced with the appropriate
system menu, eg "SNES". Here you have all your regular items: "power,
reset, controller port selection, etc." There is also a new "Unload
Cartridge" option, which is how you restore the "Cartridge" menu again.
I have no plans to emulate any other systems, but if I ever do emulate
something that doesn't take cartridges, I'll change the name to just
"Load" or something.

The cheat editor / state manager will look and act exactly the same. The
settings panel will look exactly the same. I'll simply show/hide
system-specific options as needed, like NES/SNES aspect ratio
correction, etc. The input mapping window will just have settings for
the currently loaded system. Video and audio tweaking will apply
cross-system, as will hotkey mapping.

The GUI stuff is mostly copy-paste, so it should only take me a week to
get it 95% back to where it was, so don't worry, this isn't total GUI
rewrite #80.
I am, however, making all the objects pointers, so that I can destruct
them all prior to main() returning, which is certainly one way of fixing
that annoying Windows/Qt crash.

Please only test on Linux. The Windows port is broken to hell, and will
give you a bad impression of the idea:
- menu groups are not hiding for some reason (all groups are showing, it
  looks hideous)
- Timer interval(0) is taking 16ms per call, capping the FPS to ~64 tops
  [FWIW, bsnes/accuracy gets 130fps, bgameboy gets 450fps, bnes gets
  800fps; all run at lowest possible granularity]
- the OS keeps beeping when you press keys (AGAIN)

Of course, Qt and GTK+ don't let you shrink a window from the requested
geometry size, because they suck. So the video scaling stuff doesn't
work all that great yet.
Man, a metric fuckton of things need to be fixed in phoenix, and
I really don't know how to fix any of them :/
2011-09-09 14:08:38 +10:00
Tim Allen
496708cffe Update to v082r03 release.
byuu says:

Couple more fixes to audio from Jonas, and I converted all types from
"unsigned" to the smallest sizes possible, which simplified a bit of the
code. Love variable-length integers.

Audio core should be really good now. Not perfect, but pretty close for
99% of games. Also fixed the window stuff for Cool World and such.
2011-09-05 13:56:22 +10:00
Tim Allen
a86c5ee59d Update to v082r02 release.
byuu says:

Has Jonas Quinn's many Game Boy APU fixes, and two more from blargg's
notes that I added.

It also has the new dynamic phoenix. So yeah, it'll crash on bsnes/Qt
exit. If anyone can fix it *properly* and wants the money, I'll pay them
$20 for the trouble =)
2011-09-05 13:48:23 +10:00
Tim Allen
d8f9204e18 Update to v082r01 release.
byuu says:

Changelog:
- if config file window coordinates are >= 30000, it snaps them back to
  128,128; should end the "why aren't windows visible?" posts
- updated GUI code to match new phoenix changes
- phoenix: Layout and Widget inherit from Sizable; directional layouts
  make no distinction between widgets and layouts
- phoenix: individual widgets / layout can maintain visible/hidden
  status in spite of their parents' visibility
2011-08-22 21:27:04 +10:00
Tim Allen
e8775319c8 Update to v082 release.
byuu says:

This release features many substantial Game Boy emulation improvements
(all courtesy of Jonas Quinn), a new audio DSP class, and BPS patching
support.

Changelog (since v081):

- added new DSP audio engine; supports sample-averaging for the Game
  Boy's high frequency rate
- GB: MMM01 images with boot loader at bottom of ROM can now be loaded
- GB: EI is delayed one cycle; fixes Bubble Bobble [Jonas Quinn]
- GB: fixed window -7 offset behavior; fixes Contra 3 first boss [Jonas
  Quinn]
- GB: disable LCD interrupts when rendering is off; fixes Super Mario
  Land 2 [Jonas Quinn]
- GB: fixed noise channel LFSR; fixes Zelda: LA lightning sound [Jonas
  Quinn]
- GB: square channels use initial_length like the noise channel [Jonas
  Quinn]
- UI: added BPS patching support; removed UPS patching support
- UI: when loading BS-X/Sufami Turbo/Game Boy games; display game title
  instead of BIOS title
- UI: modified timestamps on screenshots for Windows/NTFS (which
  disallows use of ':')
2011-08-21 01:02:27 +10:00
Tim Allen
095181af62 Update to v081r04 release.
byuu says:

- GB: square channels cache initial_length and invert the length value
  on writes [Jonas Quinn]
- GB: updated LCD disable to just ignore interrupts and pixel writes,
  fixes Contra
- BPS patch information and cartridge sections are now copied from the
  patch metadata, if it is present
- fixed bpslinear out-of-bounds issue, which will be in snespurify v11
  official [Danish]
- simplified Makefile again since command-line trumps manual assignments
2011-08-19 21:36:26 +10:00
Tim Allen
b28c54770c Update to v081r03 release.
byuu says:

- GameBoy: fixed window behavior for Contra 3 first boss [Jonas Quinn]
- GameBoy: fixed noise channel for Zelda: LA intro [Jonas Quinn]
- GameBoy: completely disable LCD when turned off, no interrupts; fixes
  Super Mario Land 2 [thanks to Jonas Quinn]
- GameBoy: keep track of where pixels come from for OBJ priority mode
  [Jonas Quinn]
- updated mode+slot-dependent name handling: simplifies Path class,
  allows SGB/BSX/ST games to show the slot title (instead of BIOS name)
  on the title bar
- Makefile allows command-line definitions for ui and profile now (make
  profile=compatibility ui=ui-libsnes)
- Makefile now allows (make pgo=instrument) and (make pgo=optimize)
- added BPS patching support, removed UPS patching support
2011-08-18 23:58:27 +10:00
Tim Allen
71763f2d98 Update to v081r02 release.
byuu says:

This release adds nall/dsp, which is a new framework for audio DSP
effects. It currently supports the usual fractional hermite resampling
and volume adjustments from ruby; but it also adds balance, and
arbitrary precision input and output (still limited to two channels, and
still signed audio [just subtract 1<<(bits-1) from an unsigned value.])
Internally, all samples are converted to doubles in the range of -1.0 to
+1.0, to allow for far greater precision with the hermite resampler and
volume/balance/etc adjustments.

As a result of this, all of the extra resampling/volume code from
ruby::audio has been removed. bsnes pulls in a copy of nall::dsp to
handle that stuff now.
2011-08-14 20:34:11 +10:00
Tim Allen
423d9ba00d Update to v081r01 release.
byuu says:

- EI takes an extra cycle to raise IME; fixes Bubble Bobble [for the
  Gameboy], and likely many more games [Jonas Quinn]
- nall/gameboy/cartridge.hpp descrambles MMM01 images (header can be at
  top or bottom of image now)
- screenshot timestamps use filename-yyyy-mm-dd hh.mm.ss.bmp format; so
  that they can save on Windows
- closing the emulator will switch to windowed mode first, so that
  geometry is preserved
2011-08-13 13:51:29 +10:00
Tim Allen
064ca4c626 Update to v081 release.
byuu says:

This release polishes up the GUI, adds some more features, and fixes
a few minor issues.

Changelog (since v080):
- rewrote S-DD1 module to decompress individual bytes at a time
- simplified SPC7110 deinterleaving code
- OBC1 should not clear RAM on reset [Jonas Quinn]
- fixed enum-cast compilation errors with the latest GCC 4.6.x releases
- added bsnes logo to about screen
- make phoenix=gtk will now build the GTK+ port on Linux
- added settings.startFullScreen to the config file for front-end users
- added advanced settings option to disable window compositor (only
  works on Windows and Xfce)
- merged settings windows into the panel approach used by bsnes/Qt in
  the past
- fixed a crashing bug on input settings window
- fixed GTK+ auto-geometry sizing
- added screenshot capture capability
- added exit emulator hotkey (defaults to being unmapped)
- Xorg keyboard polling now uses cached Display variable [Bisqwit]
- cheat code database updated [mightymo]
2011-08-12 22:33:07 +10:00
Tim Allen
10906d8418 Update to v080r08 release.
byuu says, in a post between the v080r07 release and the v080r08
release:

phoenix/Windows:

The slider and scrollbar setParent calls setLength+setPosition, but
setLength sets position = 0 (due to new length possibly invalidating
previous position.)
Cache position first to fix this, can now reparent widgets with proper
slider/scroll positions.

ListView had a workaround where the horizontal scrollbar was always
appearing on single-column lists. The workaround was forcing the config
settings list in bsnes to only select the text portions of each item in
the list, instead of the entire lines. The workaround was needed because
without setting a single header text, the header text count was equal to
zero, causing autoSizeColumns to have no effect. Made the constructor
call setHeaderText("") to guarantee size() >= 1 always. Removes the need
for the workaround, and gives a good file browser and configuration
setting window.

phoenix/Qt:

Worked around Qt bugs #258,674+258,675: if you click a list item with
your mouse, currentItem()->isSelected() returns false. It does not
return true until you select an item with a keyboard key. I forced it to
set the selected item upon currentItemChanged() message. It was also not
sending a changed message upon clearing the selection and then selecting
the same item again. I had to do something undocumented:
setCurrentItem(nullptr) so that currentItemChanged works again.

phoenix/All:

Fonts are now initialized to the platform default settings, Tahoma or
Sans 8-point. This lets geometry on widgets not attached to windows work
better. Makes the ../... buttons smaller pretty much everywhere.

byuu says, announcing the v080r08 release:

Fixed all of the above phoenix issues, and improved the auto-disabling
of buttons on the input setting and state manager windows.
Also manually initiailized lastConfigure for Valgrind in GTK+. Windows
and GTK+ ports look a lot nicer now.
2011-08-08 22:04:47 +10:00
Tim Allen
e88ab60663 Update to v080r07 release.
byuu says:

- fixed a long-standing crash: when you have a device index above the
  range permitted by another port, the app would crash (eg Controller
  Port 2 -> Mouse, then switch to Hotkeys)
- Qt bug workaround: have to use currentItemChanged signal instead of
  itemSelectionChanged signal for QTreeWidget, otherwise scrolling with
  mouse gives you the previous item with currentItem() ...
- added support for toggling the Xfce compositor
- added support for detecting if the compositor is enabled in the first
  place on Windows, so that it won't get turned on when you had it off
  permanently
- added advanced setting to toggle behavior (never disable, disable only
  in fullscreen mode, disable whenever emulator is open)
- worked around GTK+ ../... button height issue
- worked around Windows slider position issue when attaching to a new
  window (need to research this one more)
- fixed up input settings window more: closing window ends assignment,
  custom mapping buttons hidden by default

Some of those bugs have been there since the phoenix port began, good
times.
2011-08-08 22:02:51 +10:00
Tim Allen
564e38ea9f Update to v080r06 release.
byuu says:

Ran out of time, so this is incomplete, but ...

Windows will disable the compositor in fullscreen mode, and enable it
when switching back to windowed mode. Should help with Vsync issues, but
of course only in fullscreen mode.

I've also merged the four settings windows back into a panel with a list
view (since I have no tab control widget.) The input settings window is
a bit incomplete, need to break assignment on window close, hide the
capture buttons on first showing, etc. Will probably try and finish that
up tonight.
2011-08-08 22:01:09 +10:00
Tim Allen
0c3f0834ab Update to v080r05 release.
byuu says:

Includes updated versions of nall and phoenix, which mostly improves the
GTK+ version. However, it appears to be crashing at the moment after
loading a game. Unfortunately it works when gdb is used, so I can't
easily debug it :/

You can now build with make phoenix=gtk if you want the GTK+ version on
Linux (the Qt version is leagues better even on Gnome, please use it if
at all possible.)

There's also settings.startFullScreen, config-file only, to allow for
front-end use. Forgot to add the reset/power hotkeys.

I also fixed compilation of ui-gameboy on GCC 4.6. I hope that's the
last switch(enum) error, those are damn annoying. Can't wait to switch
to GCC 4.6 on Windows.
2011-08-07 00:03:52 +10:00
Tim Allen
f38af85e0a Update to v080r04 release.
byuu says:

Adds nall/inflate.hpp and nall/unzip.hpp. Updates nall/resource.hpp to
encode and decode using ZIP/deflate files, rather than a much simpler
(and less powerful) LZSS implementation. Cuts the bsnes-logo.hpp file
from 270KB to 130KB, and the binary overhead from 80KB to 35KB.
2011-07-24 23:51:01 +10:00
Tim Allen
8276700381 Update to v080r03 release.
byuu says:

Wow, nothing in 19 days. Anyway, I wanted to get Nick's logo back in on
the about screen. Adds 80kb to both the binary and source archive, but
eh. Gotta have some style. Nothing else new.
2011-07-23 20:14:47 +10:00
Tim Allen
ec69109c0b Update to v080r02 release.
byuu says:

- added qstrlower and qstrupper; mainly for the sake of others wanting
  to patch bass
- added: string sha256(const uint8_t *data, unsigned size); for easier
  hash generation
- cleaned up the NEC DSP and Hitachi DSP XML mapping code; they are
  consistent now as well
- "necdsp" in paths.cfg is now "firmware", since it also affects the
  Hitachi DSP
- XML mapping was using program= for DSP-n/ST-001n and data= for Cx4;
  they both use firmware= now instead
- fixed icd2/interface casting issue for GCC 4.6.0 (thanks for the
  reminder, vEX)
- removed the last parts of code that used string << foo; and removed
  that from nall/string entirely
  - I need to do this for the debugger as well, I'll make sure that it
    compiles before v081 though
- converted all string(...) syntax to { ... } syntax that I could
  (obviously it won't cast to a function that takes const char* instead
  of const string&)

Probably some other tiny things. Just basic maintenance here.
2011-07-07 22:59:26 +10:00
Tim Allen
8ae6444af7 Update to v080r01 release.
byuu says:

There was one unfortunate aspect of the S-DD1 module: you had to give it
the DMA length and a target buffer, and it would do the entire
decompression at once. Real hardware would work by streaming the data
byte by byte. So with that, I went ahead and rewrote the code to handle
byte-based streaming.

This WIP is an important milestone for me personally. Up until now,
bsnes has always had code that was directly copy-pasted from other
authors. With all of the DSP and Cx4 chips rewritten in LLE, and the
SPC7110 algorithm already ported over from C, and archive decompression
code removed for a long time, the S-DD1 was the only module left like
this. It's obviously not that big of a deal. The code is basically still
a copy of the original. S-DD1 decomp from Andreas Naive, SPC7110 decomp
from neviksti, and S-DSP from blargg. And the rest of the emulator is of
course only possible because of code and research before it, although
everything else has no resemblance at all to code before it. The main
advantage, really, is absolute code consistency. I always use the same
variant of K&R, for instance. I dunno, I guess I just never really liked
the "Build-a-Bear Workshop" style of emulators, like is so prominent in
the Genesis scene: "My new Genesis emu (uses Starscream/Musashi 68K
core, Marat Fayzullin's Z80 core, YM2612 core from Game_Music_Emu, VDP
core from Gens, SVP core from picodrive)", sorry, but you wrote
a front-end, not an emulator :/

I also updated the SPC7110 decompression module: I merged the class
inside the SPC7110 class (not sure why it was separate before), and
replaced the morton lookup tables with for-loops. The morton tables were
added to be a tiny bit faster when I was more interested in speed than
code clarity. It may be a tiny bit slower (or faster due to less L2
cache usage), but you won't even notice an FPS drop, and it cuts out
a good chunk of code and some tables. Lastly, I added pinput_poll() to
video_refresh(). Forgot to remove Interface::input_poll() from the C++
side, will have to do that later.
2011-06-28 21:36:00 +10:00
Tim Allen
5fc86eae6d Update to v080 release.
byuu says:

This release adds low-level emulation of the Hitachi HG51B169 DSP, which
was used in Mega Man X2 and Mega Man X3 as the Cx4 chip. It also fixes
a regression in both the sound core and cheat engine.

You will now need the HG51B169 data ROM to play MMX2/MMX3.

Once again, Cx4 LLE could not have been possible without the help of Dr.
Decapitator, Jonas Quinn, Overload and Segher. Be sure to thank them,
please!

Changelog:
* added Cx4 low-level emulation; removed Cx4 high-level emulation code
* fixed S-SMP synchronization to S-CPU on CPUIO writes
* controllers now have their own threads and classes
* serial controller is now emulated as an actual controller, rather than
  as a coprocessor
* added link coprocessor module for special chip research and homebrew
* fixed cheat codes that target mask ROM addresses [Cydrak]
* fixed compilation error with the latest GCC 4.6.0 beta releases
* added flexibility to XML memory mapping file format
* updated to mightymo's latest cheat pack (2011-06-20)
2011-06-26 22:51:37 +10:00
Tim Allen
927c97eb06 Update to v079r06 release.
byuu says:

It does add some more code to the CPU::step() function, so performance
probably went down actually, by about 1%. Removing the input.tick() call
didn't compensate as much as I'd hoped.
Hooked up Super Scope and Justifier support. The good news is that the
Justifier alignment doesn't get fucked up anymore when you go
off-screen. Never could fix that in the old version.
The bad news is that it takes a major speed hit for the time being.
I need to figure out how to run the CPU and input threads out of order.
Every time I try, the input gets thrown off by most of a scanline.
Right now, I'm forced to sync constantly to get the latching position
really accurate. But worst case, I can cut the syncs down by skipping
large chunks around the cursor position, +/-40 clock cycles. So it's
only temporarily slow.
Lastly, killed the old Input class, merged Controllers class into it.
I actually like Controllers as a name better, but it doesn't jive with
video/audio/input, so oh well.
2011-06-25 22:56:32 +10:00
Tim Allen
cf09d41669 Update to v079r05 release.
byuu says:

- Fixed GCC-4.6 casting errors in ui/input/input.cpp.
- Fixed some of the opcode mnemonics specified in the HG51B169 core (was
  unable to speed up the code)
- Started on a new core input system: snes/controller. More on that
  here:

    http://board.byuu.org/viewtopic.php?f=16&t=1761

- Have not yet attempted to add threading support to the controllers, so
  serial is still there as a coprocessor.
- I'm going to move the Controllers {} class back to Input {} once all
  individual controllers have been ported over.

Note: Super Scope and Justifier do not have counter latching support
yet, so you can't really use them. The gamepad, multitap and mouse all
work great; and the SS/Justifier cursors work at least. I also colored
the SS cursor red, so that all three (SS, Justifier, chained secondary
Justifier) all have unique R/G/B colors now. Should prevent confusion
between the SS and one Justifier.
2011-06-24 20:43:29 +10:00
Tim Allen
724747ac9e Update to v079r04 release.
byuu says:

Back from vacation. We were successful in emulating the Cx4 using LLE
during my vacation. We finished on June 15th. And now that I'm back,
I've rewritten the code and merged it into bsnes official. With that,
the very last HLE emulation code in bsnes has now been purged.

[...]

The emulation is as minimal as possible. If I don't see an opcode or
feature actually used, I don't implement it. The one exception being
that I do support the vector override functionality. And there are also
dummy handlers for ld ?,$2e + loop, so that the chip won't stall out.
But things like "byte 4" on rdram/wrram, the two-bit destination
selections for all but ld, etc are treated as invalid opcodes, since we
aren't 100% sure if they are there and work as we hypothesize. I also
only map in known registers into the 256-entry register list. This
leaves 90% of the map empty.

The chip runs at 20MHz, and it will disable the ROM while running. DMA
does transfer one byte at a time against the clock and also locks out
the ROM. rdbus won't fetch from IRAM, only from ROM. DMA transfer only
reads from ROM, and only writes to RAM. Unless someone verifies that
they can do more, I'll leave it that way. I don't yet actually buffer
the program ROM into the internal program RAM just yet, but that is on
the to-do list. We aren't entirely sure how that works either, but my
plan is to just lock the Cx4 CPU and load in 512-bytes.

There's still a few unknown registers in $7f40-5f that I don't do
anything with yet. The secondary chip disable is going to be the
weirdest one, since MMX3 only has one chip. I'd really rather not have
to specify the ROM mapping as two separate chips on MMX2 and as one on
MMX3 just to support this, so I don't know yet.

Save state support is of course there already.

Speed hit is 118fps HLE -> 109fps LLE in most scenes. Not bad, honestly.
2011-06-22 23:27:55 +10:00
Tim Allen
e1e275eb38 Update to v079r03 release.
byuu says:

This fixes the S-SMP synchronization on CPUIO writes that was broken by
improvements in v078.01. Terranigma will work now. Also adds the 'link'
coprocessor module that was added in v079.01, and improved in v079.02.
2011-06-13 22:26:48 +10:00
Tim Allen
e30fcade43 Update to v079r02 release.
byuu says:

Added "unsigned link_run();" which acts as its own thread synchronized
against the S-CPU. Specify the frequency in the configuration file.
I intend to prototype the Cx4 LLE openly using the link module, and that
required timing support, so there we go.

It's very basic, and it synchronizes the CPU to the coprocessors and
vice versa after every call to link_run(). Meaning performance won't be
super exceptional at full 21MHz or higher, but then this is for
prototyping only. I didn't want to expose cothreading, yielding, calls
back into bsnes' core, calls to sync up the S-CPU, etc.
2011-06-13 22:22:06 +10:00
Tim Allen
42dbf73d18 Update to v079r01 release.
This version adds a "link" SNES coprocessor module, which just loads
a shared library. It was posted outside the v079 WIP thread, in this
thread:

    http://board.byuu.org/viewtopic.php?f=16&t=1700
2011-06-13 22:13:30 +10:00
Tim Allen
2a90e12999 Update to v079 release.
byuu says:

This release includes Nintendo Super System DIP switch emulation and
improved PPU rendering accuracy, among other things.

Changelog:
- added Nintendo Super System DIP switch emulation [requires XML setting
  maps]
- emulated Super Game Boy $6001 VRAM offset selection port [ikari_01]
- fixed randomness initialization of S-SMP port registers [fixes
  DBZ:Hyper Dimension and Ninja Warriors]
- mosaic V-countdown caches BGOFS registers (fixes Super Turrican
  2 effect) [reported by zal16]
- non-mosaic BGOFS registers are always cached at H=60 (fixes NHL '94
  and Super Mario World flickering)
- fixed 2xSaI family of renderers on 64-bit systems
- cleaned up SMP source code
- phoenix: fixed a bug when closing bsnes while minimized

Please note that the mosaic BGOFS fix is only for the accuracy profile.
Unfortunately the older scanline-based compatibility renderer's code is
nearly unmaintainable at this point, so I haven't yet been able to
backport the fixes.

Also, I have written a new cycle-accurate SMP core that does not use
libco. The aim is to implement it into Snes9X v1.54. But it would of
course be prudent to test the new core first.

[...then in the next post...]

Decided to keep that Super Mario World part a surprise, so ... surprise!

Realized while working on the Super Turrican 2 mosaic fix, and from
looking at NHL '94 and Dai Kaijuu Monogatari 2's behavior, that BGOFS
registers must be cached between H=0 and H=88 for the entire scanline
... they can't work otherwise, and it'd be stupid for the PPU to re-add
the offset to the position on every pixel anyway. I chose H=60 for now.
Once I am set up with the RGB monitor and the North American cartridge
dumping is completed, I'll set it on getting exact timings for all these
things. It'll probably require a smallish speed hit to allow exact-cycle
timing events for everything in the PPU.
2011-06-05 13:45:04 +10:00
Tim Allen
d129b72ced Update to v078r07 release.
byuu says:

Would appreciate testing on any games with mosaic, especially Mode7
mosaic.I have tested Super Turrican 2, Sim Earth, Contra III and SNES
Test Program.

This only applies to BG modes 0-6, and technically should not affect
Mode7 at all. I am not sure if Mode7 needs the same change made or not,
but given the way it fetches that could prove quite challenging. I also
simplified the background renderer a good bit. See eg the pixel copy
stuff in Background::run().

I've only fixed this in the accuracy renderer. I'm sorry, but the
compatibility renderer is a fucking mess. I haven't really touched it in
four or five years now.

Will probably just revert to the accuracy/SMP in the performance profile
for the next release since it's not being used otherwise. People can
toggle it on if they want to try it out.
2011-06-05 13:25:24 +10:00
Tim Allen
bc0b86891a Update to v078r06 release.
byuu says:

This adds ikari_01's emulation of the ICD2 (Super Game Boy) $6001 register.

It basically removes a really ugly hack where I was intercepting the DMA
transfer destination address to determine while Game Boy tile row to
transfer.  This should make implementing SGB emulation in other
emulators easier, as said hooks were very emulator-specific.
2011-05-08 23:46:37 +10:00
Tim Allen
52443936e6 Update to v078r05 release.
byuu says:

This WIP adds Nintendo Super System emulation, at least of its DIP
switches.  This is done via XML mapping, like so:

    <?xml version="1.0" encoding="UTF-8"?>
    <cartridge region="NTSC">
      <name>ActRaiser</name>
      <rom>
	<map mode="linear" address="00-7f:8000-ffff"/>
	<map mode="linear" address="80-ff:8000-ffff"/>
      </rom>
      <nss>
	<setting name="Difficulty">
	  <option value="0000" name="Easy"/>
	  <option value="0001" name="Normal"/>
	  <option value="0002" name="Hard"/>
	  <option value="0003" name="Expert"/>
	</setting>
	<setting name="Lives">
	  <option value="0000" name="5 lives"/>
	  <option value="0004" name="4 lives"/>
	  <option value="0008" name="3 lives"/>
	  <option value="000c" name="2 lives"/>
	</setting>
      </nss>
    </cartridge>

The value field is a 16-bit value. All selected options are ORed
together to produce the final DIP switch values.  The number of options
per setting is unlimited, but there are only sixteen settings allowed
(you can't have more settings than you have switches, that's just
stupid.)

In the example above, d0-d1 controls difficulty, and d2-d3 controls # of
lives. d4-d15 appear to be unused, as far as I can tell.
2011-05-07 00:16:46 +10:00
Tim Allen
6694a1c986 Update to v078r04 release.
byuu says:

Changelog:
- file and slot load dialogs should now have perfectly square buttons
  that are based on the platform's default button height.
- cleaned up bsnes/Accuracy SMP source code (removed old !! stuff, stage
  3 timer is now uint4, memory access switch/case cleaned up,
  sSMPTimer->Timer, etc.)
- cleaned up bsnes/Accuracy memory access functions (read/writestack ->
  read/writesp, read/writeaddr -> read/write)
- minor optimization to bsnes/Performance SMP core in cycle-mode
2011-05-05 21:40:22 +10:00
Tim Allen
7ffaeb2ac1 Update to v078r03 release.
byuu says:

I apparently wasted two days writing that SMP core for nothing.  I had
a perfectly well-written and well-tested core in bsnes v045.  The old
opcode.b files that were a cycle-based markup language.

So I took that core, and wrote new parsers to generate both opcode-based
(one switch) and cycle-based (two switch) cores. Throw in a
little #define magic around CYCLE_ACCURATE, and it is compile-time
toggleable.

EWJ2's bug was due to not resetting the timer variables, and Bahamut
Lagoon's was due to dividing timer frequencies by 3, but failing to
remove the 0->1 transition phase (should have done the latter and
divided by two.)

Anyway, all fixed up.
2011-05-05 21:37:46 +10:00
Tim Allen
67e6a6e742 Update to v078r02 release.
byuu says:

New S-SMP core is feature-complete, but still buggy.  It's good enough
for perfect audio in Zelda 3 and Super Mario World, but there are plenty
of issues.  No audio in Bahamut Lagoon, deadlock in Earthworm Jim 2,
etc.

With this core, bsnes/Performance runs about 3-5% faster than with the
old one. That won't seem like much, because the S-SMP is the least
demanding portion of the SNES.  blargg's SMP core netted me a 5-8%
speedup the last time I tried it, so I'm sure there's still room to
speed things up.

The core is opcode-based, but has dummy op_io() calls (they compile to
nothing), so it is trivial to make it cycle-based if desired.  I'm not
convinced that is necessary, but we shall see once we get the opcode
bugs ironed out.
2011-05-03 19:58:12 +10:00
Tim Allen
9a3650c6ab Update to v078r01 release.
byuu says:

Started on a new SMP core for bsnes/Performance. I wanted to start
clean, and only copied over the debugger+disassembler portions from the
existing version.  I figured that if I took the existing one and tried
trimming it down, that it'd end up with too much old baggage.  But so
far, the opcodes are looking mostly the same anyway, only I'm
using #defines and a switch table in place of the template function
trickery.

I have enough written now that I can run Zelda 3 at least (although it
gets stuck in a loop immediately after.) No real point in comparing
speed yet, because it'll definitely go down as it becomes more complete.
2011-05-02 23:53:16 +10:00
Tim Allen
0a3d6e4c53 Update to v078 release.
byuu says:

Finally, a new release. I have been very busy finishing up SNES box,
cartridge and PCB scanning plus cataloguing the data, however this
release still has some significant improvements.

Most notably would be randomization on startup. This will help match the
behavior of real hardware and uninitialized memory + registers. It
should help catch homebrew software that forgets to initialize things
properly. Of course, I was not able to test the complete library, so it
is possible that if I've randomized anything that should be constant,
that this could cause a regression. You can disable this randomization
for netplay or to work around any incompatibilities by editing bsnes.cfg
and setting snes.random to false.

The GUI also received some updates. Widget sizes are now computed based
on font sizes, giving it a perfectly native look (because it is native.)
I've also added a hotkey remapping screen to the input settings. Not
only can you remap inputs to controllers now, but those who did not know
the hotkey bindings can now quickly see which ones exist and what they
are mapped to.

Changelog (since v077):

- memory and most registers are now randomly initialized on power-up
- fixed auto joypad polling issue in Super Star Wars
- fixed .nec and .rtc file extensions (they were missing the dot) [krom]
- PPU/accuracy now clears overscan region on any frame when it is
  disabled
- PPU/compatibility no longer auto-blends hires pixels (use NTSC filter
  for this)
- added hotkey remapping dialog to input settings window
- added a few new hotkeys, including quick-reset
- phoenix API now auto-sizes widgets based on font sizes
- file dialog once again remembers previously selected file when
  possible
2011-04-30 23:12:15 +10:00
Tim Allen
378b78dad7 Update to v077r05 release.
byuu says:

Changelog:
- fixed .nec and both .rtc file extensions (thanks krom)
- randomized most S-PPU registers, should trip up some broken homebrew
  that does not initialize all registers
- randomization is now seeded with time(0) rather than 'byuu'
- SNES::interface.video_refresh() now always receives
  {256,512}x{240,480}
- PPU/accuracy scanline 0 does not render the screen back color anymore,
  fixes strange coloring look on first scanline in PAL TV mode in
  non-overscan games
- disabled hires blending in PPU/compatibility; all three cores act the
  same now
2011-04-27 18:57:31 +10:00
Tim Allen
721e0b1762 Update to v077r04 release.
byuu says:

Changelog:
- setGeometry is called after append(layout) now. This fixes the window
  sizing on Qt.
- removed enum Style {} code, as it's no longer necessary.
- removed Filter, Shader path selection code from the file load dialog,
  since that is menu-driven now.
- improved the file load dialog to remember last selected file when mode
  doesn't change (had to split a switch statement into two switches.)
- added Hotkeys port onto input settings window, allowing one to
  dynamically see and remap GUI shortcuts
- added power cycle / reset shortcuts

Still very minimal with the hotkeys, so I packed them all into one group
for now. A few more I'd like to add, but I don't want to get ridiculous
like with the Qt GUI.
2011-03-26 22:31:07 +11:00
Tim Allen
2bf3dbf375 Update to v077r03 release.
byuu says:

Fixed up the geometry calculation code. There is now minimumGeometry()
[returns minimum size needed to display a layout, treats MaximumSize as
MinimumSize], and minimumLayoutGeometry() [like minimumGeometry(), but
it will return MaximumSize if a single container item has that
attribute. Used mostly internally for layout sizing.]

It looks great on Windows, but it looks visually off on Qt. Not exactly
sure what's up there. When I make a test application, everything looks
great. Going to have to clone a bsnes window that's having a problem (eg
bsnes main debugger checkbox window), and see what's up.
2011-03-23 19:04:37 +11:00
Tim Allen
396003e7f6 Update to v077r02 release.
byuu says:

Wouldn't recommend using this, but it has bsnes ported to the new auto-size calculating phoenix API.

Known issues:
- minimumWidth/Height on layouts isn't working right, windows that use
  it are usually too small
- Windows gives 0,0 size for empty text string sizes, which messes up
  a lot of default sizes for LineEdit controls
2011-03-22 23:56:49 +11:00
Tim Allen
a92a554d7b Update to v077r01 release.
byuu says:

Changelog:
- fixed auto joypad polling bug (fixes Super Star Wars start button
  input)
- added pseudo-random class; so far it is RAM only [WRAM, APURAM, VRAM,
  OAM, CGRAM]
- added new system configuration options to bsnes.cfg

The pseudo-random class is optional. For right now, I am defaulting it
to enabled. bsnes.cfg::snes.random = true.
You can of course turn it off if you want. This will break Death Brade
and Unnamed Euro Racer, no questions about it.
So I don't know if I want to leave this on or off by default. Leaving it
on will thwart emulator detection code and help to keep code that relies
on uninitialized memory from working, but leaving it off will increase
compatibility.
2011-03-21 00:57:55 +11:00
Tim Allen
9ea35ce569 Update to v077 release.
byuu says:

Changelog (since v076):
- video filters and shaders now populate inside main menu; no longer
  have to select them as files
- fixed 2xSaI, Super 2xSaI and Super Eagle on 32-bit platforms; still
  buggy on 64-bit Windows
- fixed linear mirroring issues (fixes Mega Man X dash bug)
- fixed RAM memory mapping bug in Sufami Turbo games
- home folder is now %APPDATA%/bsnes or ~/.config/bsnes
- added paths.cfg file, which will allow you to specify custom paths for
  any file types
- save states and cheat files for multi-slot games are based on slot
  names instead of BIOS names
- fixed compilation warning on OS X with nall::decimal
- fixed calculation bug in nall::fp
- Makefile now has options variable, example: make options=debugger
- configuration files and cheat database can now reside in the same
  folder as the binary itself
- updated to 2011-03-11 release of mightymo's cheat database
2011-03-17 23:49:46 +11:00
Tim Allen
348bace8ed Update to v076r07 release.
byuu says:

Rather than make the libsnes API incompatible with previous versions,
I just implemented path as return { basename, hint };
So you will still use the set basename function already there as before.
So either DSP/MSU1/Serial all go in the ROM folder, or they all go
somewhere else. You can be fancy and detect the gametype and override
the basename as you like, if you really want.

Bumped the API to 1.3, and added const char* snes_library_id(void); it
will return "bsnes v076.07" at the moment. The internal string is
static, but don't try caching it or modifying it anyway. You'll have to
split the name and version yourself if you want them separately. API is
backward-compatible to 1.0 still.

Also improved string::assign and string::append to take a variadic
number of arguments. To make this happen, I had to make to_string return
const char* so that infinite recursion did not happen.
2011-03-17 21:39:55 +11:00
Tim Allen
5cbf5b617b Update to v076r06 release.
byuu says:

Changelog:
- path code finished for ui/, just need to expose for ui-libsnes/ now
- filters and shaders use radio items now, so you know which is active
- smooth video was placed inside video mode (list is getting too long)
- .bsnes -> .config/bsnes in make install
- pixelshaders -> snesshader, added Makefile with make install target
- snesfilter, added Makefile with make install and make clean targets
- maybe other stuff
2011-03-17 21:20:51 +11:00
Tim Allen
d5cd21eb0c Update to v076r05 release.
byuu says:

Changelog:
- QMenu::setVisible() does nothing, have to use
  QMenu::menuAction::setVisible()
- improved path system, especially for ST games (states will be
  /path/to/slotA+notdir(slotB).ext, saves are per-game and per-path)
- paths are now valid when you load just the BS-X/ST/SGB BIOSes with no
  carts inserted; maybe useful for BS-X I guess
- removed video filter and pixel shader code from video settings dialog
- added Settings->Video Filter and Settings->Video Shader menu lists
- fixed the SaI family of filters in lores-mode only; although I don't
  really know how or why the change fixed them, the code is too vague

The menu list for the video filters and shaders are populated from
either base/filters and base/shaders, or user/.config/bsnes/filters and
user/.config/bsnes/shaders. It tries the first, and if it does not find
anything it tries the second, just like the configuration files.

That meant doing away with multiple folders for the shaders, so now the
shaders have a suffix to indicate what driver uses them, eg
"Curvature.OpenGL.shader" and "Sepia.Direct3D.shader" -- probably nicer
to use GLSL/HLSL, but using the driver name lets me sub in the currently
loaded video driver with no special casing. So the filter if you have eg
OpenGL loaded is "*.OpenGL.shader"; and for SDL you get "*.SDL.shader",
which will obviously not be there as the non-GL-based SDL driver doesn't
support shaders.

If there are no filters or no shaders available, the menu options do not
show up. The lists are not radio items with active item ticked states
just yet, but they will be.
2011-03-14 22:04:21 +11:00
Tim Allen
8b7dd89059 Update to v076r04 release.
byuu says:

Changelog:
- fixed Sufami Turbo ROM and RAM mapping bugs
- more paths work, definitely need to clean up parameter names and enum
  typenames now

I had to cheat just a bit on the ST SRAM. For now, I am specifying the
RAM size in the XML file.

The base XML isn't supposed to know about the slots though. What I need
to do is write an ST header parser to get actual RAM sizes, and then
from there generate an ST-specific XML file (like I do for the Game Boy)
to specify this info. Would also be nice for some BS-X info.

Added NECDSP, MSU1 and Serial paths. This eliminates
SNES::Cartridge::basename.
2011-03-08 22:23:47 +11:00
Tim Allen
6c4e3ec790 Update to v076r03 release.
byuu says:

Changelog:
- paths.cfg work completed
- save states/archives and cheat files for multi-slot games are more
  intelligent now

For paths.cfg, there are three types of entries. Each have different
special prefixes.

Folder paths: sfc, bs, st, gb, filter, shader
By default, bsnes will remember the last path you loaded a file of said
type from. It will be prefixed with "recent/" in the file. Specify an
explicit hard-coded path to override this.

BIOS paths: satellaviewBios, sufamiTurboBios, superGameBoyBios
Remembers an explicit hard-coded path to the BIOS you selected last.
I was thinking that a nice feature would be for the "Load Special"
windows to pop open the slot A load dialog if a BIOS was selected.
Select a game from this popup and it loads directly, cancel it to get
the regular window to override the BIOS.

Save paths: srm, rtc, bsa, bst, cht, log
Paths to write various files that the emulator generates. Note: srm
groups bsp, bss and sav for now. Was being lazy.
There are four special prefixes for these:

    "base/" -- gets replaced with the executable path
    "user/" -- gets replaced with the same folder where bsnes.cfg goes
	       (%APPDATA%/bsnes or ~/.config/bsnes) -- good for hiding
	       files
    "./"    -- gets replaced with the current ROM path
    "../"   -- gets replaced with the folder above the current ROM path

If you want to go up two folders or more, then use a hard-coded path. If
that's not good enough, kill yourself because God hates you.
2011-03-04 19:57:00 +11:00
Tim Allen
8d64f9b155 Update to v076r02 release.
byuu says:

Changelog:
- fixed a crashing bug when you toggle a cheat code and then load a save state
- added paths.cfg
- bsnes now remembers the most recent path per file-type, like bsnes/Qt
  used to do
- re-added -s to Linux linker flags
- fixed crash with libsnes/SGB XML parsing
2011-03-02 00:31:28 +11:00
Tim Allen
bc5fd8c53c Update to v076r01 release.
byuu says:

Changelog:
- fixed linear mirroring issue in memory map (fixes dash in Mega Man X)
- home path for Windows is now %APPDATA%/bsnes (not %APPDATA%/.bsnes)
- home path for OS X and Linux is now ~/.config/bsnes (not ~/.bsnes)
- bsnes-geometry.cfg is now geometry.cfg; and it stores width,height
- I do not yet restore width, height; because the GTK+ and Qt APIs treat window
  resize as implying setMinimumSize
- added bsnes/ui/path; which I have some significant plans for
- fixed a bug in realpath (specified path is not always a folder, so we should
  not always append / as with userpath)
- bsnes.cfg, geometry.cfg and cheats.xml may now optionally exist in the same
  folder as the binary itself
- ruby only imports the nall namespace after including system headers (should
  fix OS X 'decimal' issue)
- nall::fp now uses atof (fixes nall::fp("0.05"))
- I split the CheatDatabase to a separate cheat-database.cpp file; it was
  pretty ugly packed into cheat-editor.cpp
- Makefile now has "options := " line; where you can add "debugger" if you
  like, and in the future maybe more options
  - also works via command-line: make options=debugger
2011-03-01 10:45:31 +11:00
Tim Allen
64072325c4 Update to v076 release.
byuu says:

Most notable in this release is that sound support has been added to my
own Super Game Boy emulation. The GUI toolkit, phoenix, has also
received a complete rewrite; with the most visible change there being
that windows are now resizable.

Changelog (since v075):
* added sound emulation to Game Boy core
* fixed Super Game Boy save state
* support added HexEdit widget to Windows and Qt targets; debugger can
  now be compiled on all platforms
* entering fullscreen now auto-hides mouse; and mouse capture is toggled
  otherwise by F12 key
* fullscreen command and geometry caching works much better on GTK+ and
  Qt targets
* phoenix rewritten from scratch; now supports resizable layout
  containers
* phoenix/Windows no longer relies on buggy SetParent API to reparent
  widgets
2011-02-27 20:11:01 +11:00
Tim Allen
017f9926fc Update to v075r16 release.
byuu says:

This has my latest API enhancements, but there are some known issues:
- resize on Windows seems to not repaint the buttons properly in rare
  cases. I may just need to revert to flickering resize.
- GTK+ reports the wrong menu height, off by two pixels, prior to the
  window being realized (made visible)
  - this results in the main window moving up two pixels after each run
    of bsnes

The menu height bug was actually there previously, it was just that Qt
and GTK+ were computing the frame margins incorrectly (ignoring the menu
bar) before.

On the bright side, ui/settings/input.cpp has been improved by way of
the new multi-layout support. The window is no longer forced to an
awkward 640 pixels wide, as the mouse axes/buttons can overlap now. The
code is also simpler since I am using the Layout::setVisible command to
toggle groups on and off instead of doing it for each and every control.
2011-02-27 20:05:10 +11:00
Tim Allen
c31543ea58 Update to v075r15 release.
byuu says:

phoenix/GTK+ rewrite completed. All three targets should now be 100%
operational with full resize support.
2011-02-24 20:27:21 +11:00
Tim Allen
7c3aaf12b0 Update to v075r14 release.
byuu says:

Adds the new phoenix/Windows. Testing would once again be appreciated,
as this is basically a rewrite of the entire core of the GUI.
2011-02-24 20:25:20 +11:00
Tim Allen
3fad0a0105 Update to v075r13 release.
byuu says (in the thread about rewriting Phoenix):

- added phoenix/reference; a dummy implementation that contains the 22KB
  of static boilerplate code needed to start a new target
- OS::setDefaultFont removed; problem is that objects in the global
  scope are constructed before you can call that function
- added Window::setWidgetFont, which is applied if your widgets have no
  custom font set already upon attaching them to the window with
  Window::setLayout, more understandable behavior
- renamed ListBox to ListView

byuu says (in the v075 WIP thread):

Found the source of lag on cartridge load. ListView::modify() was not
locking Qt messages, so it was causing a CheatEditor::refresh (copies
16MB of memory each call) for all 128 cheat items.

Final issue now is that nested submenus (menus inside of menus) are not
applying Window::setMenuFont yet.
2011-02-16 23:35:40 +11:00
Tim Allen
72a2967eeb Update to v075r12 release.
byuu says:

phoenix has been completely rewritten from scratch, and bsnes/ui + bsnes/ui-gameboy have been updated to use the new API. Debugger works too. Currently, only phoenix/Qt is completed, and there are two known issues:

1: font sizes of menu items are wrong, I can fix this easily enough
2: there's some sort of multi-second lag when loading games, not sure
   what's happening there yet

The new phoenix isn't exactly complete yet, still making some key
changes, and then I'll start on phoenix/Windows and phoenix/GTK+.

The most noticeable difference is that you don't have to give all of the
header paths and PHOENIX_PLATFORM defines when compiling individual GUI
object files. It's only needed for phoenix.cpp itself. The overall
structure of the phoenix source folder is much saner as well for
sync.sh.

I'm really surprised things are working as well as they are for
a two-day power rewrite of an entire phoenix target. The other targets
won't be as bad insofar as the core stuff is completed this time. And
thank god for that, I was about ready to kill myself after writing
dozens of lines like this:

    HorizontalSlider::HorizontalSlider() : state(*new State),
    base_from_member<pHorizontalSlider&>(*new pHorizontalSlider(*this)),
    Widget(base_from_member<pHorizontalSlider&>::value),
    p(base_from_member<pHorizontalSlider&>::value) {}

But each platform does have some new, unique problems. phoenix/GTK+ was
acting screwy prior to the rewrite, and will most likely still have
issues. Even more important, one of the major points of this rewrite was
having the new phoenix/core cache widget settings/data, so that I can
destroy and recreate widgets rather than relying on SetParent. This
means that simple copying of the old phoenix/Windows won't work, and
this new method is significantly more involved.
2011-02-15 23:22:37 +11:00
Tim Allen
a8ee35633c Update to v075r11 release.
byuu says:

Rewrote the way menus are attached, they act like layouts/widgets now.

All three phoenix targets once again work with both radio menu items and
radio widgets. Both GTK+ and Qt have built-in group controls right
inside the widgets, so I don't have to keep my own groups around
anymore. They do act screwy at widget creation though, have to jump
through some hoops to get it to work right. All I can say is, definitely
set all child widgets to the parent before trying to check any of them.

My long-term goal for the main window is to honor the fullscreen video
setting as a generic setting, and let the window scale auto-fit the best
possible size that matches your scale preference into the output window,
centered just like fullscreen. For now, I've just set it to a fixed
window size until I finish working on phoenix. The scale X settings will
just be to snap the window to an exact size in case you don't want any
black borders, they won't be radio items and the bsnes-geometry.cfg file
will save width/height information as well.

Simplified the sizing requirements for creating layouts and updated all
bsnes windows to support the new system. Layouts also expose their
minimum width/height values, which I use to create perfectly sized
windows on all three platforms. This will fix cut-off heights on the
last Windows WIP. Qt is being annoying though and forcing a minimum
window size of 300,100 despite me telling it to use a smaller window
size. Always have to fight with Qt, I swear to god.
2011-02-10 21:08:12 +11:00
Tim Allen
7dda70baa4 Update to v075r10 release.
byuu says:

phoenix/Windows and phoenix/Qt are mostly fully operational now. All
platforms support dynamic layout resizing. I tried WM_GETMINMAXINFO
(thanks, OV2), but it was acting kind of choppy on resize, and it would
get confused and go crazy if you snapped one direction to the minimum
height but not another, so for now I'm leaving it off.

phoenix/GTK+ will be missing some functionality in regards to window
geometry. The other two have a more coherent strategy now: geometry() is
the client area, and setGeometry moves the client area to where you ask
for. This makes truly centering your client area trivial.
frameGeometry() includes the borders, menu and status. There is no
setFrameGeometry(), not sure if I really even want that, but it could be
useful so who knows. All targets also support non-resizable windows.

X11 is of course horrendously poor with frame sizes, Qt and GTK+ don't
even pretend to simulate them, so they say the frame is 0x0 pixels in
size until your widget is fully realized and visible to the end user. So
for now, to get window positioning right, I have to wait until the
window appears and then reposition the window again, causing a slight
jump. My plan is to build some persistent caching support directly into
phoenix. From here, I can just have the window snap the very first time
you run your very first phoenix app. I'll then determine the frame size
information, and use that to create future windows. Once they spawn,
I'll recheck and update the frame size info in case it has changed (eg
user changed themes.) Saving settings into .config/phoenix will allow me
to avoid having to snap the window every time on first startup. If the
config file is missing or unwritable, too bad, happens every time then.

I'm thinking about renaming onResize to onSize, and getting rid of
Window::create(). Rather make it spawn like every other control in its
constructor.
2011-02-07 20:20:07 +11:00
Tim Allen
2c61ce2522 Update to v075r09 release.
byuu says:

Ported phoenix/Windows and phoenix/GTK+ over to the new system. There
are some problems that need to be addressed:

- Windows ComboBox height setting needs widget creation height to
  properly scale itself (make Widget::setGeometry virtual and override
  ComboBox::setGeometry)
- Windows Canvas is completely broken
- GTK+ Canvas is slow as shit compared to Qt Canvas, probably nothing
  I can do about it, have to do a very costly conversion because GTK+ is
  stupid and uses BGR like Nintendo
- GTK+ listboxes are fucking insanely complicated to set up. Currently
  I just split the second-half of creation to the setHeaderText call,
  but when you don't call that, things explode
  - I'm probably going to have to completely destroy and recreate
    listboxes when changing the header text / column count
- Qt resize code is still impossible to get right, it's not letting me
  size a window > 2/3rds of the screen size (it's in their docs)
  - I swear, Qt is the most painful API in the world to move/size
    windows with
- now that Window is separate, it really needs geometry() and
  frameGeometry() as the two are quite different
- I need a way to toggle window resizability for fixed layouts, Qt is
  once again going to be a nightmare as it lacks a way to do this other
  than fixed layouts
- GTK+ currently explodes on bsnes, millions of console messages,
  wonderful
- plenty more I'm forgetting

One bit of really cool/good news though: I made
Fixed/Horizontal/Vertical layouts external to phoenix itself. The code
is included for all targets so that it's always there and compiled into
one object, but the great news is that you can easily write your own
layout widgets and they'll work on all toolkits instantly.

That resize issue with bsnes was so simple it's annoying: my FixedLayout
container was repositioning on geometry updates. Made it only do it once
at creation like it should.

bsnes now has a fancy resize, grow the window and get black borders,
shrink it and the video shrinks with it. I plan to make it fancier with
constraint settings (center, scale, stretch). Basically I want to turn
the fullscreen setting into a general setting that also applies to
windowed scaling. I will probably turn the video scale X sizes into
regular items instead of radio boxes, so you can easily reset to a fixed
size whenever you want. Update bsnes to remember width,height geometry
as well and it should be quite nice.
2011-02-07 20:18:01 +11:00
Tim Allen
266495b475 Update to v075r08 release.
byuu says:

Eleven hours of work. Window is now a base type (inherits from Object,
not Widget), same for Layout. FixedLayout still inherits from Layout.
Added HorizontalLayout and VerticalLayout types, that can append each
other to themselves to create box layouts. Layout margins are supported,
spacing is specified inline (I find this a much better way to fine-grain
spacing than Qt's single setSpacing function), and alignment is handled
strictly via padding widgets (insert a zero-sized label and it will
automatically grow to consume all extra space.)

Overall, my box packing model is slightly less powerful than Qt's, but
it is a good deal simpler and and easier to use in 90% of cases. The one
limitation I hit was with my input settings window, I'm not currently
able to embed two different layouts and toggle one on and the other off
to show only either { mouse x-axis, y-axis } or { mouse left, middle,
right }, so they instead just space out differently and I had to grow
the input window width a bit to compensate.

Resizing works great, pretty cool seeing that this is the first time
I've ever written my own resizer. I had to fight with Qt for several
hours to the point of potentially developing an aneurysm, but I finally
got it to properly handle geometry and sizing stuff. Some weird issue
with the bsnes viewport widget, I tell it to resize and for some reason
it doesn't. Cheap hack, I just make it constantly resize every video
refresh and it eventually takes. Wish I knew what was up with that.

All of bsnes now uses dynamic layouts sans the main window, so you can
resize them however you like.

This is still all Qt-only, I'm afraid. The other two ports are
in-progress.
2011-02-07 20:15:43 +11:00
Tim Allen
133d568f76 Update to v075r07 release.
byuu says:

This has the phoenix changes applied. Instead of widgets attaching
directly to windows, you now attach them to layouts, which can then be
attached to windows. Layouts are widgets themselves, so adding layouts
to layouts is trivial. It also allows for multi-widget show/hide, etc.

Right now there is only FixedLayout, but of course the plan is to
support a BoxLayout, that lets you add HorizontalLayout and
VerticalLayout containers to it, thus enabling auto-resize and simpler
form layout.

So far only phoenix/Qt is 100% moved over. phoenix/GTK+ has about 1/3rd
ported, and phoenix/Windows only has one control ported over as
a proof-of-concept.

On the user side, bsnes, bgameboy, snespurify and curse have been moved
to this new layout system. All of bsnes works great with it, as far as
I can tell. Fullscreen, debugger, etc are good.
2011-02-07 20:14:14 +11:00
Tim Allen
b433838e9f Update to v075r06 release.
byuu says:

Removed the floating-point volume adjustments from the wave channel and
the left/right speaker mixers. Also, against my better judgment I'm
backing out of left/right computation when they are both turned off.
This basically makes non-stereo games run faster, but will make stereo
games appear to run slower. I don't like it when end-users experience
mystery slowdowns.

Anyway, it appears that the audio calculation is really fucking
demanding. Knocks FPS from 800 down to 300. I thought it might be libco,
so I took it out and it only went up to 305fps o.O

There is also some sort of problem with bsnes/Super Game Boy audio. The
latency is really great when you first start, but it seems to drift
apart over time until it is well over 500ms, and then it either pops or
fades back to very low, sub-50ms latency again. The way I handle mixing
is that the coprocessor audio samples go into a resampler to the native
SNES rate, and fed to an output buffer. SNES audio samples go there
untouched. When there is a sample in each, I add them together and
average the result (I still don't understand why we divide by two since
these are signed integers), and output it immediately. It's just-in-time
sampling, so as long as DSP v Coprocessor do not drift very far, it
should have very low latency. And I make the CPU sync DSP and
Coprocessor once per scanline, which is something like 15 samples or so.
2011-02-03 22:17:35 +11:00
Tim Allen
a3abe8ebaa Update to v075r05 release.
byuu says:

Added Game Boy sound emulation, all four channels.
It's really, really, really bad. Plenty of bugs, I don't even know what
the fuck a high-pass filter is so that isn't there. Hermite resampling
from 4MHz down to 44KHz. But it's tolerable.
I don't understand what sweep is for at all, and I'm sure I have that
insane recursive reload behavior wrong.

This is pretty much my own design. I referenced blargg's gb snd emu,
blargg's older gb apu ref, Cydrak's APU core, that lousy gbdev wiki
article, the completely and utterly worthless pandocs, and received
nothing but bad and wrong information that just wasted my time from

But I managed to pull it off. It's also painfully slow, like 250fps on
my machine slow. Countless optimizations are possible.
2011-02-02 21:38:28 +11:00
Tim Allen
f88ef9e9a2 Update to v075r04 release.
byuu says:

Changelog:
- hooked up everything necessary for Game Boy sound emulation ...
- bgameboy and bsnes/SGB input 4MHz frequency, and output 44.1KHz
  frequency (produces soft static for now, to verify it is working)
- rewrote all of gameboy/apu, it now has a 4MHz worker thread, and
  separate classes/folders for each channel+master, and serializes

So it's basically all I can do without actual emulation code or
human-readable documentation/example code.
2011-02-02 21:37:31 +11:00
Tim Allen
a136378a7b Update to v075r03 release.
byuu says:

Changelog:
- added full HexEditor widget to phoenix/Qt (has dynamic scrollbar like
  phoenix/GTK, but does not yet support page up/down scrolling)
- optimized debugger to look great with either phoenix/GTK or phoenix/Qt
- fixed phoenix/Qt fullscreen mode (had to allow resizing of the layout,
  and resize the container)
- fixed phoenix/Qt Window::setBackgroundColor() bug that was making
  statusbar invisible
- entering fullscreen now captures mouse, leaving fullscreen releases it
  - so by default, no cursor in fullscreen mode now
- F12 key was assigned the task of toggling mouse capture,
  Tools->Capture Mouse was removed
- above change allows toggling mouse capture in fullscreen if you like

It wasn't my idea, but toggling the mouse capture in fullscreen also hiding the mouse cursor is what I call genius design. Two birds with one stone, and very intuitive.

Also, the default GUI on Linux for bsnes and bgameboy is now Qt, instead
of GTK+. I did this because Qt's fullscreen is far more stable, and
I fixed up the remaining bugs anyway.
2011-02-02 21:35:15 +11:00
Tim Allen
012cdd4b14 Update to v075r02 release.
byuu says:

Changelog:
- added ui-libsnes directory back into source archive; make archive-all
  includes it now
- added basic HexEditor widget to phoenix/Windows
2011-02-02 21:33:35 +11:00
Tim Allen
eecc085e42 Update to v075r01 release.
byuu says:

Changelog:
- fixed Super Game Boy save state support
- both SNES and GameBoy only initialize serialize size on cartridge load
  once now, just like I've already done with memory mapping
- added nall/public_cast.hpp for fun ... don't worry, I'm never actually
  going to use it in production code :D
2011-01-29 20:48:44 +11:00
Tim Allen
6b4104867f Update to v075 release.
byuu says:

This release brings improved Super Game Boy emulation, the final SHA256
hashes for the DSP-(1,1B,2,3,4) and ST-(0010,0011) coprocessors, user
interface improvements, and major internal code restructuring.

Changelog (since v074):
- completely rewrote memory sub-system to support 1-byte granularity in
  XML mapping
- removed Memory inheritance and MMIO class completely, any address can
  be mapped to any function now
- SuperFX: removed SuperFXBus : Bus, now implemented manually
- SA-1: removed SA1Bus : Bus, now implemented manually
- entire bus mapping is now static, happens once on cartridge load
- as a result, read/write handlers now handle MMC mapping; slower
  average case, far faster worst case
- namespace memory is no more, RAM arrays are stored inside the chips
  they are owned by now
- GameBoy: improved CPU HALT emulation, fixes Zelda: Link's Awakening
  scrolling
- GameBoy: added serial emulation (cannot connect to another GB yet),
  fixes Shin Megami Tensei - Devichil
- GameBoy: improved LCD STAT emulation, fixes Sagaia
- ui: added fullscreen support (F11 key), video settings allows for
  three scale settings
- ui: fixed brightness, contrast, gamma, audio volume, input frequency
  values on program startup
- ui: since Qt is dead, config file becomes bsnes.cfg once again
- Super Game Boy: you can now load the BIOS without a game inserted to
  see a pretty white box
- ui-gameboy: can be built without SNES components now
- libsnes: now a UI target, compile with 'make ui=ui-libsnes'
- libsnes: added WRAM, APURAM, VRAM, OAM, CGRAM access (cheat search,
  etc)
- source: removed launcher/, as the Qt port is now gone
- source: Makefile restructuring to better support new ui targets
- source: lots of other internal code cleanup work
2011-01-27 19:52:34 +11:00
Tim Allen
53fe43afd8 Update to v074r11 release.
byuu says:

Changelog:
- debugger compiles on all three profiles
- libsnes compiles on all three platforms (no API changes to libsnes)
- memory.cpp : namespace memory removed (wram -> cpu, apuram -> smp,
  vram, oam, cgram -> ppu)
- sa1.cpp : namespace memory removed (SA-1 specific functions merged
  inline to SA1::bus_read,write)
- GameBoy: added serial link support with interrupts and proper 8192hz
  timing, but obviously it acts as if no other GB is connected to it
- GameBoy: added STAT OAM interrupt, and better STAT d1,d0 mode values
- UI: since Qt is dead, I've renamed the config files back to bsnes.cfg
  and bsnes-geometry.cfg
- SA1: IRAM was not syncing to CPU on SA-1 side
- PPU/Accuracy and PPU/Performance needed Sprite oam renamed to Sprite
  sprite; so that I could add uint8 oam[544]
  - makes more sense anyway, OAM = object attribute memory, obj or
    sprite are better names for Sprite rendering class
- more cleanup
2011-01-24 20:03:17 +11:00
Tim Allen
054bdd4094 Update to v074r10 release.
byuu says:

Major WIP, countless changes. I really went to town on cleaning up the
source today with all kinds of new ideas. I'll post the ones I remember,
use diff -ru to get the rest.

What I like the most is my new within template:

    template<unsigned lo, unsigned hi>
    alwaysinline bool within(unsigned addr) {
      static const unsigned mask = ~(hi ^ lo);
      return (addr & mask) == lo;
    }

Before, you would see code like this:

    if((addr & 0xe0e000) == 0x206000) {  //$20-3f:6000-7fff

The comment is basically necessary, and you have to trust that the mask
is right, or do the math yourself.

Now, it looks like this:

    if(within<0x20, 0x3f, 0x6000, 0x7fff>(addr)) {

That's the same as within<0x206000, 0x3f7fff>, I just made an
SNES-variant to more closely simulate my XML mapping style:
20-3f:6000-7fff.

Now obviously this has limitations, it only works in base-2 and it can't
manage some tricky edge cases like (addr & 0x408000) == 0x008000 for
00-3f|80-bf:8000-ffff. But for the most part, I'll be using this where
I can. The Game Boy is fully ported over to it (via the MBCs), but the
SNES only has the BS-X town cartridge moved over so far. SuperFX and
SA-1 at the very least could benefit.

Next up, since the memory map is now static, there's really no reason to
remap the entire thing at power-on and reset. So it is now set up at
cartridge load and that's it. I moved the CPU/PPU/WRAM mapping out of
memory.cpp and into their respective processors. A bit of duplication
only because there are multiple processor cores for the different
profiles, but I'm not worried about that. This is also going to be
necessary to fix the debugger.

Next, Coprocessor::enable() actually does what I initially intended it
to now: it is called once to turn a chip on after cartridge load. It's
not called on power cycle anymore. This should help fix power-cycle on
my serial simulation code, and was needed to map the bus exactly one
time. Although most stuff is mapped through XML, some chips still need
some manual hooks for monitoring and such (eg S-DD1.)

Next, I've started killing off memory::, it was initially an
over-reaction to the question of where to put APURAM (in the SMP or
DSP?). The idea was to have this namespace that contained all memory for
everything. But it was very annoying and tedious, and various chips
ignored the convention anyway like ST-0011 RAM, which couldn't work
anyway since it is natively uint16 and not uint8. Cx4 will need 24-bit
RAM eventually, too. There's 8->24-bit functions in there now, because
the HLE code is hideous.

So far, all the cartridge.cpp memory:: types have been destroyed.
memory::cartrom, memory::cartram become cartridge.rom and cartridge.ram.
memory::cartrtc was moved into the SRTC and SPC7110 classes directly.
memory::bsxflash was moved into BSXFlash. memory::bsxram and
memory::bsxpram were moved into BSXCartridge (the town cartridge).
memory::st[AB](rom|ram) were moved into a new area,
snes/chip/sufamiturbo. The snes/chip moniker really doesn't work so
well, since it also has base units, and the serial communications stuff
which is through the controller port, but oh well, now it also has the
base structure for the Sufami Turbo cartridge too. So now we have
sufamiturbo.slotA.rom, sufamiturbo.slotB.ram, etc.

Next, the ST-0010/ST-0011 actually save the data RAM to disk. This
wasn't at all compatible with my old system, and I didn't want to keep
adding memory types to check inside the main UI cartridge RAM loading
and saving routines.

So I built a NonVolatileRAM vector inside SNES::Cartridge, and any chip
that has memory it wants to save and load from disk can append onto it
: data, size, id ("srm", "rtc", "nec", etc) and slot (0 = cartridge,
1 = slot A, 2 = slot B)

To load and save memory, we just do a simple: foreach(memory,
SNES::cartridge.nvram) load/saveMemory(memory).

As a result, you can now keep your save games in F1 Race of Champions II
and Hayazashi Nidan Morita Shougi. Technically I think Metal Combat
should work this way as well, having the RAM being part of the chip
itself, but for now that chip just writes directly into cartridge.ram,
so it also technically saves to disk for now.

To avoid a potential conflict with a manipulated memory map, BS-X SRAM
and PSRAM are now .bss and .bsp, and not .srm and .psr. Honestly I don't
like .srm as an extension either, but it doesn't bother me enough to
break save RAM compatibility with other emulators, so don't worry about
that changing.

I finally killed off MappedRAM initializing size to ~0 (-1U). A size of
zero means there is no memory there just the same. This was an old
holdover for handling MMIO mapping, if I recall correctly. Something
about a size of zero on MMIO-Memory objects causing it to wrap the
address, so ~0 would let it map direct addresses ... or something.
Whatever, that's not needed at all anymore.

BSXBase becomes BSXSatellaview, and I've defaulted the device to being
attached since it won't affect non-BSX games anyway. Eventually the GUI
needs to make that an option. BSXCart becomes BSXCartridge. BSXFlash
remains unchanged.

I probably need to make Coprocessor::disable() functions now to free up
memory on unload, but it shouldn't hurt anything the way it is.

libsnes is most definitely broken to all hell and back now, and the
debugger is still shot. I suppose we'll need some tricky code to work
with the old ID system, and we'll need to add some more IDs for the new
memory types.
2011-01-24 19:59:45 +11:00
Tim Allen
ecf96726f9 Update to v074r09 release.
byuu says:

This WIP fixes up the last bit from the old memory mapping system, the
BS-X Satellaview town cartridge now has a static memory mapper that is
dynamically decoded based on register settings. Tested with BS Town + BS
Zelda, and I can get in-game just fine. The mapping code is actually
a lot more readable this way, too.
2011-01-22 19:18:03 +11:00
Tim Allen
cab5917806 Update to v074r08 release.
byuu says:

The nall::function binding for the memory map apparently breaks when the
debugger is enabled, as PPU:: becomes PPUdebugger::, etc; and C++ isn't
smart enough to upconvert for us.
Not sure how I am going to work around that yet ...

Changelog:
- improved GameBoy::CPU::Halt emulation, fixes Legend of Zelda intro
  water+world-map scrolling at the same time
- added GameBoy::APU skeleton, and hooked up MMIO read/write for all
  registers
- modified nall integer->string functions
2011-01-22 19:15:49 +11:00
Tim Allen
c833b69087 Update to v074r07 release.
byuu says:

Fullscreen works on all ports, but Qt is in general pretty wonky at the
moment. Don't really care right now.

F11 toggles fullscreen, there is no menu or status in fullscreen, and it
auto-scales to the highest even multiple that it can.
It copies all other settings (filter, shader, aspect correction, video
region, vsync, async) from your windowed mode settings.
You cannot enable the menu or status bars, because those are a major
pain in the ass to support with both GTK+ and Qt returning nonsense
geometries.
Combine with each platform treating whether or not to handle menus
and/or statuses as part of the geometry or not, and it's a recipe for
pain.
It is pseudo-fullscreen for now, but if we have some spiffy code in the
future to set a true fullscreen that works on Linux (and hopefully OS
X), I'll add a true-FS option to ruby later.
2011-01-18 21:20:05 +11:00
Tim Allen
1a065bafb1 Update to v074r06 release.
byuu says:

This WIP uses the 16MB+64MB memory tables for 1:1 mapping of the S-CPU
bus.
Minimum RAM requirement goes up to 128MB, dare I be bold here and
recommend you have 256MB.

I also hooked up the basic bindings for making pseudo-fullscreen windows
in phoenix/Windows and phoenix/GTK+, but both have some serious issues.
- GTK+ won't resize my form container, even though it's the same code
  I used successfully in bsnes v039 and prior with hiro
- Windows scale selection breaks the faux-fullscreen effects
- I am intending to write off the menu/status bars and just auto-size
  the video to fill the screen, nice and simple
2011-01-18 21:17:48 +11:00
Tim Allen
ea077a7d96 Update to v074r05 release.
byuu says:

Oh good, that turned out to be a lot easier than I expected.
Almost all of the work was already done yesterday in porting the SA-1
over to a static map.
2011-01-17 00:22:51 +11:00
Tim Allen
a937f9b79b Update to v074r04 release.
byuu says:

SuperFXBus was inheriting from Bus, in other words using a copy of the
same memory mapping subsystem.
I've removed that and made it a simple mask, since only ROM+RAM are
mapped there.
2011-01-17 00:17:45 +11:00
Tim Allen
2d73086569 Update to v074r03 release.
byuu says:

You guys are going to hate the hell out of this one. It's twenty hours
of non-stop work, no exaggeration at all. Started at 4AM, just wrapped
up now at 8PM.
I rewrote the entire memory subsystem.

Old system:
65536 pages that map 256 bytes each
Mapping a new page overwrites old page
Granularity capped at 256 bytes minimum, requiring ST-001x to map
    60:0000-00ff instead of 60:0000,0001
Classes inherit from MMIO and Memory, forcing only one mappable function
    per class, and fixed names
MMIO sub-mapper inside memory: 00-3f:2000-5fff for one-byte granularity
Can dynamically change the map at run-time, MMC register settings
    perform dynamic remapping

New system:
XML mapping is still based around banklo-bankhi:addrlo-addrhi, as that
    shapes almost everything on the SNES very well
Internally, 2048 pages that map 8192 bytes each
Pages are vectors, scans O(n) from last to first (O(log n) would not
    help, n is never > 3)
Can multi-cast writes, but not reads [for the obvious reason of: which
    read do you return?]
Can map reads and writes separately
Granularity of one for entire 24-bit address range, no need for MMIO
    - whatever is in XML is exactly what you get
Read/Write tables bind function callbacks, so I can have any number of
    functions with any names from any classes with no inheritance (no
    more uPD7725DR, uPD7725SR helpers, etc)
Less memory usage overall due to less tables [ I tried 16 million tables
    and it used 2GB of RAM >_o ]
Cannot dynamically change the map at run-time, MMC read/write functions
    perform address translation [worse average case speed, better worst
    case speed]

Now the hate me part, functors can't beat virtual functions for speed.
There are speed penalties involved:
-4.5% on average games
-11% on SuperFX games (SFX has its own bus)
-15% on SA-1 games (SA-1 has two buses)
Of course the two that need the speed the most get the biggest hits.

I'm afraid there's really not a lot of wiggle room to boost speed back
up.
I suppose one bright spot is that we can much more easily try out
entirely new mapping systems now, since the dynamic portions have been
eliminated.
2011-01-15 15:30:29 +11:00
Tim Allen
5810e69be3 Update to v074r02 release.
byuu says:

Changelog:
- updated/fixed st0011.bin SHA256 sum
- removed launcher/
- building ui-gameboy only builds the Game Boy core, not the SNES core
- binary name output is bgameboy for ui-gameboy
- make install/make uninstall work as expected with the extra data files

[Editor's note - those last three changes seem to have been made in
v074r01]
2011-01-13 21:08:27 +11:00
Tim Allen
a198e555dc Update to v074r01 release.
byuu says:

Changelog:
- fixed libsnes to compile again, the GB RTC constant is there but
  doesn't do anything just yet (no serialize support in GameBoy core)
- libsnes: added SNES_MEMORY_(WRAM,APURAM,VRAM,OAM,CGRAM) -- really only
  for the first one, it allows libsnes users to implement their own
  cheat search
- you can now load the SGB BIOS without a game!! please be sure to enjoy
  the blinking cartridge icon emulation :D
- necdsp (uPD7725,96050) - simplified code a bit: removed persistent
  regs.idb, simplified jumps, merged exec() with main loop, etc.
- nall::function - fixed an initialization bug when copy-constructing
  objects
- nall::vector - use calloc instead of malloc to help safeguard against
  uninitialized class data (potentially hides errors, but better than
  crashing in production)
2011-01-13 21:07:04 +11:00
Tim Allen
20afa076ef Update to v074 release.
byuu says (since v073):

This release adds full low-level emulation of the NEC uPD96050
coprocessor, used by the ST-0010 (F1 Race of Champions II) and the
ST-0011 (Hayazashi Nidan Morita Shougi). The former was already playable
with HLE, but lacked timing emulation. The latter has never been
playable through emulation before now. But as with SD Gundam GX before,
you really weren't missing much.

[...]

Also new in this release is my own Game Boy emulator. It is being used
to provide native Super Game Boy support, built directly into bsnes.
This core is released under the GPLv2, but I am willing to grant a more
permissive license for other SNES emulators, if anyone is interested.

Of course I cannot compete with the quality of gambatte, and certainly
not from only a weeks' worth of work. Currently, there is no Game
Boy-side sound output and there are quite a few bugs remaining in its
emulation core. I would appreciate any help on this, the Game Boy is not
my forte. So yes, we are taking a step back today, so that we may take
two steps forward in the future.

[...]

Lastly, the debugger is still Linux-only, but it is now stable enough to
be considered usable. Check it out if you like, compile with -DDEBUGGER
to enable it.
2011-01-11 21:30:47 +11:00
Tim Allen
92da6bde26 Update to v073r07 release.
byuu says:

I give up for now. This WIP doesn't really improve uPD any, but it does
have major fixes to the debugger.
Debugger is still Linux-only for want of a HexEditor widget, but the
Linux one is now usable.
Before it'd trace and search for breakpoint at sub-1fps. Fixed it to not
break out of core for simple things and it'll run at near-fullspeed for
BPs, half-speed for tracing to file (lots of I/O.)
2011-01-10 23:21:57 +11:00
Tim Allen
73113da41e Update to v073r06 release.
byuu says:

Above WIP will automatically map in the ST-001x chips, no need for an
XML file.
F1 Race of Champions II (J) is fully playable, at least. It's forced to
15MHz like the ST-0011 for now.

The core (snes/chip/necdsp/core) is somewhat unstable at the moment,
some debugging hooks commented out and some hacks / ideas floating
around in there. Disassembler can't handle long jumps yet.
2011-01-10 23:19:01 +11:00
Tim Allen
a7ffc31282 Update to v073r05 release.
Added uPD96050 emulation, but it's not working right now. I'm totally
stumped. The ST-0010 player cars aren't moving right, and it crashes
sometimes on exit like it's going out of bounds.

I had decided to try and avoid duplicating the 20KB uPD7725 core, so
I made a new folder:
snes/chip/necdsp
snes/chip/necdsp/upd7725
snes/chip/necdsp/upd96050

The latter two derive from the former, and they specify the PC, RP and
DP sizes, which allocates appropriate memory.
I use simple runtime-masked registers (to avoid template hell on every
uPDcore function), and then I derive from that to complete each actual
DSP. The uPD7725 seems to work great, but the uPD96050 is fucked and
I don't know why :(
Help would be appreciated, it must be something simple because I am
certain the cars were working before.

Kinda wish I didn't scrap the old code now :(
2011-01-08 21:20:59 +11:00
Tim Allen
1c6a8543cd Update to v073r04 release.
I've merged the bgameboy GUI into the bsnes project, as it's only ~3KB
and it means I don't have to keep manually editing and copying two
projects around. You can set ui := ui-gameboy to build bgameboy as
a standalone, and ui := ui to build the bsnes you are used to. I will be
polishing it to allow changing the binary output name, not building the
SNES portions when not needed, etc in time.

So that'll end bgameboy standalone releases, at least for now. If it
ever gets important enough to split back out again I can, but I prefer
it this way. bgameboy was never meant to be mainstream anyway, just
a component for bsnes.
2011-01-08 21:08:57 +11:00
Tim Allen
4dbce5a0b2 Update to v073r03 release.
byuu says:

Changelog:
- much tighter SGB integration, but this is still a work-in-progress
  - memory::gb(rom,ram,rtc) is gone, uses GameBoy:: memory structures
    directly (a big gain, no need to copy memory to save and load)
  - UI-based cartridge loading works with GameBoy:: directly as well
    - libsnes will need to be updated internally to reflect this
  - games can save and load (even before bgameboy can, hah)
  - save states hooked up, but they crash the DMG. I don't know why, as
    if it was hard enough saving states with libco, try doing it for an
    emulator inside an emulator >_<
- last remnants of old SGB stuff removed, <sueprgameboy> XML converted
  to <icd2>
- looks like the XML list idea is looking pretty useless for
  SNES::Cartridge now that bgameboy handles its own XML mapping
2011-01-08 21:06:09 +11:00
Tim Allen
3f960374ad Update to v073r02 release.
byuu says:

Changelog:
- removed bsnes/supergameboy (libgameboy -> libgambatte binding)
- added direct ICD2-R coprocessor emulation
- linked in bgameboy to the ICD2-R module
- Makefile removes -Isnes, all files adjusted from <name.hpp> to
  <snes/name.hpp> [relic from asnes split]

You can now play Super Game Boy games with the core bsnes library.
2011-01-08 21:01:51 +11:00
Tim Allen
d8a386031f Update to release v000r11.
byuu says:

Changelog:
- adds XML memory mapping to cartridge loading;
  nall/gameboy/cartridge.hpp will bullshit one for now
- still need to add proper MMM01 detection (menu code goes at end of ROM
  apparently)
- added save state support, which works here (but not inside bsnes, go
  figure), to aid in debugging. Expect constant changes for now a long
  while, it's way too early to add states
2011-01-07 22:11:56 +11:00
Tim Allen
f0796e546e Update to release v000r10.
byuu says:

Changelog:
- fixed LYC interrupt at LY=0 (fixes Makai Toushi SaGa)
- fixed MBC3 ROM bank mapping (fixes Harvest Moon GBC)
- added Super Game Boy MLT_REQ support to JOYP, needed for ICD2-R emulation
- temporarily changed System::run() to execute only four cycles before
  exiting for bsnes, will make two versions later
- uses actual boot ROMs, has DMG+SGB1 for now. Need SGB2, don't care
  about CGB. Defaults to SGB1, no way to select just yet.  DMG 4-second
  wait is annoying. Does not force games to act like SGB on bgameboy
  itself, because that has no ICD2 and fails the required MLT_REQ check
2011-01-06 21:16:07 +11:00
Tim Allen
2d49a4408d Update to release v000r09.
byuu says:

Changelog:
- added skeleton HuC1 (gets to a menu)
- added skeleton HuC3 (gets to a menu, this one is supposedly a lot more
  complex (IR, RTC, etc.))
- added MMM01 emulation
2011-01-05 20:59:22 +11:00
Tim Allen
a7ffbd784b Update to release v000r08.
byuu says:

Changelog:
- rewrote sprite rendering, grabs first ten sprites, draws them in
  revere order of a: X-index, b: OAM appearance order
- simplified tile decoding to use less variables
- added MBC3 emulation (for now, RTC is always enabled)
- STOP can be broken via joypad IF, this may not be correct though (it
  may trigger even without P10-13 being modified)
- cleaned up all MBC emulation to use masks instead of ranges
- MBC2 uses 512-byte table now, ignores high 4-bits. Easier this way I guess
- tools menu temporarily has a console tracer enable option
- some other stuff

No real visible improvements :(
2011-01-04 21:42:27 +11:00
Tim Allen
afdb3c4d20 Update to release v000r07.
byuu says:

Changelog:
- fixed sprite Vflip check
- fixed up window rendering (well, mostly, works great in Megaman II but
  not so great in Makaitoushi SaGa)
- added MBC2, MBC5 (already had MBC0, MBC1)
- removed reset, hooked up power cycle and Vsync toggle
- some other stuff

Makaitoushi SaGa locks on the main menu after some graphical glitches on
the title screen, damn.
Shin Megami Tensei - Devichil Black Book locks up immediately, hitting
HALT opcodes all the time, damn again.

Megaman II should be fully playable now.
Contra 3 is really close, but goes crazy on the turtle boss fight.
2011-01-03 15:28:36 +11:00
Tim Allen
ebd6a52811 Update to release v000r06.
byuu says:

Added MBC1 emulation, although battery RAM doesn't save or load to disk
yet.
Made up a fake MBC0 which is really just saying 'no MBC', for consistent
handling of all MBCs.
Added bumpers to stop ROM/RAM out of bounds accesses.
Added STAT interrupts for LY coincidence, Vblank and Hblank (not for OAM
access yet, I don't know the timings.)
Fixed timer interrupt [Jonas Quinn]
Made all interrupts call a CPU function instead of just setting a flag
for better control (to allow below addition.)
Added HALT and STOP emulation, the latter permanently locks the Game Boy
for now. The former breaks on interrupts.
Rewrote all the rendering code to suck 50% less, though it's still
absolutely miserable and scanline-based.
Added pixel-level horizontal scrolling to BGs.
Fixed OBJ rendering error that was making them render upside down (I was
flipping to compensate before.)
Added OBJ 8x16 mode.
Added OBJ priority support.
Added window (but it's broken to all hell on Mega Man II.)
2011-01-02 15:46:54 +11:00
Tim Allen
42a9f9cfa4 Update to release v000r05.
byuu says:

Fixed all of the previously mentioned problems by myself and Jonas
Quinn.
Fixed up JOYP and hooked up JOYP interrupts, they work on JOYP writes as
well if your selection makes the low four bits change to != 0xF.
Added basic sprite emulation, very very very lousy but it works for
Tetris.
Fixed DAA, fuck that opcode. Fixes blargg's CPU tests 1 and 11 (for some
odd reason.) Only test 2 is failing, on the "EI" test. Maybe it relies
on STAT interrupts?
Did some other stuff.

Tetris is now 100% fully playable. But that renderer is an abomination.
Soooooo simplistic and missing so many edge cases.
But holy shit, a fully playable commercial game in three days. I would
have killed to have made that progress when I started on bsnes.
2010-12-31 16:43:47 +11:00
Tim Allen
2330ed6e8c Update to release v000r04.
byuu says:

[screenshot of the Tetris title screen]

Less than fourty-eight hours after starting on this. I guess you weren't
kidding, Exophase.
2010-12-30 18:18:47 +11:00
Tim Allen
71780949b0 Update to release v000r03.
byuu says:

All 512 instructions implemented. To make debugging flags easier and to
reduce the code size, I made parent routines for all the bit-logic that
sets flags. This bumped up the speed to 3,045fps. So about 51x faster
than a real Game Boy.

I suspect the frame rate to plummet rapidly as I emulate more stuff and
try and get timings more accurate. Wild ballpark, I'd guess 300fps or
so. Not based on anything, just a made up number. I have no idea what it
will end up being.

So I still need:
* decode MMIO reads/writes
* add CPU interrupt support
* add LCD emulation (probably the hardest part)
* add PCM emulation (well, this would likely be the hardest; but it's
  not essential right now)
* debug the holy living shit out of the CPU core. Anyone want to help
  now by looking it over? :D
2010-12-30 18:18:23 +11:00
Tim Allen
1c3c7fe0a7 Update to release v000r02.
byuu says:

314 of 512 opcodes implemented, can execute the first 67,450
instructions of Tetris.

I also added an MMIO bus, ala bsnes, so that I can map and access
individual registers with a single indirection.
2010-12-29 22:03:42 +11:00
Tim Allen
e0a9f1cf2c Update to release v000r01.
byuu says:

Hooked up a scheduler to enter/exit the CPU core wherever I want. Added
basic 4*1024*1024hz clock, and about eleven or so opcodes. Creating the
disassembler as I encounter each new opcode, not skipping ahead to do
all 'like other' opcodes, eg if I add 'dec b', I don't then add 'dec c'
until I encounter it.
2010-12-28 17:03:02 +11:00
Tim Allen
246d6aaf08 Add .gitignore files to populate obj/ and out/ 2010-12-28 12:57:58 +11:00
Tim Allen
da7d9f2662 Initial commit of bgameboy v000.
The source tarball also included empty obj/ and out/ directories which
git does not support.

byuu says:

Project started, so basically everything is new.

It's basically a rough skeleton that mimics bsnes project structure.
Eventually the src/gameboy folder will be copied into bsnes-official and
used by the chip/supergameboy core.
The middleware layer (supergameboy/interface) will be merged into a new
chip/icd2 folder that will represent direct Super Game Boy emulation in
the future.
At least, if all goes according to plan.

There is a simple GUI that can load ROMs, but do nothing after it. It's
not hooked up to ruby yet.
There is a basic system class and interface to expose the
video/audio/input functions.
There is a basic memory bus that doesn't support any MBCs yet.
There is a CPU skeleton that only handles easy read/write access to the
CPU registers (AF is a really fucked up register.)
The core is not hooked up to libco yet, but I intend for it to be, so
that I can run the CPU + LCD how I like.
If it turns out the LCD+audio is easily enslavable, then I'll probably
drop libco and just run it like a regular emulator, using a thread
wrapper around it in bsnes only. We'll see.

The CPU doesn't actually support any opcodes, and loading a ROM won't
actually execute anything.
2010-12-28 12:53:15 +11:00
Tim Allen
e0a5452e8d Update to v073r01 release.
byuu says:

While perhaps not perfect, pretty good is better than nothing ... I've
added emulation of auto-joypad poll timing.
Going off ikari_01's confirmation of what we suspected, that the strobe
happens every 256 clocks, I've set up emulation as follows:
Upon reset, our clock counter is reset to zero.
At the start of each frame, our poll counter is reset to zero.
Every 256 clocks, we call the step_auto_joypad_poll() function.
If we are at V=225/240+ (based on overscan setting), we check the poll
counter.
At zero, we poll the actual controller and set the joypad polling flag
in $4212.d0 to 1.
From zero through fifteen, we read in one bit for each controller and
shift it into the register.
At sixteen, we turn off the joypad polling flag.
The 256-clock divider allows the start point of polling for each frame
to fluctuate wildly like real hardware.
I count regardless of auto joypad enable, as per $4212.d0's behavior;
but only poll when it's actually enabled.
I do not consume any actual time from this polling. I honestly don't
know if I even should, or if it manages to do it in the background.
If it should consume time, then this most likely happens between opcode
edges and we'll have to adjust the code a good bit.

All commercial games should continue to work fine, but this will likely
break some hacks/translations not tested on hardware.
Without the timing emulation, reading $4218-421f before V=~228 would
basically give you the valid input controller values of the previous
frame.
Now, like hardware, it should give you a state that is part previous
frame, part current frame shifted into it. Button positions won't be
reliable and will shift every 256 clocks.

I've also removed the Qt GUI, and renamed ui-phoenix to just ui. This
removes 400kb of source code (phoenix is a lean 130kb), and drops the
archive size from 564KB to 475KB. Combined with the DSP HLE, and we've
knocked off ~570KB of source cruft from the entire project. I am looking
forward to not having to specify which GUI is included anymore.
2010-12-27 18:29:57 +11:00
Tim Allen
6ea4bc031f Update to v073 release.
byuu says:

This release marks a major step forward, offering full low-level
emulation of all four DSP coprocessors based on the NEC uPD77C25
processor core. Many people were responsible for this milestone: Dr.
Decapitator for the actual decapping and extraction; Lord Nightmare for
the cartridges and some special analysis tools; myself, Jonas Quinn and
Cydrak for the uPD77C25 emulation; and all of the donors who raised the
necessary $1,000 for the necessary hardware and equipment needed to pull
this all off. To say thanks to the donors, I am releasing the uPD77C25
emulation core to the public domain, so that everyone can benefit from
it.

All four DSP emulations will be improved by this by way of having
realistic timing; the DSP-4 will benefit further as the high-level
emulation was incomplete and somewhat buggy; and the DSP-3 will benefit
the most as the high-levle emulation there was not complete enough to be
playable. As a result, most notably, this means bsnes v073 is the first
emulator to fully be able to play SD Gundam GX (J)!

As bsnes' primary goal is accuracy, the LLE DSP support renders the old
HLE DSP support obsolete. Ergo, I have removed the 166KB of HLE source
code, and replaced it with the uPD77C25 core, which comprises a mere
20KB of source code. As this LLE module supports save states, this also
means that for the first time, DSP-3 and DSP-4 games have save state
support.

On the other hand, this also means that to run any DSP game, you will
need the appropriate program ROM. As these are copyrighted, I cannot
distribute them nor tell you where to get them. All I can do is provide
you with the necessary filenames and hashes.

Changelog (since v072 release):
* added NEC uPD77C25 emulation core
* added low-level emulation of the DSP-1, DSP-1B, DSP-2, DSP-3, DSP-4
  coprocessors
* removed high-level emulation of the DSP-n coprocessors
* added blargg's libco::ppc.c module, which is far more portable, even
  running on the PS3
* added software filter support via binary plugins
* added debugger (currently Linux-only); but it is as yet unstable
* added pause shortcut
* updated mightymo's cheat code database
2010-12-26 23:24:34 +11:00
Tim Allen
676a3adbf7 Update to v072r14 release.
byuu says:

Changelog:
* added SNES::interface.message(const string&) so that the core can send
  messages for the GUI to display
* failing to load a DSP-n ROM, or failing the DSP-n SHA256 hash (if
  there is one) will result in a warning message
* all DSP-1 games by default once again use the DSP-1B program, now that
  it has been redumped and reverified
* fixed bugs in uPD77C25 SHL2 and SHL4 opcodes; fixes DSP-2 and DSP-4
  emulation
* removed all DSP HLE (DSP-1, DSP-2, DSP-3, DSP-4)
* as a result of LLE, DSP-3 and DSP-4 games can now load and save states
2010-12-26 23:11:31 +11:00
Tim Allen
b27e0a719d Update to v072r13 release.
byuu says:

The DSP-1 and DSP-3 emulation appears to be great.
However, there are bugs in the other two.
DSP-2, Dungeon Master: the graphics in-game appear corrupt. It looks
like the first two pixels have the right color, the next six have the
wrong color, resulting in vertical stripes.
DSP-4, Top Gear 3000: the car sprites appear to be showing 8x8 tiles
instead of 16x16 files, resulting in 3/4ths of the cars being invisible,
but only up close.
Dr. Decapitator and Lord Nightmare are supremely confident that our
dumps are 100% accurate, there was no bus wavering at all this time.
We believe they are bugs in the uPD77C25 emulation.
I desperately need help! I have spent the past several hours trying to
ascertain what the problem is, to no avail.
I've tried messing with just about every flag, every register, checking
for use of OV1, S1, custom opcodes, etc ... I am having no luck.
I'm going to keep trying with even more sophisticated cross-analysis.
But Cydrak, if you would please rework that magic of yours, I'd be
eternally grateful :D
2010-12-26 23:08:43 +11:00
Tim Allen
a62aa94b65 Update to v072r12 release.
byuu says:

This release defaults DSP-3 loading to use the uPD77C25 core. It also
pre-emptively does the same for the DSP-2 and DSP-4. v072r11 did this
for the DSP-1.

I've also renamed my string<>integer conversion function names:

strhex -> hex
strsigned -> integer
strunsigned -> decimal
strbin -> binary
strdouble -> fp (this one will no doubt be trouble since 'file fp' is
    a common idiom. floatingpoint is too long, float and double are
    already reserved.)
2010-12-23 01:13:14 +11:00
Tim Allen
9762a092d2 Update to v072r11 release.
A number of changes in this release were contributed by Cydrak in the
WIP thread, who described his changes from r09/r10 thusly:

- Call cpu.synchronize_coprocessor() on external R/W to avoid missing data
- Sign-extend K, L before multiplying
- Load IDB before ALU. Supports the MOV A, d; XOR A, A idiom which is
  all over the place
- Use 16-bit types in flag checks (notably Z)
- Flags mostly unified; hopefully at least OV0 and SGN work
- Carry-in comes from the *other* accumulator's flags, this is used for
  long arithmetic
- CMP is ~q (see the many CMP A; INC A where values get negated)
- SHR1 is arithmetic shift and retains the sign bit (Mario Kart sprites
  and physics are broken without it)
- SHL1 has carry-in per the datasheet, it doesn't seem to be used though
- XCHG probably byteswaps, but it's not used either
- Reversed DR external R/W order again, big-endian seems to break it

byuu described the remaining changes:

You do not need the XML files anymore, bsnes will automatically choose
the new uPD module, and look for dsp1b.bin.
If you make your own XML file, you can force the old HLE mode, or use
a differently-named PROM.
If and when we get the DSP-2,3,4 modules, bsnes v072.11 and above should
already be able to run them, assuming no more emulation core bugs.
2010-12-23 01:07:36 +11:00
Tim Allen
05526571e7 Update to v072r10 release.
byuu says:

Current code.
2010-12-23 01:05:21 +11:00
Tim Allen
3bd29088d1 Update to v072r09 release.
Unfortunately, I missed the v072r08 release; it was taken down before
I saw the announcement.

byuu says (about v072r08):

This WIP adds NEC uPD77C25 emulation. Unfortunately it's not at all functional yet, there are way too many things I don't understand about the chip.
I'm absolutely going to need help to complete this.

[...]

For now, you need the included PCB XML to manually map the program/data ROM in, which are included with the archive. You'll have to rewrite the map yourself to run other DSP-1 games, unless they have the same layout as Mario Kart. I am using the US [!] version, name it mariokart.sfc and put all the archive files and the ROM together.

From here, bsnes will load up the ROMs, and start executing instructions. Since the emulation is so incomplete, it just deadlocks on the "Nintendo" logo as if there were no DSP on the cart at all, but if you enable tracing, you'll see it actually starts doing a lot of stuff before getting stuck in a really long and confusing loop.

[Note: the DSP-1B program and data ROMs are not included in this commit.
The PCB XML file mentioned above looks like this:

<?xml version='1.0' encoding='UTF-8'?>
<cartridge region='NTSC'>
  <rom>
    <map mode='shadow' address='00-3f:8000-ffff'/>
    <map mode='linear' address='40-7f:0000-ffff'/>
    <map mode='shadow' address='80-bf:8000-ffff'/>
    <map mode='linear' address='c0-ff:0000-ffff'/>
  </rom>
  <ram size='800'>
    <map mode='linear' address='20-3f:6000-7fff'/>
    <map mode='linear' address='a0-bf:6000-7fff'/>
    <map mode='linear' address='70-7f:0000-ffff'/>
  </ram>
  <upd77c25 program="dsp1b-program.bin" data="dsp1b-data.bin">
    <dr>
      <map address='00-1f:6000-6fff'/>
      <map address='80-9f:6000-6fff'/>
    </dr>
    <sr>
      <map address='00-1f:7000-7fff'/>
      <map address='80-9f:7000-7fff'/>
    </sr>
  </upd77c25>
</cartridge>

Save it as 'mariokart.xml']

byuu says (about v072r09):

Fixes OP/LD RQM=1 on DR modify, Mario Kart can get in-game, but the
track is completely corrupted.
Reorders order of operations for OP, in an attempt to mimic parallelism.
Added support for OP KLM DST.
Added S1 flag setting, probably not correct.
2010-12-17 21:54:28 +11:00
Tim Allen
26643a43de Update to v070r07 release.
byuu says:

I'm happy enough with the debugger now. Not 100% up to par with the old
one, but it also does some new things the old one didn't.
- step into / step over are disabled unless they can be done safely
- this means step over is usually grayed unless you hit step into first,
  due to bsnes not being opcode-based (you can't skip an opcode that is
  half-executed)
- you can now trace console output to disk
- stepping the CPU will print stepped SMP opcodes if the checkbox for it
  is on and vice versa
- button added to clear the console log
2010-11-03 00:08:00 +11:00
Tim Allen
7e8958b102 Update to v072r06 release.
(there was no r05 release posted to the WIP thread)

byuu says:

Updated libsnes to use new file and function names.
Also added EditBox::setCursorPosition for GTK+ and Qt, only used by the
debugger so far so that when text is added, it auto-scrolls to the
bottom.
2010-11-01 23:00:46 +11:00
Tim Allen
edac93b800 Update to v072r04 release.
(there was no r03 release posted to the WIP thread)

byuu says:

nall/snes/smp.hpp created, ~68 addressing modes compared to the CPU's
~27, ugh. All hooked up, you can step into / step over / trace the S-SMP
now as well.
2010-10-30 19:18:43 +11:00
Tim Allen
0730f847e5 Update to v072r02 release.
byuu says:

Just debugger work here. About three or four hours to write
nall/snes/cpu.hpp, which is basically opcode encoding information for
disassembly.
2010-10-27 20:49:18 +11:00
Tim Allen
5ae0c80ee8 Update to v072r01 release.
byuu says:

- added pause shortcut ('P' key, as pause/break is too finicky)
- pause and auto-pause show on status bar
- added a debugger skeleton, very very primitive and completely unusable
  - don't try it yet
- added software filter support

Also included is the new snesfilter library. It has all of the filters
the old one had, as well as scanline filters since that's not in my GUI
anymore
If you want scanlines and other software filters, then you can either
make your own hybrid two-in-one software filter, or make a pixel shader
(I don't have one of those yet.)
2010-10-26 23:01:41 +11:00
Tim Allen
d0ef8e7488 Update to v072 release.
byuu says:

Just some very minor fixes.
2010-10-23 16:08:05 +11:00
Tim Allen
6c3aec7dc9 Update to v071 release.
byuu says (since v070):

- fixed a regression in the accuracy/compatibility CPU core with IRQ
  masking; fixes World Heroes 2
- fixed OAM address reset on $2100 writes for performance PPU core;
  fixes Mahjongg 2 and others
- DSP-1 always returns high 8-bits of status register; fixes Ace wo
  Nerae! freeze [Jonas Quinn]
- performance core can now take advantage of serial support
- pixel shaders now use a unified XML format; in the future they will
  support multi-pass shaders and textures
- major code restructuring
- first public release of phoenix GUI port
- mightymo's cheat code pack is now an external file for the phoenix
  port
- phoenix port stores cheat codes in XML format as well, unifying all
  file formats to the same markup language
2010-10-22 20:54:59 +11:00
Tim Allen
4016ae1d43 Update to v070r17 release.
byuu says:

- fixes DSP-1 status register for "Ace wo Nerae!"
- fixes IRQ masking for "World Heroes II"
- fixes compilation for the Qt port's debugger
2010-10-20 22:51:19 +11:00
Tim Allen
9e53c51b58 Update to v070r16 release.
(there was no r15 release posted to the WIP thread)

byuu says:

This mostly contains improvements for nall, like path unification.
This should fix FitzRoy's issue with .. on Windows.
2010-10-20 22:51:19 +11:00
Tim Allen
ce2b543679 Update to v070r14 release.
(there was no r13 release posted to the WIP thread)

byuu says:

- nall/string: trim and split functions now take the limit as a template
  parameter for clarity, trim_once variants are removed
  - quotable.trim<1>("\""); //remove quotes from string
  - cheatcode.split<3>(","); //split up to three times, third one is
    a description that may have commas
  - foobar.trim(" "); //remove any and all spaces
- nall/string: added wildcard() and iwildcard() functions for pattern
  matching
- nall/directory: accepts an optional pattern parameter to perform
  wildcard matching
  - lstring cartridges = directory::contents(path, "*.sfc");
  - some people may prefer directory::contents("/path/to/files/*.sfc"),
    but I like not having to build a string when you have the path
    separated already
- nall/qt: removed entirely, now resides in bsnes/ui-qt/template; I do
  intend to replace the check/radio actions with native Qt versions
  later
- bsnes/data: new folder, share the parts that both UIs use; bsnes.ico,
  bsnes.png, bsnes.Desktop, cheats.xml; simplify Makefile install target
- Makefile: install target now creates .bsnes folder and copies
  cheats.xml there for you
- Makefile: gconftool hack removed, not needed for phoenix, will work
  around with Qt later
- will probably make bsnes/Qt read the cheats.xml file externally as
  well, as that file makes each profile 1MB bigger when embedded
  - as such, will probably make bsnes also look in the binary directory
    for that file, so Windows users don't have to copy it to their
    userdata folder
2010-10-20 22:51:19 +11:00
Tim Allen
1a29b59225 Update to v070r12 release.
byuu says:

- removed support for images with copier headers
- phoenix/Windows: Label properly refreshes on text changes, fixes video
  settings sliders
- alt/ppu-performance: fixed mosaic Voffset bug, fixes Super Bowling et al
- alt/cpu: fixed CPU::joylatch() reporting, allows serial applications
  to work with performance profile
- hooked up SNES::cartridge.basename, allows MSU1 and serial support
  with the phoenix UI
- updated UPS patching code for bsnes/Qt, allowing it to compile again,
  hidden config option file.bypassPatchCrc32 was removed
2010-10-20 22:51:19 +11:00
Tim Allen
1926561ced Update to v070r11 release.
byuu says:

- phoenix/All: converted all instances of const char* to const
  nall::string&
  - above used to require: label.setText(string("FPS: ", fps)); but can
    now use: label.setText({"FPS", fps});
  - also avoids the need for the internal implementations to have to
    check for null string pointers
- phoenix/GTK+: no longer disabling double buffering on the viewport.
  Does not cause flickering, and fixes redraw issue on window resize
- phoenix/Qt: like phoenix/GTK+, it will use the default font on the
  menubar as well, so child menu items are consistently sized now
- Linux: file browser can list contents of / and won't let you go
  higher; Windows needs a similar guard for n:/ or \\
- UPS soft-patching support added
- external XML memory map loading support added
- cartridge folder support added: if folder ends in .sfc and there is
  ONE .sfc ROM inside it, it will load the folder as if it were a ROM
- input assignment refreshes text instead of reloading the list, this
  saves your position
  - auto-advance wasn't working very well, will try again later
- input clear all button removed since it's pretty fast now to do
  clear+down:repeat
2010-10-20 22:51:19 +11:00
Tim Allen
e2db2c24fc Update to v070r10 release.
byuu says:

- added workaround to phoenix/Windows to prevent horizontal scrollbar
  always being visible on single-column ListBoxes
- phoenix gains Window::geometry()
- added code to save and restore window positions, as in bsnes/Qt.
  Positions are saved to bsnes-phoenix-geometry.cfg this time
- resizing the main window will keep its position onscreen now

There's one issue with GTK+, if you close a window and then call
gtk_window_get_position(), it returns the previously set position rather
than where you actually placed the window. My easy fix of calling
gtk_window_get_position right before actually closing the window didn't
work, so for now you'll have to live with it.
2010-10-20 22:51:19 +11:00
Tim Allen
8a53e9ed22 Update to v070r09 release.
byuu says:

- removed native OS dialog option, I don't plan to add all the code
  required to make it optional everywhere
- cheat database supported, although it's external now. Either in the
  .bsnes folder or with the binary, named cheats.xml
- cheats.xml is external so that binaries can be much smaller, important
  for multiple profiles
- added "find codes" button to cheat editor (need to gray it out
  permanently if cheats.xml isn't found)
- added cheat database add window, works the same as bsnes/Qt, but it
  will also alert you if you run out of empty cheat slots upon import
- note: I should rename that ok button to "Import"
- hooked up callbacks for multitap/mouse/SS/justifier input
- added mapping for mouse axes and buttons
- used a simplified approach that only lets you map left/middle/right
  buttons, but doesn't need a separate popup window or fake controls
- moved capture mouse command to tools menu
- different from Qt where you'd click inside the main window, meant to
  be safer from accidental capture, escape still releases capture
- made a skeleton for GUI hotkey support, but the only hotkey is escape
2010-10-20 22:51:19 +11:00
Tim Allen
5286481d8d Update to v070r08 release.
byuu says:

- all three ports of phoenix gain the ability to use
  ListBox::setCheckable(), checked(row), setChecked(row, checked
  = true);
- cheat editor updated to take advantage of this

Some fun differences between the implementations. Windows was the least
flexible, it only lets you have a check at the start of each item.
Luckily that's all I need for my purposes so it'll work. It's also a lot
easier, as now I don't need a ton of extra code to try and set
per-column checkboxes. Now both Windows and Qt can put text into the
first item with the checkbox, but GTK+ cannot. Further, Qt needs this
because even if you hide the checkbox column, it still tries to search
for typed text from the checkbox column. GTK+ does this too, but unlike
GTK+, Qt lacks an API call to set the search column. Since my code
basically has to change this in real-time since you have to call the
setProperty functions after create(), this means I always set up the
checkbox columns regardless of whether or not they are used. For Qt,
I had to work around this and it'll be an annoying edge case if you try
and use setCheckable(true) and then setCheckable(false), because Qt has
no way to clear the checkboxes from an item once you've enabled them for
the first time. But without doing it this way, there's no way for eg the
ROM file loader to allow type-searching, so that's the way I do it.
Windows works the same, and GTK+ has a separate column (hidden from the
phoenix API standpoint) for the checkboxes, with no column header label
text.

All in all, a major hassle, but it was the only really major GUI hit
from leaving Qt, aside from the horror that's going to be the debugger,
which needs all kinds of highly specialized controls.
2010-10-20 22:51:19 +11:00
Tim Allen
440a59c879 Update to v070r07 release.
byuu says:

- added menu options to select controller port devices, they do actually
  work too
- however, input mapping can't map analog axes yet, and the mouse can't
  be captured yet, so it's of little use
- added clear and clear all buttons to the input mapper window, mainly
  because there was no reason not to (escape clears active input too)
- going to be adding a "special" button in the future that lets you map
  mouse axes and buttons
- fixed phoenix/Qt port, both the video rendering and Window::focused()
  commands work now

The way I've implemented mouse mapping has always been screwy. So the
special button is going to pop open another window. For digital mapping,
it'll let you choose a mouse button, and for analog mapping, it'll let
you choose an axis. May add in some manual joypad assignment stuff in
there for analog joypad buttons, those things are impossible to
auto-detect.
2010-10-20 22:51:19 +11:00
Tim Allen
96e9333ec2 Update to v070r06 release.
(there was no r05 release posted to the WIP thread)

byuu says:

- bsnes/phoenix uses XML for per-game cheat codes, markup is identical
  to the main database
- added clear and clear all buttons to the cheat code editor
- phoenix/GTK+ sets all child menu elements to match the parent menu font
- phoenix/Windows will draw a black canvas for the Viewport widget
  (phoenix/GTK+ still needs this)
2010-10-20 22:51:19 +11:00
Tim Allen
775c111fef Update to v070r04 release.
byuu says:

- fixed new config file input driver name (you'll have to delete your old config, or change to a different driver and back and restart)
- fixed slot loader windows' OK button placement
- fixed nall/directory.hpp when list size was zero
- rewrote nall/function.hpp, no longer requires <functional> or union tricks
- added state manager

The state manager is a little bit different this time. It's functionally
identical to bsnes/Qt, 100% of the way. But when you save slots, it
stores them in RAM. It only writes the BSA archive upon ROM unload
/ program exit. Yes, this means that technically if the emulator
crashes, you'll lose your states. But a) that very rarely happens, and
b) the old way was thrashing the disk like crazy, every letter you typed
dumped up to 8MB to disk. With this new method, I can simply store
a boolean valid flag before each slot, and pack the file better. Before,
a save on only slot 3 would be 3*state size (~1.2mb), it will now be
3bytes+state size (~400kb.) I have also added a proper signature because
of this, so it will detect when you load an archive for a previous
serializer version and ignore it. When you go to save (unload the game),
if there are no valid slots, the BSA archive gets unlinked (deleted.)

I am also planning a feature around the now-hidden "slot 0". My idea is
for it to be a fallback slot. How many times have you loaded a state
when you meant to save and said, "shit, now I lost some of my progress"?
The idea is that whenever you load a state, right before loading, it
will save to slot 0. When you unload the game, or exit the emulator, it
will also save to slot 0. You will be able to load from slot 0 from the
menu, but not save to it. It will appear at the bottom of the load list.
And lastly, I'll add an advanced option to auto-load slot 0 if it
exists, which will enable "close the emulator and restart where you left
off." functionality.
2010-10-20 22:51:19 +11:00
Tim Allen
3ffa44cef9 Add pixel shaders from the external tarball.
byuu has traditionally kept these shaders separately, but I don't see
why they shouldn't be stored alongside the code that uses them.

Unlike previous versions of pixel shaders, these are updated to use the
new file-format introduced in v070r03.
2010-10-20 22:51:19 +11:00
Tim Allen
f28d70f9e6 Update to v070r03 release.
byuu says:

- fixed a bug in xml_element::parse() with <![CDATA[...]]> tags
- merged FragmentShader and and VertexShader into Shader, which is an
  XML file that contains all relevant data
- updated Qt port to reflect the above
- added support for pixel shaders to the phoenix port
- updated all pixel shaders to use the new format
- ruby won't crash if you give an HLSL driver a GLSL shader or vice
  versa, but it will still crash on bad programs
- phoenix::Viewport has its own window class, that paints a black brush
  background

[The XML shader] format is subject to change, more specifically I may
change the <source> tag from HLSL shaders.
In the long-long term, it'd be nice to extend the format to allow
multiple shaders to be chained together and to encode base64 texture
files.
But for now, this is good enough.
2010-10-20 22:51:19 +11:00
Tim Allen
73fdbf893f Update to v070r02 release.
byuu says:

- added NTSC/PAL TV output mode selection
- added loading support for BSX Slotted, BSX, Sufami Turbo and Super
  Game Boy games
2010-10-20 22:51:18 +11:00
Tim Allen
da5263bfc3 Update to v070r01 release.
byuu says:

- phoenix supports onActivate, or return key pressed, on text boxes
- phoenix supports setGeometry() on all widgets
- input settings can now map analog axes and analog buttons
- analog button support is simplified over bsnes/Qt, and it supports the
  trigger inversion you see between Xbox 360 and Thrustmaster
  controllers
- load cartridge window lets you press enter in the path box to select
  the folder, but currently allows invalid folders (makes list empty)
- load cartridge won't reset your view if the folder doesn't change
  - this means the last ROM you loaded is highlighted the next time you
    go to load cartridge; you're welcome, FitzRoy :P
- removed quit system menu option
- added dummy controller port system menu options, there's no code
  behind them yet
- added power/reset menu options, dropped the power checkbox in favor of
  a standard power cycle option, removes unnecessary complexity
- added video mode scaling, 1x to 5x; and aspect ratio correction
- added video mode smooth toggle
- added audio settings panel with volume and input frequency adjustment
  - config file is where you can control output frequency and latency,
    they are too niche for a GUI
- fixed a realpath() crash on Linux when the bsnes binary was in /usr/bin
2010-10-20 22:51:18 +11:00
Tim Allen
449a3ad426 Update to v070 release.
byuu says:

This release represents the coup de grâce of bsnes/Qt.

Changelog:
- configuration file is now called bsnes-qt.cfg; the first run of this
  release will start with a clean state
- MSU1 now supports audio looping via new PCM file format
- disabled state load/save menu due to a serious bug in Qt 4.6.0 for
  Windows
- RawInput: all keyboards merged to KB0, it should no longer be required
  to reconfigure the keyboard out-of-the-box
- RawInput: fixed a bug where Xbox 360 controller states were being
  overwritten by DirectInput controllers
- RawInput: fixed a device sorting bug caused by moving ruby to Unicode
- Direct3D: fixed a pixel shader bug caused by moving ruby to Unicode
- Linux port: fixed sudo make install target
- Linux port: default to gcc/g++ instead of gcc-4.5/g++-4.5 for one last
  release
- updated to mightymo's 2010-09-20 cheat pack
2010-10-20 22:51:18 +11:00
Tim Allen
ccfff86140 Update to v069 release.
byuu says (since v068):

- added new effect toggle tool window, which allows toggling of BG/OAM
  graphics layers and DSP audio channels
- added an option to use the native OS file and folder open dialogs
  instead of my custom browser
- added a new state selection window
- added frame skipping support, which is only used during fast
  forwarding; as a result, fast forward is now ~80% faster
- removed unnecessary icons, added workaround for checkbox/radiobox menu
  icons on Linux/GNOME
- added RTS/CTS support to serial simulation
- all cores: OAM high table even address writes should update OAM latch
  data register [blargg]
- accuracy core: major improvements to mosaic emulation
- accuracy core: added additional hardware-based caching, resulting in
  a ~15% speed boost
- accuracy core: emulated CGRAM address invalidation for writes during
  active display
- performance core: added new S-PPU renderer, resulting in a ~10% speed
  bost
2010-10-20 22:51:18 +11:00
Tim Allen
4525d00eba Update to v068r25 release.
byuu says:

This is basically the v069 release candidate, heavy testing would really
be appreciated. I'd like for v070 to be the first official phoenix
release, but if a major bug slips past us that will ruin it.

The big change is that save state support was added to the
PPU-performance core.
2010-10-20 22:51:18 +11:00
Tim Allen
d0d8c2a921 Update to v068r24 release.
(there was no r23 release posted to the WIP thread)

byuu says:

Fixes OAM latchdata for all 3 cores and CGRAM address invalidation for
the accuracy core (the only one that really does it because it needs
cycle PPU timing.) Also removes the OAM/CGRAM read/write functions to
put them inside the actual MMIO functions. Easier to handle all the
special cases that way. VRAM is a bit more annoying since there's two
read and two write functions.

This should fix battletech/mechwarrior 3050 palette at least.
2010-10-20 22:51:18 +11:00
Tim Allen
8a91c95002 Update to v068r22 release.
byuu says:

Wanted to torture myself, so I implemented the hardest window of all,
the cheat code editor. I had to sacrifice checkboxes inside lists,
unfortunately, but it's a necessary evil. Maybe some day if we can port
checkboxes inside list items to Windows and GTK+, we can add it back. It
should be the only really apparent GUI sacrifice, though. You toggle
cheats by double-clicking them in the list. Easy to do, but not
apparent.

I also added in the focus policy.
2010-10-20 22:51:18 +11:00
Tim Allen
9484d1bc92 Update to v068r21 release.
byuu says:

Changelog:
- adds synchronize video
- adds synchronize audio
- adds mute audio
- adds advanced settings window with driver selection only
- adds the pretty section header thing I started going toward with Qt
- adds a configuration file, saves to bsnes-phoenix.cfg (I don't make
  the .bsnes folder yet)
- the status bar shows [A] for accuracy, [C] for compatibility and [P]
  for carburetor
2010-10-20 22:51:18 +11:00
Tim Allen
4163059b21 Update to v068r20 release.
byuu says:

Changelog:
- fixed window casting crash in phoenix
- added perfect forwarding to nall::string variadic templates to fix
  file load dialog crash in phoenix
- disabled copy constructors in utf8_t to prevent this problem from
  occurring again in the future
- separated canvas window proc by creating a separate class for it
  (ironically it was a desktop window causing the first crash)
- use processorArchitecture="*" to make compilation easier
- fixed status bar font assignment in phoenix/Windows
- added InitCommonControls + CoInitialize for XAudio2 on XP
- had to use DirectSound for audio; XAudio2 is crashing on exit which
  breaks the profiling (only a problem because you can't change the
  drivers without recompiling, there's really no reason to profile
  XAudio2 anyway)
2010-10-20 22:51:18 +11:00
Tim Allen
697f23d45c Update to v068r19 release.
byuu says:

This adds proper manifest files to get the nice XP/Vista controls. Need
to find a way to auto-detect MinGW 32 vs 64 since I can't use $shell or
`` on gcc -v on Windows. For now you have to edit the
ui-phoenix/Makefile by hand.

I've implemented the video settings window. I am going to be using
separate windows this time. As nice as having everything in one place
was, I didn't like being forced to stretch things to fill out the
one-size-fits-all tab window I was using before. That and I don't feel
like implementing tab support with phoenix anyway.

The menu gets a load cartridge command, and bsnes writes save RAM files
now. Loading by file dialog crashes on 64-bit. Something's fucked up
there, but I don't know what. Again, help would be great here :)
2010-10-20 22:48:46 +11:00
Tim Allen
b671e49644 Update to v068r18 release.
byuu says:

This WIP fixes the Mode7 repeat issue in the accuracy core.

More importantly, it's the first build to include phoenix. There is
a stub GUI that does basically nothing right now. It will give you
a window, a command to close the emulator, and an FPS meter so you can
tell how fast it is. To load a ROM, you have to drag the ROM on top of
the binary. I don't know if it will work if the filename+path has spaces
in it or not, so avoid that to be safe.

[...]

For some reason, the 64-bit binary sometimes crashes on start, maybe 1:6
times. So just keep trying. I don't know what's up with that, I'd
appreciate if someone here wanted to debug that for me though :D

One really good bit of news, there was that old hiro bug where keyboard
input would cause the main window to beep. I spied on the main event
loop and, as suspected, the status bar was getting focus and rejecting
key presses. What. The. Fuck. Why would a status bar ever need focus? So
I set WM_DISABLED on it, which luckily leaves the font color alone.
I also had to use WM_DISABLED on the Viewport widget that I use for
video output. These two combined let me have my main window with no
keyboard beeping AND allow tab+shift-tab to work as you'd expect on
other windows, so hooray.

Now, at the moment there's no Manifest included, because Microsoft for
some reason includes the processorArcitecture in the file. So I can't
use the same manifest for 32-bit and 64-bit mode, or the binary will
crash on one or the other. Fuck. So the status bar may look old-school
or something, whatever, it's only temporary.

Next up, my goal is to avoid the hiro icon corruption bullshit by making
phoenix itself try and use an internal resource icon. So just compile
your app with that resource icon and voila, perfect icon. Not in there
yet so you get the white box.

Input is hard-coded, up/down/left/right/z/x/a/s/d/c/apostrophe/return.

Lastly, compilation is ... in a serious state of flux. The code is set
to compile bsnes/phoenix-gtk right now. Try it at your own risk. Give me
a few WIPs to get everything nice and refined. Ubuntu users will need
gcc-4.5, which you can get by adding the Maverick Meerkat repository,
updating apt, installing the gcc-4.5 + g++-4.5 packages, and then
removing and re-updating your apt/sources.list file so you don't end up
fucking your whole system when you run apt again in the future.

For anyone who can work with all of that, great! Please post a framerate
comparison between 32-bit and 64-bit builds. Any game, any screen, so
long as the FPS is not fluctuating when you measure it (eg don't do it
during an attract sequence.)

If anyone complains about the 64-bit binary not working and it turns out
they are on 32-bit Windows, they are going to be removed from this WIP
forum :P
2010-10-20 22:47:14 +11:00
Tim Allen
92ab697f8c Update to v068r17 release.
byuu says:

This hopefully fixes vertical and horizontal mosaic with the accurate
S-PPU core.

It also adds frame-skipping support to the compatibility and performance
S-PPU cores. This is not visible to the user interface, because I feel
that virtually nobody is going to play with frame-skipping on when they
could use a faster emulation with it off. However, I did use it to
enhance the 'Fast Forward' key. When you press it, it will now turn off
video and audio sync, and set a frameskip of 9. This allows you to speed
things up an additional ~60% over your max theoretical speed without
frameskipping. ~35% with the compatible core, because the PPU is less of
a bottleneck for it. Slowdown was improved, it will turn on audio sync
if it is off until you release the key to ensure you actually get 30fps.

Eventually it'd probably be wise to set a cap on the fast forward speed,
but I hardly think it's an issue on today's computers.
2010-10-20 22:30:35 +11:00
Tim Allen
4147dc42d0 Update to v068r16 release.
byuu says:

Testing this one and all the new features would be appreciated.

New features?

http://img203.imageshack.us/img203/505/bsnes20100907.jpg

[For future reference, the above URL points to a screenshot of bsnes' Qt
GUI running with the following windows (apart from the main window) visible:
 - A new 'state selection' dialog wih buttons labelled 'Slot 1' through
   'Slot 10'.
 - The 'Tools' dialog open to a new 'Effect Toggle' tab, which has
   checkboxes for the various PPU backgrounds and sprites, and SPU
   channels.
 - The 'Configuration Settings' dialog open to the 'Advanced' tab, with
   a "Use Native OS File Dialogs" checkbox.
 - A 'Load Cartridge' dialog, which is the standard Windows file-open
   dialog.
It seems these are the new features referred to. -- Ed]
2010-10-20 22:30:35 +11:00
Tim Allen
05fca49b11 Update to v068r15 release.
byuu says:

This adds a new "Effect Toggle" window to the tools tab list. There's no
menu entry for it yet, oversight, but you can go to another tool and tab
to it.

The effect toggle window lets you toggle background/OAM layers on
a per-priority basis and DSP sound channels. This only works with the
compatibility and performance cores, because I'm not going to allow
accuracy-violating hacks like that into the core.

Non-essential icons have been removed, there's six of them left at the
moment. I am too much of a consistency guy to only have some scattered
around. I know other apps do that, but I'm not going to do that, and
I grow tired of trying to hammer in icons that don't really represent
the actions. Anyway, it still looks pretty good I think.
2010-10-20 22:30:35 +11:00
Tim Allen
3a81ac94a5 Update to v068r14 release.
byuu says:

Holy hell, that was a total brain twister. After hours of crazy bit
twiddling and debug printf's, I finally figured out how to allow both
lores and hires scrolling in the accurate PPU renderer. In the process,
I modified the main loop to run from -7 to 255, regardless of the hires
setting, and perform X adjustment inside the tile fetching. This fixed
a strange main/subscreen misalignment issue, so I was able to restore
the proper sub-then-main rendering for the final screen output stage.
Code looks a good bit cleaner this way overall.

I also added load state and save state menus to the tools menu, so you
can use the menubar to load and save to ten slots. I am thinking that
I should nuke the icons. As pretty as they are, it's getting tiresome
trying to find icons for everything, I have no pictures to represent
loading or saving a slot, nor to represent individual slots. I'll just
stick to radios and checkboxes.
2010-10-20 22:30:35 +11:00
Tim Allen
3f43747474 Update to v068r13 release.
byuu says:

Bug-fix night for the new PPUs.

Accuracy:

Fixed BG palette clamping, which fixes Taz-Mania.

Added blocking for CGRAM writes during active display, to match the
compatibility core. It really should override to the last fetched
palette color, I'll probably try that out soon enough.

Performance:

Mosaic should match the other renderers. Unfortunately, as suspected, it
murders speed. 290->275fps. It's now only 11fps faster, hardly worth it
at all. But the old rendering code is really awful, so maybe it's for
the best it gets refreshed.
It's really tough to understand why this is such a performance hit, it's
just a decrement+compare check four times per pixel. But yeah, it hits
it really, really hard.

Fixed a missing check in Mode4 offset-per-tile, fixes vertical alignment
of a test image in the SNES Test Program.
2010-10-20 22:30:35 +11:00
Tim Allen
5b4702afc4 Update to v068r12 release.
(there was no r11 release posted to the WIP thread)

byuu says:

This took ten hours of mind boggling insanity to pull off.

It upgrades the S-PPU dot-based renderer to fetch one tile, and then
output all of its pixels before fetching again. It sounds easy enough,
but it's insanely difficult. I ended up taking one small shortcut, in
that rather than fetch at -7, I fetch at the first instance where a tile
is needed to plot to x=0. So if you have {-3 to +4 } as a tile, it
fetches at -3. That won't work so well on hardware, if two BGs fetch at
the same X offset, they won't have time.

I have had no luck staggering the reads at BG1=-7, BG3=-5, etc. While
I can shift and fetch just fine, what happens is that when a new tile is
fetched in, that gives a new palette, priority, etc; and this ends up
happening between two tiles which results in the right-most edges of the
screen ending up with the wrong colors and such.

Offset-per-tile is cheap as always. Although looking at it, I'm not sure
how BG3 could pre-fetch, especially with the way one or two OPT modes
can fetch two tiles.

There's no magic in Hoffset caching yet, so the SMW1 pixel issue is
still there.

Mode 7 got a bugfix, it was off-by-one horizontally from the mosaic
code. After re-designing the BG mosaic, I ended up needing a separate
mosaic for Mode7, and in the process I fixed that bug. The obvious
change is that the Chrono Trigger Mode7->Mode2 transition doesn't cause
the pendulum to jump anymore.

Windows were simplified just a tad. The range testing is shared for all
modes now. Ironically, it's a bit slower, but I'll take less code over
more speed for the accuracy core.

Speaking of speed, because there's so much less calculations per pixel
for BGs, performance for the entire emulator has gone up by 30% in the
accuracy core. Pretty neat overall, I can maintain 60fps in all but,
yeah you can guess can't you?
2010-10-20 22:30:35 +11:00
Tim Allen
7df9157abd Update to v068r10 release.
(there was no r09 release posted to the WIP thread)

byuu says:

It is feature-complete, but horizontal mosaic is less accurate. I have
an idea for a mosaic color ring buffer to get it equally accurate, but
I haven't implemented it yet. For now it's just a simple x & ~(mosaic >>
1) trick that is passable.

Hires blending was left out, as it's more processor intensive and
blargg's NTSC does a better job with that anyway.

There's some OPT vertical positioning issues in the SNES Test Program's
character test; Goodbye, Anthrox has some sort of fast CPU DMA issue;
etc.

Total speedup is a mere 13.5%. Not quite the 50% I wanted in the best
case, but I'll take what I can get.

254->289fps in Zelda 3 on my E8400 now. There's another 15% hiding with
blargg's SMP and 5-10% with blargg's fast DSP, but they lose too much
accuracy. It'd put me at or below Snes9X accuracy, while still being 50%
slower.

SSE2 was performing worse this time, both on x86 and amd64, so I left
that optimization off.

So, barring a miracle, this is about the best it's going to get.
2010-10-20 22:30:35 +11:00
Tim Allen
f1009ec634 Update to v068r08 release.
byuu says:

This gets the basic new PPU skeleton up and running, still missing
a lot:
- Mode7
- direct color mode
- OAM color exemption (this one will impact performance negatively)
- vertical mosaic
- horizontal mosaic (this one may impact performance negatively)
- offset per tile
- interlace
- hires
- pseudo-hires

But it's correct enough to play most games okay.

So far, the new PPU is about 11% faster on my Atom, and 17% faster on my
E8400. I was hoping for more, but the window masking and sprite
calculation is just kicking my ass.

The 11/17 figure is total emulator overhead, so that means raw PPU vs
PPU, the new one is at least 22-34% faster than the old one.

I don't really have any ideas for additional optimizations. I'm even
using little-endian word reads where applicable. But at any rate, I need
to get all the above implemented correctly before trying to push
optimizations even further.
2010-10-20 22:30:35 +11:00
Tim Allen
0bf6c40d1f Update to v068r07 release.
(there was no r06 release posted to the WIP thread)

byuu says:

New PPU renderer is coming along. Lots of new ideas, especially with
regards to the way the background renders in tiles rather than in
pixels. That skips the need for tile caching and compares, and it even
gets scrolling right.

The sprite item+tile lists are computing, but they are not rendering
yet.

It's a good deal faster for now, obviously, because 90% of the PPU
features are missing.
2010-10-20 22:30:35 +11:00
Tim Allen
2bafd18a5a Update to v068r05 release.
byuu says:

Started over again on the new S-PPU, heh. Three hours wasted last night
I guess.
I wanted to make the new one more like the accurate core in its
structure: multiple class instances for each background. It makes the
code easier to read, results in less structure insanity
(regs.main_enabled[bg] -> main_enabled), and will probably make it a tad
easier to parallelize if we want to go that route eg for the ARM.

Still very incomplete.
2010-10-20 22:30:35 +11:00
Tim Allen
c434e8a0d5 Update to v068r04 release.
(there was no r03 release posted to the WIP thread)

byuu says:

This should provide hardware-accurate mosaic support in the accurate
renderer, with the exception that I'm still not sure what mid-frame
vertical mosaic or mid-scanline horizontal mosaic writes do. Either the
code I have is correct, or it bypasses the mosaic adjust and gives the
exact H/V positions.

I've also renamed the fast folder to alternative (thinking about naming
it simply alt instead), and started on a brand new PPU renderer. So far
it's just a barebones setup with some MMIO support and VRAM/OAM/CGRAM
writing. I'm not even confident that I can get this to be faster than
the current scanline renderer, but it's the only avenue that we have
left for any kind of significant bsnes speedup, so I have to try. I'm
going to finish up the MMIO stuff first, that way we have a clean slate
with no actual rendering. And then from here we can try various
different approaches.
2010-10-20 22:30:35 +11:00
Tim Allen
39b1acb177 Update to v068r02 release.
byuu says:

This adds mosaic improvements to the S-PPU dot renderer. Specifically,
it eliminates the mosaic_table entirely, and performs mosaic adjustment
per pixel instead. It also moves from a mosaic countdown for mosaic Y to
a mosaic counter (incrementing).

In the process, I realized Sim Earth's map was broken, so I fixed that.
In doing so, I also fixed my old Mode7 demo that was always off-by-one,
causing different results on real hardware versus emulation. But then
I broke both Final Fantasy 5 and Air Strike Patrol effects that use
Mode7 but no mosaic.

I'm not really sure what's going on, but I think I am close. This is the
first time I can reproduce the Mode7 test ROM results without screwing
with M7Y which was obviously wrong. I think that somehow a mosaic >=
1 is glitching the Ycounter for the BG layers to tick one extra time.

There's a workaround that's not very nice to get everything going right
now. It could very well be that the workaround is hardware accurate, but
I can't help but feel there's a more eloquent way of doing this.
2010-10-20 22:30:35 +11:00
Tim Allen
920d139302 Update to v068r01 release.
byuu says:

This adds RTS/CTS support to the serial communications emulation. Okay,
well the PC acts as if it is always ready, because it always is even on
the real thing, but the PC-waiting-for-SNES side works.

Source only, hardware communication only works on OS X and Linux
(Windows serial communication is totally different, I don't feel like
writing a Windows version), more documentation will come later.
2010-10-20 22:30:34 +11:00
2441 changed files with 269301 additions and 182356 deletions

3
.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
purify/*.o
purify/purify
purify/analyze-gba

107
bsnes/Makefile Executable file → Normal file
View File

@@ -1,35 +1,59 @@
include nall/Makefile
snes := snes
profile := compatibility
ui := qt
fc := fc
sfc := sfc
gb := gb
gba := gba
nds := nds
profile := accuracy
target := ethos
# options += debugger
# arch := win32
# console := true
# compiler
c := $(compiler) -std=gnu99
cpp := $(subst cc,++,$(compiler)) -std=gnu++0x
flags := -O3 -fomit-frame-pointer -I. -I$(snes)
link :=
objects :=
flags := -I. -O3 -fomit-frame-pointer
link := -s
objects := libco
# profile-guided instrumentation
# flags += -fprofile-generate
# link += -lgcov
# profile-guided optimization mode
# pgo := instrument
# pgo := optimize
# profile-guided optimization
# flags += -fprofile-use
ifeq ($(pgo),instrument)
flags += -fprofile-generate
link += -lgcov
else ifeq ($(pgo),optimize)
flags += -fprofile-use
endif
# platform
ifeq ($(platform),x)
link += -s -ldl -lX11 -lXext
flags += -march=native
link += -ldl -lX11 -lXext
else ifeq ($(platform),osx)
else ifeq ($(platform),win)
link += -mwindows
# link += -mconsole
link += -mthreads -s -luuid -lkernel32 -luser32 -lgdi32 -lshell32
link += -enable-stdcall-fixup -Wl,-enable-auto-import -Wl,-enable-runtime-pseudo-reloc
ifeq ($(arch),win32)
flags += -m32
link += -m32
endif
ifeq ($(console),true)
link += -mconsole
else
link += -mwindows
endif
link += -mthreads -luuid -lkernel32 -luser32 -lgdi32 -lcomctl32 -lcomdlg32 -lshell32 -lole32
link += -Wl,-enable-auto-import -Wl,-enable-runtime-pseudo-reloc
else
unknown_platform: help;
endif
ui := target-$(target)
# implicit rules
compile = \
$(strip \
@@ -45,35 +69,13 @@ compile = \
all: build;
include $(snes)/Makefile
include $(ui)/Makefile
obj/libco.o: libco/libco.c libco/*
objects := $(patsubst %,obj/%.o,$(objects))
include $(ui)/Makefile
flags := $(flags) $(foreach o,$(call strupper,$(options)),-D$o)
# targets
build: ui_build $(objects)
ifeq ($(platform),osx)
test -d ../bsnes-$(profile).app || mkdir -p ../bsnes-$(profile).app/Contents/MacOS
$(strip $(cpp) -o ../bsnes-$(profile).app/Contents/MacOS/bsnes-$(profile) $(objects) $(link))
else
$(strip $(cpp) -o out/bsnes-$(profile) $(objects) $(link))
endif
install:
ifeq ($(platform),x)
install -D -m 755 out/bsnes-$(profile) $(DESTDIR)$(prefix)/bin/bsnes-$(profile)
install -D -m 644 qt/data/bsnes.png $(DESTDIR)$(prefix)/share/pixmaps/bsnes.png
install -D -m 644 qt/data/bsnes.desktop $(DESTDIR)$(prefix)/share/applications/bsnes.desktop
endif
uninstall:
ifeq ($(platform),x)
rm $(DESTDIR)$(prefix)/bin/bsnes-$(profile)
rm $(DESTDIR)$(prefix)/share/pixmaps/bsnes.png
rm $(DESTDIR)$(prefix)/share/applications/bsnes.desktop
endif
clean: ui_clean
clean:
-@$(call delete,obj/*.o)
-@$(call delete,obj/*.a)
-@$(call delete,obj/*.so)
@@ -86,7 +88,24 @@ clean: ui_clean
-@$(call delete,*.pdb)
-@$(call delete,*.manifest)
archive-all:
tar -cjf bsnes-`date +%Y%m%d`.tar.bz2 launcher libco nall obj out qt ruby snes Makefile sync.sh cc.bat clean.bat
sync:
if [ -d ./libco ]; then rm -r ./libco; fi
if [ -d ./nall ]; then rm -r ./nall; fi
if [ -d ./ruby ]; then rm -r ./ruby; fi
if [ -d ./phoenix ]; then rm -r ./phoenix; fi
cp -r ../libco ./libco
cp -r ../nall ./nall
cp -r ../ruby ./ruby
cp -r ../phoenix ./phoenix
rm -r libco/doc
rm -r libco/test
rm -r nall/test
rm -r ruby/_test
rm -r phoenix/nall
rm -r phoenix/test
archive:
if [ -f bsnes.tar.xz ]; then rm bsnes.tar.xz; fi
tar -cJf bsnes.tar.xz `ls`
help:;

View File

@@ -1,2 +0,0 @@
@mingw32-make -j 2
@pause

View File

@@ -1 +0,0 @@
@mingw32-make clean

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity type="win32" name="bsnes" version="1.0.0.0" processorArchitecture="*"/>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"/>
</dependentAssembly>
</dependency>
</assembly>

View File

0
bsnes/launcher/bsnes.ico → bsnes/data/bsnes.ico Executable file → Normal file
View File

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 22 KiB

0
bsnes/qt/data/bsnes.png → bsnes/data/bsnes.png Executable file → Normal file
View File

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

105898
bsnes/data/cheats.xml Normal file

File diff suppressed because it is too large Load Diff

3812
bsnes/data/laevateinn.hpp Normal file

File diff suppressed because it is too large Load Diff

137
bsnes/emulator/emulator.hpp Normal file
View File

@@ -0,0 +1,137 @@
#ifndef EMULATOR_HPP
#define EMULATOR_HPP
namespace Emulator {
static const char Name[] = "bsnes";
static const char Version[] = "091";
static const char Author[] = "byuu";
static const char License[] = "GPLv3";
}
#include <nall/platform.hpp>
#include <nall/algorithm.hpp>
#include <nall/directory.hpp>
#include <nall/dl.hpp>
#include <nall/dsp.hpp>
#include <nall/endian.hpp>
#include <nall/file.hpp>
#include <nall/function.hpp>
#include <nall/priority-queue.hpp>
#include <nall/property.hpp>
#include <nall/random.hpp>
#include <nall/serializer.hpp>
#include <nall/sha256.hpp>
#include <nall/stdint.hpp>
#include <nall/string.hpp>
#include <nall/utility.hpp>
#include <nall/varint.hpp>
#include <nall/vector.hpp>
#include <nall/stream/memory.hpp>
#include <nall/stream/vector.hpp>
using namespace nall;
#include "interface.hpp"
//debugging function hook:
//no overhead (and no debugger invocation) if not compiled with -DDEBUGGER
//wraps testing of function to allow invocation without a defined callback
template<typename T> struct hook;
template<typename R, typename... P> struct hook<R (P...)> {
function<R (P...)> callback;
R operator()(P... p) const {
#if defined(DEBUGGER)
if(callback) return callback(std::forward<P>(p)...);
#endif
return R();
}
hook() {}
hook(const hook &hook) { callback = hook.callback; }
hook(void *function) { callback = function; }
hook(R (*function)(P...)) { callback = function; }
template<typename C> hook(R (C::*function)(P...), C *object) { callback = {function, object}; }
template<typename C> hook(R (C::*function)(P...) const, C *object) { callback = {function, object}; }
template<typename L> hook(const L& function) { callback = function; }
hook& operator=(const hook& hook) { callback = hook.callback; return *this; }
};
#if defined(DEBUGGER)
#define privileged public
#else
#define privileged private
#endif
typedef int1_t int1;
typedef int2_t int2;
typedef int3_t int3;
typedef int4_t int4;
typedef int5_t int5;
typedef int6_t int6;
typedef int7_t int7;
typedef int8_t int8;
typedef int9_t int9;
typedef int10_t int10;
typedef int11_t int11;
typedef int12_t int12;
typedef int13_t int13;
typedef int14_t int14;
typedef int15_t int15;
typedef int16_t int16;
typedef int17_t int17;
typedef int18_t int18;
typedef int19_t int19;
typedef int20_t int20;
typedef int21_t int21;
typedef int22_t int22;
typedef int23_t int23;
typedef int24_t int24;
typedef int25_t int25;
typedef int26_t int26;
typedef int27_t int27;
typedef int28_t int28;
typedef int29_t int29;
typedef int30_t int30;
typedef int31_t int31;
typedef int32_t int32;
typedef int64_t int64;
typedef uint1_t uint1;
typedef uint2_t uint2;
typedef uint3_t uint3;
typedef uint4_t uint4;
typedef uint5_t uint5;
typedef uint6_t uint6;
typedef uint7_t uint7;
typedef uint8_t uint8;
typedef uint9_t uint9;
typedef uint10_t uint10;
typedef uint11_t uint11;
typedef uint12_t uint12;
typedef uint13_t uint13;
typedef uint14_t uint14;
typedef uint15_t uint15;
typedef uint16_t uint16;
typedef uint17_t uint17;
typedef uint18_t uint18;
typedef uint19_t uint19;
typedef uint20_t uint20;
typedef uint21_t uint21;
typedef uint22_t uint22;
typedef uint23_t uint23;
typedef uint24_t uint24;
typedef uint25_t uint25;
typedef uint26_t uint26;
typedef uint27_t uint27;
typedef uint28_t uint28;
typedef uint29_t uint29;
typedef uint30_t uint30;
typedef uint31_t uint31;
typedef uint32_t uint32;
typedef uint_t<33> uint33;
typedef uint64_t uint64;
typedef varuint_t<unsigned> varuint;
#endif

View File

@@ -0,0 +1,118 @@
#ifndef EMULATOR_INTERFACE_HPP
#define EMULATOR_INTERFACE_HPP
namespace Emulator {
struct Interface {
struct Information {
string name;
unsigned width;
unsigned height;
bool overscan;
double aspectRatio;
bool resettable;
struct Capability {
bool states;
bool cheats;
} capability;
} information;
struct Media {
unsigned id;
string name;
string type;
string load;
};
vector<Media> media;
struct Device {
unsigned id;
unsigned portmask;
string name;
struct Input {
unsigned id;
unsigned type; //0 = digital, 1 = analog (relative), 2 = analog (absolute)
string name;
unsigned guid;
};
vector<Input> input;
vector<unsigned> order;
};
struct Port {
unsigned id;
string name;
vector<Device> device;
};
vector<Port> port;
struct Bind {
virtual void loadRequest(unsigned, const string&, const string&) {}
virtual void loadRequest(unsigned, const string&) {}
virtual void saveRequest(unsigned, const string&) {}
virtual uint32_t videoColor(unsigned, uint16_t, uint16_t, uint16_t) { return 0u; }
virtual void videoRefresh(const uint32_t*, unsigned, unsigned, unsigned) {}
virtual void audioSample(int16_t, int16_t) {}
virtual int16_t inputPoll(unsigned, unsigned, unsigned) { return 0; }
virtual unsigned dipSettings(const XML::Node&) { return 0; }
virtual string path(unsigned) { return ""; }
virtual void notify(const string &text) { print(text, "\n"); }
} *bind;
//callback bindings (provided by user interface)
void loadRequest(unsigned id, const string &name, const string &type) { return bind->loadRequest(id, name, type); }
void loadRequest(unsigned id, const string &path) { return bind->loadRequest(id, path); }
void saveRequest(unsigned id, const string &path) { return bind->saveRequest(id, path); }
uint32_t videoColor(unsigned source, uint16_t red, uint16_t green, uint16_t blue) { return bind->videoColor(source, red, green, blue); }
void videoRefresh(const uint32_t *data, unsigned pitch, unsigned width, unsigned height) { return bind->videoRefresh(data, pitch, width, height); }
void audioSample(int16_t lsample, int16_t rsample) { return bind->audioSample(lsample, rsample); }
int16_t inputPoll(unsigned port, unsigned device, unsigned input) { return bind->inputPoll(port, device, input); }
unsigned dipSettings(const XML::Node &node) { return bind->dipSettings(node); }
string path(unsigned group) { return bind->path(group); }
template<typename... Args> void notify(Args&... args) { return bind->notify({std::forward<Args>(args)...}); }
//information
virtual double videoFrequency() = 0;
virtual double audioFrequency() = 0;
//media interface
virtual bool loaded() { return false; }
virtual string sha256() { return ""; }
virtual unsigned group(unsigned id) = 0;
virtual void load(unsigned id, const string &manifest) {}
virtual void save() {}
virtual void load(unsigned id, const stream &memory, const string &markup = "") {}
virtual void save(unsigned id, const stream &memory) {}
virtual void unload() {}
//system interface
virtual void connect(unsigned port, unsigned device) {}
virtual void power() {}
virtual void reset() {}
virtual void run() {}
//time functions
virtual bool rtc() { return false; }
virtual void rtcsync() {}
//state functions
virtual serializer serialize() = 0;
virtual bool unserialize(serializer&) = 0;
//cheat functions
virtual void cheatSet(const lstring& = lstring{}) {}
//utility functions
virtual void paletteUpdate() {}
//debugger functions
virtual bool tracerEnable(bool) { return false; }
virtual void exportMemory() {}
Interface() : bind(nullptr) {}
};
}
#endif

16
bsnes/fc/Makefile Normal file
View File

@@ -0,0 +1,16 @@
fc_objects := fc-interface fc-system fc-scheduler fc-input
fc_objects += fc-memory fc-cartridge fc-cpu fc-apu fc-ppu
fc_objects += fc-cheat fc-video
objects += $(fc_objects)
obj/fc-interface.o: $(fc)/interface/interface.cpp $(call rwildcard,$(fc)/interface/)
obj/fc-system.o: $(fc)/system/system.cpp $(call rwildcard,$(fc)/system/)
obj/fc-scheduler.o: $(fc)/scheduler/scheduler.cpp $(call rwildcard,$(fc)/scheduler/)
obj/fc-input.o: $(fc)/input/input.cpp $(call rwildcard,$(fc)/input/)
obj/fc-memory.o: $(fc)/memory/memory.cpp $(call rwildcard,$(fc)/memory/)
obj/fc-cartridge.o: $(fc)/cartridge/cartridge.cpp $(call rwildcard,$(fc)/cartridge/)
obj/fc-cpu.o: $(fc)/cpu/cpu.cpp $(call rwildcard,$(fc)/cpu/)
obj/fc-apu.o: $(fc)/apu/apu.cpp $(call rwildcard,$(fc)/apu/)
obj/fc-ppu.o: $(fc)/ppu/ppu.cpp $(call rwildcard,$(fc)/ppu/)
obj/fc-cheat.o: $(fc)/cheat/cheat.cpp $(call rwildcard,$(fc)/cheat/)
obj/fc-video.o: $(fc)/video/video.cpp $(call rwildcard,$(fc)/video/)

329
bsnes/fc/apu/apu.cpp Normal file
View File

@@ -0,0 +1,329 @@
#include <fc/fc.hpp>
namespace Famicom {
#include "envelope.cpp"
#include "sweep.cpp"
#include "pulse.cpp"
#include "triangle.cpp"
#include "noise.cpp"
#include "dmc.cpp"
#include "serialization.cpp"
APU apu;
const uint8 APU::length_counter_table[32] = {
0x0a, 0xfe, 0x14, 0x02, 0x28, 0x04, 0x50, 0x06, 0xa0, 0x08, 0x3c, 0x0a, 0x0e, 0x0c, 0x1a, 0x0e,
0x0c, 0x10, 0x18, 0x12, 0x30, 0x14, 0x60, 0x16, 0xc0, 0x18, 0x48, 0x1a, 0x10, 0x1c, 0x20, 0x1e,
};
const uint16 APU::ntsc_noise_period_table[16] = {
4, 8, 16, 32, 64, 96, 128, 160, 202, 254, 380, 508, 762, 1016, 2034, 4068,
};
const uint16 APU::pal_noise_period_table[16] = {
4, 7, 14, 30, 60, 88, 118, 148, 188, 236, 354, 472, 708, 944, 1890, 3778,
};
const uint16 APU::ntsc_dmc_period_table[16] = {
428, 380, 340, 320, 286, 254, 226, 214, 190, 160, 142, 128, 106, 84, 72, 54,
};
const uint16 APU::pal_dmc_period_table[16] = {
398, 354, 316, 298, 276, 236, 210, 198, 176, 148, 132, 118, 98, 78, 66, 50,
};
void APU::Main() {
apu.main();
}
void APU::main() {
while(true) {
if(scheduler.sync == Scheduler::SynchronizeMode::All) {
scheduler.exit(Scheduler::ExitReason::SynchronizeEvent);
}
unsigned pulse_output, triangle_output, noise_output, dmc_output;
pulse_output = pulse[0].clock();
pulse_output += pulse[1].clock();
triangle_output = triangle.clock();
noise_output = noise.clock();
dmc_output = dmc.clock();
clock_frame_counter_divider();
signed output = pulse_dac[pulse_output] + dmc_triangle_noise_dac[dmc_output][triangle_output][noise_output];
output = filter.run_hipass_strong(output);
output += cartridge_sample;
output = filter.run_hipass_weak(output);
//output = filter.run_lopass(output);
output = sclamp<16>(output);
interface->audioSample(output, output);
tick();
}
}
void APU::tick() {
clock += 12;
if(clock >= 0 && scheduler.sync != Scheduler::SynchronizeMode::All) co_switch(cpu.thread);
}
void APU::set_irq_line() {
cpu.set_irq_apu_line(frame.irq_pending || dmc.irq_pending);
}
void APU::set_sample(int16 sample) {
cartridge_sample = sample;
}
void APU::power() {
filter.hipass_strong = 0;
filter.hipass_weak = 0;
filter.lopass = 0;
pulse[0].power();
pulse[1].power();
triangle.power();
noise.power();
dmc.power();
}
void APU::reset() {
create(APU::Main, 21477272);
pulse[0].reset();
pulse[1].reset();
triangle.reset();
noise.reset();
dmc.reset();
frame.irq_pending = 0;
frame.mode = 0;
frame.counter = 0;
frame.divider = 1;
enabled_channels = 0;
cartridge_sample = 0;
set_irq_line();
}
uint8 APU::read(uint16 addr) {
if(addr == 0x4015) {
uint8 result = 0x00;
result |= pulse[0].length_counter ? 0x01 : 0;
result |= pulse[1].length_counter ? 0x02 : 0;
result |= triangle.length_counter ? 0x04 : 0;
result |= noise.length_counter ? 0x08 : 0;
result |= dmc.length_counter ? 0x10 : 0;
result |= frame.irq_pending ? 0x40 : 0;
result |= dmc.irq_pending ? 0x80 : 0;
frame.irq_pending = false;
set_irq_line();
return result;
}
return cpu.mdr();
}
void APU::write(uint16 addr, uint8 data) {
const unsigned n = (addr >> 2) & 1; //pulse#
switch(addr) {
case 0x4000: case 0x4004:
pulse[n].duty = data >> 6;
pulse[n].envelope.loop_mode = data & 0x20;
pulse[n].envelope.use_speed_as_volume = data & 0x10;
pulse[n].envelope.speed = data & 0x0f;
break;
case 0x4001: case 0x4005:
pulse[n].sweep.enable = data & 0x80;
pulse[n].sweep.period = (data & 0x70) >> 4;
pulse[n].sweep.decrement = data & 0x08;
pulse[n].sweep.shift = data & 0x07;
pulse[n].sweep.reload = true;
break;
case 0x4002: case 0x4006:
pulse[n].period = (pulse[n].period & 0x0700) | (data << 0);
pulse[n].sweep.pulse_period = (pulse[n].sweep.pulse_period & 0x0700) | (data << 0);
break;
case 0x4003: case 0x4007:
pulse[n].period = (pulse[n].period & 0x00ff) | (data << 8);
pulse[n].sweep.pulse_period = (pulse[n].sweep.pulse_period & 0x00ff) | (data << 8);
pulse[n].duty_counter = 7;
pulse[n].envelope.reload_decay = true;
if(enabled_channels & (1 << n)) {
pulse[n].length_counter = length_counter_table[(data >> 3) & 0x1f];
}
break;
case 0x4008:
triangle.halt_length_counter = data & 0x80;
triangle.linear_length = data & 0x7f;
break;
case 0x400a:
triangle.period = (triangle.period & 0x0700) | (data << 0);
break;
case 0x400b:
triangle.period = (triangle.period & 0x00ff) | (data << 8);
triangle.reload_linear = true;
if(enabled_channels & (1 << 2)) {
triangle.length_counter = length_counter_table[(data >> 3) & 0x1f];
}
break;
case 0x400c:
noise.envelope.loop_mode = data & 0x20;
noise.envelope.use_speed_as_volume = data & 0x10;
noise.envelope.speed = data & 0x0f;
break;
case 0x400e:
noise.short_mode = data & 0x80;
noise.period = data & 0x0f;
break;
case 0x400f:
noise.envelope.reload_decay = true;
if(enabled_channels & (1 << 3)) {
noise.length_counter = length_counter_table[(data >> 3) & 0x1f];
}
break;
case 0x4010:
dmc.irq_enable = data & 0x80;
dmc.loop_mode = data & 0x40;
dmc.period = data & 0x0f;
dmc.irq_pending = dmc.irq_pending && dmc.irq_enable && !dmc.loop_mode;
set_irq_line();
break;
case 0x4011:
dmc.dac_latch = data & 0x7f;
break;
case 0x4012:
dmc.addr_latch = data;
break;
case 0x4013:
dmc.length_latch = data;
break;
case 0x4015:
if((data & 0x01) == 0) pulse[0].length_counter = 0;
if((data & 0x02) == 0) pulse[1].length_counter = 0;
if((data & 0x04) == 0) triangle.length_counter = 0;
if((data & 0x08) == 0) noise.length_counter = 0;
(data & 0x10) ? dmc.start() : dmc.stop();
dmc.irq_pending = false;
set_irq_line();
enabled_channels = data & 0x1f;
break;
case 0x4017:
frame.mode = data >> 6;
frame.counter = 0;
if(frame.mode & 2) clock_frame_counter();
if(frame.mode & 1) {
frame.irq_pending = false;
set_irq_line();
}
frame.divider = FrameCounter::NtscPeriod;
break;
}
}
signed APU::Filter::run_hipass_strong(signed sample) {
hipass_strong += ((((int64)sample << 16) - (hipass_strong >> 16)) * HiPassStrong) >> 16;
return sample - (hipass_strong >> 32);
}
signed APU::Filter::run_hipass_weak(signed sample) {
hipass_weak += ((((int64)sample << 16) - (hipass_weak >> 16)) * HiPassWeak) >> 16;
return sample - (hipass_weak >> 32);
}
signed APU::Filter::run_lopass(signed sample) {
lopass += ((((int64)sample << 16) - (lopass >> 16)) * LoPass) >> 16;
return (lopass >> 32);
}
void APU::clock_frame_counter() {
frame.counter++;
if(frame.counter & 1) {
pulse[0].clock_length();
pulse[0].sweep.clock(0);
pulse[1].clock_length();
pulse[1].sweep.clock(1);
triangle.clock_length();
noise.clock_length();
}
pulse[0].envelope.clock();
pulse[1].envelope.clock();
triangle.clock_linear_length();
noise.envelope.clock();
if(frame.counter == 0) {
if(frame.mode & 2) frame.divider += FrameCounter::NtscPeriod;
if(frame.mode == 0) {
frame.irq_pending = true;
set_irq_line();
}
}
}
void APU::clock_frame_counter_divider() {
frame.divider -= 2;
if(frame.divider <= 0) {
clock_frame_counter();
frame.divider += FrameCounter::NtscPeriod;
}
}
APU::APU() {
for(unsigned amp = 0; amp < 32; amp++) {
if(amp == 0) {
pulse_dac[amp] = 0;
} else {
pulse_dac[amp] = 16384.0 * 95.88 / (8128.0 / amp + 100.0);
}
}
for(unsigned dmc_amp = 0; dmc_amp < 128; dmc_amp++) {
for(unsigned triangle_amp = 0; triangle_amp < 16; triangle_amp++) {
for(unsigned noise_amp = 0; noise_amp < 16; noise_amp++) {
if(dmc_amp == 0 && triangle_amp == 0 && noise_amp == 0) {
dmc_triangle_noise_dac[dmc_amp][triangle_amp][noise_amp] = 0;
} else {
dmc_triangle_noise_dac[dmc_amp][triangle_amp][noise_amp]
= 16384.0 * 159.79 / (100.0 + 1.0 / (triangle_amp / 8227.0 + noise_amp / 12241.0 + dmc_amp / 22638.0));
}
}
}
}
}
}

65
bsnes/fc/apu/apu.hpp Normal file
View File

@@ -0,0 +1,65 @@
struct APU : Thread {
static void Main();
void main();
void tick();
void set_irq_line();
void set_sample(int16 sample);
void power();
void reset();
uint8 read(uint16 addr);
void write(uint16 addr, uint8 data);
void serialize(serializer&);
APU();
struct Filter {
enum : signed { HiPassStrong = 225574, HiPassWeak = 57593, LoPass = 86322413 };
int64 hipass_strong;
int64 hipass_weak;
int64 lopass;
signed run_hipass_strong(signed sample);
signed run_hipass_weak(signed sample);
signed run_lopass(signed sample);
void serialize(serializer&);
} filter;
#include "envelope.hpp"
#include "sweep.hpp"
#include "pulse.hpp"
#include "triangle.hpp"
#include "noise.hpp"
#include "dmc.hpp"
struct FrameCounter {
enum : unsigned { NtscPeriod = 14915 }; //~(21.477MHz / 6 / 240hz)
bool irq_pending;
uint2 mode;
uint2 counter;
signed divider;
void serialize(serializer&);
} frame;
void clock_frame_counter();
void clock_frame_counter_divider();
uint8 enabled_channels;
int16 cartridge_sample;
int16 pulse_dac[32];
int16 dmc_triangle_noise_dac[128][16][16];
static const uint8 length_counter_table[32];
static const uint16 ntsc_dmc_period_table[16];
static const uint16 pal_dmc_period_table[16];
static const uint16 ntsc_noise_period_table[16];
static const uint16 pal_noise_period_table[16];
};
extern APU apu;

117
bsnes/fc/apu/dmc.cpp Normal file
View File

@@ -0,0 +1,117 @@
void APU::DMC::start() {
if(length_counter == 0) {
read_addr = 0x4000 + (addr_latch << 6);
length_counter = (length_latch << 4) + 1;
}
}
void APU::DMC::stop() {
length_counter = 0;
dma_delay_counter = 0;
cpu.set_rdy_line(1);
cpu.set_rdy_addr({ false, 0u });
}
uint8 APU::DMC::clock() {
uint8 result = dac_latch;
if(dma_delay_counter > 0) {
dma_delay_counter--;
if(dma_delay_counter == 1) {
cpu.set_rdy_addr({ true, uint16(0x8000 | read_addr) });
} else if(dma_delay_counter == 0) {
cpu.set_rdy_line(1);
cpu.set_rdy_addr({ false, 0u });
dma_buffer = cpu.mdr();
have_dma_buffer = true;
length_counter--;
read_addr++;
if(length_counter == 0) {
if(loop_mode) {
start();
} else if(irq_enable) {
irq_pending = true;
apu.set_irq_line();
}
}
}
}
if(--period_counter == 0) {
if(have_sample) {
signed delta = (((sample >> bit_counter) & 1) << 2) - 2;
unsigned data = dac_latch + delta;
if((data & 0x80) == 0) dac_latch = data;
}
if(++bit_counter == 0) {
if(have_dma_buffer) {
have_sample = true;
sample = dma_buffer;
have_dma_buffer = false;
} else {
have_sample = false;
}
}
period_counter = ntsc_dmc_period_table[period];
}
if(length_counter > 0 && have_dma_buffer == false && dma_delay_counter == 0) {
cpu.set_rdy_line(0);
dma_delay_counter = 4;
}
return result;
}
void APU::DMC::power() {
}
void APU::DMC::reset() {
length_counter = 0;
irq_pending = 0;
period = 0;
period_counter = ntsc_dmc_period_table[0];
irq_enable = 0;
loop_mode = 0;
dac_latch = 0;
addr_latch = 0;
length_latch = 0;
read_addr = 0;
dma_delay_counter = 0;
bit_counter = 0;
have_dma_buffer = 0;
dma_buffer = 0;
have_sample = 0;
sample = 0;
}
void APU::DMC::serialize(serializer &s) {
s.integer(length_counter);
s.integer(irq_pending);
s.integer(period);
s.integer(period_counter);
s.integer(irq_enable);
s.integer(loop_mode);
s.integer(dac_latch);
s.integer(addr_latch);
s.integer(length_latch);
s.integer(read_addr);
s.integer(dma_delay_counter);
s.integer(bit_counter);
s.integer(have_dma_buffer);
s.integer(dma_buffer);
s.integer(have_sample);
s.integer(sample);
}

32
bsnes/fc/apu/dmc.hpp Normal file
View File

@@ -0,0 +1,32 @@
struct DMC {
unsigned length_counter;
bool irq_pending;
uint4 period;
unsigned period_counter;
bool irq_enable;
bool loop_mode;
uint8 dac_latch;
uint8 addr_latch;
uint8 length_latch;
uint15 read_addr;
unsigned dma_delay_counter;
uint3 bit_counter;
bool have_dma_buffer;
uint8 dma_buffer;
bool have_sample;
uint8 sample;
void start();
void stop();
uint8 clock();
void power();
void reset();
void serialize(serializer&);
} dmc;

39
bsnes/fc/apu/envelope.cpp Normal file
View File

@@ -0,0 +1,39 @@
unsigned APU::Envelope::volume() const {
return use_speed_as_volume ? speed : decay_volume;
}
void APU::Envelope::clock() {
if(reload_decay) {
reload_decay = false;
decay_volume = 0x0f;
decay_counter = speed + 1;
return;
}
if(--decay_counter == 0) {
decay_counter = speed + 1;
if(decay_volume || loop_mode) decay_volume--;
}
}
void APU::Envelope::power() {
}
void APU::Envelope::reset() {
speed = 0;
use_speed_as_volume = 0;
loop_mode = 0;
reload_decay = 0;
decay_counter = 0;
decay_volume = 0;
}
void APU::Envelope::serialize(serializer &s) {
s.integer(speed);
s.integer(use_speed_as_volume);
s.integer(loop_mode);
s.integer(reload_decay);
s.integer(decay_counter);
s.integer(decay_volume);
}

16
bsnes/fc/apu/envelope.hpp Normal file
View File

@@ -0,0 +1,16 @@
struct Envelope {
uint4 speed;
bool use_speed_as_volume;
bool loop_mode;
bool reload_decay;
uint8 decay_counter;
uint4 decay_volume;
unsigned volume() const;
void clock();
void power();
void reset();
void serialize(serializer&);
};

57
bsnes/fc/apu/noise.cpp Normal file
View File

@@ -0,0 +1,57 @@
void APU::Noise::clock_length() {
if(envelope.loop_mode == 0) {
if(length_counter > 0) length_counter--;
}
}
uint8 APU::Noise::clock() {
if(length_counter == 0) return 0;
uint8 result = (lfsr & 1) ? envelope.volume() : 0;
if(--period_counter == 0) {
unsigned feedback;
if(short_mode) {
feedback = ((lfsr >> 0) & 1) ^ ((lfsr >> 6) & 1);
} else {
feedback = ((lfsr >> 0) & 1) ^ ((lfsr >> 1) & 1);
}
lfsr = (lfsr >> 1) | (feedback << 14);
period_counter = apu.ntsc_noise_period_table[period];
}
return result;
}
void APU::Noise::power() {
}
void APU::Noise::reset() {
length_counter = 0;
envelope.speed = 0;
envelope.use_speed_as_volume = 0;
envelope.loop_mode = 0;
envelope.reload_decay = 0;
envelope.decay_counter = 0;
envelope.decay_volume = 0;
period = 0;
period_counter = 1;
short_mode = 0;
lfsr = 1;
}
void APU::Noise::serialize(serializer &s) {
s.integer(length_counter);
envelope.serialize(s);
s.integer(period);
s.integer(period_counter);
s.integer(short_mode);
s.integer(lfsr);
}

18
bsnes/fc/apu/noise.hpp Normal file
View File

@@ -0,0 +1,18 @@
struct Noise {
unsigned length_counter;
Envelope envelope;
uint4 period;
unsigned period_counter;
bool short_mode;
uint15 lfsr;
void clock_length();
uint8 clock();
void power();
void reset();
void serialize(serializer&);
} noise;

51
bsnes/fc/apu/pulse.cpp Normal file
View File

@@ -0,0 +1,51 @@
void APU::Pulse::clock_length() {
if(envelope.loop_mode == 0) {
if(length_counter) length_counter--;
}
}
uint8 APU::Pulse::clock() {
if(sweep.check_period() == false) return 0;
if(length_counter == 0) return 0;
static const unsigned duty_table[] = { 1, 2, 4, 6 };
uint8 result = (duty_counter < duty_table[duty]) ? envelope.volume() : 0;
if(sweep.pulse_period < 0x008) result = 0;
if(--period_counter == 0) {
period_counter = (sweep.pulse_period + 1) * 2;
duty_counter++;
}
return result;
}
void APU::Pulse::power() {
envelope.power();
sweep.power();
}
void APU::Pulse::reset() {
envelope.reset();
sweep.reset();
length_counter = 0;
duty = 0;
duty_counter = 0;
period = 0;
period_counter = 1;
}
void APU::Pulse::serialize(serializer &s) {
s.integer(length_counter);
envelope.serialize(s);
sweep.serialize(s);
s.integer(duty);
s.integer(duty_counter);
s.integer(period);
s.integer(period_counter);
}

20
bsnes/fc/apu/pulse.hpp Normal file
View File

@@ -0,0 +1,20 @@
struct Pulse {
unsigned length_counter;
Envelope envelope;
Sweep sweep;
uint2 duty;
uint3 duty_counter;
uint11 period;
unsigned period_counter;
void clock_length();
bool check_period();
uint8 clock();
void power();
void reset();
void serialize(serializer&);
} pulse[2];

View File

@@ -0,0 +1,28 @@
void APU::serialize(serializer &s) {
Thread::serialize(s);
filter.serialize(s);
pulse[0].serialize(s);
pulse[1].serialize(s);
triangle.serialize(s);
dmc.serialize(s);
frame.serialize(s);
s.integer(enabled_channels);
s.integer(cartridge_sample);
}
void APU::Filter::serialize(serializer &s) {
s.integer(hipass_strong);
s.integer(hipass_weak);
s.integer(lopass);
}
void APU::FrameCounter::serialize(serializer &s) {
s.integer(irq_pending);
s.integer(mode);
s.integer(counter);
s.integer(divider);
}

53
bsnes/fc/apu/sweep.cpp Normal file
View File

@@ -0,0 +1,53 @@
bool APU::Sweep::check_period() {
if(pulse_period > 0x7ff) return false;
if(decrement == 0) {
if((pulse_period + (pulse_period >> shift)) & 0x800) return false;
}
return true;
}
void APU::Sweep::clock(unsigned channel) {
if(--counter == 0) {
counter = period + 1;
if(enable && shift && pulse_period > 8) {
signed delta = pulse_period >> shift;
if(decrement) {
pulse_period -= delta;
if(channel == 0) pulse_period--;
} else if((pulse_period + delta) < 0x800) {
pulse_period += delta;
}
}
}
if(reload) {
reload = false;
counter = period + 1;
}
}
void APU::Sweep::power() {
shift = 0;
decrement = 0;
period = 0;
counter = 1;
enable = 0;
reload = 0;
pulse_period = 0;
}
void APU::Sweep::reset() {
}
void APU::Sweep::serialize(serializer &s) {
s.integer(shift);
s.integer(decrement);
s.integer(period);
s.integer(counter);
s.integer(enable);
s.integer(reload);
s.integer(pulse_period);
}

16
bsnes/fc/apu/sweep.hpp Normal file
View File

@@ -0,0 +1,16 @@
struct Sweep {
uint8 shift;
bool decrement;
uint3 period;
uint8 counter;
bool enable;
bool reload;
uint11 pulse_period;
bool check_period();
void clock(unsigned channel);
void power();
void reset();
void serialize(serializer&);
};

58
bsnes/fc/apu/triangle.cpp Normal file
View File

@@ -0,0 +1,58 @@
void APU::Triangle::clock_length() {
if(halt_length_counter == 0) {
if(length_counter > 0) length_counter--;
}
}
void APU::Triangle::clock_linear_length() {
if(reload_linear) {
linear_length_counter = linear_length;
} else if(linear_length_counter) {
linear_length_counter--;
}
if(halt_length_counter == 0) reload_linear = false;
}
uint8 APU::Triangle::clock() {
uint8 result = step_counter & 0x0f;
if((step_counter & 0x10) == 0) result ^= 0x0f;
if(length_counter == 0 || linear_length_counter == 0) return result;
if(--period_counter == 0) {
step_counter++;
period_counter = period + 1;
}
return result;
}
void APU::Triangle::power() {
reset();
}
void APU::Triangle::reset() {
length_counter = 0;
linear_length = 0;
halt_length_counter = 0;
period = 0;
period_counter = 1;
step_counter = 0;
linear_length_counter = 0;
reload_linear = 0;
}
void APU::Triangle::serialize(serializer &s) {
s.integer(length_counter);
s.integer(linear_length);
s.integer(halt_length_counter);
s.integer(period);
s.integer(period_counter);
s.integer(step_counter);
s.integer(linear_length_counter);
s.integer(reload_linear);
}

21
bsnes/fc/apu/triangle.hpp Normal file
View File

@@ -0,0 +1,21 @@
struct Triangle {
unsigned length_counter;
uint8 linear_length;
bool halt_length_counter;
uint11 period;
unsigned period_counter;
uint5 step_counter;
uint8 linear_length_counter;
bool reload_linear;
void clock_length();
void clock_linear_length();
uint8 clock();
void power();
void reset();
void serialize(serializer&);
} triangle;

View File

@@ -0,0 +1,117 @@
//BANDAI-FCG
struct BandaiFCG : Board {
uint8 chr_bank[8];
uint8 prg_bank;
uint2 mirror;
bool irq_counter_enable;
uint16 irq_counter;
uint16 irq_latch;
void main() {
while(true) {
if(scheduler.sync == Scheduler::SynchronizeMode::All) {
scheduler.exit(Scheduler::ExitReason::SynchronizeEvent);
}
if(irq_counter_enable) {
if(--irq_counter == 0xffff) {
cpu.set_irq_line(1);
irq_counter_enable = false;
}
}
tick();
}
}
unsigned ciram_addr(unsigned addr) const {
switch(mirror) {
case 0: return ((addr & 0x0400) >> 0) | (addr & 0x03ff);
case 1: return ((addr & 0x0800) >> 1) | (addr & 0x03ff);
case 2: return 0x0000 | (addr & 0x03ff);
case 3: return 0x0400 | (addr & 0x03ff);
}
}
uint8 prg_read(unsigned addr) {
if(addr & 0x8000) {
bool region = addr & 0x4000;
unsigned bank = (region == 0 ? prg_bank : 0x0f);
return prgrom.read((bank << 14) | (addr & 0x3fff));
}
return cpu.mdr();
}
void prg_write(unsigned addr, uint8 data) {
if(addr >= 0x6000) {
switch(addr & 15) {
case 0x00: case 0x01: case 0x02: case 0x03:
case 0x04: case 0x05: case 0x06: case 0x07:
chr_bank[addr & 7] = data;
break;
case 0x08:
prg_bank = data & 0x0f;
break;
case 0x09:
mirror = data & 0x03;
break;
case 0x0a:
cpu.set_irq_line(0);
irq_counter_enable = data & 0x01;
irq_counter = irq_latch;
break;
case 0x0b:
irq_latch = (irq_latch & 0xff00) | (data << 0);
break;
case 0x0c:
irq_latch = (irq_latch & 0x00ff) | (data << 8);
break;
case 0x0d:
//TODO: serial EEPROM support
break;
}
}
}
uint8 chr_read(unsigned addr) {
if(addr & 0x2000) return ppu.ciram_read(ciram_addr(addr));
addr = (chr_bank[addr >> 10] << 10) | (addr & 0x03ff);
return Board::chr_read(addr);
}
void chr_write(unsigned addr, uint8 data) {
if(addr & 0x2000) return ppu.ciram_write(ciram_addr(addr), data);
addr = (chr_bank[addr >> 10] << 10) | (addr & 0x03ff);
return Board::chr_write(addr, data);
}
void power() {
reset();
}
void reset() {
for(auto &n : chr_bank) n = 0;
prg_bank = 0;
mirror = 0;
irq_counter_enable = 0;
irq_counter = 0;
irq_latch = 0;
}
void serialize(serializer &s) {
Board::serialize(s);
s.array(chr_bank);
s.integer(prg_bank);
s.integer(mirror);
s.integer(irq_counter_enable);
s.integer(irq_counter);
s.integer(irq_latch);
}
BandaiFCG(XML::Document &document) : Board(document) {
}
};

View File

@@ -0,0 +1,174 @@
#include "bandai-fcg.cpp"
#include "konami-vrc1.cpp"
#include "konami-vrc2.cpp"
#include "konami-vrc3.cpp"
#include "konami-vrc4.cpp"
#include "konami-vrc6.cpp"
#include "konami-vrc7.cpp"
#include "nes-axrom.cpp"
#include "nes-bnrom.cpp"
#include "nes-cnrom.cpp"
#include "nes-exrom.cpp"
#include "nes-fxrom.cpp"
#include "nes-gxrom.cpp"
#include "nes-hkrom.cpp"
#include "nes-nrom.cpp"
#include "nes-pxrom.cpp"
#include "nes-sxrom.cpp"
#include "nes-txrom.cpp"
#include "nes-uxrom.cpp"
#include "sunsoft-5b.cpp"
uint8 Board::Memory::read(unsigned addr) const {
return data[mirror(addr, size)];
}
void Board::Memory::write(unsigned addr, uint8 byte) {
if(writable) data[mirror(addr, size)] = byte;
}
unsigned Board::mirror(unsigned addr, unsigned size) {
unsigned base = 0;
if(size) {
unsigned mask = 1 << 23;
while(addr >= size) {
while(!(addr & mask)) mask >>= 1;
addr -= mask;
if(size > mask) {
size -= mask;
base += mask;
}
mask >>= 1;
}
base += addr;
}
return base;
}
void Board::main() {
while(true) {
if(scheduler.sync == Scheduler::SynchronizeMode::All) {
scheduler.exit(Scheduler::ExitReason::SynchronizeEvent);
}
cartridge.clock += 12 * 4095;
tick();
}
}
void Board::tick() {
cartridge.clock += 12;
if(cartridge.clock >= 0 && scheduler.sync != Scheduler::SynchronizeMode::All) co_switch(cpu.thread);
}
uint8 Board::chr_read(unsigned addr) {
if(chrram.size) return chrram.data[mirror(addr, chrram.size)];
if(chrrom.size) return chrrom.data[mirror(addr, chrrom.size)];
return 0u;
}
void Board::chr_write(unsigned addr, uint8 data) {
if(chrram.size) chrram.data[mirror(addr, chrram.size)] = data;
}
void Board::power() {
}
void Board::reset() {
}
void Board::serialize(serializer &s) {
if(prgram.size) s.array(prgram.data, prgram.size);
if(chrram.size) s.array(chrram.data, chrram.size);
}
Board::Board(XML::Document &document) {
cartridge.board = this;
auto &cartridge = document["cartridge"];
information.type = cartridge["board"]["type"].data;
information.battery = cartridge["prg"]["ram"]["nonvolatile"].data == "true";
auto &prom = cartridge["prg"]["rom"];
auto &pram = cartridge["prg"]["ram"];
auto &crom = cartridge["chr"]["rom"];
auto &cram = cartridge["chr"]["ram"];
prgrom.size = numeral(prom["size"].data);
prgram.size = numeral(pram["size"].data);
chrrom.size = numeral(crom["size"].data);
chrram.size = numeral(cram["size"].data);
if(prgrom.size) prgrom.data = new uint8[prgrom.size]();
if(prgram.size) prgram.data = new uint8[prgram.size]();
if(chrrom.size) chrrom.data = new uint8[chrrom.size]();
if(chrram.size) chrram.data = new uint8[chrram.size]();
if(prom["name"].data) interface->loadRequest(ID::ProgramROM, prom["name"].data);
if(pram["name"].data) interface->loadRequest(ID::ProgramRAM, pram["name"].data);
if(crom["name"].data) interface->loadRequest(ID::CharacterROM, crom["name"].data);
if(cram["name"].data) interface->loadRequest(ID::CharacterRAM, cram["name"].data);
if(pram["name"].data) Famicom::cartridge.memory.append({ID::ProgramRAM, pram["name"].data});
if(cram["name"].data) Famicom::cartridge.memory.append({ID::CharacterRAM, cram["name"].data});
prgram.writable = true;
chrram.writable = true;
}
Board::~Board() {
}
Board* Board::load(const string &manifest) {
XML::Document document(manifest);
string type = document["cartridge"]["board"]["type"].data;
if(type == "BANDAI-FCG" ) return new BandaiFCG(document);
if(type == "KONAMI-VRC-1") return new KonamiVRC1(document);
if(type == "KONAMI-VRC-2") return new KonamiVRC2(document);
if(type == "KONAMI-VRC-3") return new KonamiVRC3(document);
if(type == "KONAMI-VRC-4") return new KonamiVRC4(document);
if(type == "KONAMI-VRC-6") return new KonamiVRC6(document);
if(type == "KONAMI-VRC-7") return new KonamiVRC7(document);
if(type == "NES-AMROM" ) return new NES_AxROM(document);
if(type == "NES-ANROM" ) return new NES_AxROM(document);
if(type == "NES-AN1ROM" ) return new NES_AxROM(document);
if(type == "NES-AOROM" ) return new NES_AxROM(document);
if(type == "NES-BNROM" ) return new NES_BNROM(document);
if(type == "NES-CNROM" ) return new NES_CNROM(document);
if(type == "NES-EKROM" ) return new NES_ExROM(document);
if(type == "NES-ELROM" ) return new NES_ExROM(document);
if(type == "NES-ETROM" ) return new NES_ExROM(document);
if(type == "NES-EWROM" ) return new NES_ExROM(document);
if(type == "NES-FJROM" ) return new NES_FxROM(document);
if(type == "NES-FKROM" ) return new NES_FxROM(document);
if(type == "NES-GNROM" ) return new NES_GxROM(document);
if(type == "NES-MHROM" ) return new NES_GxROM(document);
if(type == "NES-HKROM" ) return new NES_HKROM(document);
if(type == "NES-NROM-128") return new NES_NROM(document);
if(type == "NES-NROM-256") return new NES_NROM(document);
if(type == "NES-PEEOROM" ) return new NES_PxROM(document);
if(type == "NES-PNROM" ) return new NES_PxROM(document);
if(type == "NES-SNROM" ) return new NES_SxROM(document);
if(type == "NES-SXROM" ) return new NES_SxROM(document);
if(type == "NES-TLROM" ) return new NES_TxROM(document);
if(type == "NES-UNROM" ) return new NES_UxROM(document);
if(type == "NES-UOROM" ) return new NES_UxROM(document);
if(type == "SUNSOFT-5B" ) return new Sunsoft5B(document);
return nullptr;
}

View File

@@ -0,0 +1,46 @@
struct Board {
struct Memory {
uint8_t *data;
unsigned size;
bool writable;
inline uint8 read(unsigned addr) const;
inline void write(unsigned addr, uint8 data);
inline Memory(uint8_t *data, unsigned size) : data(data), size(size) {}
inline Memory() : data(nullptr), size(0u), writable(false) {}
inline ~Memory() { if(data) delete[] data; }
};
static unsigned mirror(unsigned addr, unsigned size);
virtual void main();
virtual void tick();
virtual uint8 prg_read(unsigned addr) = 0;
virtual void prg_write(unsigned addr, uint8 data) = 0;
virtual uint8 chr_read(unsigned addr);
virtual void chr_write(unsigned addr, uint8 data);
virtual inline void scanline(unsigned y) {}
virtual void power();
virtual void reset();
virtual void serialize(serializer&);
Board(XML::Document &document);
virtual ~Board();
static Board* load(const string &manifest);
struct Information {
string type;
bool battery;
} information;
Memory prgrom;
Memory prgram;
Memory chrrom;
Memory chrram;
};

View File

@@ -0,0 +1,40 @@
struct KonamiVRC1 : Board {
VRC1 vrc1;
uint8 prg_read(unsigned addr) {
if(addr & 0x8000) return prgrom.read(vrc1.prg_addr(addr));
return cpu.mdr();
}
void prg_write(unsigned addr, uint8 data) {
if(addr & 0x8000) return vrc1.reg_write(addr, data);
}
uint8 chr_read(unsigned addr) {
if(addr & 0x2000) return ppu.ciram_read(vrc1.ciram_addr(addr));
return Board::chr_read(vrc1.chr_addr(addr));
}
void chr_write(unsigned addr, uint8 data) {
if(addr & 0x2000) return ppu.ciram_write(vrc1.ciram_addr(addr), data);
return Board::chr_write(vrc1.chr_addr(addr), data);
}
void power() {
vrc1.power();
}
void reset() {
vrc1.reset();
}
void serialize(serializer &s) {
Board::serialize(s);
vrc1.serialize(s);
}
KonamiVRC1(XML::Document &document) : Board(document), vrc1(*this) {
}
};

View File

@@ -0,0 +1,57 @@
struct KonamiVRC2 : Board {
struct Settings {
struct Pinout {
unsigned a0;
unsigned a1;
} pinout;
} settings;
VRC2 vrc2;
uint8 prg_read(unsigned addr) {
if(addr < 0x6000) return cpu.mdr();
if(addr < 0x8000) return vrc2.ram_read(addr);
return prgrom.read(vrc2.prg_addr(addr));
}
void prg_write(unsigned addr, uint8 data) {
if(addr < 0x6000) return;
if(addr < 0x8000) return vrc2.ram_write(addr, data);
bool a0 = (addr & settings.pinout.a0);
bool a1 = (addr & settings.pinout.a1);
addr &= 0xfff0;
addr |= (a0 << 0) | (a1 << 1);
return vrc2.reg_write(addr, data);
}
uint8 chr_read(unsigned addr) {
if(addr & 0x2000) return ppu.ciram_read(vrc2.ciram_addr(addr));
return Board::chr_read(vrc2.chr_addr(addr));
}
void chr_write(unsigned addr, uint8 data) {
if(addr & 0x2000) return ppu.ciram_write(vrc2.ciram_addr(addr), data);
return Board::chr_write(vrc2.chr_addr(addr), data);
}
void power() {
vrc2.power();
}
void reset() {
vrc2.reset();
}
void serialize(serializer &s) {
Board::serialize(s);
vrc2.serialize(s);
}
KonamiVRC2(XML::Document &document) : Board(document), vrc2(*this) {
settings.pinout.a0 = 1 << decimal(document["cartridge"]["chip"]["pinout"]["a0"].data);
settings.pinout.a1 = 1 << decimal(document["cartridge"]["chip"]["pinout"]["a1"].data);
}
};

View File

@@ -0,0 +1,57 @@
struct KonamiVRC3 : Board {
struct Settings {
bool mirror; //0 = horizontal, 1 = vertical
} settings;
VRC3 vrc3;
void main() {
vrc3.main();
}
uint8 prg_read(unsigned addr) {
if((addr & 0xe000) == 0x6000) return prgram.read(addr & 0x1fff);
if(addr & 0x8000) return prgrom.read(vrc3.prg_addr(addr));
return cpu.mdr();
}
void prg_write(unsigned addr, uint8 data) {
if((addr & 0xe000) == 0x6000) return prgram.write(addr & 0x1fff, data);
if(addr & 0x8000) return vrc3.reg_write(addr, data);
}
uint8 chr_read(unsigned addr) {
if(addr & 0x2000) {
if(settings.mirror == 0) addr = ((addr & 0x0800) >> 1) | (addr & 0x03ff);
return ppu.ciram_read(addr & 0x07ff);
}
return chrram.read(addr);
}
void chr_write(unsigned addr, uint8 data) {
if(addr & 0x2000) {
if(settings.mirror == 0) addr = ((addr & 0x0800) >> 1) | (addr & 0x03ff);
return ppu.ciram_write(addr & 0x07ff, data);
}
return chrram.write(addr, data);
}
void power() {
vrc3.power();
}
void reset() {
vrc3.reset();
}
void serialize(serializer &s) {
Board::serialize(s);
vrc3.serialize(s);
}
KonamiVRC3(XML::Document &document) : Board(document), vrc3(*this) {
settings.mirror = document["cartridge"]["mirror"]["mode"].data == "vertical" ? 1 : 0;
}
};

View File

@@ -0,0 +1,61 @@
struct KonamiVRC4 : Board {
struct Settings {
struct Pinout {
unsigned a0;
unsigned a1;
} pinout;
} settings;
VRC4 vrc4;
void main() {
return vrc4.main();
}
uint8 prg_read(unsigned addr) {
if(addr < 0x6000) return cpu.mdr();
if(addr < 0x8000) return prgram.read(addr);
return prgrom.read(vrc4.prg_addr(addr));
}
void prg_write(unsigned addr, uint8 data) {
if(addr < 0x6000) return;
if(addr < 0x8000) return prgram.write(addr, data);
bool a0 = (addr & settings.pinout.a0);
bool a1 = (addr & settings.pinout.a1);
addr &= 0xfff0;
addr |= (a1 << 1) | (a0 << 0);
return vrc4.reg_write(addr, data);
}
uint8 chr_read(unsigned addr) {
if(addr & 0x2000) return ppu.ciram_read(vrc4.ciram_addr(addr));
return Board::chr_read(vrc4.chr_addr(addr));
}
void chr_write(unsigned addr, uint8 data) {
if(addr & 0x2000) return ppu.ciram_write(vrc4.ciram_addr(addr), data);
return Board::chr_write(vrc4.chr_addr(addr), data);
}
void power() {
vrc4.power();
}
void reset() {
vrc4.reset();
}
void serialize(serializer &s) {
Board::serialize(s);
vrc4.serialize(s);
}
KonamiVRC4(XML::Document &document) : Board(document), vrc4(*this) {
settings.pinout.a0 = 1 << decimal(document["cartridge"]["chip"]["pinout"]["a0"].data);
settings.pinout.a1 = 1 << decimal(document["cartridge"]["chip"]["pinout"]["a1"].data);
}
};

View File

@@ -0,0 +1,42 @@
struct KonamiVRC6 : Board {
VRC6 vrc6;
uint8 prg_read(unsigned addr) {
if((addr & 0xe000) == 0x6000) return vrc6.ram_read(addr);
if(addr & 0x8000) return prgrom.read(vrc6.prg_addr(addr));
return cpu.mdr();
}
void prg_write(unsigned addr, uint8 data) {
if((addr & 0xe000) == 0x6000) return vrc6.ram_write(addr, data);
if(addr & 0x8000) {
addr = (addr & 0xf003);
if(prgram.size) addr = (addr & ~3) | ((addr & 2) >> 1) | ((addr & 1) << 1);
return vrc6.reg_write(addr, data);
}
}
uint8 chr_read(unsigned addr) {
if(addr & 0x2000) return ppu.ciram_read(vrc6.ciram_addr(addr));
return Board::chr_read(vrc6.chr_addr(addr));
}
void chr_write(unsigned addr, uint8 data) {
if(addr & 0x2000) return ppu.ciram_write(vrc6.ciram_addr(addr), data);
return Board::chr_write(vrc6.chr_addr(addr), data);
}
void serialize(serializer &s) {
Board::serialize(s);
vrc6.serialize(s);
}
void main() { vrc6.main(); }
void power() { vrc6.power(); }
void reset() { vrc6.reset(); }
KonamiVRC6(XML::Document &document) : Board(document), vrc6(*this) {
}
};

View File

@@ -0,0 +1,47 @@
struct KonamiVRC7 : Board {
VRC7 vrc7;
void main() {
return vrc7.main();
}
uint8 prg_read(unsigned addr) {
if(addr < 0x6000) return cpu.mdr();
if(addr < 0x8000) return prgram.read(addr);
return prgrom.read(vrc7.prg_addr(addr));
}
void prg_write(unsigned addr, uint8 data) {
if(addr < 0x6000) return;
if(addr < 0x8000) return prgram.write(addr, data);
return vrc7.reg_write(addr, data);
}
uint8 chr_read(unsigned addr) {
if(addr & 0x2000) return ppu.ciram_read(vrc7.ciram_addr(addr));
return chrram.read(vrc7.chr_addr(addr));
}
void chr_write(unsigned addr, uint8 data) {
if(addr & 0x2000) return ppu.ciram_write(vrc7.ciram_addr(addr), data);
return chrram.write(vrc7.chr_addr(addr), data);
}
void power() {
vrc7.power();
}
void reset() {
vrc7.reset();
}
void serialize(serializer &s) {
Board::serialize(s);
vrc7.serialize(s);
}
KonamiVRC7(XML::Document &document) : Board(document), vrc7(*this) {
}
};

View File

@@ -0,0 +1,51 @@
//NES-AMROM
//NES-ANROM
//NES-AN1ROM
//NES-AOROM
struct NES_AxROM : Board {
uint4 prg_bank;
bool mirror_select;
uint8 prg_read(unsigned addr) {
if(addr & 0x8000) return prgrom.read((prg_bank << 15) | (addr & 0x7fff));
return cpu.mdr();
}
void prg_write(unsigned addr, uint8 data) {
if(addr & 0x8000) {
prg_bank = data & 0x0f;
mirror_select = data & 0x10;
}
}
uint8 chr_read(unsigned addr) {
if(addr & 0x2000) return ppu.ciram_read((mirror_select << 10) | (addr & 0x03ff));
return Board::chr_read(addr);
}
void chr_write(unsigned addr, uint8 data) {
if(addr & 0x2000) return ppu.ciram_write((mirror_select << 10) | (addr & 0x03ff), data);
return Board::chr_write(addr, data);
}
void power() {
}
void reset() {
prg_bank = 0x0f;
mirror_select = 0;
}
void serialize(serializer &s) {
Board::serialize(s);
s.integer(prg_bank);
s.integer(mirror_select);
}
NES_AxROM(XML::Document &document) : Board(document) {
}
};

View File

@@ -0,0 +1,52 @@
//NES-BN-ROM-01
struct NES_BNROM : Board {
struct Settings {
bool mirror; //0 = horizontal, 1 = vertical
} settings;
uint2 prg_bank;
uint8 prg_read(unsigned addr) {
if(addr & 0x8000) return prgrom.read((prg_bank << 15) | (addr & 0x7fff));
return cpu.mdr();
}
void prg_write(unsigned addr, uint8 data) {
if(addr & 0x8000) prg_bank = data & 0x03;
}
uint8 chr_read(unsigned addr) {
if(addr & 0x2000) {
if(settings.mirror == 0) addr = ((addr & 0x0800) >> 1) | (addr & 0x03ff);
return ppu.ciram_read(addr);
}
return Board::chr_read(addr);
}
void chr_write(unsigned addr, uint8 data) {
if(addr & 0x2000) {
if(settings.mirror == 0) addr = ((addr & 0x0800) >> 1) | (addr & 0x03ff);
return ppu.ciram_write(addr, data);
}
return Board::chr_write(addr, data);
}
void power() {
}
void reset() {
prg_bank = 0;
}
void serialize(serializer &s) {
Board::serialize(s);
s.integer(prg_bank);
}
NES_BNROM(XML::Document &document) : Board(document) {
settings.mirror = document["cartridge"]["mirror"]["mode"].data == "vertical" ? 1 : 0;
}
};

View File

@@ -0,0 +1,54 @@
//NES-CNROM
struct NES_CNROM : Board {
struct Settings {
bool mirror; //0 = horizontal, 1 = vertical
} settings;
uint2 chr_bank;
uint8 prg_read(unsigned addr) {
if(addr & 0x8000) return prgrom.read(addr & 0x7fff);
return cpu.mdr();
}
void prg_write(unsigned addr, uint8 data) {
if(addr & 0x8000) chr_bank = data & 0x03;
}
uint8 chr_read(unsigned addr) {
if(addr & 0x2000) {
if(settings.mirror == 0) addr = ((addr & 0x0800) >> 1) | (addr & 0x03ff);
return ppu.ciram_read(addr & 0x07ff);
}
addr = (chr_bank * 0x2000) + (addr & 0x1fff);
return Board::chr_read(addr);
}
void chr_write(unsigned addr, uint8 data) {
if(addr & 0x2000) {
if(settings.mirror == 0) addr = ((addr & 0x0800) >> 1) | (addr & 0x03ff);
return ppu.ciram_write(addr & 0x07ff, data);
}
addr = (chr_bank * 0x2000) + (addr & 0x1fff);
Board::chr_write(addr, data);
}
void power() {
}
void reset() {
chr_bank = 0;
}
void serialize(serializer &s) {
Board::serialize(s);
s.integer(chr_bank);
}
NES_CNROM(XML::Document &document) : Board(document) {
settings.mirror = document["cartridge"]["mirror"]["mode"].data == "vertical" ? 1 : 0;
}
};

View File

@@ -0,0 +1,53 @@
struct NES_ExROM : Board {
enum class Revision : unsigned {
EKROM,
ELROM,
ETROM,
EWROM,
} revision;
MMC5 mmc5;
void main() {
mmc5.main();
}
uint8 prg_read(unsigned addr) {
return mmc5.prg_read(addr);
}
void prg_write(unsigned addr, uint8 data) {
mmc5.prg_write(addr, data);
}
uint8 chr_read(unsigned addr) {
return mmc5.chr_read(addr);
}
void chr_write(unsigned addr, uint8 data) {
mmc5.chr_write(addr, data);
}
void scanline(unsigned y) {
mmc5.scanline(y);
}
void power() {
mmc5.power();
}
void reset() {
mmc5.reset();
}
void serialize(serializer &s) {
Board::serialize(s);
mmc5.serialize(s);
}
NES_ExROM(XML::Document &document) : Board(document), mmc5(*this) {
revision = Revision::ELROM;
}
};

View File

@@ -0,0 +1,91 @@
//MMC4
struct NES_FxROM : Board {
enum Revision : unsigned {
FJROM,
FKROM,
} revision;
uint4 prg_bank;
uint5 chr_bank[2][2];
bool mirror;
bool latch[2];
uint8 prg_read(unsigned addr) {
if(addr < 0x6000) return cpu.mdr();
if(addr < 0x8000) return prgram.read(addr);
unsigned bank = addr < 0xc000 ? prg_bank : (uint4)0x0f;
return prgrom.read((bank * 0x4000) | (addr & 0x3fff));
}
void prg_write(unsigned addr, uint8 data) {
if(addr < 0x6000) return;
if(addr < 0x8000) return prgram.write(addr, data);
switch(addr & 0xf000) {
case 0xa000: prg_bank = data & 0x0f; break;
case 0xb000: chr_bank[0][0] = data & 0x1f; break;
case 0xc000: chr_bank[0][1] = data & 0x1f; break;
case 0xd000: chr_bank[1][0] = data & 0x1f; break;
case 0xe000: chr_bank[1][1] = data & 0x1f; break;
case 0xf000: mirror = data & 0x01; break;
}
}
unsigned ciram_addr(unsigned addr) const {
switch(mirror) {
case 0: return ((addr & 0x0400) >> 0) | (addr & 0x03ff); //vertical mirroring
case 1: return ((addr & 0x0800) >> 1) | (addr & 0x03ff); //horizontal mirroring
}
}
uint8 chr_read(unsigned addr) {
if(addr & 0x2000) return ppu.ciram_read(ciram_addr(addr));
bool region = addr & 0x1000;
unsigned bank = chr_bank[region][latch[region]];
if((addr & 0x0ff8) == 0x0fd8) latch[region] = 0;
if((addr & 0x0ff8) == 0x0fe8) latch[region] = 1;
return Board::chr_read((bank * 0x1000) | (addr & 0x0fff));
}
void chr_write(unsigned addr, uint8 data) {
if(addr & 0x2000) return ppu.ciram_write(ciram_addr(addr), data);
bool region = addr & 0x1000;
unsigned bank = chr_bank[region][latch[region]];
if((addr & 0x0ff8) == 0x0fd8) latch[region] = 0;
if((addr & 0x0ff8) == 0x0fe8) latch[region] = 1;
return Board::chr_write((bank * 0x1000) | (addr & 0x0fff), data);
}
void power() {
}
void reset() {
prg_bank = 0;
chr_bank[0][0] = 0;
chr_bank[0][1] = 0;
chr_bank[1][0] = 0;
chr_bank[1][1] = 0;
mirror = 0;
latch[0] = 0;
latch[1] = 0;
}
void serialize(serializer &s) {
Board::serialize(s);
s.integer(prg_bank);
s.integer(chr_bank[0][0]);
s.integer(chr_bank[0][1]);
s.integer(chr_bank[1][0]);
s.integer(chr_bank[1][1]);
s.integer(mirror);
s.array(latch);
}
NES_FxROM(XML::Document &document) : Board(document) {
revision = Revision::FKROM;
}
};

View File

@@ -0,0 +1,61 @@
//NES-GNROM
//NES-MHROM
struct NES_GxROM : Board {
struct Settings {
bool mirror; //0 = horizontal, 1 = vertical
} settings;
uint2 prg_bank;
uint2 chr_bank;
uint8 prg_read(unsigned addr) {
if(addr & 0x8000) return prgrom.read((prg_bank << 15) | (addr & 0x7fff));
return cpu.mdr();
}
void prg_write(unsigned addr, uint8 data) {
if(addr & 0x8000) {
prg_bank = (data & 0x30) >> 4;
chr_bank = (data & 0x03) >> 0;
}
}
uint8 chr_read(unsigned addr) {
if(addr & 0x2000) {
if(settings.mirror == 0) addr = ((addr & 0x0800) >> 1) | (addr & 0x03ff);
return ppu.ciram_read(addr & 0x07ff);
}
addr = (chr_bank * 0x2000) + (addr & 0x1fff);
return Board::chr_read(addr);
}
void chr_write(unsigned addr, uint8 data) {
if(addr & 0x2000) {
if(settings.mirror == 0) addr = ((addr & 0x0800) >> 1) | (addr & 0x03ff);
return ppu.ciram_write(addr & 0x07ff, data);
}
addr = (chr_bank * 0x2000) + (addr & 0x1fff);
Board::chr_write(addr, data);
}
void power() {
}
void reset() {
prg_bank = 0;
chr_bank = 0;
}
void serialize(serializer &s) {
Board::serialize(s);
s.integer(prg_bank);
s.integer(chr_bank);
}
NES_GxROM(XML::Document &document) : Board(document) {
settings.mirror = document["cartridge"]["mirror"]["mode"].data == "vertical" ? 1 : 0;
}
};

View File

@@ -0,0 +1,48 @@
struct NES_HKROM : Board {
MMC6 mmc6;
void main() {
mmc6.main();
}
uint8 prg_read(unsigned addr) {
if((addr & 0xf000) == 0x7000) return mmc6.ram_read(addr);
if(addr & 0x8000) return prgrom.read(mmc6.prg_addr(addr));
return cpu.mdr();
}
void prg_write(unsigned addr, uint8 data) {
if((addr & 0xf000) == 0x7000) return mmc6.ram_write(addr, data);
if(addr & 0x8000) return mmc6.reg_write(addr, data);
}
uint8 chr_read(unsigned addr) {
mmc6.irq_test(addr);
if(addr & 0x2000) return ppu.ciram_read(mmc6.ciram_addr(addr));
return Board::chr_read(mmc6.chr_addr(addr));
}
void chr_write(unsigned addr, uint8 data) {
mmc6.irq_test(addr);
if(addr & 0x2000) return ppu.ciram_write(mmc6.ciram_addr(addr), data);
return Board::chr_write(mmc6.chr_addr(addr), data);
}
void power() {
mmc6.power();
}
void reset() {
mmc6.reset();
}
void serialize(serializer &s) {
Board::serialize(s);
mmc6.serialize(s);
}
NES_HKROM(XML::Document &document) : Board(document), mmc6(*this) {
}
};

View File

@@ -0,0 +1,43 @@
//NES-NROM-128
//NES-NROM-256
struct NES_NROM : Board {
struct Settings {
bool mirror; //0 = horizontal, 1 = vertical
} settings;
uint8 prg_read(unsigned addr) {
if(addr & 0x8000) return prgrom.read(addr);
return cpu.mdr();
}
void prg_write(unsigned addr, uint8 data) {
}
uint8 chr_read(unsigned addr) {
if(addr & 0x2000) {
if(settings.mirror == 0) addr = ((addr & 0x0800) >> 1) | (addr & 0x03ff);
return ppu.ciram_read(addr & 0x07ff);
}
if(chrram.size) return chrram.read(addr);
return chrrom.read(addr);
}
void chr_write(unsigned addr, uint8 data) {
if(addr & 0x2000) {
if(settings.mirror == 0) addr = ((addr & 0x0800) >> 1) | (addr & 0x03ff);
return ppu.ciram_write(addr & 0x07ff, data);
}
if(chrram.size) return chrram.write(addr, data);
}
void serialize(serializer &s) {
Board::serialize(s);
}
NES_NROM(XML::Document &document) : Board(document) {
settings.mirror = document["cartridge"]["mirror"]["mode"].data == "vertical" ? 1 : 0;
}
};

View File

@@ -0,0 +1,97 @@
//MMC2
struct NES_PxROM : Board {
enum Revision : unsigned {
PEEOROM,
PNROM,
} revision;
uint4 prg_bank;
uint5 chr_bank[2][2];
bool mirror;
bool latch[2];
uint8 prg_read(unsigned addr) {
if(addr < 0x6000) return cpu.mdr();
if(addr < 0x8000) return prgram.read(addr);
unsigned bank = 0;
switch((addr / 0x2000) & 3) {
case 0: bank = prg_bank; break;
case 1: bank = 0x0d; break;
case 2: bank = 0x0e; break;
case 3: bank = 0x0f; break;
}
return prgrom.read((bank * 0x2000) | (addr & 0x1fff));
}
void prg_write(unsigned addr, uint8 data) {
if(addr < 0x6000) return;
if(addr < 0x8000) return prgram.write(addr, data);
switch(addr & 0xf000) {
case 0xa000: prg_bank = data & 0x0f; break;
case 0xb000: chr_bank[0][0] = data & 0x1f; break;
case 0xc000: chr_bank[0][1] = data & 0x1f; break;
case 0xd000: chr_bank[1][0] = data & 0x1f; break;
case 0xe000: chr_bank[1][1] = data & 0x1f; break;
case 0xf000: mirror = data & 0x01; break;
}
}
unsigned ciram_addr(unsigned addr) const {
switch(mirror) {
case 0: return ((addr & 0x0400) >> 0) | (addr & 0x03ff); //vertical mirroring
case 1: return ((addr & 0x0800) >> 1) | (addr & 0x03ff); //horizontal mirroring
}
}
uint8 chr_read(unsigned addr) {
if(addr & 0x2000) return ppu.ciram_read(ciram_addr(addr));
bool region = addr & 0x1000;
unsigned bank = chr_bank[region][latch[region]];
if((addr & 0x0ff8) == 0x0fd8) latch[region] = 0;
if((addr & 0x0ff8) == 0x0fe8) latch[region] = 1;
return Board::chr_read((bank * 0x1000) | (addr & 0x0fff));
}
void chr_write(unsigned addr, uint8 data) {
if(addr & 0x2000) return ppu.ciram_write(ciram_addr(addr), data);
bool region = addr & 0x1000;
unsigned bank = chr_bank[region][latch[region]];
if((addr & 0x0ff8) == 0x0fd8) latch[region] = 0;
if((addr & 0x0ff8) == 0x0fe8) latch[region] = 1;
return Board::chr_write((bank * 0x1000) | (addr & 0x0fff), data);
}
void power() {
}
void reset() {
prg_bank = 0;
chr_bank[0][0] = 0;
chr_bank[0][1] = 0;
chr_bank[1][0] = 0;
chr_bank[1][1] = 0;
mirror = 0;
latch[0] = 0;
latch[1] = 0;
}
void serialize(serializer &s) {
Board::serialize(s);
s.integer(prg_bank);
s.integer(chr_bank[0][0]);
s.integer(chr_bank[0][1]);
s.integer(chr_bank[1][0]);
s.integer(chr_bank[1][1]);
s.integer(mirror);
s.array(latch);
}
NES_PxROM(XML::Document &document) : Board(document) {
revision = Revision::PNROM;
}
};

View File

@@ -0,0 +1,101 @@
struct NES_SxROM : Board {
enum class Revision : unsigned {
SAROM,
SBROM,
SCROM,
SC1ROM,
SEROM,
SFROM,
SGROM,
SHROM,
SH1ROM,
SIROM,
SJROM,
SKROM,
SLROM,
SL1ROM,
SL2ROM,
SL3ROM,
SLRROM,
SMROM,
SNROM,
SOROM,
SUROM,
SXROM,
} revision;
MMC1 mmc1;
void main() {
return mmc1.main();
}
unsigned ram_addr(unsigned addr) {
unsigned bank = 0;
if(revision == Revision::SOROM) bank = (mmc1.chr_bank[0] & 0x08) >> 3;
if(revision == Revision::SUROM) bank = (mmc1.chr_bank[0] & 0x0c) >> 2;
if(revision == Revision::SXROM) bank = (mmc1.chr_bank[0] & 0x0c) >> 2;
return (bank << 13) | (addr & 0x1fff);
}
uint8 prg_read(unsigned addr) {
if((addr & 0xe000) == 0x6000) {
if(revision == Revision::SNROM) {
if(mmc1.chr_bank[0] & 0x10) return cpu.mdr();
}
if(mmc1.ram_disable) return 0x00;
return prgram.read(ram_addr(addr));
}
if(addr & 0x8000) {
addr = mmc1.prg_addr(addr);
if(revision == Revision::SXROM) {
addr |= ((mmc1.chr_bank[0] & 0x10) >> 4) << 18;
}
return prgrom.read(addr);
}
return cpu.mdr();
}
void prg_write(unsigned addr, uint8 data) {
if((addr & 0xe000) == 0x6000) {
if(revision == Revision::SNROM) {
if(mmc1.chr_bank[0] & 0x10) return;
}
if(mmc1.ram_disable) return;
return prgram.write(ram_addr(addr), data);
}
if(addr & 0x8000) return mmc1.mmio_write(addr, data);
}
uint8 chr_read(unsigned addr) {
if(addr & 0x2000) return ppu.ciram_read(mmc1.ciram_addr(addr));
return Board::chr_read(mmc1.chr_addr(addr));
}
void chr_write(unsigned addr, uint8 data) {
if(addr & 0x2000) return ppu.ciram_write(mmc1.ciram_addr(addr), data);
return Board::chr_write(mmc1.chr_addr(addr), data);
}
void power() {
mmc1.power();
}
void reset() {
mmc1.reset();
}
void serialize(serializer &s) {
Board::serialize(s);
mmc1.serialize(s);
}
NES_SxROM(XML::Document &document) : Board(document), mmc1(*this) {
revision = Revision::SXROM;
}
};

View File

@@ -0,0 +1,67 @@
struct NES_TxROM : Board {
enum class Revision : unsigned {
TBROM,
TEROM,
TFROM,
TGROM,
TKROM,
TKSROM,
TLROM,
TL1ROM,
TL2ROM,
TLSROM,
TNROM,
TQROM,
TR1ROM,
TSROM,
TVROM,
} revision;
MMC3 mmc3;
void main() {
mmc3.main();
}
uint8 prg_read(unsigned addr) {
if((addr & 0xe000) == 0x6000) return mmc3.ram_read(addr);
if(addr & 0x8000) return prgrom.read(mmc3.prg_addr(addr));
return cpu.mdr();
}
void prg_write(unsigned addr, uint8 data) {
if((addr & 0xe000) == 0x6000) return mmc3.ram_write(addr, data);
if(addr & 0x8000) return mmc3.reg_write(addr, data);
}
uint8 chr_read(unsigned addr) {
mmc3.irq_test(addr);
if(addr & 0x2000) return ppu.ciram_read(mmc3.ciram_addr(addr));
return Board::chr_read(mmc3.chr_addr(addr));
}
void chr_write(unsigned addr, uint8 data) {
mmc3.irq_test(addr);
if(addr & 0x2000) return ppu.ciram_write(mmc3.ciram_addr(addr), data);
return Board::chr_write(mmc3.chr_addr(addr), data);
}
void power() {
mmc3.power();
}
void reset() {
mmc3.reset();
}
void serialize(serializer &s) {
Board::serialize(s);
mmc3.serialize(s);
}
NES_TxROM(XML::Document &document) : Board(document), mmc3(*this) {
revision = Revision::TLROM;
}
};

View File

@@ -0,0 +1,55 @@
//NES-UNROM
//NES-UOROM
struct NES_UxROM : Board {
struct Settings {
bool mirror; //0 = horizontal, 1 = vertical
} settings;
uint4 prg_bank;
uint8 prg_read(unsigned addr) {
if((addr & 0xc000) == 0x8000) return prgrom.read((prg_bank << 14) | (addr & 0x3fff));
if((addr & 0xc000) == 0xc000) return prgrom.read(( 0x0f << 14) | (addr & 0x3fff));
return cpu.mdr();
}
void prg_write(unsigned addr, uint8 data) {
if(addr & 0x8000) prg_bank = data & 0x0f;
}
uint8 chr_read(unsigned addr) {
if(addr & 0x2000) {
if(settings.mirror == 0) addr = ((addr & 0x0800) >> 1) | (addr & 0x03ff);
return ppu.ciram_read(addr);
}
return Board::chr_read(addr);
}
void chr_write(unsigned addr, uint8 data) {
if(addr & 0x2000) {
if(settings.mirror == 0) addr = ((addr & 0x0800) >> 1) | (addr & 0x03ff);
return ppu.ciram_write(addr, data);
}
return Board::chr_write(addr, data);
}
void power() {
}
void reset() {
prg_bank = 0;
}
void serialize(serializer &s) {
Board::serialize(s);
s.integer(prg_bank);
}
NES_UxROM(XML::Document &document) : Board(document) {
settings.mirror = document["cartridge"]["mirror"]["mode"].data == "vertical" ? 1 : 0;
}
};

View File

@@ -0,0 +1,226 @@
//SUNSOFT-5B
struct Sunsoft5B : Board {
uint4 mmu_port;
uint4 apu_port;
uint8 prg_bank[4];
uint8 chr_bank[8];
uint2 mirror;
bool irq_enable;
bool irq_counter_enable;
uint16 irq_counter;
int16 dac[16];
struct Pulse {
bool disable;
uint12 frequency;
uint4 volume;
uint16 counter; //12-bit countdown + 4-bit phase
uint1 duty;
uint4 output;
void clock() {
if(--counter == 0) {
counter = frequency << 4;
duty ^= 1;
}
output = duty ? volume : (uint4)0;
if(disable) output = 0;
}
void reset() {
disable = 1;
frequency = 1;
volume = 0;
counter = 0;
duty = 0;
output = 0;
}
void serialize(serializer &s) {
s.integer(disable);
s.integer(frequency);
s.integer(volume);
s.integer(counter);
s.integer(duty);
s.integer(output);
}
} pulse[3];
void main() {
while(true) {
if(scheduler.sync == Scheduler::SynchronizeMode::All) {
scheduler.exit(Scheduler::ExitReason::SynchronizeEvent);
}
if(irq_counter_enable) {
if(--irq_counter == 0xffff) {
cpu.set_irq_line(irq_enable);
}
}
pulse[0].clock();
pulse[1].clock();
pulse[2].clock();
int16 output = dac[pulse[0].output] + dac[pulse[1].output] + dac[pulse[2].output];
apu.set_sample(-output);
tick();
}
}
uint8 prg_read(unsigned addr) {
if(addr < 0x6000) return cpu.mdr();
uint8 bank = 0x3f; //((addr & 0xe000) == 0xe000
if((addr & 0xe000) == 0x6000) bank = prg_bank[0];
if((addr & 0xe000) == 0x8000) bank = prg_bank[1];
if((addr & 0xe000) == 0xa000) bank = prg_bank[2];
if((addr & 0xe000) == 0xc000) bank = prg_bank[3];
bool ram_enable = bank & 0x80;
bool ram_select = bank & 0x40;
bank &= 0x3f;
if(ram_select) {
if(ram_enable == false) return cpu.mdr();
return prgram.data[addr & 0x1fff];
}
addr = (bank << 13) | (addr & 0x1fff);
return prgrom.read(addr);
}
void prg_write(unsigned addr, uint8 data) {
if((addr & 0xe000) == 0x6000) {
prgram.data[addr & 0x1fff] = data;
}
if(addr == 0x8000) {
mmu_port = data & 0x0f;
}
if(addr == 0xa000) {
switch(mmu_port) {
case 0: chr_bank[0] = data; break;
case 1: chr_bank[1] = data; break;
case 2: chr_bank[2] = data; break;
case 3: chr_bank[3] = data; break;
case 4: chr_bank[4] = data; break;
case 5: chr_bank[5] = data; break;
case 6: chr_bank[6] = data; break;
case 7: chr_bank[7] = data; break;
case 8: prg_bank[0] = data; break;
case 9: prg_bank[1] = data; break;
case 10: prg_bank[2] = data; break;
case 11: prg_bank[3] = data; break;
case 12: mirror = data & 3; break;
case 13:
irq_enable = data & 0x80;
irq_counter_enable = data & 0x01;
if(irq_enable == 0) cpu.set_irq_line(0);
break;
case 14: irq_counter = (irq_counter & 0xff00) | (data << 0); break;
case 15: irq_counter = (irq_counter & 0x00ff) | (data << 8); break;
}
}
if(addr == 0xc000) {
apu_port = data & 0x0f;
}
if(addr == 0xe000) {
switch(apu_port) {
case 0: pulse[0].frequency = (pulse[0].frequency & 0xff00) | (data << 0); break;
case 1: pulse[0].frequency = (pulse[0].frequency & 0x00ff) | (data << 8); break;
case 2: pulse[1].frequency = (pulse[1].frequency & 0xff00) | (data << 0); break;
case 3: pulse[1].frequency = (pulse[1].frequency & 0x00ff) | (data << 8); break;
case 4: pulse[2].frequency = (pulse[2].frequency & 0xff00) | (data << 0); break;
case 5: pulse[2].frequency = (pulse[2].frequency & 0x00ff) | (data << 8); break;
case 7:
pulse[0].disable = data & 0x01;
pulse[1].disable = data & 0x02;
pulse[2].disable = data & 0x04;
break;
case 8: pulse[0].volume = data & 0x0f; break;
case 9: pulse[1].volume = data & 0x0f; break;
case 10: pulse[2].volume = data & 0x0f; break;
}
}
}
unsigned chr_addr(unsigned addr) {
uint8 bank = (addr >> 10) & 7;
return (chr_bank[bank] << 10) | (addr & 0x03ff);
}
unsigned ciram_addr(unsigned addr) {
switch(mirror) {
case 0: return ((addr & 0x0400) >> 0) | (addr & 0x03ff); //vertical
case 1: return ((addr & 0x0800) >> 1) | (addr & 0x03ff); //horizontal
case 2: return 0x0000 | (addr & 0x03ff); //first
case 3: return 0x0400 | (addr & 0x03ff); //second
}
}
uint8 chr_read(unsigned addr) {
if(addr & 0x2000) return ppu.ciram_read(ciram_addr(addr));
return Board::chr_read(chr_addr(addr));
}
void chr_write(unsigned addr, uint8 data) {
if(addr & 0x2000) return ppu.ciram_write(ciram_addr(addr), data);
return Board::chr_write(chr_addr(addr), data);
}
void power() {
for(signed n = 0; n < 16; n++) {
double volume = 1.0 / pow(2, 1.0 / 2 * (15 - n));
dac[n] = volume * 8192.0;
}
}
void reset() {
mmu_port = 0;
apu_port = 0;
for(auto &n : prg_bank) n = 0;
for(auto &n : chr_bank) n = 0;
mirror = 0;
irq_enable = 0;
irq_counter_enable = 0;
irq_counter = 0;
pulse[0].reset();
pulse[1].reset();
pulse[2].reset();
}
void serialize(serializer &s) {
Board::serialize(s);
s.integer(mmu_port);
s.integer(apu_port);
s.array(prg_bank);
s.array(chr_bank);
s.integer(mirror);
s.integer(irq_enable);
s.integer(irq_counter_enable);
s.integer(irq_counter);
pulse[0].serialize(s);
pulse[1].serialize(s);
pulse[2].serialize(s);
}
Sunsoft5B(XML::Document &document) : Board(document) {
}
};

View File

@@ -0,0 +1,82 @@
#include <fc/fc.hpp>
namespace Famicom {
#include "chip/chip.cpp"
#include "board/board.cpp"
Cartridge cartridge;
void Cartridge::Main() {
cartridge.main();
}
void Cartridge::main() {
board->main();
}
void Cartridge::load(const string &manifest) {
information.markup = manifest;
Board::load(manifest); //this call will set Cartridge::board if successful
if(board == nullptr) return;
sha256_ctx sha;
uint8 hash[32];
sha256_init(&sha);
sha256_chunk(&sha, board->prgrom.data, board->prgrom.size);
sha256_chunk(&sha, board->chrrom.data, board->chrrom.size);
sha256_final(&sha);
sha256_hash(&sha, hash);
string result;
for(auto &byte : hash) result.append(hex<2>(byte));
sha256 = result;
system.load();
loaded = true;
}
void Cartridge::unload() {
if(loaded == false) return;
loaded = false;
memory.reset();
}
void Cartridge::power() {
board->power();
}
void Cartridge::reset() {
create(Cartridge::Main, 21477272);
board->reset();
}
Cartridge::Cartridge() {
loaded = false;
}
uint8 Cartridge::prg_read(unsigned addr) {
return board->prg_read(addr);
}
void Cartridge::prg_write(unsigned addr, uint8 data) {
return board->prg_write(addr, data);
}
uint8 Cartridge::chr_read(unsigned addr) {
return board->chr_read(addr);
}
void Cartridge::chr_write(unsigned addr, uint8 data) {
return board->chr_write(addr, data);
}
void Cartridge::scanline(unsigned y) {
return board->scanline(y);
}
void Cartridge::serialize(serializer &s) {
Thread::serialize(s);
return board->serialize(s);
}
}

View File

@@ -0,0 +1,44 @@
#include "chip/chip.hpp"
#include "board/board.hpp"
struct Cartridge : Thread, property<Cartridge> {
static void Main();
void main();
void load(const string &manifest);
void unload();
void power();
void reset();
readonly<bool> loaded;
readonly<string> sha256;
struct Information {
string markup;
} information;
struct Memory {
unsigned id;
string name;
};
vector<Memory> memory;
void serialize(serializer&);
Cartridge();
//privileged:
Board *board;
uint8 prg_read(unsigned addr);
void prg_write(unsigned addr, uint8 data);
uint8 chr_read(unsigned addr);
void chr_write(unsigned addr, uint8 data);
//scanline() is for debugging purposes only:
//boards must detect scanline edges on their own
void scanline(unsigned y);
};
extern Cartridge cartridge;

View File

@@ -0,0 +1,17 @@
#include "mmc1.cpp"
#include "mmc3.cpp"
#include "mmc5.cpp"
#include "mmc6.cpp"
#include "vrc1.cpp"
#include "vrc2.cpp"
#include "vrc3.cpp"
#include "vrc4.cpp"
#include "vrc6.cpp"
#include "vrc7.cpp"
void Chip::tick() {
board.tick();
}
Chip::Chip(Board &board) : board(board) {
}

View File

@@ -0,0 +1,7 @@
struct Board;
struct Chip {
Board &board;
void tick();
Chip(Board &board);
};

View File

@@ -0,0 +1,136 @@
struct MMC1 : Chip {
enum class Revision : unsigned {
MMC1,
MMC1A,
MMC1B1,
MMC1B2,
MMC1B3,
MMC1C,
} revision;
unsigned writedelay;
unsigned shiftaddr;
unsigned shiftdata;
bool chr_mode;
bool prg_size; //0 = 32K, 1 = 16K
bool prg_mode;
uint2 mirror; //0 = first, 1 = second, 2 = vertical, 3 = horizontal
uint5 chr_bank[2];
bool ram_disable;
uint4 prg_bank;
void main() {
while(true) {
if(scheduler.sync == Scheduler::SynchronizeMode::All) {
scheduler.exit(Scheduler::ExitReason::SynchronizeEvent);
}
if(writedelay) writedelay--;
tick();
}
}
unsigned prg_addr(unsigned addr) {
bool region = addr & 0x4000;
unsigned bank = (prg_bank & ~1) + region;
if(prg_size) {
bank = (region == 0 ? 0x0 : 0xf);
if(region != prg_mode) bank = prg_bank;
}
return (bank << 14) | (addr & 0x3fff);
}
unsigned chr_addr(unsigned addr) {
bool region = addr & 0x1000;
unsigned bank = chr_bank[region];
if(chr_mode == 0) bank = (chr_bank[0] & ~1) | region;
return (bank << 12) | (addr & 0x0fff);
}
unsigned ciram_addr(unsigned addr) {
switch(mirror) {
case 0: return 0x0000 | (addr & 0x03ff);
case 1: return 0x0400 | (addr & 0x03ff);
case 2: return ((addr & 0x0400) >> 0) | (addr & 0x03ff);
case 3: return ((addr & 0x0800) >> 1) | (addr & 0x03ff);
}
}
void mmio_write(unsigned addr, uint8 data) {
if(writedelay) return;
writedelay = 2;
if(data & 0x80) {
shiftaddr = 0;
prg_size = 1;
prg_mode = 1;
} else {
shiftdata = ((data & 1) << 4) | (shiftdata >> 1);
if(++shiftaddr == 5) {
shiftaddr = 0;
switch((addr >> 13) & 3) {
case 0:
chr_mode = (shiftdata & 0x10);
prg_size = (shiftdata & 0x08);
prg_mode = (shiftdata & 0x04);
mirror = (shiftdata & 0x03);
break;
case 1:
chr_bank[0] = (shiftdata & 0x1f);
break;
case 2:
chr_bank[1] = (shiftdata & 0x1f);
break;
case 3:
ram_disable = (shiftdata & 0x10);
prg_bank = (shiftdata & 0x0f);
break;
}
}
}
}
void power() {
}
void reset() {
writedelay = 0;
shiftaddr = 0;
shiftdata = 0;
chr_mode = 0;
prg_size = 1;
prg_mode = 1;
mirror = 0;
chr_bank[0] = 0;
chr_bank[1] = 1;
ram_disable = 0;
prg_bank = 0;
}
void serialize(serializer &s) {
s.integer(writedelay);
s.integer(shiftaddr);
s.integer(shiftdata);
s.integer(chr_mode);
s.integer(prg_size);
s.integer(prg_mode);
s.integer(mirror);
s.array(chr_bank);
s.integer(ram_disable);
s.integer(prg_bank);
}
MMC1(Board &board) : Chip(board) {
revision = Revision::MMC1B2;
}
};

View File

@@ -0,0 +1,189 @@
struct MMC3 : Chip {
bool chr_mode;
bool prg_mode;
uint3 bank_select;
uint8 prg_bank[2];
uint8 chr_bank[6];
bool mirror;
bool ram_enable;
bool ram_write_protect;
uint8 irq_latch;
uint8 irq_counter;
bool irq_enable;
unsigned irq_delay;
bool irq_line;
uint16 chr_abus;
void main() {
while(true) {
if(scheduler.sync == Scheduler::SynchronizeMode::All) {
scheduler.exit(Scheduler::ExitReason::SynchronizeEvent);
}
if(irq_delay) irq_delay--;
cpu.set_irq_line(irq_line);
tick();
}
}
void irq_test(unsigned addr) {
if(!(chr_abus & 0x1000) && (addr & 0x1000)) {
if(irq_delay == 0) {
if(irq_counter == 0) {
irq_counter = irq_latch;
} else if(--irq_counter == 0) {
if(irq_enable) irq_line = 1;
}
}
irq_delay = 6;
}
chr_abus = addr;
}
unsigned prg_addr(unsigned addr) const {
switch((addr >> 13) & 3) {
case 0:
if(prg_mode == 1) return (0x3e << 13) | (addr & 0x1fff);
return (prg_bank[0] << 13) | (addr & 0x1fff);
case 1:
return (prg_bank[1] << 13) | (addr & 0x1fff);
case 2:
if(prg_mode == 0) return (0x3e << 13) | (addr & 0x1fff);
return (prg_bank[0] << 13) | (addr & 0x1fff);
case 3:
return (0x3f << 13) | (addr & 0x1fff);
}
}
unsigned chr_addr(unsigned addr) const {
if(chr_mode == 0) {
if(addr <= 0x07ff) return (chr_bank[0] << 10) | (addr & 0x07ff);
if(addr <= 0x0fff) return (chr_bank[1] << 10) | (addr & 0x07ff);
if(addr <= 0x13ff) return (chr_bank[2] << 10) | (addr & 0x03ff);
if(addr <= 0x17ff) return (chr_bank[3] << 10) | (addr & 0x03ff);
if(addr <= 0x1bff) return (chr_bank[4] << 10) | (addr & 0x03ff);
if(addr <= 0x1fff) return (chr_bank[5] << 10) | (addr & 0x03ff);
} else {
if(addr <= 0x03ff) return (chr_bank[2] << 10) | (addr & 0x03ff);
if(addr <= 0x07ff) return (chr_bank[3] << 10) | (addr & 0x03ff);
if(addr <= 0x0bff) return (chr_bank[4] << 10) | (addr & 0x03ff);
if(addr <= 0x0fff) return (chr_bank[5] << 10) | (addr & 0x03ff);
if(addr <= 0x17ff) return (chr_bank[0] << 10) | (addr & 0x07ff);
if(addr <= 0x1fff) return (chr_bank[1] << 10) | (addr & 0x07ff);
}
}
unsigned ciram_addr(unsigned addr) const {
if(mirror == 0) return ((addr & 0x0400) >> 0) | (addr & 0x03ff);
if(mirror == 1) return ((addr & 0x0800) >> 1) | (addr & 0x03ff);
}
uint8 ram_read(unsigned addr) {
if(ram_enable) return board.prgram.data[addr & 0x1fff];
return 0x00;
}
void ram_write(unsigned addr, uint8 data) {
if(ram_enable && !ram_write_protect) board.prgram.data[addr & 0x1fff] = data;
}
void reg_write(unsigned addr, uint8 data) {
switch(addr & 0xe001) {
case 0x8000:
chr_mode = data & 0x80;
prg_mode = data & 0x40;
bank_select = data & 0x07;
break;
case 0x8001:
switch(bank_select) {
case 0: chr_bank[0] = data & ~1; break;
case 1: chr_bank[1] = data & ~1; break;
case 2: chr_bank[2] = data; break;
case 3: chr_bank[3] = data; break;
case 4: chr_bank[4] = data; break;
case 5: chr_bank[5] = data; break;
case 6: prg_bank[0] = data & 0x3f; break;
case 7: prg_bank[1] = data & 0x3f; break;
}
break;
case 0xa000:
mirror = data & 0x01;
break;
case 0xa001:
ram_enable = data & 0x80;
ram_write_protect = data & 0x40;
break;
case 0xc000:
irq_latch = data;
break;
case 0xc001:
irq_counter = 0;
break;
case 0xe000:
irq_enable = false;
irq_line = 0;
break;
case 0xe001:
irq_enable = true;
break;
}
}
void power() {
}
void reset() {
chr_mode = 0;
prg_mode = 0;
bank_select = 0;
prg_bank[0] = 0;
prg_bank[1] = 0;
chr_bank[0] = 0;
chr_bank[1] = 0;
chr_bank[2] = 0;
chr_bank[3] = 0;
chr_bank[4] = 0;
chr_bank[5] = 0;
mirror = 0;
ram_enable = 1;
ram_write_protect = 0;
irq_latch = 0;
irq_counter = 0;
irq_enable = false;
irq_delay = 0;
irq_line = 0;
chr_abus = 0;
}
void serialize(serializer &s) {
s.integer(chr_mode);
s.integer(prg_mode);
s.integer(bank_select);
s.array(prg_bank);
s.array(chr_bank);
s.integer(mirror);
s.integer(ram_enable);
s.integer(ram_write_protect);
s.integer(irq_latch);
s.integer(irq_counter);
s.integer(irq_enable);
s.integer(irq_delay);
s.integer(irq_line);
s.integer(chr_abus);
}
MMC3(Board &board) : Chip(board) {
}
};

View File

@@ -0,0 +1,497 @@
struct MMC5 : Chip {
enum class Revision : unsigned {
MMC5,
MMC5B,
} revision;
uint8 exram[1024];
//programmable registers
uint2 prg_mode; //$5100
uint2 chr_mode; //$5101
uint2 prgram_write_protect[2]; //$5102,$5103
uint2 exram_mode; //$5104
uint2 nametable_mode[4]; //$5105
uint8 fillmode_tile; //$5106
uint8 fillmode_color; //$5107
bool ram_select; //$5113
uint2 ram_bank; //$5113
uint8 prg_bank[4]; //$5114-5117
uint10 chr_sprite_bank[8]; //$5120-5127
uint10 chr_bg_bank[4]; //$5128-512b
uint2 chr_bank_hi; //$5130
bool vs_enable; //$5200
bool vs_side; //$5200
uint5 vs_tile; //$5200
uint8 vs_scroll; //$5201
uint8 vs_bank; //$5202
uint8 irq_line; //$5203
bool irq_enable; //$5204
uint8 multiplicand; //$5205
uint8 multiplier; //$5206
//status registers
unsigned cpu_cycle_counter;
unsigned irq_counter;
bool irq_pending;
bool in_frame;
unsigned vcounter;
unsigned hcounter;
uint16 chr_access[4];
bool chr_active;
bool sprite_8x16;
uint8 exbank;
uint8 exattr;
bool vs_fetch;
uint8 vs_vpos;
uint8 vs_hpos;
void main() {
while(true) {
if(scheduler.sync == Scheduler::SynchronizeMode::All) {
scheduler.exit(Scheduler::ExitReason::SynchronizeEvent);
}
//scanline() resets this; if no scanlines detected, enter video blanking period
if(++cpu_cycle_counter >= 200) blank(); //113-114 normal; ~2500 across Vblank period
cpu.set_irq_line(irq_enable && irq_pending);
tick();
}
}
void scanline(unsigned y) {
//used for testing only, to verify MMC5 scanline detection is accurate:
//if(y != vcounter && y <= 240) print(y, " vs ", vcounter, "\n");
}
uint8 prg_access(bool write, unsigned addr, uint8 data = 0x00) {
unsigned bank;
if((addr & 0xe000) == 0x6000) {
bank = (ram_select << 2) | ram_bank;
addr &= 0x1fff;
} else if(prg_mode == 0) {
bank = prg_bank[3] & ~3;
addr &= 0x7fff;
} else if(prg_mode == 1) {
if((addr & 0xc000) == 0x8000) bank = (prg_bank[1] & ~1);
if((addr & 0xe000) == 0xc000) bank = (prg_bank[3] & ~1);
addr &= 0x3fff;
} else if(prg_mode == 2) {
if((addr & 0xe000) == 0x8000) bank = (prg_bank[1] & ~1) | 0;
if((addr & 0xe000) == 0xa000) bank = (prg_bank[1] & ~1) | 1;
if((addr & 0xe000) == 0xc000) bank = (prg_bank[2]);
if((addr & 0xe000) == 0xe000) bank = (prg_bank[3]);
addr &= 0x1fff;
} else if(prg_mode == 3) {
if((addr & 0xe000) == 0x8000) bank = prg_bank[0];
if((addr & 0xe000) == 0xa000) bank = prg_bank[1];
if((addr & 0xe000) == 0xc000) bank = prg_bank[2];
if((addr & 0xe000) == 0xe000) bank = prg_bank[3];
addr &= 0x1fff;
}
bool rom = bank & 0x80;
bank &= 0x7f;
if(write == false) {
if(rom) {
return board.prgrom.read((bank << 13) | addr);
} else {
return board.prgram.read((bank << 13) | addr);
}
} else {
if(rom) {
board.prgrom.write((bank << 13) | addr, data);
} else {
if(prgram_write_protect[0] == 2 && prgram_write_protect[1] == 1) {
board.prgram.write((bank << 13) | addr, data);
}
}
return 0x00;
}
}
uint8 prg_read(unsigned addr) {
if((addr & 0xfc00) == 0x5c00) {
if(exram_mode >= 2) return exram[addr & 0x03ff];
return cpu.mdr();
}
if(addr >= 0x6000) {
return prg_access(0, addr);
}
switch(addr) {
case 0x5204: {
uint8 result = (irq_pending << 7) | (in_frame << 6);
irq_pending = false;
return result;
}
case 0x5205: return (multiplier * multiplicand) >> 0;
case 0x5206: return (multiplier * multiplicand) >> 8;
}
}
void prg_write(unsigned addr, uint8 data) {
if((addr & 0xfc00) == 0x5c00) {
//writes 0x00 *during* Vblank (not during screen rendering ...)
if(exram_mode == 0 || exram_mode == 1) exram[addr & 0x03ff] = in_frame ? data : 0x00;
if(exram_mode == 2) exram[addr & 0x03ff] = data;
return;
}
if(addr >= 0x6000) {
prg_access(1, addr, data);
return;
}
switch(addr) {
case 0x2000:
sprite_8x16 = data & 0x20;
break;
case 0x2001:
//if BG+sprites are disabled; enter video blanking period
if((data & 0x18) == 0) blank();
break;
case 0x5100: prg_mode = data & 3; break;
case 0x5101: chr_mode = data & 3; break;
case 0x5102: prgram_write_protect[0] = data & 3; break;
case 0x5103: prgram_write_protect[1] = data & 3; break;
case 0x5104:
exram_mode = data & 3;
break;
case 0x5105:
nametable_mode[0] = (data & 0x03) >> 0;
nametable_mode[1] = (data & 0x0c) >> 2;
nametable_mode[2] = (data & 0x30) >> 4;
nametable_mode[3] = (data & 0xc0) >> 6;
break;
case 0x5106:
fillmode_tile = data;
break;
case 0x5107:
fillmode_color = data & 3;
fillmode_color |= fillmode_color << 2;
fillmode_color |= fillmode_color << 4;
break;
case 0x5113:
ram_select = data & 0x04;
ram_bank = data & 0x03;
break;
case 0x5114: prg_bank[0] = data; break;
case 0x5115: prg_bank[1] = data; break;
case 0x5116: prg_bank[2] = data; break;
case 0x5117: prg_bank[3] = data | 0x80; break;
case 0x5120: chr_sprite_bank[0] = (chr_bank_hi << 8) | data; chr_active = 0; break;
case 0x5121: chr_sprite_bank[1] = (chr_bank_hi << 8) | data; chr_active = 0; break;
case 0x5122: chr_sprite_bank[2] = (chr_bank_hi << 8) | data; chr_active = 0; break;
case 0x5123: chr_sprite_bank[3] = (chr_bank_hi << 8) | data; chr_active = 0; break;
case 0x5124: chr_sprite_bank[4] = (chr_bank_hi << 8) | data; chr_active = 0; break;
case 0x5125: chr_sprite_bank[5] = (chr_bank_hi << 8) | data; chr_active = 0; break;
case 0x5126: chr_sprite_bank[6] = (chr_bank_hi << 8) | data; chr_active = 0; break;
case 0x5127: chr_sprite_bank[7] = (chr_bank_hi << 8) | data; chr_active = 0; break;
case 0x5128: chr_bg_bank[0] = (chr_bank_hi << 8) | data; chr_active = 1; break;
case 0x5129: chr_bg_bank[1] = (chr_bank_hi << 8) | data; chr_active = 1; break;
case 0x512a: chr_bg_bank[2] = (chr_bank_hi << 8) | data; chr_active = 1; break;
case 0x512b: chr_bg_bank[3] = (chr_bank_hi << 8) | data; chr_active = 1; break;
case 0x5130:
chr_bank_hi = data & 3;
break;
case 0x5200:
vs_enable = data & 0x80;
vs_side = data & 0x40;
vs_tile = data & 0x1f;
break;
case 0x5201:
vs_scroll = data;
break;
case 0x5202:
vs_bank = data;
break;
case 0x5203:
irq_line = data;
break;
case 0x5204:
irq_enable = data & 0x80;
break;
case 0x5205:
multiplicand = data;
break;
case 0x5206:
multiplier = data;
break;
}
}
unsigned chr_sprite_addr(unsigned addr) {
if(chr_mode == 0) {
auto bank = chr_sprite_bank[7];
return (bank * 0x2000) + (addr & 0x1fff);
}
if(chr_mode == 1) {
auto bank = chr_sprite_bank[(addr / 0x1000) * 4 + 3];
return (bank * 0x1000) + (addr & 0x0fff);
}
if(chr_mode == 2) {
auto bank = chr_sprite_bank[(addr / 0x0800) * 2 + 1];
return (bank * 0x0800) + (addr & 0x07ff);
}
if(chr_mode == 3) {
auto bank = chr_sprite_bank[(addr / 0x0400)];
return (bank * 0x0400) + (addr & 0x03ff);
}
}
unsigned chr_bg_addr(unsigned addr) {
addr &= 0x0fff;
if(chr_mode == 0) {
auto bank = chr_bg_bank[3];
return (bank * 0x2000) + (addr & 0x0fff);
}
if(chr_mode == 1) {
auto bank = chr_bg_bank[3];
return (bank * 0x1000) + (addr & 0x0fff);
}
if(chr_mode == 2) {
auto bank = chr_bg_bank[(addr / 0x0800) * 2 + 1];
return (bank * 0x0800) + (addr & 0x07ff);
}
if(chr_mode == 3) {
auto bank = chr_bg_bank[(addr / 0x0400)];
return (bank * 0x0400) + (addr & 0x03ff);
}
}
unsigned chr_vs_addr(unsigned addr) {
return (vs_bank * 0x1000) + (addr & 0x0ff8) + (vs_vpos & 7);
}
void blank() {
in_frame = false;
}
void scanline() {
hcounter = 0;
if(in_frame == false) {
in_frame = true;
irq_pending = false;
vcounter = 0;
} else {
if(vcounter == irq_line) irq_pending = true;
vcounter++;
}
cpu_cycle_counter = 0;
}
uint8 ciram_read(unsigned addr) {
if(vs_fetch && (hcounter & 2) == 0) return exram[vs_vpos / 8 * 32 + vs_hpos / 8];
if(vs_fetch && (hcounter & 2) != 0) return exram[vs_vpos / 32 * 8 + vs_hpos / 32 + 0x03c0];
switch(nametable_mode[(addr >> 10) & 3]) {
case 0: return ppu.ciram_read(0x0000 | (addr & 0x03ff));
case 1: return ppu.ciram_read(0x0400 | (addr & 0x03ff));
case 2: return exram_mode < 2 ? exram[addr & 0x03ff] : 0x00;
case 3: return (hcounter & 2) == 0 ? fillmode_tile : fillmode_color;
}
}
uint8 chr_read(unsigned addr) {
chr_access[0] = chr_access[1];
chr_access[1] = chr_access[2];
chr_access[2] = chr_access[3];
chr_access[3] = addr;
//detect two unused nametable fetches at end of each scanline
if((chr_access[0] & 0x2000) == 0
&& (chr_access[1] & 0x2000)
&& (chr_access[2] & 0x2000)
&& (chr_access[3] & 0x2000)) scanline();
if(in_frame == false) {
vs_fetch = false;
if(addr & 0x2000) return ciram_read(addr);
return board.chrrom.read(chr_active ? chr_bg_addr(addr) : chr_sprite_addr(addr));
}
bool bg_fetch = (hcounter < 256 || hcounter >= 320);
uint8 result = 0x00;
if((hcounter & 7) == 0) {
vs_hpos = hcounter >= 320 ? hcounter - 320 : hcounter + 16;
vs_vpos = vcounter + vs_scroll;
vs_fetch = vs_enable && bg_fetch && exram_mode < 2
&& (vs_side ? vs_hpos / 8 >= vs_tile : vs_hpos / 8 < vs_tile);
if(vs_vpos >= 240) vs_vpos -= 240;
result = ciram_read(addr);
exbank = (chr_bank_hi << 6) | (exram[addr & 0x03ff] & 0x3f);
exattr = exram[addr & 0x03ff] >> 6;
exattr |= exattr << 2;
exattr |= exattr << 4;
} else if((hcounter & 7) == 2) {
result = ciram_read(addr);
if(bg_fetch && exram_mode == 1) result = exattr;
} else {
if(vs_fetch) result = board.chrrom.read(chr_vs_addr(addr));
else if(sprite_8x16 ? bg_fetch : chr_active) result = board.chrrom.read(chr_bg_addr(addr));
else result = board.chrrom.read(chr_sprite_addr(addr));
if(bg_fetch && exram_mode == 1) result = board.chrrom.read(exbank * 0x1000 + (addr & 0x0fff));
}
hcounter += 2;
return result;
}
void chr_write(unsigned addr, uint8 data) {
if(addr & 0x2000) {
switch(nametable_mode[(addr >> 10) & 3]) {
case 0: return ppu.ciram_write(0x0000 | (addr & 0x03ff), data);
case 1: return ppu.ciram_write(0x0400 | (addr & 0x03ff), data);
case 2: exram[addr & 0x03ff] = data; break;
}
}
}
void power() {
}
void reset() {
for(auto &n : exram) n = 0xff;
prg_mode = 3;
chr_mode = 0;
for(auto &n : prgram_write_protect) n = 0;
exram_mode = 0;
for(auto &n : nametable_mode) n = 0;
fillmode_tile = 0;
fillmode_color = 0;
ram_select = 0;
ram_bank = 0;
prg_bank[0] = 0x00;
prg_bank[1] = 0x00;
prg_bank[2] = 0x00;
prg_bank[3] = 0xff;
for(auto &n : chr_sprite_bank) n = 0;
for(auto &n : chr_bg_bank) n = 0;
chr_bank_hi = 0;
vs_enable = 0;
vs_side = 0;
vs_tile = 0;
vs_scroll = 0;
vs_bank = 0;
irq_line = 0;
irq_enable = 0;
multiplicand = 0;
multiplier = 0;
cpu_cycle_counter = 0;
irq_counter = 0;
irq_pending = 0;
in_frame = 0;
vcounter = 0;
hcounter = 0;
for(auto &n : chr_access) n = 0;
chr_active = 0;
sprite_8x16 = 0;
exbank = 0;
exattr = 0;
vs_fetch = 0;
vs_vpos = 0;
vs_hpos = 0;
}
void serialize(serializer &s) {
s.array(exram);
s.integer(prg_mode);
s.integer(chr_mode);
for(auto &n : prgram_write_protect) s.integer(n);
s.integer(exram_mode);
for(auto &n : nametable_mode) s.integer(n);
s.integer(fillmode_tile);
s.integer(fillmode_color);
s.integer(ram_select);
s.integer(ram_bank);
for(auto &n : prg_bank) s.integer(n);
for(auto &n : chr_sprite_bank) s.integer(n);
for(auto &n : chr_bg_bank) s.integer(n);
s.integer(chr_bank_hi);
s.integer(vs_enable);
s.integer(vs_side);
s.integer(vs_tile);
s.integer(vs_scroll);
s.integer(vs_bank);
s.integer(irq_line);
s.integer(irq_enable);
s.integer(multiplicand);
s.integer(multiplier);
s.integer(cpu_cycle_counter);
s.integer(irq_counter);
s.integer(irq_pending);
s.integer(in_frame);
s.integer(vcounter);
s.integer(hcounter);
for(auto &n : chr_access) s.integer(n);
s.integer(chr_active);
s.integer(sprite_8x16);
s.integer(exbank);
s.integer(exattr);
s.integer(vs_fetch);
s.integer(vs_vpos);
s.integer(vs_hpos);
}
MMC5(Board &board) : Chip(board) {
revision = Revision::MMC5;
}
};

View File

@@ -0,0 +1,200 @@
struct MMC6 : Chip {
bool chr_mode;
bool prg_mode;
bool ram_enable;
uint3 bank_select;
uint8 prg_bank[2];
uint8 chr_bank[6];
bool mirror;
bool ram_readable[2];
bool ram_writable[2];
uint8 irq_latch;
uint8 irq_counter;
bool irq_enable;
unsigned irq_delay;
bool irq_line;
uint16 chr_abus;
void main() {
while(true) {
if(scheduler.sync == Scheduler::SynchronizeMode::All) {
scheduler.exit(Scheduler::ExitReason::SynchronizeEvent);
}
if(irq_delay) irq_delay--;
cpu.set_irq_line(irq_line);
tick();
}
}
void irq_test(unsigned addr) {
if(!(chr_abus & 0x1000) && (addr & 0x1000)) {
if(irq_delay == 0) {
if(irq_counter == 0) {
irq_counter = irq_latch;
} else if(--irq_counter == 0) {
if(irq_enable) irq_line = 1;
}
}
irq_delay = 6;
}
chr_abus = addr;
}
unsigned prg_addr(unsigned addr) const {
switch((addr >> 13) & 3) {
case 0:
if(prg_mode == 1) return (0x3e << 13) | (addr & 0x1fff);
return (prg_bank[0] << 13) | (addr & 0x1fff);
case 1:
return (prg_bank[1] << 13) | (addr & 0x1fff);
case 2:
if(prg_mode == 0) return (0x3e << 13) | (addr & 0x1fff);
return (prg_bank[0] << 13) | (addr & 0x1fff);
case 3:
return (0x3f << 13) | (addr & 0x1fff);
}
}
unsigned chr_addr(unsigned addr) const {
if(chr_mode == 0) {
if(addr <= 0x07ff) return (chr_bank[0] << 10) | (addr & 0x07ff);
if(addr <= 0x0fff) return (chr_bank[1] << 10) | (addr & 0x07ff);
if(addr <= 0x13ff) return (chr_bank[2] << 10) | (addr & 0x03ff);
if(addr <= 0x17ff) return (chr_bank[3] << 10) | (addr & 0x03ff);
if(addr <= 0x1bff) return (chr_bank[4] << 10) | (addr & 0x03ff);
if(addr <= 0x1fff) return (chr_bank[5] << 10) | (addr & 0x03ff);
} else {
if(addr <= 0x03ff) return (chr_bank[2] << 10) | (addr & 0x03ff);
if(addr <= 0x07ff) return (chr_bank[3] << 10) | (addr & 0x03ff);
if(addr <= 0x0bff) return (chr_bank[4] << 10) | (addr & 0x03ff);
if(addr <= 0x0fff) return (chr_bank[5] << 10) | (addr & 0x03ff);
if(addr <= 0x17ff) return (chr_bank[0] << 10) | (addr & 0x07ff);
if(addr <= 0x1fff) return (chr_bank[1] << 10) | (addr & 0x07ff);
}
}
unsigned ciram_addr(unsigned addr) const {
if(mirror == 0) return ((addr & 0x0400) >> 0) | (addr & 0x03ff);
if(mirror == 1) return ((addr & 0x0800) >> 1) | (addr & 0x03ff);
}
uint8 ram_read(unsigned addr) {
if(ram_enable == false) return cpu.mdr();
if(ram_readable[0] == false && ram_readable[1] == false) return cpu.mdr();
bool region = addr & 0x0200;
if(ram_readable[region] == false) return 0x00;
return board.prgram.read((region * 0x0200) + (addr & 0x01ff));
}
void ram_write(unsigned addr, uint8 data) {
if(ram_enable == false) return;
bool region = addr & 0x0200;
if(ram_writable[region] == false) return;
return board.prgram.write((region * 0x0200) + (addr & 0x01ff), data);
}
void reg_write(unsigned addr, uint8 data) {
switch(addr & 0xe001) {
case 0x8000:
chr_mode = data & 0x80;
prg_mode = data & 0x40;
ram_enable = data & 0x20;
bank_select = data & 0x07;
if(ram_enable == false) {
for(auto &n : ram_readable) n = false;
for(auto &n : ram_writable) n = false;
}
break;
case 0x8001:
switch(bank_select) {
case 0: chr_bank[0] = data & ~1; break;
case 1: chr_bank[1] = data & ~1; break;
case 2: chr_bank[2] = data; break;
case 3: chr_bank[3] = data; break;
case 4: chr_bank[4] = data; break;
case 5: chr_bank[5] = data; break;
case 6: prg_bank[0] = data & 0x3f; break;
case 7: prg_bank[1] = data & 0x3f; break;
}
break;
case 0xa000:
mirror = data & 0x01;
break;
case 0xa001:
if(ram_enable == false) break;
ram_readable[1] = data & 0x80;
ram_writable[1] = data & 0x40;
ram_readable[0] = data & 0x20;
ram_writable[0] = data & 0x10;
break;
case 0xc000:
irq_latch = data;
break;
case 0xc001:
irq_counter = 0;
break;
case 0xe000:
irq_enable = false;
irq_line = 0;
break;
case 0xe001:
irq_enable = true;
break;
}
}
void power() {
}
void reset() {
chr_mode = 0;
prg_mode = 0;
ram_enable = 0;
bank_select = 0;
for(auto &n : prg_bank) n = 0;
for(auto &n : chr_bank) n = 0;
mirror = 0;
for(auto &n : ram_readable) n = 0;
for(auto &n : ram_writable) n = 0;
irq_latch = 0;
irq_counter = 0;
irq_enable = 0;
irq_delay = 0;
irq_line = 0;
chr_abus = 0;
}
void serialize(serializer &s) {
s.integer(chr_mode);
s.integer(prg_mode);
s.integer(ram_enable);
s.integer(bank_select);
for(auto &n : prg_bank) s.integer(n);
for(auto &n : chr_bank) s.integer(n);
s.integer(mirror);
for(auto &n : ram_readable) s.integer(n);
for(auto &n : ram_writable) s.integer(n);
s.integer(irq_latch);
s.integer(irq_counter);
s.integer(irq_enable);
s.integer(irq_delay);
s.integer(irq_line);
s.integer(chr_abus);
}
MMC6(Board &board) : Chip(board) {
}
};

View File

@@ -0,0 +1,80 @@
struct VRC1 : Chip {
uint4 prg_bank[3];
uint4 chr_banklo[2];
bool chr_bankhi[2];
bool mirror;
unsigned prg_addr(unsigned addr) const {
unsigned bank = 0x0f;
if((addr & 0xe000) == 0x8000) bank = prg_bank[0];
if((addr & 0xe000) == 0xa000) bank = prg_bank[1];
if((addr & 0xe000) == 0xc000) bank = prg_bank[2];
return (bank * 0x2000) + (addr & 0x1fff);
}
unsigned chr_addr(unsigned addr) const {
unsigned bank = chr_banklo[(bool)(addr & 0x1000)];
bank |= chr_bankhi[(bool)(addr & 0x1000)] << 4;
return (bank * 0x1000) + (addr & 0x0fff);
}
unsigned ciram_addr(unsigned addr) const {
switch(mirror) {
case 0: return ((addr & 0x0400) >> 0) | (addr & 0x03ff); //vertical mirroring
case 1: return ((addr & 0x0800) >> 1) | (addr & 0x03ff); //horizontal mirroring
}
throw;
}
void reg_write(unsigned addr, uint8 data) {
switch(addr & 0xf000) {
case 0x8000:
prg_bank[0] = data & 0x0f;
break;
case 0x9000:
chr_bankhi[1] = data & 0x04;
chr_bankhi[0] = data & 0x02;
mirror = data & 0x01;
break;
case 0xa000:
prg_bank[1] = data & 0x0f;
break;
case 0xc000:
prg_bank[2] = data & 0x0f;
break;
case 0xe000:
chr_banklo[0] = data & 0x0f;
break;
case 0xf000:
chr_banklo[1] = data & 0x0f;
break;
}
}
void power() {
}
void reset() {
for(auto &n : prg_bank) n = 0;
for(auto &n : chr_banklo) n = 0;
for(auto &n : chr_bankhi) n = 0;
mirror = 0;
}
void serialize(serializer &s) {
for(auto &n : prg_bank) s.integer(n);
for(auto &n : chr_banklo) s.integer(n);
for(auto &n : chr_bankhi) s.integer(n);
s.integer(mirror);
}
VRC1(Board &board) : Chip(board) {
}
};

View File

@@ -0,0 +1,110 @@
struct VRC2 : Chip {
uint5 prg_bank[2];
uint8 chr_bank[8];
uint2 mirror;
bool latch;
unsigned prg_addr(unsigned addr) const {
unsigned bank;
switch(addr & 0xe000) {
case 0x8000: bank = prg_bank[0]; break;
case 0xa000: bank = prg_bank[1]; break;
case 0xc000: bank = 0x1e; break;
case 0xe000: bank = 0x1f; break;
}
return (bank * 0x2000) + (addr & 0x1fff);
}
unsigned chr_addr(unsigned addr) const {
unsigned bank = chr_bank[addr / 0x0400];
return (bank * 0x0400) + (addr & 0x03ff);
}
unsigned ciram_addr(unsigned addr) const {
switch(mirror) {
case 0: return ((addr & 0x0400) >> 0) | (addr & 0x03ff); //vertical mirroring
case 1: return ((addr & 0x0800) >> 1) | (addr & 0x03ff); //horizontal mirroring
case 2: return 0x0000 | (addr & 0x03ff); //one-screen mirroring (first)
case 3: return 0x0400 | (addr & 0x03ff); //one-screen mirroring (second)
}
throw;
}
uint8 ram_read(unsigned addr) {
if(board.prgram.size == 0) {
if((addr & 0xf000) == 0x6000) return cpu.mdr() | latch;
return cpu.mdr();
}
return board.prgram.read(addr & 0x1fff);
}
void ram_write(unsigned addr, uint8 data) {
if(board.prgram.size == 0) {
if((addr & 0xf000) == 0x6000) latch = data & 0x01;
return;
}
return board.prgram.write(addr & 0x1fff, data);
}
void reg_write(unsigned addr, uint8 data) {
switch(addr) {
case 0x8000: case 0x8001: case 0x8002: case 0x8003:
prg_bank[0] = data & 0x1f;
break;
case 0x9000: case 0x9001: case 0x9002: case 0x9003:
mirror = data & 0x03;
break;
case 0xa000: case 0xa001: case 0xa002: case 0xa003:
prg_bank[1] = data & 0x1f;
break;
case 0xb000: chr_bank[0] = (chr_bank[0] & 0xf0) | ((data & 0x0f) << 0); break;
case 0xb001: chr_bank[0] = (chr_bank[0] & 0x0f) | ((data & 0x0f) << 4); break;
case 0xb002: chr_bank[1] = (chr_bank[1] & 0xf0) | ((data & 0x0f) << 0); break;
case 0xb003: chr_bank[1] = (chr_bank[1] & 0x0f) | ((data & 0x0f) << 4); break;
case 0xc000: chr_bank[2] = (chr_bank[2] & 0xf0) | ((data & 0x0f) << 0); break;
case 0xc001: chr_bank[2] = (chr_bank[2] & 0x0f) | ((data & 0x0f) << 4); break;
case 0xc002: chr_bank[3] = (chr_bank[3] & 0xf0) | ((data & 0x0f) << 0); break;
case 0xc003: chr_bank[3] = (chr_bank[3] & 0x0f) | ((data & 0x0f) << 4); break;
case 0xd000: chr_bank[4] = (chr_bank[4] & 0xf0) | ((data & 0x0f) << 0); break;
case 0xd001: chr_bank[4] = (chr_bank[4] & 0x0f) | ((data & 0x0f) << 4); break;
case 0xd002: chr_bank[5] = (chr_bank[5] & 0xf0) | ((data & 0x0f) << 0); break;
case 0xd003: chr_bank[5] = (chr_bank[5] & 0x0f) | ((data & 0x0f) << 4); break;
case 0xe000: chr_bank[6] = (chr_bank[6] & 0xf0) | ((data & 0x0f) << 0); break;
case 0xe001: chr_bank[6] = (chr_bank[6] & 0x0f) | ((data & 0x0f) << 4); break;
case 0xe002: chr_bank[7] = (chr_bank[7] & 0xf0) | ((data & 0x0f) << 0); break;
case 0xe003: chr_bank[7] = (chr_bank[7] & 0x0f) | ((data & 0x0f) << 4); break;
}
}
void power() {
}
void reset() {
for(auto &n : prg_bank) n = 0;
for(auto &n : chr_bank) n = 0;
mirror = 0;
latch = 0;
}
void serialize(serializer &s) {
for(auto &n : prg_bank) s.integer(n);
for(auto &n : chr_bank) s.integer(n);
s.integer(mirror);
s.integer(latch);
}
VRC2(Board &board) : Chip(board) {
}
};

View File

@@ -0,0 +1,100 @@
struct VRC3 : Chip {
uint4 prg_bank;
bool irq_mode;
bool irq_enable;
bool irq_acknowledge;
uint16 irq_latch;
struct {
union {
uint16 w;
struct { uint8 order_lsb2(l, h); };
};
} irq_counter;
bool irq_line;
void main() {
while(true) {
if(scheduler.sync == Scheduler::SynchronizeMode::All) {
scheduler.exit(Scheduler::ExitReason::SynchronizeEvent);
}
if(irq_enable) {
if(irq_mode == 0) { //16-bit
if(++irq_counter.w == 0) {
irq_line = 1;
irq_enable = irq_acknowledge;
irq_counter.w = irq_latch;
}
}
if(irq_mode == 1) { //8-bit
if(++irq_counter.l == 0) {
irq_line = 1;
irq_enable = irq_acknowledge;
irq_counter.l = irq_latch;
}
}
}
cpu.set_irq_line(irq_line);
tick();
}
}
unsigned prg_addr(unsigned addr) const {
unsigned bank = (addr < 0xc000 ? (unsigned)prg_bank : 0x0f);
return (bank * 0x4000) + (addr & 0x3fff);
}
void reg_write(unsigned addr, uint8 data) {
switch(addr & 0xf000) {
case 0x8000: irq_latch = (irq_latch & 0xfff0) | ((data & 0x0f) << 0); break;
case 0x9000: irq_latch = (irq_latch & 0xff0f) | ((data & 0x0f) << 4); break;
case 0xa000: irq_latch = (irq_latch & 0xf0ff) | ((data & 0x0f) << 8); break;
case 0xb000: irq_latch = (irq_latch & 0x0fff) | ((data & 0x0f) << 12); break;
case 0xc000:
irq_mode = data & 0x04;
irq_enable = data & 0x02;
irq_acknowledge = data & 0x01;
if(irq_enable) irq_counter.w = irq_latch;
break;
case 0xd000:
irq_line = 0;
irq_enable = irq_acknowledge;
break;
case 0xf000:
prg_bank = data & 0x0f;
break;
}
}
void power() {
}
void reset() {
prg_bank = 0;
irq_mode = 0;
irq_enable = 0;
irq_acknowledge = 0;
irq_latch = 0;
irq_counter.w = 0;
irq_line = 0;
}
void serialize(serializer &s) {
s.integer(prg_bank);
s.integer(irq_mode);
s.integer(irq_enable);
s.integer(irq_acknowledge);
s.integer(irq_latch);
s.integer(irq_counter.w);
s.integer(irq_line);
}
VRC3(Board &board) : Chip(board) {
}
};

View File

@@ -0,0 +1,184 @@
struct VRC4 : Chip {
bool prg_mode;
uint5 prg_bank[2];
uint2 mirror;
uint8 chr_bank[8];
uint8 irq_latch;
bool irq_mode;
bool irq_enable;
bool irq_acknowledge;
uint8 irq_counter;
signed irq_scalar;
bool irq_line;
void main() {
while(true) {
if(scheduler.sync == Scheduler::SynchronizeMode::All) {
scheduler.exit(Scheduler::ExitReason::SynchronizeEvent);
}
if(irq_enable) {
if(irq_mode == 0) {
irq_scalar -= 3;
if(irq_scalar <= 0) {
irq_scalar += 341;
if(irq_counter == 0xff) {
irq_counter = irq_latch;
irq_line = 1;
} else {
irq_counter++;
}
}
}
if(irq_mode == 1) {
if(irq_counter == 0xff) {
irq_counter = irq_latch;
irq_line = 1;
} else {
irq_counter++;
}
}
}
cpu.set_irq_line(irq_line);
tick();
}
}
unsigned prg_addr(unsigned addr) const {
unsigned bank = 0, banks = board.prgrom.size / 0x2000;
switch(addr & 0xe000) {
case 0x8000: bank = prg_mode == 0 ? (unsigned)prg_bank[0] : banks - 2; break;
case 0xa000: bank = prg_bank[1]; break;
case 0xc000: bank = prg_mode == 0 ? banks - 2 : (unsigned)prg_bank[0]; break;
case 0xe000: bank = banks - 1; break;
}
return (bank * 0x2000) + (addr & 0x1fff);
}
unsigned chr_addr(unsigned addr) const {
unsigned bank = chr_bank[addr / 0x0400];
return (bank * 0x0400) + (addr & 0x03ff);
}
unsigned ciram_addr(unsigned addr) const {
switch(mirror) {
case 0: return ((addr & 0x0400) >> 0) | (addr & 0x03ff); //vertical mirroring
case 1: return ((addr & 0x0800) >> 1) | (addr & 0x03ff); //horizontal mirroring
case 2: return 0x0000 | (addr & 0x03ff); //one-screen mirroring (first)
case 3: return 0x0400 | (addr & 0x03ff); //one-screen mirroring (second)
}
throw;
}
void reg_write(unsigned addr, uint8 data) {
switch(addr) {
case 0x8000: case 0x8001: case 0x8002: case 0x8003:
prg_bank[0] = data & 0x1f;
break;
case 0x9000: case 0x9001:
mirror = data & 0x03;
break;
case 0x9002: case 0x9003:
prg_mode = data & 0x02;
break;
case 0xa000: case 0xa001: case 0xa002: case 0xa003:
prg_bank[1] = data & 0x1f;
break;
case 0xb000: chr_bank[0] = (chr_bank[0] & 0xf0) | ((data & 0x0f) << 0); break;
case 0xb001: chr_bank[0] = (chr_bank[0] & 0x0f) | ((data & 0x0f) << 4); break;
case 0xb002: chr_bank[1] = (chr_bank[1] & 0xf0) | ((data & 0x0f) << 0); break;
case 0xb003: chr_bank[1] = (chr_bank[1] & 0x0f) | ((data & 0x0f) << 4); break;
case 0xc000: chr_bank[2] = (chr_bank[2] & 0xf0) | ((data & 0x0f) << 0); break;
case 0xc001: chr_bank[2] = (chr_bank[2] & 0x0f) | ((data & 0x0f) << 4); break;
case 0xc002: chr_bank[3] = (chr_bank[3] & 0xf0) | ((data & 0x0f) << 0); break;
case 0xc003: chr_bank[3] = (chr_bank[3] & 0x0f) | ((data & 0x0f) << 4); break;
case 0xd000: chr_bank[4] = (chr_bank[4] & 0xf0) | ((data & 0x0f) << 0); break;
case 0xd001: chr_bank[4] = (chr_bank[4] & 0x0f) | ((data & 0x0f) << 4); break;
case 0xd002: chr_bank[5] = (chr_bank[5] & 0xf0) | ((data & 0x0f) << 0); break;
case 0xd003: chr_bank[5] = (chr_bank[5] & 0x0f) | ((data & 0x0f) << 4); break;
case 0xe000: chr_bank[6] = (chr_bank[6] & 0xf0) | ((data & 0x0f) << 0); break;
case 0xe001: chr_bank[6] = (chr_bank[6] & 0x0f) | ((data & 0x0f) << 4); break;
case 0xe002: chr_bank[7] = (chr_bank[7] & 0xf0) | ((data & 0x0f) << 0); break;
case 0xe003: chr_bank[7] = (chr_bank[7] & 0x0f) | ((data & 0x0f) << 4); break;
case 0xf000:
irq_latch = (irq_latch & 0xf0) | ((data & 0x0f) << 0);
break;
case 0xf001:
irq_latch = (irq_latch & 0x0f) | ((data & 0x0f) << 4);
break;
case 0xf002:
irq_mode = data & 0x04;
irq_enable = data & 0x02;
irq_acknowledge = data & 0x01;
if(irq_enable) {
irq_counter = irq_latch;
irq_scalar = 341;
}
irq_line = 0;
break;
case 0xf003:
irq_enable = irq_acknowledge;
irq_line = 0;
break;
}
}
void power() {
}
void reset() {
prg_mode = 0;
for(auto &n : prg_bank) n = 0;
mirror = 0;
for(auto &n : chr_bank) n = 0;
irq_latch = 0;
irq_mode = 0;
irq_enable = 0;
irq_acknowledge = 0;
irq_counter = 0;
irq_scalar = 0;
irq_line = 0;
}
void serialize(serializer &s) {
s.integer(prg_mode);
for(auto &n : prg_bank) s.integer(n);
s.integer(mirror);
for(auto &n : chr_bank) s.integer(n);
s.integer(irq_latch);
s.integer(irq_mode);
s.integer(irq_enable);
s.integer(irq_acknowledge);
s.integer(irq_counter);
s.integer(irq_scalar);
s.integer(irq_line);
}
VRC4(Board &board) : Chip(board) {
}
};

View File

@@ -0,0 +1,321 @@
struct VRC6 : Chip {
uint8 prg_bank[2];
uint8 chr_bank[8];
uint2 mirror;
uint8 irq_latch;
bool irq_mode;
bool irq_enable;
bool irq_acknowledge;
uint8 irq_counter;
signed irq_scalar;
bool irq_line;
struct Pulse {
bool mode;
uint3 duty;
uint4 volume;
bool enable;
uint12 frequency;
uint12 divider;
uint4 cycle;
uint4 output;
void clock() {
if(--divider == 0) {
divider = frequency + 1;
cycle++;
output = (mode == 1 || cycle > duty) ? volume : (uint4)0;
}
if(enable == false) output = 0;
}
void serialize(serializer &s) {
s.integer(mode);
s.integer(duty);
s.integer(volume);
s.integer(enable);
s.integer(frequency);
s.integer(divider);
s.integer(cycle);
s.integer(output);
}
} pulse1, pulse2;
struct Sawtooth {
uint6 rate;
bool enable;
uint12 frequency;
uint12 divider;
uint1 phase;
uint3 stage;
uint8 accumulator;
uint5 output;
void clock() {
if(--divider == 0) {
divider = frequency + 1;
if(++phase == 0) {
accumulator += rate;
if(++stage == 7) {
stage = 0;
accumulator = 0;
}
}
}
output = accumulator >> 3;
if(enable == false) output = 0;
}
void serialize(serializer &s) {
s.integer(rate);
s.integer(enable);
s.integer(frequency);
s.integer(divider);
s.integer(phase);
s.integer(stage);
s.integer(accumulator);
s.integer(output);
}
} sawtooth;
void main() {
while(true) {
if(scheduler.sync == Scheduler::SynchronizeMode::All) {
scheduler.exit(Scheduler::ExitReason::SynchronizeEvent);
}
if(irq_enable) {
if(irq_mode == 0) {
irq_scalar -= 3;
if(irq_scalar <= 0) {
irq_scalar += 341;
if(irq_counter == 0xff) {
irq_counter = irq_latch;
irq_line = 1;
} else {
irq_counter++;
}
}
}
if(irq_mode == 1) {
if(irq_counter == 0xff) {
irq_counter = irq_latch;
irq_line = 1;
} else {
irq_counter++;
}
}
}
cpu.set_irq_line(irq_line);
pulse1.clock();
pulse2.clock();
sawtooth.clock();
signed output = (pulse1.output + pulse2.output + sawtooth.output) << 7;
apu.set_sample(-output);
tick();
}
}
unsigned prg_addr(unsigned addr) const {
if((addr & 0xc000) == 0x8000) return (prg_bank[0] << 14) | (addr & 0x3fff);
if((addr & 0xe000) == 0xc000) return (prg_bank[1] << 13) | (addr & 0x1fff);
if((addr & 0xe000) == 0xe000) return ( 0xff << 13) | (addr & 0x1fff);
}
unsigned chr_addr(unsigned addr) const {
unsigned bank = chr_bank[(addr >> 10) & 7];
return (bank << 10) | (addr & 0x03ff);
}
unsigned ciram_addr(unsigned addr) const {
switch(mirror) {
case 0: return ((addr & 0x0400) >> 0) | (addr & 0x03ff); //vertical mirroring
case 1: return ((addr & 0x0800) >> 1) | (addr & 0x03ff); //horizontal mirroring
case 2: return 0x0000 | (addr & 0x03ff); //one-screen mirroring (first)
case 3: return 0x0400 | (addr & 0x03ff); //one-screen mirroring (second)
}
}
uint8 ram_read(unsigned addr) {
return board.prgram.data[addr & 0x1fff];
}
void ram_write(unsigned addr, uint8 data) {
board.prgram.data[addr & 0x1fff] = data;
}
void reg_write(unsigned addr, uint8 data) {
switch(addr) {
case 0x8000: case 0x8001: case 0x8002: case 0x8003:
prg_bank[0] = data;
break;
case 0x9000:
pulse1.mode = data & 0x80;
pulse1.duty = (data & 0x70) >> 4;
pulse1.volume = data & 0x0f;
break;
case 0x9001:
pulse1.frequency = (pulse1.frequency & 0x0f00) | ((data & 0xff) << 0);
break;
case 0x9002:
pulse1.frequency = (pulse1.frequency & 0x00ff) | ((data & 0x0f) << 8);
pulse1.enable = data & 0x80;
break;
case 0xa000:
pulse2.mode = data & 0x80;
pulse2.duty = (data & 0x70) >> 4;
pulse2.volume = data & 0x0f;
break;
case 0xa001:
pulse2.frequency = (pulse2.frequency & 0x0f00) | ((data & 0xff) << 0);
break;
case 0xa002:
pulse2.frequency = (pulse2.frequency & 0x00ff) | ((data & 0x0f) << 8);
pulse2.enable = data & 0x80;
break;
case 0xb000:
sawtooth.rate = data & 0x3f;
break;
case 0xb001:
sawtooth.frequency = (sawtooth.frequency & 0x0f00) | ((data & 0xff) << 0);
break;
case 0xb002:
sawtooth.frequency = (sawtooth.frequency & 0x00ff) | ((data & 0x0f) << 8);
sawtooth.enable = data & 0x80;
break;
case 0xb003:
mirror = (data >> 2) & 3;
break;
case 0xc000: case 0xc001: case 0xc002: case 0xc003:
prg_bank[1] = data;
break;
case 0xd000: case 0xd001: case 0xd002: case 0xd003:
chr_bank[0 + (addr & 3)] = data;
break;
case 0xe000: case 0xe001: case 0xe002: case 0xe003:
chr_bank[4 + (addr & 3)] = data;
break;
case 0xf000:
irq_latch = data;
break;
case 0xf001:
irq_mode = data & 0x04;
irq_enable = data & 0x02;
irq_acknowledge = data & 0x01;
if(irq_enable) {
irq_counter = irq_latch;
irq_scalar = 341;
}
irq_line = 0;
break;
case 0xf002:
irq_enable = irq_acknowledge;
irq_line = 0;
break;
}
}
void power() {
}
void reset() {
prg_bank[0] = 0;
prg_bank[1] = 0;
chr_bank[0] = 0;
chr_bank[1] = 0;
chr_bank[2] = 0;
chr_bank[3] = 0;
chr_bank[4] = 0;
chr_bank[5] = 0;
chr_bank[6] = 0;
chr_bank[7] = 0;
mirror = 0;
irq_latch = 0;
irq_mode = 0;
irq_enable = 0;
irq_acknowledge = 0;
irq_counter = 0;
irq_scalar = 0;
irq_line = 0;
pulse1.mode = 0;
pulse1.duty = 0;
pulse1.volume = 0;
pulse1.enable = 0;
pulse1.frequency = 0;
pulse1.divider = 1;
pulse1.cycle = 0;
pulse1.output = 0;
pulse2.mode = 0;
pulse2.duty = 0;
pulse2.volume = 0;
pulse2.enable = 0;
pulse2.frequency = 0;
pulse2.divider = 1;
pulse2.cycle = 0;
pulse2.output = 0;
sawtooth.rate = 0;
sawtooth.enable = 0;
sawtooth.frequency = 0;
sawtooth.divider = 1;
sawtooth.phase = 0;
sawtooth.stage = 0;
sawtooth.accumulator = 0;
sawtooth.output = 0;
}
void serialize(serializer &s) {
pulse1.serialize(s);
pulse2.serialize(s);
sawtooth.serialize(s);
s.array(prg_bank);
s.array(chr_bank);
s.integer(mirror);
s.integer(irq_latch);
s.integer(irq_mode);
s.integer(irq_enable);
s.integer(irq_acknowledge);
s.integer(irq_counter);
s.integer(irq_scalar);
s.integer(irq_line);
}
VRC6(Board &board) : Chip(board) {
}
};

View File

@@ -0,0 +1,154 @@
//Konami VRC7
//Yamaha YM2413 OPLL audio - not emulated
struct VRC7 : Chip {
uint8 prg_bank[3];
uint8 chr_bank[8];
uint2 mirror;
uint8 irq_latch;
bool irq_mode;
bool irq_enable;
bool irq_acknowledge;
uint8 irq_counter;
signed irq_scalar;
bool irq_line;
void main() {
while(true) {
if(scheduler.sync == Scheduler::SynchronizeMode::All) {
scheduler.exit(Scheduler::ExitReason::SynchronizeEvent);
}
if(irq_enable) {
if(irq_mode == 0) {
irq_scalar -= 3;
if(irq_scalar <= 0) {
irq_scalar += 341;
if(irq_counter == 0xff) {
irq_counter = irq_latch;
irq_line = 1;
} else {
irq_counter++;
}
}
}
if(irq_mode == 1) {
if(irq_counter == 0xff) {
irq_counter = irq_latch;
irq_line = 1;
} else {
irq_counter++;
}
}
}
cpu.set_irq_line(irq_line);
tick();
}
}
void reg_write(unsigned addr, uint8 data) {
switch(addr) {
case 0x8000: prg_bank[0] = data; break;
case 0x8010: prg_bank[1] = data; break;
case 0x9000: prg_bank[2] = data; break;
case 0x9010: break; //APU addr port
case 0x9030: break; //APU data port
case 0xa000: chr_bank[0] = data; break;
case 0xa010: chr_bank[1] = data; break;
case 0xb000: chr_bank[2] = data; break;
case 0xb010: chr_bank[3] = data; break;
case 0xc000: chr_bank[4] = data; break;
case 0xc010: chr_bank[5] = data; break;
case 0xd000: chr_bank[6] = data; break;
case 0xd010: chr_bank[7] = data; break;
case 0xe000: mirror = data & 0x03; break;
case 0xe010:
irq_latch = data;
break;
case 0xf000:
irq_mode = data & 0x04;
irq_enable = data & 0x02;
irq_acknowledge = data & 0x01;
if(irq_enable) {
irq_counter = irq_latch;
irq_scalar = 341;
}
irq_line = 0;
break;
case 0xf010:
irq_enable = irq_acknowledge;
irq_line = 0;
break;
}
}
unsigned prg_addr(unsigned addr) const {
unsigned bank = 0;
switch(addr & 0xe000) {
case 0x8000: bank = prg_bank[0]; break;
case 0xa000: bank = prg_bank[1]; break;
case 0xc000: bank = prg_bank[2]; break;
case 0xe000: bank = 0xff; break;
}
return (bank * 0x2000) + (addr & 0x1fff);
}
unsigned chr_addr(unsigned addr) const {
unsigned bank = chr_bank[addr / 0x0400];
return (bank * 0x0400) + (addr & 0x03ff);
}
unsigned ciram_addr(unsigned addr) const {
switch(mirror) {
case 0: return ((addr & 0x0400) >> 0) | (addr & 0x03ff); //vertical mirroring
case 1: return ((addr & 0x0800) >> 1) | (addr & 0x03ff); //horizontal mirroring
case 2: return 0x0000 | (addr & 0x03ff); //one-screen mirroring (first)
case 3: return 0x0400 | (addr & 0x03ff); //one-screen mirroring (second)
}
}
void power() {
}
void reset() {
for(auto &n : prg_bank) n = 0;
for(auto &n : chr_bank) n = 0;
mirror = 0;
irq_latch = 0;
irq_mode = 0;
irq_enable = 0;
irq_acknowledge = 0;
irq_counter = 0;
irq_scalar = 0;
irq_line = 0;
}
void serialize(serializer &s) {
s.array(prg_bank);
s.array(chr_bank);
s.integer(mirror);
s.integer(irq_latch);
s.integer(irq_mode);
s.integer(irq_enable);
s.integer(irq_acknowledge);
s.integer(irq_counter);
s.integer(irq_scalar);
s.integer(irq_line);
}
VRC7(Board &board) : Chip(board) {
}
};

88
bsnes/fc/cheat/cheat.cpp Normal file
View File

@@ -0,0 +1,88 @@
#include <fc/fc.hpp>
namespace Famicom {
Cheat cheat;
bool Cheat::decode(const string &code_, unsigned &addr, unsigned &data, unsigned &comp) {
static bool initialize = false;
static uint8 mapProActionReplay[256], mapGameGenie[256];
if(initialize == false) {
initialize = true;
for(auto &n : mapProActionReplay) n = ~0;
mapProActionReplay['0'] = 0; mapProActionReplay['1'] = 1; mapProActionReplay['2'] = 2; mapProActionReplay['3'] = 3;
mapProActionReplay['4'] = 4; mapProActionReplay['5'] = 5; mapProActionReplay['6'] = 6; mapProActionReplay['7'] = 7;
mapProActionReplay['8'] = 8; mapProActionReplay['9'] = 9; mapProActionReplay['A'] = 10; mapProActionReplay['B'] = 11;
mapProActionReplay['C'] = 12; mapProActionReplay['D'] = 13; mapProActionReplay['E'] = 14; mapProActionReplay['F'] = 15;
for(auto &n : mapGameGenie) n = ~0;
mapGameGenie['A'] = 0; mapGameGenie['P'] = 1; mapGameGenie['Z'] = 2; mapGameGenie['L'] = 3;
mapGameGenie['G'] = 4; mapGameGenie['I'] = 5; mapGameGenie['T'] = 6; mapGameGenie['Y'] = 7;
mapGameGenie['E'] = 8; mapGameGenie['O'] = 9; mapGameGenie['X'] = 10; mapGameGenie['U'] = 11;
mapGameGenie['K'] = 12; mapGameGenie['S'] = 13; mapGameGenie['V'] = 14; mapGameGenie['N'] = 15;
}
string code = code_;
code.upper();
unsigned length = code.length(), bits = 0;
if(code.wildcard("????:??")) {
code = { substr(code, 0, 4), substr(code, 5, 2) };
for(unsigned n = 0; n < 6; n++) if(mapProActionReplay[code[n]] > 15) return false;
bits = hex(code);
addr = (bits >> 8) & 0xffff;
data = (bits >> 0) & 0xff;
comp = ~0;
return true;
}
if(code.wildcard("????:??:??")) {
code = { substr(code, 0, 4), substr(code, 5, 2), substr(code, 8, 2) };
for(unsigned n = 0; n < 8; n++) if(mapProActionReplay[code[n]] > 15) return false;
bits = hex(code);
addr = (bits >> 16) & 0xffff;
data = (bits >> 8) & 0xff;
comp = (bits >> 0) & 0xff;
return true;
}
if(length == 6) {
for(unsigned n = 0; n < 6; n++) if(mapGameGenie[code[n]] > 15) return false;
for(unsigned n = 0; n < 6; n++) bits |= mapGameGenie[code[n]] << (20 - n * 4);
unsigned addrTable[] = { 10, 9, 8, 7, 2, 1, 0, 19, 14, 13, 12, 11, 6, 5, 4 };
unsigned dataTable[] = { 23, 18, 17, 16, 3, 22, 21, 20 };
addr = 0x8000, data = 0x00, comp = ~0;
for(unsigned n = 0; n < 15; n++) addr |= bits & (1 << addrTable[n]) ? 0x4000 >> n : 0;
for(unsigned n = 0; n < 8; n++) data |= bits & (1 << dataTable[n]) ? 0x80 >> n : 0;
return true;
}
if(length == 8) {
for(unsigned n = 0; n < 8; n++) if(mapGameGenie[code[n]] > 15) return false;
for(unsigned n = 0; n < 8; n++) bits |= mapGameGenie[code[n]] << (28 - n * 4);
unsigned addrTable[] = { 18, 17, 16, 15, 10, 9, 8, 27, 22, 21, 20, 19, 14, 13, 12 };
unsigned dataTable[] = { 31, 26, 25, 24, 3, 30, 29, 28 };
unsigned compTable[] = { 7, 2, 1, 0, 11, 6, 5,4 };
addr = 0x8000, data = 0x00, comp = 0x00;
for(unsigned n = 0; n < 15; n++) addr |= bits & (1 << addrTable[n]) ? 0x4000 >> n : 0;
for(unsigned n = 0; n < 8; n++) data |= bits & (1 << dataTable[n]) ? 0x80 >> n : 0;
for(unsigned n = 0; n < 8; n++) comp |= bits & (1 << compTable[n]) ? 0x80 >> n : 0;
return true;
}
return false;
}
void Cheat::synchronize() {
for(auto &n : override) n = false;
for(unsigned n = 0; n < size(); n++) {
override[operator[](n).addr] = true;
}
}
}

14
bsnes/fc/cheat/cheat.hpp Normal file
View File

@@ -0,0 +1,14 @@
struct CheatCode {
unsigned addr;
unsigned data;
unsigned comp;
};
struct Cheat : public vector<CheatCode> {
static bool decode(const string &code, unsigned &addr, unsigned &data, unsigned &comp);
void synchronize();
bool override[65536];
};
extern Cheat cheat;

110
bsnes/fc/cpu/cpu.cpp Normal file
View File

@@ -0,0 +1,110 @@
#include <fc/fc.hpp>
namespace Famicom {
#include "timing.cpp"
#include "serialization.cpp"
CPU cpu;
void CPU::Enter() {
while(true) {
if(scheduler.sync == Scheduler::SynchronizeMode::All) {
scheduler.exit(Scheduler::ExitReason::SynchronizeEvent);
}
cpu.main();
}
}
void CPU::main() {
if(status.interrupt_pending) {
interrupt();
return;
}
exec();
}
void CPU::add_clocks(unsigned clocks) {
apu.clock -= clocks;
if(apu.clock < 0 && scheduler.sync != Scheduler::SynchronizeMode::All) co_switch(apu.thread);
ppu.clock -= clocks;
if(ppu.clock < 0 && scheduler.sync != Scheduler::SynchronizeMode::All) co_switch(ppu.thread);
cartridge.clock -= clocks;
if(cartridge.clock < 0 && scheduler.sync != Scheduler::SynchronizeMode::All) co_switch(cartridge.thread);
}
void CPU::power() {
R6502::power();
for(unsigned addr = 0; addr < 0x0800; addr++) ram[addr] = 0xff;
ram[0x0008] = 0xf7;
ram[0x0009] = 0xef;
ram[0x000a] = 0xdf;
ram[0x000f] = 0xbf;
}
void CPU::reset() {
R6502::reset();
create(CPU::Enter, 21477272);
regs.pc = bus.read(0xfffc) << 0;
regs.pc |= bus.read(0xfffd) << 8;
status.interrupt_pending = false;
status.nmi_pending = false;
status.nmi_line = 0;
status.irq_line = 0;
status.irq_apu_line = 0;
status.rdy_line = 1;
status.rdy_addr = { false, 0x0000 };
status.oam_dma_pending = false;
status.oam_dma_page = 0x00;
status.controller_latch = false;
status.controller_port0 = 0;
status.controller_port1 = 0;
}
uint8 CPU::debugger_read(uint16 addr) {
return bus.read(addr);
}
uint8 CPU::ram_read(uint16 addr) {
return ram[addr & 0x07ff];
}
void CPU::ram_write(uint16 addr, uint8 data) {
ram[addr & 0x07ff] = data;
}
uint8 CPU::read(uint16 addr) {
if(addr == 0x4016) {
return (mdr() & 0xc0) | input.data(0);
}
if(addr == 0x4017) {
return (mdr() & 0xc0) | input.data(1);
}
return apu.read(addr);
}
void CPU::write(uint16 addr, uint8 data) {
if(addr == 0x4014) {
status.oam_dma_page = data;
status.oam_dma_pending = true;
}
if(addr == 0x4016) {
input.latch(data & 0x01);
}
return apu.write(addr, data);
}
}

55
bsnes/fc/cpu/cpu.hpp Normal file
View File

@@ -0,0 +1,55 @@
struct CPU : Processor::R6502, Thread {
uint8 ram[0x0800];
struct Status {
bool interrupt_pending;
bool nmi_pending;
bool nmi_line;
bool irq_line;
bool irq_apu_line;
bool rdy_line;
optional<uint16> rdy_addr;
bool oam_dma_pending;
uint8 oam_dma_page;
bool controller_latch;
unsigned controller_port0;
unsigned controller_port1;
} status;
static void Enter();
void main();
void add_clocks(unsigned clocks);
void power();
void reset();
uint8 debugger_read(uint16 addr);
uint8 ram_read(uint16 addr);
void ram_write(uint16 addr, uint8 data);
uint8 read(uint16 addr);
void write(uint16 addr, uint8 data);
void serialize(serializer&);
//timing.cpp
uint8 op_read(uint16 addr);
void op_write(uint16 addr, uint8 data);
void last_cycle();
void nmi(uint16 &vector);
void oam_dma();
void set_nmi_line(bool);
void set_irq_line(bool);
void set_irq_apu_line(bool);
void set_rdy_line(bool);
void set_rdy_addr(optional<uint16>);
};
extern CPU cpu;

View File

@@ -0,0 +1,23 @@
void CPU::serialize(serializer &s) {
R6502::serialize(s);
Thread::serialize(s);
s.array(ram);
s.integer(status.interrupt_pending);
s.integer(status.nmi_pending);
s.integer(status.nmi_line);
s.integer(status.irq_line);
s.integer(status.irq_apu_line);
s.integer(status.rdy_line);
s.integer(status.rdy_addr.valid);
s.integer(status.rdy_addr.value);
s.integer(status.oam_dma_pending);
s.integer(status.oam_dma_page);
s.integer(status.controller_latch);
s.integer(status.controller_port0);
s.integer(status.controller_port1);
}

63
bsnes/fc/cpu/timing.cpp Normal file
View File

@@ -0,0 +1,63 @@
uint8 CPU::op_read(uint16 addr) {
if(status.oam_dma_pending) {
status.oam_dma_pending = false;
op_read(addr);
oam_dma();
}
while(status.rdy_line == 0) {
regs.mdr = bus.read(status.rdy_addr ? status.rdy_addr() : addr);
add_clocks(12);
}
regs.mdr = bus.read(addr);
add_clocks(12);
return regs.mdr;
}
void CPU::op_write(uint16 addr, uint8 data) {
bus.write(addr, regs.mdr = data);
add_clocks(12);
}
void CPU::last_cycle() {
status.interrupt_pending = ((status.irq_line | status.irq_apu_line) & ~regs.p.i) | status.nmi_pending;
}
void CPU::nmi(uint16 &vector) {
if(status.nmi_pending) {
status.nmi_pending = false;
vector = 0xfffa;
}
}
void CPU::oam_dma() {
for(unsigned n = 0; n < 256; n++) {
uint8 data = op_read((status.oam_dma_page << 8) + n);
op_write(0x2004, data);
}
}
void CPU::set_nmi_line(bool line) {
//edge-sensitive (0->1)
if(!status.nmi_line && line) status.nmi_pending = true;
status.nmi_line = line;
}
void CPU::set_irq_line(bool line) {
//level-sensitive
status.irq_line = line;
}
void CPU::set_irq_apu_line(bool line) {
//level-sensitive
status.irq_apu_line = line;
}
void CPU::set_rdy_line(bool line) {
status.rdy_line = line;
}
void CPU::set_rdy_addr(optional<uint16> addr) {
status.rdy_addr = addr;
}

62
bsnes/fc/fc.hpp Normal file
View File

@@ -0,0 +1,62 @@
#ifndef FC_HPP
#define FC_HPP
#include <emulator/emulator.hpp>
#include <processor/r6502/r6502.hpp>
namespace Famicom {
namespace Info {
static const char Name[] = "bnes";
static const unsigned SerializerVersion = 2;
}
}
/*
bnes - Famicom emulator
authors: byuu, Ryphecha
license: GPLv3
project started: 2011-09-05
*/
#include <libco/libco.h>
namespace Famicom {
struct Thread {
cothread_t thread;
unsigned frequency;
int64 clock;
inline void create(void (*entrypoint)(), unsigned frequency) {
if(thread) co_delete(thread);
thread = co_create(65536 * sizeof(void*), entrypoint);
this->frequency = frequency;
clock = 0;
}
inline void serialize(serializer &s) {
s.integer(frequency);
s.integer(clock);
}
inline Thread() : thread(nullptr) {
}
inline ~Thread() {
if(thread) co_delete(thread);
}
};
#include <fc/system/system.hpp>
#include <fc/scheduler/scheduler.hpp>
#include <fc/input/input.hpp>
#include <fc/memory/memory.hpp>
#include <fc/cartridge/cartridge.hpp>
#include <fc/cpu/cpu.hpp>
#include <fc/apu/apu.hpp>
#include <fc/ppu/ppu.hpp>
#include <fc/cheat/cheat.hpp>
#include <fc/video/video.hpp>
#include <fc/interface/interface.hpp>
}
#endif

53
bsnes/fc/input/input.cpp Normal file
View File

@@ -0,0 +1,53 @@
#include <fc/fc.hpp>
namespace Famicom {
#include "serialization.cpp"
Input input;
void Input::latch(bool data) {
latchdata = data;
if(latchdata == 1) {
counter1 = 0;
counter2 = 0;
}
}
bool Input::data(bool port) {
bool result = 0;
if(port == 0) {
if(port1 == Device::Joypad) {
if(counter1 >= 8) return 1;
result = interface->inputPoll(0, 0u, counter1);
if(latchdata == 0) counter1++;
}
}
if(port == 1) {
if(port2 == Device::Joypad) {
if(counter2 >= 8) return 1;
result = interface->inputPoll(1, 0u, counter2);
if(latchdata == 0) counter2++;
}
}
return result;
}
void Input::connect(bool port, Device device) {
if(port == 0) port1 = device, counter1 = 0;
if(port == 1) port2 = device, counter2 = 0;
}
void Input::power() {
}
void Input::reset() {
latchdata = 0;
counter1 = 0;
counter2 = 0;
}
}

25
bsnes/fc/input/input.hpp Normal file
View File

@@ -0,0 +1,25 @@
struct Input {
enum class Device : unsigned {
Joypad,
None,
};
void latch(bool data);
bool data(bool port);
void connect(bool port, Device device);
void power();
void reset();
void serialize(serializer &s);
private:
Device port1;
Device port2;
bool latchdata;
unsigned counter1;
unsigned counter2;
};
extern Input input;

View File

@@ -0,0 +1,8 @@
void Input::serialize(serializer &s) {
s.integer((unsigned&)port1);
s.integer((unsigned&)port2);
s.integer(latchdata);
s.integer(counter1);
s.integer(counter2);
}

View File

@@ -0,0 +1,155 @@
#include <fc/fc.hpp>
namespace Famicom {
Interface *interface = nullptr;
double Interface::videoFrequency() {
return 21477272.0 / (262.0 * 1364.0 - 4.0);
}
double Interface::audioFrequency() {
return 21477272.0 / 12.0;
}
bool Interface::loaded() {
return cartridge.loaded();
}
string Interface::sha256() {
return cartridge.sha256();
}
unsigned Interface::group(unsigned id) {
switch(id) {
case ID::ProgramROM:
case ID::ProgramRAM:
case ID::CharacterROM:
case ID::CharacterRAM:
return 1;
}
throw;
}
void Interface::load(unsigned id, const string &manifest) {
cartridge.load(manifest);
}
void Interface::save() {
for(auto &memory : cartridge.memory) {
saveRequest(memory.id, memory.name);
}
}
void Interface::load(unsigned id, const stream &stream, const string &manifest) {
if(id == ID::ProgramROM) {
stream.read(cartridge.board->prgrom.data, min(cartridge.board->prgrom.size, stream.size()));
}
if(id == ID::ProgramRAM) {
stream.read(cartridge.board->prgram.data, min(cartridge.board->prgram.size, stream.size()));
}
if(id == ID::CharacterROM) {
stream.read(cartridge.board->chrrom.data, min(cartridge.board->chrrom.size, stream.size()));
}
if(id == ID::CharacterRAM) {
stream.read(cartridge.board->chrram.data, min(cartridge.board->chrram.size, stream.size()));
}
}
void Interface::save(unsigned id, const stream &stream) {
if(id == ID::ProgramRAM) {
stream.write(cartridge.board->prgram.data, cartridge.board->prgram.size);
}
if(id == ID::CharacterRAM) {
stream.write(cartridge.board->chrram.data, cartridge.board->chrram.size);
}
}
void Interface::unload() {
save();
cartridge.unload();
}
void Interface::power() {
system.power();
}
void Interface::reset() {
system.reset();
}
void Interface::run() {
system.run();
}
serializer Interface::serialize() {
system.runtosave();
return system.serialize();
}
bool Interface::unserialize(serializer &s) {
return system.unserialize(s);
}
void Interface::cheatSet(const lstring &list) {
cheat.reset();
for(auto &code : list) {
lstring codelist = code.split("+");
for(auto &part : codelist) {
unsigned addr, data, comp;
if(Cheat::decode(part, addr, data, comp)) cheat.append({addr, data, comp});
}
}
cheat.synchronize();
}
void Interface::paletteUpdate() {
video.generate_palette();
}
Interface::Interface() {
interface = this;
information.name = "Famicom";
information.width = 256;
information.height = 240;
information.overscan = true;
information.aspectRatio = 8.0 / 7.0;
information.resettable = true;
information.capability.states = true;
information.capability.cheats = true;
media.append({ID::Famicom, "Famicom", "fc"});
{
Device device{0, ID::Port1 | ID::Port2, "Controller"};
device.input.append({0, 0, "A" });
device.input.append({1, 0, "B" });
device.input.append({2, 0, "Select"});
device.input.append({3, 0, "Start" });
device.input.append({4, 0, "Up" });
device.input.append({5, 0, "Down" });
device.input.append({6, 0, "Left" });
device.input.append({7, 0, "Right" });
device.order = {4, 5, 6, 7, 1, 0, 2, 3};
this->device.append(device);
}
port.append({0, "Port 1"});
port.append({1, "Port 2"});
for(auto &device : this->device) {
for(auto &port : this->port) {
if(device.portmask & (1 << port.id)) {
port.device.append(device);
}
}
}
}
}

View File

@@ -0,0 +1,58 @@
#ifndef FC_HPP
namespace Famicom {
#endif
struct ID {
enum : unsigned {
System,
Famicom,
};
enum : unsigned {
ProgramROM,
ProgramRAM,
CharacterROM,
CharacterRAM,
};
enum : unsigned {
Port1 = 1,
Port2 = 2,
};
};
struct Interface : Emulator::Interface {
double videoFrequency();
double audioFrequency();
bool loaded();
string sha256();
unsigned group(unsigned id);
void load(unsigned id, const string &manifest);
void save();
void load(unsigned id, const stream &stream, const string &manifest = "");
void save(unsigned id, const stream &stream);
void unload();
void power();
void reset();
void run();
serializer serialize();
bool unserialize(serializer&);
void cheatSet(const lstring&);
void paletteUpdate();
Interface();
private:
vector<Device> device;
};
extern Interface *interface;
#ifndef FC_HPP
}
#endif

View File

@@ -0,0 +1,41 @@
#include <fc/fc.hpp>
namespace Famicom {
Bus bus;
//$0000-07ff = RAM (2KB)
//$0800-1fff = RAM (mirror)
//$2000-2007 = PPU
//$2008-3fff = PPU (mirror)
//$4000-4017 = APU + I/O
//$4018-ffff = Cartridge
uint8 Bus::read(uint16 addr) {
uint8 data = cartridge.prg_read(addr);
if(addr <= 0x1fff) data = cpu.ram_read(addr);
else if(addr <= 0x3fff) data = ppu.read(addr);
else if(addr <= 0x4017) data = cpu.read(addr);
if(cheat.override[addr]) {
for(unsigned n = 0; n < cheat.size(); n++) {
if(cheat[n].addr == addr) {
if(cheat[n].comp > 255 || cheat[n].comp == data) {
data = cheat[n].data;
break;
}
}
}
}
return data;
}
void Bus::write(uint16 addr, uint8 data) {
cartridge.prg_write(addr, data);
if(addr <= 0x1fff) return cpu.ram_write(addr, data);
if(addr <= 0x3fff) return ppu.write(addr, data);
if(addr <= 0x4017) return cpu.write(addr, data);
}
}

View File

@@ -0,0 +1,6 @@
struct Bus {
uint8 read(uint16 addr);
void write(uint16 addr, uint8 data);
};
extern Bus bus;

487
bsnes/fc/ppu/ppu.cpp Normal file
View File

@@ -0,0 +1,487 @@
#include <fc/fc.hpp>
namespace Famicom {
#include "serialization.cpp"
PPU ppu;
void PPU::Main() {
ppu.main();
}
void PPU::main() {
while(true) {
if(scheduler.sync == Scheduler::SynchronizeMode::PPU) {
scheduler.exit(Scheduler::ExitReason::SynchronizeEvent);
}
raster_scanline();
}
}
void PPU::tick() {
if(status.ly == 240 && status.lx == 340) status.nmi_hold = 1;
if(status.ly == 241 && status.lx == 0) status.nmi_flag = status.nmi_hold;
if(status.ly == 241 && status.lx == 2) cpu.set_nmi_line(status.nmi_enable && status.nmi_flag);
if(status.ly == 260 && status.lx == 340) status.sprite_zero_hit = 0, status.sprite_overflow = 0;
if(status.ly == 260 && status.lx == 340) status.nmi_hold = 0;
if(status.ly == 261 && status.lx == 0) status.nmi_flag = status.nmi_hold;
if(status.ly == 261 && status.lx == 2) cpu.set_nmi_line(status.nmi_enable && status.nmi_flag);
clock += 4;
if(clock >= 0) co_switch(cpu.thread);
status.lx++;
}
void PPU::scanline() {
status.lx = 0;
if(++status.ly == 262) {
status.ly = 0;
frame();
}
cartridge.scanline(status.ly);
}
void PPU::frame() {
status.field ^= 1;
scheduler.exit(Scheduler::ExitReason::FrameEvent);
}
void PPU::power() {
}
void PPU::reset() {
create(PPU::Main, 21477272);
status.mdr = 0x00;
status.field = 0;
status.ly = 0;
status.bus_data = 0x00;
status.address_latch = 0;
status.vaddr = 0x0000;
status.taddr = 0x0000;
status.xaddr = 0x00;
status.nmi_hold = 0;
status.nmi_flag = 0;
//$2000
status.nmi_enable = false;
status.master_select = 0;
status.sprite_size = 0;
status.bg_addr = 0x0000;
status.sprite_addr = 0x0000;
status.vram_increment = 1;
//$2001
status.emphasis = 0;
status.sprite_enable = false;
status.bg_enable = false;
status.sprite_edge_enable = false;
status.bg_edge_enable = false;
status.grayscale = false;
//$2002
status.sprite_zero_hit = false;
status.sprite_overflow = false;
//$2003
status.oam_addr = 0x00;
for(auto &n : buffer) n = 0;
for(auto &n : ciram ) n = 0;
for(auto &n : cgram ) n = 0;
for(auto &n : oam ) n = 0;
}
uint8 PPU::read(uint16 addr) {
uint8 result = 0x00;
switch(addr & 7) {
case 2: //PPUSTATUS
result |= status.nmi_flag << 7;
result |= status.sprite_zero_hit << 6;
result |= status.sprite_overflow << 5;
result |= status.mdr & 0x1f;
status.address_latch = 0;
status.nmi_hold = 0;
cpu.set_nmi_line(status.nmi_flag = 0);
break;
case 4: //OAMDATA
result = oam[status.oam_addr];
if((status.oam_addr & 3) == 3) result &= 0xe3;
break;
case 7: //PPUDATA
if(raster_enable() && (status.ly <= 240 || status.ly == 261)) return 0x00;
addr = status.vaddr & 0x3fff;
if(addr <= 0x1fff) {
result = status.bus_data;
status.bus_data = cartridge.chr_read(addr);
} else if(addr <= 0x3eff) {
result = status.bus_data;
status.bus_data = cartridge.chr_read(addr);
} else if(addr <= 0x3fff) {
result = cgram_read(addr);
status.bus_data = cartridge.chr_read(addr);
}
status.vaddr += status.vram_increment;
break;
}
return result;
}
void PPU::write(uint16 addr, uint8 data) {
status.mdr = data;
switch(addr & 7) {
case 0: //PPUCTRL
status.nmi_enable = data & 0x80;
status.master_select = data & 0x40;
status.sprite_size = data & 0x20;
status.bg_addr = (data & 0x10) ? 0x1000 : 0x0000;
status.sprite_addr = (data & 0x08) ? 0x1000 : 0x0000;
status.vram_increment = (data & 0x04) ? 32 : 1;
status.taddr = (status.taddr & 0x73ff) | ((data & 0x03) << 10);
cpu.set_nmi_line(status.nmi_enable && status.nmi_hold && status.nmi_flag);
return;
case 1: //PPUMASK
status.emphasis = data >> 5;
status.sprite_enable = data & 0x10;
status.bg_enable = data & 0x08;
status.sprite_edge_enable = data & 0x04;
status.bg_edge_enable = data & 0x02;
status.grayscale = data & 0x01;
return;
case 2: //PPUSTATUS
return;
case 3: //OAMADDR
status.oam_addr = data;
return;
case 4: //OAMDATA
oam[status.oam_addr++] = data;
return;
case 5: //PPUSCROLL
if(status.address_latch == 0) {
status.xaddr = data & 0x07;
status.taddr = (status.taddr & 0x7fe0) | (data >> 3);
} else {
status.taddr = (status.taddr & 0x0c1f) | ((data & 0x07) << 12) | ((data >> 3) << 5);
}
status.address_latch ^= 1;
return;
case 6: //PPUADDR
if(status.address_latch == 0) {
status.taddr = (status.taddr & 0x00ff) | ((data & 0x3f) << 8);
} else {
status.taddr = (status.taddr & 0x7f00) | data;
status.vaddr = status.taddr;
}
status.address_latch ^= 1;
return;
case 7: //PPUDATA
if(raster_enable() && (status.ly <= 240 || status.ly == 261)) return;
addr = status.vaddr & 0x3fff;
if(addr <= 0x1fff) {
cartridge.chr_write(addr, data);
} else if(addr <= 0x3eff) {
cartridge.chr_write(addr, data);
} else if(addr <= 0x3fff) {
cgram_write(addr, data);
}
status.vaddr += status.vram_increment;
return;
}
}
uint8 PPU::ciram_read(uint16 addr) {
return ciram[addr & 0x07ff];
}
void PPU::ciram_write(uint16 addr, uint8 data) {
ciram[addr & 0x07ff] = data;
}
uint8 PPU::cgram_read(uint16 addr) {
if((addr & 0x13) == 0x10) addr &= ~0x10;
uint8 data = cgram[addr & 0x1f];
if(status.grayscale) data &= 0x30;
return data;
}
void PPU::cgram_write(uint16 addr, uint8 data) {
if((addr & 0x13) == 0x10) addr &= ~0x10;
cgram[addr & 0x1f] = data;
}
//
//vaddr = 0yyy VHYY YYYX XXXX
//yyy = fine Yscroll (y:d0-d2)
//V = V nametable (y:d8)
//H = H nametable (x:d8)
//YYYYY = Y nametable (y:d3-d7)
//XXXXX = X nametable (x:d3-d7)
bool PPU::raster_enable() const {
return (status.bg_enable || status.sprite_enable);
}
unsigned PPU::nametable_addr() const {
return 0x2000 + (status.vaddr & 0x0c00);
}
unsigned PPU::scrollx() const {
return ((status.vaddr & 0x1f) << 3) | status.xaddr;
}
unsigned PPU::scrolly() const {
return (((status.vaddr >> 5) & 0x1f) << 3) | ((status.vaddr >> 12) & 7);
}
unsigned PPU::sprite_height() const {
return status.sprite_size == 0 ? 8 : 16;
}
//
uint8 PPU::chr_load(uint16 addr) {
if(raster_enable() == false) return 0x00;
return cartridge.chr_read(addr);
}
//
void PPU::scrollx_increment() {
if(raster_enable() == false) return;
status.vaddr = (status.vaddr & 0x7fe0) | ((status.vaddr + 0x0001) & 0x001f);
if((status.vaddr & 0x001f) == 0x0000) {
status.vaddr ^= 0x0400;
}
}
void PPU::scrolly_increment() {
if(raster_enable() == false) return;
status.vaddr = (status.vaddr & 0x0fff) | ((status.vaddr + 0x1000) & 0x7000);
if((status.vaddr & 0x7000) == 0x0000) {
status.vaddr = (status.vaddr & 0x7c1f) | ((status.vaddr + 0x0020) & 0x03e0);
if((status.vaddr & 0x03e0) == 0x03c0) { //0x03c0 == 30 << 5; 30 * 8 = 240
status.vaddr &= 0x7c1f;
status.vaddr ^= 0x0800;
}
}
}
//
void PPU::raster_pixel() {
uint32 *output = buffer + status.ly * 256;
unsigned mask = 0x8000 >> (status.xaddr + (status.lx & 7));
unsigned palette = 0, object_palette = 0;
bool object_priority = 0;
palette |= (raster.tiledatalo & mask) ? 1 : 0;
palette |= (raster.tiledatahi & mask) ? 2 : 0;
if(palette) {
unsigned attr = raster.attribute;
if(mask >= 256) attr >>= 2;
palette |= (attr & 3) << 2;
}
if(status.bg_enable == false) palette = 0;
if(status.bg_edge_enable == false && status.lx < 8) palette = 0;
if(status.sprite_enable == true)
for(signed sprite = 7; sprite >= 0; sprite--) {
if(status.sprite_edge_enable == false && status.lx < 8) continue;
if(raster.oam[sprite].id == 64) continue;
unsigned spritex = status.lx - raster.oam[sprite].x;
if(spritex >= 8) continue;
if(raster.oam[sprite].attr & 0x40) spritex ^= 7;
unsigned mask = 0x80 >> spritex;
unsigned sprite_palette = 0;
sprite_palette |= (raster.oam[sprite].tiledatalo & mask) ? 1 : 0;
sprite_palette |= (raster.oam[sprite].tiledatahi & mask) ? 2 : 0;
if(sprite_palette == 0) continue;
if(raster.oam[sprite].id == 0 && palette && status.lx != 255) status.sprite_zero_hit = 1;
sprite_palette |= (raster.oam[sprite].attr & 3) << 2;
object_priority = raster.oam[sprite].attr & 0x20;
object_palette = 16 + sprite_palette;
}
if(object_palette) {
if(palette == 0 || object_priority == 0) palette = object_palette;
}
if(raster_enable() == false) palette = 0;
output[status.lx] = video.palette[(status.emphasis << 6) | cgram_read(palette)];
}
void PPU::raster_sprite() {
if(raster_enable() == false) return;
unsigned n = raster.oam_iterator++;
signed ly = (status.ly == 261 ? -1 : status.ly);
unsigned y = ly - oam[(n * 4) + 0];
if(y >= sprite_height()) return;
if(raster.oam_counter == 8) {
status.sprite_overflow = 1;
return;
}
raster.soam[raster.oam_counter].id = n;
raster.soam[raster.oam_counter].y = oam[(n * 4) + 0];
raster.soam[raster.oam_counter].tile = oam[(n * 4) + 1];
raster.soam[raster.oam_counter].attr = oam[(n * 4) + 2];
raster.soam[raster.oam_counter].x = oam[(n * 4) + 3];
raster.oam_counter++;
}
void PPU::raster_scanline() {
if((status.ly >= 240 && status.ly <= 260)) {
for(unsigned x = 0; x < 341; x++) tick();
return scanline();
}
raster.oam_iterator = 0;
raster.oam_counter = 0;
for(unsigned n = 0; n < 8; n++) {
raster.soam[n].id = 64;
raster.soam[n].y = 0xff;
raster.soam[n].tile = 0xff;
raster.soam[n].attr = 0xff;
raster.soam[n].x = 0xff;
raster.soam[n].tiledatalo = 0;
raster.soam[n].tiledatahi = 0;
}
for(unsigned tile = 0; tile < 32; tile++) { // 0-255
unsigned nametable = chr_load(0x2000 | (status.vaddr & 0x0fff));
unsigned tileaddr = status.bg_addr + (nametable << 4) + (scrolly() & 7);
raster_pixel();
tick();
raster_pixel();
tick();
unsigned attribute = chr_load(0x23c0 | (status.vaddr & 0x0fc0) | ((scrolly() >> 5) << 3) | (scrollx() >> 5));
if(scrolly() & 16) attribute >>= 4;
if(scrollx() & 16) attribute >>= 2;
raster_pixel();
tick();
scrollx_increment();
if(tile == 31) scrolly_increment();
raster_pixel();
raster_sprite();
tick();
unsigned tiledatalo = chr_load(tileaddr + 0);
raster_pixel();
tick();
raster_pixel();
tick();
unsigned tiledatahi = chr_load(tileaddr + 8);
raster_pixel();
tick();
raster_pixel();
raster_sprite();
tick();
raster.nametable = (raster.nametable << 8) | nametable;
raster.attribute = (raster.attribute << 2) | (attribute & 3);
raster.tiledatalo = (raster.tiledatalo << 8) | tiledatalo;
raster.tiledatahi = (raster.tiledatahi << 8) | tiledatahi;
}
for(unsigned n = 0; n < 8; n++) raster.oam[n] = raster.soam[n];
for(unsigned sprite = 0; sprite < 8; sprite++) { //256-319
unsigned nametable = chr_load(0x2000 | (status.vaddr & 0x0fff));
tick();
if(raster_enable() && sprite == 0) status.vaddr = (status.vaddr & 0x7be0) | (status.taddr & 0x041f); //257
tick();
unsigned attribute = chr_load(0x23c0 | (status.vaddr & 0x0fc0) | ((scrolly() >> 5) << 3) | (scrollx() >> 5));
unsigned tileaddr = (sprite_height() == 8)
? status.sprite_addr + raster.oam[sprite].tile * 16
: ((raster.oam[sprite].tile & ~1) * 16) + ((raster.oam[sprite].tile & 1) * 0x1000);
tick();
tick();
unsigned spritey = (status.ly - raster.oam[sprite].y) & (sprite_height() - 1);
if(raster.oam[sprite].attr & 0x80) spritey ^= (sprite_height() - 1);
tileaddr += spritey + (spritey & 8);
raster.oam[sprite].tiledatalo = chr_load(tileaddr + 0);
tick();
tick();
raster.oam[sprite].tiledatahi = chr_load(tileaddr + 8);
tick();
tick();
if(raster_enable() && sprite == 6 && status.ly == 261) status.vaddr = status.taddr; //304
}
for(unsigned tile = 0; tile < 2; tile++) { //320-335
unsigned nametable = chr_load(0x2000 | (status.vaddr & 0x0fff));
unsigned tileaddr = status.bg_addr + (nametable << 4) + (scrolly() & 7);
tick();
tick();
unsigned attribute = chr_load(0x23c0 | (status.vaddr & 0x0fc0) | ((scrolly() >> 5) << 3) | (scrollx() >> 5));
if(scrolly() & 16) attribute >>= 4;
if(scrollx() & 16) attribute >>= 2;
tick();
scrollx_increment();
tick();
unsigned tiledatalo = chr_load(tileaddr + 0);
tick();
tick();
unsigned tiledatahi = chr_load(tileaddr + 8);
tick();
tick();
raster.nametable = (raster.nametable << 8) | nametable;
raster.attribute = (raster.attribute << 2) | (attribute & 3);
raster.tiledatalo = (raster.tiledatalo << 8) | tiledatalo;
raster.tiledatahi = (raster.tiledatahi << 8) | tiledatahi;
}
//336-339
chr_load(0x2000 | (status.vaddr & 0x0fff));
tick();
bool skip = (raster_enable() && status.field == 1 && status.ly == 261);
tick();
chr_load(0x2000 | (status.vaddr & 0x0fff));
tick();
tick();
//340
if(skip == false) tick();
return scanline();
}
}

107
bsnes/fc/ppu/ppu.hpp Normal file
View File

@@ -0,0 +1,107 @@
struct PPU : Thread {
static void Main();
void main();
void tick();
void scanline();
void frame();
void power();
void reset();
uint8 read(uint16 addr);
void write(uint16 addr, uint8 data);
uint8 ciram_read(uint16 addr);
void ciram_write(uint16 addr, uint8 data);
uint8 cgram_read(uint16 addr);
void cgram_write(uint16 addr, uint8 data);
bool raster_enable() const;
unsigned nametable_addr() const;
unsigned scrollx() const;
unsigned scrolly() const;
unsigned sprite_height() const;
uint8 chr_load(uint16 addr);
void scrollx_increment();
void scrolly_increment();
void raster_pixel();
void raster_sprite();
void raster_scanline();
void serialize(serializer&);
struct Status {
uint8 mdr;
bool field;
unsigned lx;
unsigned ly;
uint8 bus_data;
bool address_latch;
uint15 vaddr;
uint15 taddr;
uint8 xaddr;
bool nmi_hold;
bool nmi_flag;
//$2000
bool nmi_enable;
bool master_select;
bool sprite_size;
unsigned bg_addr;
unsigned sprite_addr;
unsigned vram_increment;
//$2001
uint3 emphasis;
bool sprite_enable;
bool bg_enable;
bool sprite_edge_enable;
bool bg_edge_enable;
bool grayscale;
//$2002
bool sprite_zero_hit;
bool sprite_overflow;
//$2003
uint8 oam_addr;
} status;
struct Raster {
uint16 nametable;
uint16 attribute;
uint16 tiledatalo;
uint16 tiledatahi;
unsigned oam_iterator;
unsigned oam_counter;
struct OAM {
uint8 id;
uint8 y;
uint8 tile;
uint8 attr;
uint8 x;
uint8 tiledatalo;
uint8 tiledatahi;
} oam[8], soam[8];
} raster;
uint32 buffer[256 * 262];
uint8 ciram[2048];
uint8 cgram[32];
uint8 oam[256];
};
extern PPU ppu;

View File

@@ -0,0 +1,74 @@
void PPU::serialize(serializer &s) {
Thread::serialize(s);
s.integer(status.mdr);
s.integer(status.field);
s.integer(status.lx);
s.integer(status.ly);
s.integer(status.bus_data);
s.integer(status.address_latch);
s.integer(status.vaddr);
s.integer(status.taddr);
s.integer(status.xaddr);
s.integer(status.nmi_hold);
s.integer(status.nmi_flag);
s.integer(status.nmi_enable);
s.integer(status.master_select);
s.integer(status.sprite_size);
s.integer(status.bg_addr);
s.integer(status.sprite_addr);
s.integer(status.vram_increment);
s.integer(status.emphasis);
s.integer(status.sprite_enable);
s.integer(status.bg_enable);
s.integer(status.sprite_edge_enable);
s.integer(status.bg_edge_enable);
s.integer(status.grayscale);
s.integer(status.sprite_zero_hit);
s.integer(status.sprite_overflow);
s.integer(status.oam_addr);
s.integer(raster.nametable);
s.integer(raster.attribute);
s.integer(raster.tiledatalo);
s.integer(raster.tiledatahi);
s.integer(raster.oam_iterator);
s.integer(raster.oam_counter);
for(unsigned n = 0; n < 8; n++) {
s.integer(raster.oam[n].id);
s.integer(raster.oam[n].y);
s.integer(raster.oam[n].tile);
s.integer(raster.oam[n].attr);
s.integer(raster.oam[n].x);
s.integer(raster.oam[n].tiledatalo);
s.integer(raster.oam[n].tiledatahi);
}
for(unsigned n = 0; n < 8; n++) {
s.integer(raster.soam[n].id);
s.integer(raster.soam[n].y);
s.integer(raster.soam[n].tile);
s.integer(raster.soam[n].attr);
s.integer(raster.soam[n].x);
s.integer(raster.soam[n].tiledatalo);
s.integer(raster.soam[n].tiledatahi);
}
s.array(buffer);
s.array(ciram);
s.array(cgram);
s.array(oam);
}

View File

@@ -0,0 +1,28 @@
#include <fc/fc.hpp>
namespace Famicom {
Scheduler scheduler;
void Scheduler::enter() {
host_thread = co_active();
co_switch(thread);
}
void Scheduler::exit(ExitReason reason) {
exit_reason = reason;
thread = co_active();
co_switch(host_thread);
}
void Scheduler::power() {
}
void Scheduler::reset() {
host_thread = co_active();
thread = cpu.thread;
sync = SynchronizeMode::None;
exit_reason = ExitReason::UnknownEvent;
}
}

View File

@@ -0,0 +1,16 @@
struct Scheduler : property<Scheduler> {
enum class SynchronizeMode : unsigned { None, PPU, All } sync;
enum class ExitReason : unsigned { UnknownEvent, FrameEvent, SynchronizeEvent };
readonly<ExitReason> exit_reason;
cothread_t host_thread; //program thread (used to exit emulation)
cothread_t thread; //active emulation thread (used to enter emulation)
void enter();
void exit(ExitReason);
void power();
void reset();
};
extern Scheduler scheduler;

View File

@@ -0,0 +1,60 @@
serializer System::serialize() {
serializer s(serialize_size);
unsigned signature = 0x31545342, version = Info::SerializerVersion;
char hash[64], description[512];
memcpy(&hash, (const char*)cartridge.sha256(), 64);
memset(&description, 0, sizeof description);
s.integer(signature);
s.integer(version);
s.array(hash);
s.array(description);
serialize_all(s);
return s;
}
bool System::unserialize(serializer &s) {
unsigned signature, version;
char hash[64], description[512];
s.integer(signature);
s.integer(version);
s.array(hash);
s.array(description);
if(signature != 0x31545342) return false;
if(version != Info::SerializerVersion) return false;
power();
serialize_all(s);
return true;
}
void System::serialize(serializer &s) {
}
void System::serialize_all(serializer &s) {
system.serialize(s);
input.serialize(s);
cartridge.serialize(s);
cpu.serialize(s);
apu.serialize(s);
ppu.serialize(s);
}
void System::serialize_init() {
serializer s;
unsigned signature = 0, version = 0;
char hash[64], description[512];
s.integer(signature);
s.integer(version);
s.array(hash);
s.array(description);
serialize_all(s);
serialize_size = s.size();
}

View File

@@ -0,0 +1,76 @@
#include <fc/fc.hpp>
namespace Famicom {
#include "serialization.cpp"
System system;
void System::run() {
scheduler.enter();
if(scheduler.exit_reason() == Scheduler::ExitReason::FrameEvent) {
interface->videoRefresh(ppu.buffer, 4 * 256, 256, 240);
}
}
void System::runtosave() {
scheduler.sync = Scheduler::SynchronizeMode::PPU;
runthreadtosave();
scheduler.sync = Scheduler::SynchronizeMode::All;
scheduler.thread = cpu.thread;
runthreadtosave();
scheduler.sync = Scheduler::SynchronizeMode::All;
scheduler.thread = apu.thread;
runthreadtosave();
scheduler.sync = Scheduler::SynchronizeMode::All;
scheduler.thread = cartridge.thread;
runthreadtosave();
scheduler.sync = Scheduler::SynchronizeMode::None;
}
void System::runthreadtosave() {
while(true) {
scheduler.enter();
if(scheduler.exit_reason() == Scheduler::ExitReason::SynchronizeEvent) break;
if(scheduler.exit_reason() == Scheduler::ExitReason::FrameEvent) {
interface->videoRefresh(ppu.buffer, 4 * 256, 256, 240);
}
}
}
void System::load() {
serialize_init();
}
void System::power() {
cartridge.power();
cpu.power();
apu.power();
ppu.power();
input.reset();
scheduler.power();
reset();
}
void System::reset() {
cartridge.reset();
cpu.reset();
apu.reset();
ppu.reset();
input.reset();
scheduler.reset();
}
void System::init() {
assert(interface != 0);
input.connect(0, Input::Device::Joypad);
input.connect(1, Input::Device::None);
}
void System::term() {
}
}

View File

@@ -0,0 +1,22 @@
struct System {
void run();
void runtosave();
void runthreadtosave();
void load();
void power();
void reset();
void init();
void term();
serializer serialize();
bool unserialize(serializer&);
void serialize(serializer&);
void serialize_all(serializer&);
void serialize_init();
unsigned serialize_size;
};
extern System system;

68
bsnes/fc/video/video.cpp Normal file
View File

@@ -0,0 +1,68 @@
#include <fc/fc.hpp>
#define VIDEO_CPP
namespace Famicom {
Video video;
void Video::generate_palette() {
for(unsigned n = 0; n < (1 << 9); n++) palette[n] = generate_color(n, 2.0, 0.0, 1.0, 1.0, 1.8);
}
Video::Video() {
palette = new unsigned[1 << 9];
}
Video::~Video() {
delete[] palette;
}
uint32_t Video::generate_color(
unsigned n, double saturation, double hue,
double contrast, double brightness, double gamma
) {
signed color = (n & 0x0f), level = color < 0xe ? (n >> 4) & 3 : 1;
static const double black = 0.518, white = 1.962, attenuation = 0.746;
static const double levels[8] = {
0.350, 0.518, 0.962, 1.550,
1.094, 1.506, 1.962, 1.962,
};
double lo_and_hi[2] = {
levels[level + 4 * (color == 0x0)],
levels[level + 4 * (color < 0xd)],
};
double y = 0.0, i = 0.0, q = 0.0;
auto wave = [](signed p, signed color) { return (color + p + 8) % 12 < 6; };
for(signed p = 0; p < 12; p++) {
double spot = lo_and_hi[wave(p, color)];
if(((n & 0x040) && wave(p, 12))
|| ((n & 0x080) && wave(p, 4))
|| ((n & 0x100) && wave(p, 8))
) spot *= attenuation;
double v = (spot - black) / (white - black);
v = (v - 0.5) * contrast + 0.5;
v *= brightness / 12.0;
y += v;
i += v * std::cos((3.141592653 / 6.0) * (p + hue));
q += v * std::sin((3.141592653 / 6.0) * (p + hue));
}
i *= saturation;
q *= saturation;
auto gammaAdjust = [=](double f) { return f < 0.0 ? 0.0 : std::pow(f, 2.2 / gamma); };
unsigned r = 65535.0 * gammaAdjust(y + 0.946882 * i + 0.623557 * q);
unsigned g = 65535.0 * gammaAdjust(y + -0.274788 * i + -0.635691 * q);
unsigned b = 65535.0 * gammaAdjust(y + -1.108545 * i + 1.709007 * q);
return interface->videoColor(n, uclamp<16>(r), uclamp<16>(g), uclamp<16>(b));
}
}

12
bsnes/fc/video/video.hpp Normal file
View File

@@ -0,0 +1,12 @@
struct Video {
unsigned *palette;
void generate_palette();
Video();
~Video();
private:
uint32_t generate_color(unsigned, double, double, double, double, double);
};
extern Video video;

16
bsnes/gb/Makefile Normal file
View File

@@ -0,0 +1,16 @@
gb_objects := gb-interface gb-system gb-scheduler
gb_objects += gb-memory gb-cartridge
gb_objects += gb-cpu gb-ppu gb-apu
gb_objects += gb-cheat gb-video
objects += $(gb_objects)
obj/gb-interface.o: $(gb)/interface/interface.cpp $(call rwildcard,$(gb)/interface/)
obj/gb-system.o: $(gb)/system/system.cpp $(call rwildcard,$(gb)/system/)
obj/gb-scheduler.o: $(gb)/scheduler/scheduler.cpp $(call rwildcard,$(gb)/scheduler/)
obj/gb-cartridge.o: $(gb)/cartridge/cartridge.cpp $(call rwildcard,$(gb)/cartridge/)
obj/gb-memory.o: $(gb)/memory/memory.cpp $(call rwildcard,$(gb)/memory/)
obj/gb-cpu.o: $(gb)/cpu/cpu.cpp $(call rwildcard,$(gb)/cpu/)
obj/gb-ppu.o: $(gb)/ppu/ppu.cpp $(call rwildcard,$(gb)/ppu/)
obj/gb-apu.o: $(gb)/apu/apu.cpp $(call rwildcard,$(gb)/apu/)
obj/gb-cheat.o: $(gb)/cheat/cheat.cpp $(call rwildcard,$(gb)/cheat/)
obj/gb-video.o: $(gb)/video/video.cpp $(call rwildcard,$(gb)/video/)

107
bsnes/gb/apu/apu.cpp Normal file
View File

@@ -0,0 +1,107 @@
#include <gb/gb.hpp>
#define APU_CPP
namespace GameBoy {
#include "square1/square1.cpp"
#include "square2/square2.cpp"
#include "wave/wave.cpp"
#include "noise/noise.cpp"
#include "master/master.cpp"
#include "serialization.cpp"
APU apu;
void APU::Main() {
apu.main();
}
void APU::main() {
while(true) {
if(scheduler.sync == Scheduler::SynchronizeMode::All) {
scheduler.exit(Scheduler::ExitReason::SynchronizeEvent);
}
if(sequencer_base == 0) { //512hz
if(sequencer_step == 0 || sequencer_step == 2 || sequencer_step == 4 || sequencer_step == 6) { //256hz
square1.clock_length();
square2.clock_length();
wave.clock_length();
noise.clock_length();
}
if(sequencer_step == 2 || sequencer_step == 6) { //128hz
square1.clock_sweep();
}
if(sequencer_step == 7) { //64hz
square1.clock_envelope();
square2.clock_envelope();
noise.clock_envelope();
}
sequencer_step++;
}
sequencer_base++;
square1.run();
square2.run();
wave.run();
noise.run();
master.run();
interface->audioSample(master.left, master.right);
clock += cpu.frequency;
if(clock >= 0 && scheduler.sync != Scheduler::SynchronizeMode::All) co_switch(scheduler.active_thread = cpu.thread);
}
}
void APU::power() {
create(Main, 4 * 1024 * 1024);
for(unsigned n = 0xff10; n <= 0xff3f; n++) bus.mmio[n] = this;
for(auto &n : mmio_data) n = 0x00;
sequencer_base = 0;
sequencer_step = 0;
square1.power();
square2.power();
wave.power();
noise.power();
master.power();
}
uint8 APU::mmio_read(uint16 addr) {
static const uint8 table[48] = {
0x80, 0x3f, 0x00, 0xff, 0xbf, //square1
0xff, 0x3f, 0x00, 0xff, 0xbf, //square2
0x7f, 0xff, 0x9f, 0xff, 0xbf, //wave
0xff, 0xff, 0x00, 0x00, 0xbf, //noise
0x00, 0x00, 0x70, //master
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, //unmapped
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //wave pattern
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //wave pattern
};
if(addr == 0xff26) {
uint8 data = master.enable << 7;
if(square1.enable) data |= 0x01;
if(square2.enable) data |= 0x02;
if( wave.enable) data |= 0x04;
if( noise.enable) data |= 0x08;
return data | table[addr - 0xff10];
}
if(addr >= 0xff10 && addr <= 0xff3f) return mmio_data[addr - 0xff10] | table[addr - 0xff10];
return 0xff;
}
void APU::mmio_write(uint16 addr, uint8 data) {
if(addr >= 0xff10 && addr <= 0xff3f) mmio_data[addr - 0xff10] = data;
if(addr >= 0xff10 && addr <= 0xff14) return square1.write (addr - 0xff10, data);
if(addr >= 0xff15 && addr <= 0xff19) return square2.write (addr - 0xff15, data);
if(addr >= 0xff1a && addr <= 0xff1e) return wave.write (addr - 0xff1a, data);
if(addr >= 0xff1f && addr <= 0xff23) return noise.write (addr - 0xff1f, data);
if(addr >= 0xff24 && addr <= 0xff26) return master.write (addr - 0xff24, data);
if(addr >= 0xff30 && addr <= 0xff3f) return wave.write_pattern(addr - 0xff30, data);
}
}

28
bsnes/gb/apu/apu.hpp Normal file
View File

@@ -0,0 +1,28 @@
struct APU : Thread, MMIO {
#include "square1/square1.hpp"
#include "square2/square2.hpp"
#include "wave/wave.hpp"
#include "noise/noise.hpp"
#include "master/master.hpp"
uint8 mmio_data[48];
uint13 sequencer_base;
uint3 sequencer_step;
Square1 square1;
Square2 square2;
Wave wave;
Noise noise;
Master master;
static void Main();
void main();
void power();
uint8 mmio_read(uint16 addr);
void mmio_write(uint16 addr, uint8 data);
void serialize(serializer&);
};
extern APU apu;

View File

@@ -0,0 +1,101 @@
#ifdef APU_CPP
void APU::Master::run() {
if(enable == false) {
center = 0;
left = 0;
right = 0;
return;
}
signed sample = 0;
sample += apu.square1.output;
sample += apu.square2.output;
sample += apu.wave.output;
sample += apu.noise.output;
center = (sample * 512) - 16384;
sample = 0;
if(channel1_left_enable) sample += apu.square1.output;
if(channel2_left_enable) sample += apu.square2.output;
if(channel3_left_enable) sample += apu.wave.output;
if(channel4_left_enable) sample += apu.noise.output;
sample = (sample * 512) - 16384;
sample = (sample * (left_volume + 1)) / 8;
left = sample;
sample = 0;
if(channel1_right_enable) sample += apu.square1.output;
if(channel2_right_enable) sample += apu.square2.output;
if(channel3_right_enable) sample += apu.wave.output;
if(channel4_right_enable) sample += apu.noise.output;
sample = (sample * 512) - 16384;
sample = (sample * (right_volume + 1)) / 8;
right = sample;
}
void APU::Master::write(unsigned r, uint8 data) {
if(r == 0) { //$ff24 NR50
left_in_enable = data & 0x80;
left_volume = (data >> 4) & 7;
right_in_enable = data & 0x08;
right_volume = (data >> 0) & 7;
}
if(r == 1) { //$ff25 NR51
channel4_left_enable = data & 0x80;
channel3_left_enable = data & 0x40;
channel2_left_enable = data & 0x20;
channel1_left_enable = data & 0x10;
channel4_right_enable = data & 0x08;
channel3_right_enable = data & 0x04;
channel2_right_enable = data & 0x02;
channel1_right_enable = data & 0x01;
}
if(r == 2) { //$ff26 NR52
enable = data & 0x80;
}
}
void APU::Master::power() {
left_in_enable = 0;
left_volume = 0;
right_in_enable = 0;
right_volume = 0;
channel4_left_enable = 0;
channel3_left_enable = 0;
channel2_left_enable = 0;
channel1_left_enable = 0;
channel4_right_enable = 0;
channel3_right_enable = 0;
channel2_right_enable = 0;
channel1_right_enable = 0;
enable = 0;
center = 0;
left = 0;
right = 0;
}
void APU::Master::serialize(serializer &s) {
s.integer(left_in_enable);
s.integer(left_volume);
s.integer(right_in_enable);
s.integer(right_volume);
s.integer(channel4_left_enable);
s.integer(channel3_left_enable);
s.integer(channel2_left_enable);
s.integer(channel1_left_enable);
s.integer(channel4_right_enable);
s.integer(channel3_right_enable);
s.integer(channel2_right_enable);
s.integer(channel1_right_enable);
s.integer(enable);
s.integer(center);
s.integer(left);
s.integer(right);
}
#endif

View File

@@ -0,0 +1,24 @@
struct Master {
bool left_in_enable;
uint3 left_volume;
bool right_in_enable;
uint3 right_volume;
bool channel4_left_enable;
bool channel3_left_enable;
bool channel2_left_enable;
bool channel1_left_enable;
bool channel4_right_enable;
bool channel3_right_enable;
bool channel2_right_enable;
bool channel1_right_enable;
bool enable;
int16 center;
int16 left;
int16 right;
void run();
void write(unsigned r, uint8 data);
void power();
void serialize(serializer&);
};

View File

@@ -0,0 +1,112 @@
#ifdef APU_CPP
bool APU::Noise::dac_enable() {
return (envelope_volume || envelope_direction);
}
void APU::Noise::run() {
if(period && --period == 0) {
period = divisor << frequency;
if(frequency < 14) {
bool bit = (lfsr ^ (lfsr >> 1)) & 1;
lfsr = (lfsr >> 1) ^ (bit << (narrow_lfsr ? 6 : 14));
}
}
uint4 sample = (lfsr & 1) ? (uint4)0 : volume;
if(enable == false) sample = 0;
output = sample;
}
void APU::Noise::clock_length() {
//if(counter && length) {
// if(--length == 0) enable = false;
//}
if(enable && counter) {
if(++length == 0) enable = false;
}
}
void APU::Noise::clock_envelope() {
if(enable && envelope_frequency && --envelope_period == 0) {
envelope_period = envelope_frequency;
if(envelope_direction == 0 && volume > 0) volume--;
if(envelope_direction == 1 && volume < 15) volume++;
}
}
void APU::Noise::write(unsigned r, uint8 data) {
if(r == 1) { //$ff20 NR41
//length = 64 - (data & 0x3f);
length = data & 0x3f;
}
if(r == 2) { //$ff21 NR42
envelope_volume = data >> 4;
envelope_direction = data & 0x08;
envelope_frequency = data & 0x07;
if(dac_enable() == false) enable = false;
}
if(r == 3) { //$ff22 NR43
frequency = data >> 4;
narrow_lfsr = data & 0x08;
divisor = (data & 0x07) << 4;
if(divisor == 0) divisor = 8;
period = divisor << frequency;
}
if(r == 4) { //$ff34 NR44
bool initialize = data & 0x80;
counter = data & 0x40;
if(initialize) {
enable = dac_enable();
lfsr = ~0U;
envelope_period = envelope_frequency;
volume = envelope_volume;
//if(length == 0) length = 64;
}
}
}
void APU::Noise::power() {
enable = 0;
envelope_volume = 0;
envelope_direction = 0;
envelope_frequency = 0;
frequency = 0;
narrow_lfsr = 0;
divisor = 0;
counter = 0;
output = 0;
length = 0;
envelope_period = 0;
volume = 0;
period = 0;
lfsr = 0;
}
void APU::Noise::serialize(serializer &s) {
s.integer(enable);
s.integer(envelope_volume);
s.integer(envelope_direction);
s.integer(envelope_frequency);
s.integer(frequency);
s.integer(narrow_lfsr);
s.integer(divisor);
s.integer(counter);
s.integer(output);
s.integer(length);
s.integer(envelope_period);
s.integer(volume);
s.integer(period);
s.integer(lfsr);
}
#endif

View File

@@ -0,0 +1,27 @@
struct Noise {
bool enable;
uint4 envelope_volume;
bool envelope_direction;
uint3 envelope_frequency;
uint4 frequency;
bool narrow_lfsr;
unsigned divisor;
bool counter;
int16 output;
uint6 length;
uint3 envelope_period;
uint4 volume;
unsigned period;
uint15 lfsr;
bool dac_enable();
void run();
void clock_length();
void clock_envelope();
void write(unsigned r, uint8 data);
void power();
void serialize(serializer&);
};

View File

@@ -0,0 +1,17 @@
#ifdef APU_CPP
void APU::serialize(serializer &s) {
Thread::serialize(s);
s.array(mmio_data);
s.integer(sequencer_base);
s.integer(sequencer_step);
square1.serialize(s);
square2.serialize(s);
wave.serialize(s);
noise.serialize(s);
master.serialize(s);
}
#endif

View File

@@ -0,0 +1,164 @@
#ifdef APU_CPP
bool APU::Square1::dac_enable() {
return (envelope_volume || envelope_direction);
}
void APU::Square1::run() {
if(period && --period == 0) {
period = 4 * (2048 - frequency);
phase++;
switch(duty) {
case 0: duty_output = (phase == 6); break; //______-_
case 1: duty_output = (phase >= 6); break; //______--
case 2: duty_output = (phase >= 4); break; //____----
case 3: duty_output = (phase <= 5); break; //------__
}
}
uint4 sample = (duty_output ? volume : (uint4)0);
if(enable == false) sample = 0;
output = sample;
}
void APU::Square1::sweep(bool update) {
if(sweep_enable == false) return;
sweep_negate = sweep_direction;
unsigned delta = frequency_shadow >> sweep_shift;
signed freq = frequency_shadow + (sweep_negate ? -delta : delta);
if(freq > 2047) {
enable = false;
} else if(sweep_shift && update) {
frequency_shadow = freq;
frequency = freq & 2047;
period = 4 * (2048 - frequency);
}
}
void APU::Square1::clock_length() {
//if(counter && length) {
// if(--length == 0) enable = false;
//}
if(counter && enable) {
if(++length == 0) enable = false;
}
}
void APU::Square1::clock_sweep() {
if(enable && sweep_frequency && --sweep_period == 0) {
sweep_period = sweep_frequency;
sweep(1);
sweep(0);
}
}
void APU::Square1::clock_envelope() {
if(enable && envelope_frequency && --envelope_period == 0) {
envelope_period = envelope_frequency;
if(envelope_direction == 0 && volume > 0) volume--;
if(envelope_direction == 1 && volume < 15) volume++;
}
}
void APU::Square1::write(unsigned r, uint8 data) {
if(r == 0) { //$ff10 NR10
if(sweep_negate && sweep_direction && !(data & 0x08)) enable = false;
sweep_frequency = (data >> 4) & 7;
sweep_direction = data & 0x08;
sweep_shift = data & 0x07;
}
if(r == 1) { //$ff11 NR11
duty = data >> 6;
//length = 64 - (data & 0x3f);
length = data & 0x3f;
}
if(r == 2) { //$ff12 NR12
envelope_volume = data >> 4;
envelope_direction = data & 0x08;
envelope_frequency = data & 0x07;
if(dac_enable() == false) enable = false;
}
if(r == 3) { //$ff13 NR13
frequency = (frequency & 0x0700) | data;
}
if(r == 4) { //$ff14 NR14
bool initialize = data & 0x80;
counter = data & 0x40;
frequency = ((data & 7) << 8) | (frequency & 0x00ff);
if(initialize) {
enable = dac_enable();
period = 4 * (2048 - frequency);
envelope_period = envelope_frequency;
volume = envelope_volume;
frequency_shadow = frequency;
sweep_period = sweep_frequency;
sweep_enable = sweep_period || sweep_shift;
sweep_negate = false;
if(sweep_shift) sweep(0);
//if(length == 0) length = 64;
}
}
}
void APU::Square1::power() {
enable = 0;
sweep_frequency = 0;
sweep_direction = 0;
sweep_shift = 0;
sweep_negate = 0;
duty = 0;
length = 0;
envelope_volume = 0;
envelope_direction = 0;
envelope_frequency = 0;
frequency = 0;
counter = 0;
output = 0;
duty_output = 0;
phase = 0;
period = 0;
envelope_period = 0;
sweep_period = 0;
frequency_shadow = 0;
sweep_enable = 0;
volume = 0;
}
void APU::Square1::serialize(serializer &s) {
s.integer(enable);
s.integer(sweep_frequency);
s.integer(sweep_direction);
s.integer(sweep_shift);
s.integer(sweep_negate);
s.integer(duty);
s.integer(length);
s.integer(envelope_volume);
s.integer(envelope_direction);
s.integer(envelope_frequency);
s.integer(frequency);
s.integer(counter);
s.integer(output);
s.integer(duty_output);
s.integer(phase);
s.integer(period);
s.integer(envelope_period);
s.integer(sweep_period);
s.integer(frequency_shadow);
s.integer(sweep_enable);
s.integer(volume);
}
#endif

View File

@@ -0,0 +1,36 @@
struct Square1 {
bool enable;
uint3 sweep_frequency;
bool sweep_direction;
uint3 sweep_shift;
bool sweep_negate;
uint2 duty;
uint6 length;
uint4 envelope_volume;
bool envelope_direction;
uint3 envelope_frequency;
uint11 frequency;
bool counter;
int16 output;
bool duty_output;
uint3 phase;
unsigned period;
uint3 envelope_period;
uint3 sweep_period;
signed frequency_shadow;
bool sweep_enable;
uint4 volume;
bool dac_enable();
void run();
void sweep(bool update);
void clock_length();
void clock_sweep();
void clock_envelope();
void write(unsigned r, uint8 data);
void power();
void serialize(serializer&);
};

View File

@@ -0,0 +1,114 @@
#ifdef APU_CPP
bool APU::Square2::dac_enable() {
return (envelope_volume || envelope_direction);
}
void APU::Square2::run() {
if(period && --period == 0) {
period = 4 * (2048 - frequency);
phase++;
switch(duty) {
case 0: duty_output = (phase == 6); break; //______-_
case 1: duty_output = (phase >= 6); break; //______--
case 2: duty_output = (phase >= 4); break; //____----
case 3: duty_output = (phase <= 5); break; //------__
}
}
uint4 sample = (duty_output ? volume : (uint4)0);
if(enable == false) sample = 0;
output = sample;
}
void APU::Square2::clock_length() {
//if(counter && length) {
// if(--length == 0) enable = false;
//}
if(counter && enable) {
if(++length == 0) enable = false;
}
}
void APU::Square2::clock_envelope() {
if(enable && envelope_frequency && --envelope_period == 0) {
envelope_period = envelope_frequency;
if(envelope_direction == 0 && volume > 0) volume--;
if(envelope_direction == 1 && volume < 15) volume++;
}
}
void APU::Square2::write(unsigned r, uint8 data) {
if(r == 1) { //$ff16 NR21
duty = data >> 6;
//length = 64 - (data & 0x3f);
length = (data & 0x3f);
}
if(r == 2) { //$ff17 NR22
envelope_volume = data >> 4;
envelope_direction = data & 0x08;
envelope_frequency = data & 0x07;
if(dac_enable() == false) enable = false;
}
if(r == 3) { //$ff18 NR23
frequency = (frequency & 0x0700) | data;
}
if(r == 4) { //$ff19 NR24
bool initialize = data & 0x80;
counter = data & 0x40;
frequency = ((data & 7) << 8) | (frequency & 0x00ff);
if(initialize) {
enable = dac_enable();
period = 4 * (2048 - frequency);
envelope_period = envelope_frequency;
volume = envelope_volume;
//if(length == 0) length = 64;
}
}
}
void APU::Square2::power() {
enable = 0;
duty = 0;
length = 0;
envelope_volume = 0;
envelope_direction = 0;
envelope_frequency = 0;
frequency = 0;
counter = 0;
output = 0;
duty_output = 0;
phase = 0;
period = 0;
envelope_period = 0;
volume = 0;
}
void APU::Square2::serialize(serializer &s) {
s.integer(enable);
s.integer(duty);
s.integer(length);
s.integer(envelope_volume);
s.integer(envelope_direction);
s.integer(envelope_frequency);
s.integer(frequency);
s.integer(counter);
s.integer(output);
s.integer(duty_output);
s.integer(phase);
s.integer(period);
s.integer(envelope_period);
s.integer(volume);
}
#endif

View File

@@ -0,0 +1,27 @@
struct Square2 {
bool enable;
uint2 duty;
uint6 length;
uint4 envelope_volume;
bool envelope_direction;
uint3 envelope_frequency;
uint11 frequency;
bool counter;
int16 output;
bool duty_output;
uint3 phase;
unsigned period;
uint3 envelope_period;
uint4 volume;
bool dac_enable();
void run();
void clock_length();
void clock_envelope();
void write(unsigned r, uint8 data);
void power();
void serialize(serializer&);
};

Some files were not shown because too many files have changed in this diff Show More