Compare commits

...

54 Commits
v033 ... v039

Author SHA1 Message Date
byuu
67318297dd Update to bsnes v039 release.
Changelog:
    - Recovered ~10% speed loss from last release via S-CPU IRQ timing optimizations
    - Implemented O(1) binary-heap priority queue for event scheduling
    - Fixed a bug where BS-X slotted carts were never mapping SRAM
    - Fixed a bug where invalid controller input was always being allowed
    - Fixed all compilation warnings with GCC 4.3 and Visual C++ 9.0
    - Added advanced options to control S-CPU ALU hardware delays
    - S-RTC and SPC7110 timers updated to handle time_t overflow (Y2k38) gracefully
    - Cheat codes can now have multiple codes per entry, and multiple lines per description
    - Rewrote config file parser; removed config/ class from emulator core
    - Windows: added 256x256 image to program icon set
    - Linux: fixed Xorg keysym mapping, key names should show correctly in all cases now
    - UI: updated video panel, added fullscreen-on-startup and NTSC merge fields options
    - UI: simplified audio panel
    - UI: boolean options on advanced panel can be toggled via double-click
    - Lots of code cleanup, especially for S-CPU IRQ handling and nall template library
2009-01-18 10:21:22 +00:00
byuu
1a6de37454 Update to bsnes v038r13? release.
<edit: removed outdated WIP>

**Delta queue support**

First up, I've added a binary min-heap delta queue. I converted all
events except IRQ/NMI test and hold. If we can convert these to use
the delta queue, there should be a speedup of 30-40% or so -- pretty
much the biggest low-hanging fruit there is. And the thing that has
plagued me for 12-18 months in the past before the major speed hit
v0.018 when I gave up and went with testing IRQ/NMI on every single
clock tick.

But it won't be easy: the delta queue works by adding an event when
you know its going to trigger. But we cannot _know_ if an IRQ or NMI
interrupt will trigger until we're at the current time. One can
literally disable or change these 2 clocks before they occur, which
would leave a bad trigger event in our queue.

IRQ/NMI hold also needs to be scheduled exactly four clocks after
IRQ/NMI trigger. Unless we queue these at least ~16 clocks in advance
of the trigger, then we may not be able to trip them exactly when
needed.

Since the test/hold are in the same inner loop, before or after the
delta queue time update, we can't just enqueue the hold and not the
test.

So, in the WIP I've included my insanely rigorous test ROMs for IRQ,
NMI and HDMA timing, and I'm asking for help. If anyone could please
help in merging sCPU::add_clocks() IRQ testing into the delta queue,
I'd be greatly in their debt.

Relevant code is at src/cpu/scpu/timing/[timing.cpp, irq.cpp] and
src/cpu/scpu/deltaqueue.cpp.

I'll be working on it as well, of course.

Note: removing events not at the top of the heap is not supported.
_If_ this is needed, it would probably be best to do an O(n) search
for the event, and overwrite the event code with 0 (meaning ignored)
than to try and pull out the event and renormalize the heap. IRQ/NMI
hold edge cases are very rare, so O(n) time shouldn't hurt speed.

**ALU delay**

Since there's no speed hit anymore, I added back hardware ALU (mul /
div) delays. While we still don't emulate the proper partial
calculation results, we should at least return 0 when reading too
soon.

The exact delay varies based upon the calculation, however. We ran
into problems with Taz-Mania in the past. So for this WIP only, I've
added settings to the advanced panel:
"temp.alu_mul_delay" + "temp.alu_div_delay"

The value has to be a _multiple of 2_ (2, 4, ... 32, 34, ...), and the
goal is to find the _highest_ possible value that will not cause any
bugs in games.

What I'm asking is for people to just set the value to something and
test a few games. If you spot a bug that's not in v038, try lowering
the value until it goes away. Then post the values here. We'll keep
lowering the current number until we find the best setting for future
releases.

Let's start with really high values that will definitely cause bugs:
ALU mul delay = 104
ALU div delay = 208

For example, pick any game ... say Zelda 3. Note how the triforces
won't render now. Lower the value until it works, post what numbers
you needed here plus the game name. Then everyone will use those
values and test other games. Rinse and repeat.

_Important note:_ you have to reset the game after changing these
values in the GUI for them to take effect.

**Fullscreen on startup**

I've added "video.start_in_fullscreen_mode". Because there's no way to
exit other than a keyboard shortcut, I've unhid the "Exit" option for
now. We can discuss the UI design stuff in the main v038 talk thread,
just stick to mentioning if you hit any bugs with it for this thread.

Thanks to all in advance for any help here!

[No archive available]
2009-01-02 12:01:00 +00:00
byuu
de47a2c7de Update to bsnes v038r12? release.
New WIP adds nothing new, but fixes Visual C++ compilation issues.
Stopped windows.h from defining min/max again, disabled (bool)intmax_t
stupidity, added a default: so VC doesn't assume a function has a
blank return path, omitted -static on libco, and reverted to always
using windres over rc. Express Edition lacks rc, and you already need
GNU make anyway, so why bother supporting rc, too?

> Can you tell me what I should include?


It looks like the taskbar is only 32x32 ... yet the result looks
really weird. Almost like the .ico file only has a 1-bit transparency
mask or something :/

Image

As you can see, all the other icons look much sharper.

> I always wondered why the entire line of an entry doesn't highlight.


I have no idea ... don't see any other listview styles I can use
that'd highlight the whole thing :/

[No archive available]
2009-01-13 15:12:00 +00:00
byuu
25ad9701ab Update to bsnes v038r11? release.
New WIP.

- invalid input is blocked again when input.allow_invalid_input ==
false
- vertical scrollbar only appears when needed in multi-line textboxes
- cheat editor properly encodes / decodes quotes and line breaks
- advanced panel now allows double clicking boolean items to toggle
their state
- cleaned up all of the nall template library
- nall::array was missing copy constructor, causing swap/sort to fail
- moved start in fullscreen to advanced panel for now
- renamed most of the options FitzRoy asked for

> Invalid input is always allowed in bsnes. The config file option
> doesn't change that.


Thank you very much, that was a huge oversight.

> In the latest WIP I've notice Pro Action Replay codes aren't working
> anymore. For example, try these codes for Super Mario World (U);


Those work fine for me ... maybe try the next WIP?

> Here's a couple of boolean advanced options I'd like to see:

> misc.minimize_to_system_tray
> misc.run_at_system_startup


System tray control is probably something the GUI library needs
anyway, but its value is completely lost for Windows 7 -- the taskbar
works similar to the system tray + quick launch. In fact, by default
tray items are hidden and require you to go through a menu to get to
them.

Run at startup would be tricky. I could only get that working on
Windows, and it's really something the user should do externally. Drag
it to the startup folder, put it in the registry, use MS config,
whatever. Also seems very niche, no? You'd still have to load a game
for it to be useful.

> maybe the two file ones as well, not sure what use those have


One is for OS X users. Some of them don't understand file extensions.
The other is for ROM hackers. It'd be needed to multi-chain UPS
patches in the future, as well.

> I'd also like a minor change in the system menu: flip the power
> settings with the controller settings.


Why? Seems arbitrary, and I like the current ordering. We can even
make up some crazy stuff to support the current ordering:

1) Looking at an SNES from top to bottom, you have the cart slot, then
power / reset, then controllers.

2) Group options that affect carts, then group options that affect
input.

> Let me know when you're ready to talk about the readme overhaul.


Will probably release v039 next weekend. Can work on the readme for
v040, I guess.

[No archive available]
2009-01-12 14:44:00 +00:00
byuu
9a5a3b8246 Update to bsnes v038r10? release.
Probably a mapping issue. Wish we could've spotted it less than 21
versions ago, would've been easier to find the regression. Ah well, at
least we found it now.

New WIP completes the multi-part cheat codes. I changed the file
format, and it may change again, so backup your old .cht files first.

Went with the unified textbox thing to allow infinite number of codes
per cheat item, though the textbox itself will stop parsing after
1,024 bytes at the moment. Really ... you're doing something wrong if
you need more than ~120 parts for one cheat code entry.

It will parse and treat spaces, +&|,;{tab} and {linefeed} as
separators for codes. You will lose the space formatting after you
okay the code and go back to edit it again.

Also one glitch if you toggle cheat status, it won't clip the extra
cheat parts as it should. Will fix it later, ran out of time. Don't
try multi-line descriptions or commas for separators just yet. Need to
iron proof that so it won't corrupt the file format.

Any testing of this new feature would be greatly appreciated.

Design questions:

- should we change the order of desc/code/enablestate on either the
main cheat window or the cheat sub-editing window? If so, why? Be
verbose, use examples.
- should we change the .cht file format? Again, please clarify what
the advantage would be.
- should we change the text labels for the sub cheat editor to
something more clear?
- should the default separator be changed from " + " to something
else? Maybe linefeed?

[No archive available]
2009-01-09 16:18:00 +00:00
byuu
daac76858b Update to bsnes v038r09? release.
Damn, absolutely loving this Aftershock I just picked up. Scary stuff
-- 80 proof and it tastes like a malt beverage.

New WIP, added the cheat code editor UI changes. The cheat code class
in the back-end still doesn't actually support multiple codes just
yet, but it will.

Image

Need to decide how many codes we should allow. A real Game Genie
didn't allow more than five, so I think we should go with either four
or six.

Also not shown, when a code you're editing is incomplete / bad,
there's a grayed out text label that appears on the right to tell you
that the code is invalid. It also disables the ok button during this
time.

I wouldn't try entering a multi-line description just yet. I don't
parse that at all. Worst case, it'll corrupt your cheat file. My plan
is to only show the first text line in the listbox, but allow extra
lines for more verbose comments.

I'm being lazy and disabling the add/edit/delete buttons from the main
window when the sub editor window is open. Prevents abuses like
deleting the code you're editing, then trying to update it.

[No archive available]
2009-01-06 15:58:00 +00:00
byuu
c63df7e009 Update to bsnes v038r08? release.
Another WIP, but nothing visible to end users. Still get it if you
don't have 07 for the nice speedup.

Mostly source-cleaning stuff.
- removed 'uint' type, replaced all instances with the proper unsigned
int.
- removed as many headers as I could from the global interface.hpp
file, including only in the cores that need each of them. Should help
compile time. Though I still have a lot of global header includes due
to needing ultra-hot sections of code inlined.
- added include protection bumpers to the CPU+SMP opcode core
generated files
- added const-correctness to a few more classes.
- updated S-RTC and SPC7110 time to handle time_t overflow: it's now
Y2K38 proof even on 32-bit signed time_t systems, and the file format
remains unchanged. But it adds one limitation that you'll lose your
time if you wait ~34 years before loading your last save game. I think
that's reasonable for now. Once 64-bit time_t systems are ubiquitous,
we should be able to trivially expand that without breaking old saves.

Relevant code (I tested with int16_t, uint16_t, int32_t, uint32_t,
int64_t and uint64_t):

      time_t diff
      = (current_time >= rtc_time)
      ? (current_time - rtc_time)
      : (std::numeric_limits<time_t>::max() - rtc_time + current_time
    + 1);  //compensate for overflow
      if(diff > std::numeric_limits<time_t>::max() / 2) diff = 0;
    //compensate for underflow


Avoided the obvious (y-x)&<time_t>::max() just in case there's some
crazy platform where the value != (some power of 2)-1. Modulus
(max()+1) won't work there either, as it'll overflow if
sizeof(unsigned) == sizeof(time_t). The +1 might throw it off by a
second on one's complement system, but I don't really care :P

Anyone with GCC 4.3 want to try something for me? Try modifying
src/lib/nall/platform.hpp and change #define alwaysinline
__attribute__((always_inline)) to:
    #define alwaysinline __attribute__((always_inline))
    __attribute__((hot))


... and let me know the FPS difference you get in some arbitrary game,
please :D

It's supposed to be like manual-PGO.

[No archive available]
2009-01-05 12:33:00 +00:00
byuu
3908890072 Update to bsnes v038r05? release.
New WIP, this one's fairly big as nightlies go.

First, moved the priority queue to a generic implementation so I can
re-use it elsewhere in the future. Took a ~1% speed hit or so by using
functors for the callback and using the signed math trick to avoid the
need for a normalize() function. Sadly it gets up to 3% slower if the
priorityqueue class code isn't placed right next to the CPU core.

Second, while I failed miserably at using the queues for IRQ / NMI
testing, I did come up with a neat compromise. NMI is only tested once
per scanline, IRQs only have PPU dot precision (every 4 clocks), the
hold time for both is four clock cycles, and scanlines for both NTSC
and PAL, even on the short colorburst scanline, are always evenly
divisible by four.
... so testing every 2 clock cycles was kind of pointless, as it'd
always be false. Since the delays between the PPU counter and CPU
trigger for NMI is 2, and IRQ is 10, they even align again with an
offset of 2.
... hence, I can call poll_interrupts() half as often by using
if(ppu.hcounter() & 2). I reverse that for the Super Scope / Justifier
dot testing and cut their overhead in half as well.

That gives us a nice ~10-15% speedup. Nowhere near the idealistic
~30-40% for range tested IRQs, because that only actually tests once
per scanline (~1364 cycles). This just cuts ~682 tests down to ~341
tests. Still, it's pretty close to half as good while still being
super clean and easy. It greatly diminishes the value of a range-based
IRQ tester, as that will only offer a ~15-20% speedup now at best.
Getting PGO working again is the new lowest-hanging fruit.

I also eked out a tiny bit more speed by adding some previous missed
"else" statements in the irq_valid testing part.

With the newfound speed, I gave a tiny bit up (1-2%) to simplify and
improve some old edge cases. It's known that IRQs won't trigger on the
very last dot of each field. It's due to the way the V and H counters
are misaligned, that we can't easily emulate.

So before I had a bunch of cruft to support that, update_interrupts()
was called at the start of each scanline, which would call irq_valid()
to run a bunch of tests to make sure the latch positions would
actually work on hardware. Writes to $4207-420a would also call the
update_interrupts() proc.

I killed all that, and now compute the HTIME position inline in
poll_interrupts(), and perform the last dot check there. Since testing
is ten clocks behind anyway, then we need only check to see if VTIME >
0 and ppu.vcounter(-6 clocks) == 0 to know that it was set for the
last dot on any given field.

This gives us two nice perks for free: one, no more need to hard-code
scanlines/frame inside the CPU core; and two, the old version was
missing an edge case in interlace mode where odd fields would allow an
IRQ on the last dot, which was simply because my old irq_valid() test
didn't have a third condition for that.

All that said, I'm getting ~157.5fps instead of ~137.5fps now in Zelda
3.

Third, I removed grayscale/sepia/invert from the video settings panel,
and stuck them in advanced. Used the new space to add checkboxes for
NTSC merge fields and the start in fullscreen thing.

Reference:
    //called once every four clock cycles;
    //as NMI steps by scanlines (divisible by 4) and IRQ by PPU
    4-cycle dots.
    //
    //ppu.(vh)counter(n) returns the value of said counters n-clocks
    before current time;
    //it is used to emulate hardware communication delay between
    opcode and interrupt units.
    alwaysinline void sCPU::poll_interrupts() {
      //NMI hold
      if(status.nmi_hold) {
        status.nmi_hold = false;
        if(status.nmi_enabled) status.nmi_transition = true;
      }

      //NMI test
      bool nmi_valid = (ppu.vcounter(2) >= (!ppu.overscan() ? 225 :
    240));
      if(!status.nmi_valid && nmi_valid) {
        //0->1 edge sensitive transition
        status.nmi_line = true;
        status.nmi_hold = true;  //hold /NMI for four cycles
      } else if(status.nmi_valid && !nmi_valid) {
        //1->0 edge sensitive transition
        status.nmi_line = false;
      }
      status.nmi_valid = nmi_valid;

      //IRQ hold
      status.irq_hold = false;
      if(status.irq_line) {
        if(status.virq_enabled || status.hirq_enabled)
    status.irq_transition = true;
      }

      //IRQ test (unrolling the duplicate Nirq_enabled tests causes
    speed hit)
      bool irq_valid = (status.virq_enabled || status.hirq_enabled);
      if(irq_valid) {
        if((status.virq_enabled && ppu.vcounter(10) !=
    (status.virq_pos))
        || (status.hirq_enabled && ppu.hcounter(10) !=
    (status.hirq_pos + 1) * 4)
        || (status.virq_pos && ppu.vcounter(6) == 0)  //IRQs cannot
    trigger on last dot of field
        ) irq_valid = false;
      }
      if(!status.irq_valid && irq_valid) {
        //0->1 edge sensitive transition
        status.irq_line = true;
        status.irq_hold = true;  //hold /IRQ for four cycles
      }
      status.irq_valid = irq_valid;
    }

[No archive available]
2009-01-04 15:41:00 +00:00
byuu
155b4fbfcd Update to bsnes v038r04? release.
New private WIP. Nothing worth downloading it over, really.
- fixed first scanline DRAM refresh event (passes irq.smc and nmi.smc
again)
- fixed PPUcounter to initialize before CPU; not that it affected
anything as-is, but it's nice for future proofing to do it right
- optimized priority queue thing to move instead of swap; didn't
affect overall emu speed sadly (still infinitesimally faster than the
last official release), but I still like the model for timing events
that will occur no matter what
- made the ALU delays more permanent advanced config options; 32 and
48 were still screwing with taz-mania ... not even a whole opcode on
the mul -- that game literally reads the regs immediately. We can't
get things any better than we already have until we emulate the
formula; so I set them both to 2 clock cycles for now, they're at
least there for hobbyist devs, who can set them fairly high to
guarantee their code would work on hardware
- removed a bit of cruft

> * RSA-1024 is busted


Really? What are its factors, then? Please tell me in private so I can
claim the $100,000 bounty when it's offered again :D
(they've only broken a 200-decimal digit one with the equivalent of 75
PC work-years, RSA-1024 has 309 and the problem is exponential, not
linear.)

[No archive available]
2009-01-03 15:26:00 +00:00
byuu
02ca0f1e69 Update to bsnes v038r05 release.
[No changelog available]
2009-01-02 20:13:50 +00:00
byuu
6cacb2517a Update to bsnes v038r03? release.
I haven't posted the new WIP, just updating on the status of it.

First, I noticed that Xorg changed the keycodes, at least for Kubuntu
8.10. belegdol, the other person at RPM fusion was mentioning that he
was getting weird key mappings like page_down for left, etc -- this
would be why. Didn't realize they were variable like that. I went back
and made a lookup table to convert the official keysyms to keycodes,
so this issue should now be fixed. Anyone packaging bsnes is free to
update to the latest WIPs to fix this if they like.

Second, I added "adjust" to brightness/contrast/gamma, and they all
start at 0% centered, go to -95% and +95%. Still not sure what to name
"Frequency adjust", so I left that alone for now.

Third, I updated the ~400 or so %0.nx sprintf statements to %.x, so
that GCC 4.2+ will shut the hell up.

Lastly, I can't come up with a good double->string conversion routine
(causes subtle rounding errors with the obvious approach), so I
wrapped strdouble() around snprintf. bsnes doesn't even use it yet,
but at least it can now ...

> How would dropdowns be better than what ZSNES is currently using?


The WIP link on Rapidshare is dead ... what are they using? If it
doesn't involve tab panels, then I can do that.

> Wouldn't these just be hardware filters like NTSC that simulate the
> lossy characteristics of certain type of analog output?


These are settings _for_ the NTSC filter to affect its quality. They
don't affect any other filters.

> There's no fundamental difference between a coprocessor and central
> processor in the scheme of emulation. That the coprocessor happened
> to be located on what we would physically categorize as the
> "cartridge" is immaterial.


There's quite a large distinction between something inside the SNES
and outside. I understand where you're coming from, but we shouldn't
pretend as though the SNES contains all these chips, either.

Sheesh, I don't even know what we're discussing here anymore :P

> You'd be crazy to externalize all your code just to allow people to
> create imaginary 10ft boards with 2ghz GPUs.


What I wouldn't give for just one person to make such a board ... :D

> The only invaluable option in that entire section is overload's
> gamma curve, everything else about the image can be destroyed in my
> video driver or monitor settings.


Haven't we covered this in the past? SNES games were played with
gamma, etc settings calibrated to NTSC / PAL televisions. Monitors are
calibrated very differently. I doubt anyone wants to go into their
driver control panels to adjust these settings every time they start
and close the emulator. And cheaper drivers (especially on Linux) may
not have these options at all.

Not saying we have to go crazy here ... I'm happy to leave out
hue/saturation settings.

> I am aware that any changes made to WIP releases are posted here on
> this forum, but maybe it's an idea to start including those as well
> on the WIP download page?


I _could_ ... but it's easier to type things up here later on at my
convenience :/

[No archive available]
2008-12-28 09:55:00 +00:00
byuu
9a8203b3c3 Update to bsnes v038r02? release.
New WIP.

- defaults are now centered for video settings panel sliders, modified
default gamma to 100 with gamma curve enabled.
- removed all the preset buttons, it looks terrible with just one.
- fixes 99% of the useless bullshit warnings with GCC 4.3, still
didn't change all the "%0.2x->%.2x" strings in the disassemblers
though.
- fixed up the double->nall::string conversion, but it still has some
rounding issues, so I can't use it yet. About ready to just implement
that as a wrapper around sprintf.

> Byuu i would like to request support for the following audio
> renderers.


Sure, you can post them here when you're done and I'll include them in
the source. If they don't cause missing driver errors on a clean
install of Win2k SP4 or newer (this is why Win/OpenAL is disabled),
then I'll enable them in the default binary as well.

[No archive available]
2008-12-22 13:20:00 +00:00
byuu
9c7ac24ff7 Update to bsnes v038r01? release.
New WIP. Audio panel was revised, it's now the same both in regular
and advanced mode.

Volume, Frequency and Latency all appear on one row and are all combo
boxes with sane defaults. Advanced mode gives them additional options.

Frequency adjust remains a slider. Given that 1 tick can mean the
difference between frame stuttering once a minute and once an hour, I
think it's worth keeping the precision.

Code-wise, I merged the ppucounter object into the PPU class (through
inheritance). This results in the following code simplification:

Before:
    ppucounter.vcounter()     //S-CPU time
    ppucounter.ppuvcounter()  //S-PPU time


After:
    ppu.vcounter()  //S-CPU time
    ivcounter()     //S-PPU time (called inside its own class, no need
    for ppu. prefix)


i just stands for "internal". It was that or slow things down with a
co_active() check inside the counter read calls.

Man, it feels weird editing C++ code after all of that CSS magic. I
find myself wanting to write a pattern-matching rule ...

    uint16 PPUcounter::vcounter() {
      return cpu_vcounter();
    }

    uint16 PPUcounter::vcounter() [class="PPU"] {
      return ppu_vcounter();
    }


> I probably would have stuck it in a carefully-styled <SPAN> rather
> than an attribute, but I notice your approach is sanctioned by HTML5
> (or at least it would be if you called it "data-date" instead of
> "date").


    <h3><span>2008-12-20</span>Title</h3>
    <blockquote><p>All that is necessary for the triumph of evil is
    that good men do nothing<span>Edmund Burke</span></p></blockquote>


Could work ... looks weird, though. Adding a class type to the spans
to state what they are makes it even more bloated, but perhaps worth
it ... hmm.

HTML5 approach looks cool, too. data- prefix isn't too bad. A good
indicator that it's not a real tag.

EDIT: oops, looks like I forgot that IE6 can't handle the text-align
attribute properly, either. Eh, I'll fix it tomorrow. Tired now.

[No archive available]
2008-12-20 11:36:00 +00:00
byuu
c13ae98863 Update to bsnes v038 release.
- eliminated S-DD1 DMA enslavement to the S-CPU; this allows the S-DD1 to behave more like the real chip, and it also simplifies the S-CPU DMA module
    - eliminated S-PPU enslavement to the S-CPU; all processor cores now run independently of each other
    - added cycle-level S-PPU timing for OAM address reset and OBSEL; fixes scanline glitches in Mega Lo Mania and Winter Olympics
    - removed ppu.hack.* settings; as they are no longer needed due to above changes
    - corrected VRAM tiledata cache bug; fixes Super Buster Bros v1.0 reset glitch
    - added memory export and trace logging key bindings to user interface
    - removed WAV logging (to trim the emulation core)
    - embedded readme and license texts inside executable
    - simplified S-CPU, S-SMP flag register handling
    - source code cleanup for S-CPU timing module
    - GUI-Linux: added style improvements to the listbox and combo box controls
    - GUI-Linux: finally added filetype filter support to the file open dialog
    - GUI-all: shrunk configuration panel [FitzRoy]
    - GUI-all: modified paths panel descriptions for clarity [FitzRoy]
2008-12-15 16:19:04 +00:00
byuu
e370a35d7d Update to bsnes v037r07? release.
New WIP.

The biggest news is that I've implemented what I was discussing
earlier, and it worked perfectly. The S-PPU enslavement to the S-CPU
is no more.

As of this point, all four processor cores, and all three of their
shared relationships, run completely independently of one another.

This required moving the inline timing code from the absolute most
timing-sensitive section of the emulator, to an entirely new external
class. It also required logging more state data, adding ~100k/second
more context switches, etc. It was unavoidable that the new approach
would be slower, but I was able to greatly mitigate the speed loss.
Right now, it stands at a ~6-8% speed loss from the previous release.

But there is good news:
1) aside from SuperFX / SA-1 support, which will require additional
processing inside the emulator core, no other changes should slow down
the emulator again. It can only get faster from here. Most
importantly, a range-based IRQ tester would offer a major speedup.
2) this approach will allow both a scanline-based and cycle-based
S-PPU core to work with only one S-CPU core. No need to subclass and
duplicate the timing code + scheduler as I was planning to before.
3) with this change, I was finally able to convert the scanline-based
S-PPU renderer to a hybrid that I've talked about with FitzRoy in the
past: this allowed me to finally cache OBSEL writes at (roughly) the
appropriate position, while still rendering the screen at a different
point. I render the screen at H=512, and cache OBSEL at H=1152. May
not be hardware accurate, but it allows Adv. of Dr. Franken + Winter
Olympics + Mega Lo Mania to all work as expected, all at the same
time.

It wasn't 100% exactly how I wanted to do things ... but I'm really
happy about this de-coupling. I've always been a purist when it comes
to implementing processor cores independently of one another, and it's
always bothered me greatly the way the CPU controlled the PPU and its
counters.

With the above changes, I've eliminated the four ppu.hack config
settings. I don't see much of a need for them.

I've also embedded the readme and license text files. FitzRoy, I
haven't had a chance to revise the readme as you were suggesting yet.
Not ignoring you there, it's just low on my priority list right now.

Lastly, I took FitzRoy's advice, and removed the WAV logger entirely.
I'm also going to leave the screenshot capture out. At least for now
... the UI is starting to get a bit too bloated for my tastes.

This is also the first uploaded WIP with the new debugging key-
bindings (tracing and memory export.) I don't expect anyone here to
have much use for them.

Anyway, testing would be appreciated. It's very likely that the OBSEL
cache position needs to be tweaked further. I recall LotR or something
also had issues with caching in the past ... but I couldn't find the
game at ::ahem:: the used game shop ... to test it.

I think there were other games that had different behavior based on
the old obsel_cache setting, too. Would be good to make sure they all
work as expected.

EDIT: Ah, "JRR Tolkein's LotR", bah. Yeah, no sprite flickering with
the new WIP. Also, speed hit only seems to affect Core 2's. No frame
drop on my Athlon. Probably something to do with locality of reference
or somesuch. Modern processors are too damned complicated :P

So then, assuming nobody spots any bugs ... how about a new release
tomorrow?

[No archive available]
2008-12-14 05:31:00 +00:00
byuu
a721c7e91b Update to bsnes v037r06? release.
What about calling the "Default" button on the paths window "Auto"
instead?

And no, label text does not wrap. That's why I have the forced line
breaks.

New WIP:
- fixes the tiledata cache glitch for Super Buster Bros V1.0; possibly
others
- adds updated nall templates: copy constructor vector class with
amortized constant growth being the most notable change. Resisted the
CC approach before because it's slower; but the amortized growth
avoids most of the overhead, and I'd rather do things through the CC
than possibly change the internal object memory base address
transparently (invalidating self-pointers and such.)
- adds snes.hide_light_cursors or something similar for Panzer88

Panzer88, I'd appreciate input on the last one. My fear is that
because the system is 100% relative, if you move your Wii remote too
far to the side, it will appear to "throw off" the alignment after the
cursor sticks to one end. Only way around that would be to use
absolute positioning.

It'd be really difficult to support both relative and absolute systems
at the same time, due to the way the drivers work. Absolute cannot
work with the mouse by its very design, and it'd be sketchy with
different window sizes and such for the light guns. And even if no
game uses it -- it _is_ possible to use a mouse on port 1, and a scope
on port 2.

[No archive available]
2008-11-25 15:05:00 +00:00
byuu
14bd3077e5 Update to bsnes v037r02? release.
New WIP.

If anyone on Linux uses this one, be careful. I'm not entirely sure,
but I think my style changes may be affecting the entire theme and not
just bsnes. I looked at example code of other popular apps that do the
same thing, though.

I'm not sure if it's just my imagination. Audacious' file open dialog
seems narrower, but every app still has the menu-style combo-boxes ...
so I don't know.

But if it is changing it -- I don't know how to revert it. Not like
it's a major change, anyway.

F-3582, cool thanks. You have the WIP URL, right?

henke37, it can't do point filtering when upscaling the image (eg the
image always gets blurry.)

[No archive available]
2008-11-03 09:16:00 +00:00
byuu
7236499e2f Update to bsnes v037r01? release.
New WIP.

For Linux users, this adds a PulseAudio driver, using
<pulse/simple.h>. Debian / Ubuntu users will need to add libpulse-dev,
or remove "audio.pulseaudio" from the ruby= line in the Makefile to
compile now.

I wasn't able to test the driver at all -- I get "Connection refused"
when I call pa_simple_new(). It appears that despite having Xubuntu
8.04, it doesn't come with PulseAudio installed. Guess they lied about
it on their website or something ...
I could install the packages, but hearing horror stories from others
-- I'd rather not.

If anyone can test for me, that'd be great. Check the console for
error messages.

Next, I finally got around to re-doing the S-DD1 driver to eliminate
the need to hook DMA transfers inside the S-CPU core to recognize
decompression events. That violated my strict feelings regarding
separation of cores and avoiding enslavement, even when it adds
significant overhead.

I'm now going with a radically different approach, that's hopefully
much more like the real hardware. It explains the way $4800 / $4801
behave, as well as why fixed transfers are required, but it may not be
faithful.

What I do is have the S-DD1 chip spy on $43x2-$43x6, and cache the
values internally. Then, whenever you read from $c0-ff:0000-ffff, it
will test if $4800 & $4801 != 0. If that's the case, we look at the
address requested, if it matches one of the active S-DD1 channels (eg
$4800 & $4801 & (1 << channel#) != 0), then we hijack the read with
decompressed data.

In my implementation, I decompress the entire block on the first read,
then stream from the buffer. On real hardware, it most likely starts
streaming on $4801.dN enable, but that's not too feasible for a few
reasons for me. Most notably the S-DD1 lib requires a size parameter.
It doesn't really matter, since we know the size from $43x5,6; so it
doesn't suffer the same problems the SPC7110 did.

Anyway, once all the data is transferred, it will clear the channel
bit from $4801. There may be some hardware differences here -- can you
perform two transfers at the same time? What happens if HDMA
terminates the DMA channel? These things never happen in Star Ocean or
SFA2, so they'll have to be tested manually.

If no channels are active or there are no address fetch matches, it
invokes the MMC to return raw ROM data.

All of that gives a ~1.5% speedup both to regular games and S-DD1
games. The former because DMA transfers don't have to test for the
S-DD1 during every transfer; the latter because I'm using a quick
lookup table (slower per fetch) in place of re-mapping the whole banks
on writes to the MMC (very slow per write.) The latter was much
cleaner and simpler, but I need the former to hook the decompression
stuff natively.

Windows binary is included, I'd appreciate if anyone could play some
Star Ocean / SFA2 and look for regressions from v037a.

> I'm just so used to seeing everyone having a "Close" button in their
> configuration dialogs I figured bsnes would have one. It just now
> that I looked around that I realised that only some of the
> configuration "panels" actually have buttons.


Ah, I see what you mean. Sorry. I can add one if you want, I suppose.

[No archive available]
2008-10-31 11:05:00 +00:00
byuu
9b03874f32 Update to bsnes v037a release.
[No changelog available]
2008-10-27 15:02:10 +00:00
byuu
a9bff19b5b Update to bsnes v037 release.
This release adds support for the SNES mouse, Super Scope and Justifier peripherals. It also simplifies cartridge loading and refines the user interface. Lastly, GZ and ZIP archives can now contain non-ANSI characters (Chinese, Japanese, Russian, ...) This support existed in the last release for all uncompressed files. Together, this means only JMA support on Windows lacks support for loading non-ANSI filenames. This is due to the library itself (really, it's more Windows' fault), and licensing issues prevent me from patching libjma as I did with zlib (bsnes is not GPL compatible.) I'm planning to work with Nach to fix this in a future release.
About the cartridge loading changes ... the emulator now determines what kind of cartridge is being loaded (eg normal, BS-X BIOS, Sufami Turbo cart, etc) by looking inside the file itself. If it detects a cart type that requires more than one ROM image to load, it will present you with the appropriate specialized load menu automatically. Aside from being more intuitive, this method also allows loading of BS-X and Sufami Turbo games from the command-line or via file association.
Changelog:
    - added mouse support to DirectInput and SDL input drivers
    - up to 96 buttons per controller; 8 buttons per mouse (5 per mouse on Linux) can be mapped now
    - added SNES mouse support (does not support speed setting yet)
    - added Super Scope support
    - added Justifier support (supports both Justifiers)
    - input management system almost completely rewritten to support new controllers
    - "Load Special" menu removed, all cart loading merged to "Load Cartridge ..." option
    - replaced "Power Cycle" and "Unload Cartridge" with "Power" -> "On" / "Off"
    - when video exceeds screen size and is scaled down, aspect ratio is now maintained [Ver Greeneyes]
    - zlib modified to support non-ANSI characters
    - cheat code count was limited to 1,024 codes before; it now supports unlimited codes per game
    - added sort by description setting for cheat code list
    - polished listbox control interaction (disable buttons when nothing selected, etc)
    - cleaned up OBC-1 chip emulation (code is functionally identical to v036)
    - added option to toggle fullscreen mode to settings menu
    - added advanced mode options to toggle base unit (none, Satellaview) and system region (Auto-detect, NTSC, PAL)
2008-10-26 19:59:04 +00:00
byuu
20be19f876 Update to bsnes v036r15? release.
Got the EP / Region stuff hidden in standard UI mode, and added the
text label to the audio panel. Didn't post the WIP, not much point in
testing that.

I think I'll just take it slow, wait another week or so, make sure no
bugs pop up; rather than rush a release this weekend.

> If there is a problem with it, please let me know as I just spent a
> while thinking about it


Yeah, I wasn't sure about the math. That's why I put the height scale
first. I think your code should be fine, too. If someone can
definitively show them to be the same, we can use that just because
it's smaller, which is nice.

> By the way, is it just me or has the NTSC filter's intentional
> glitchyness gotten erratic and unpleasant? It's like it randomly
> gets a seizure


I believe I turned off the NTSC filter's merge fields setting, now
that we have vsync. It needs to have its own panel just for that
filter, I'm just really lazy and don't want to add the hooks to
libfilter to allow modifying NTSC filter settings :/

The merge fields thing looks good when not running at perfect 60hz,
but it's less faithful. I figured more people would be using that
filter with the idea of faithfulness, and thus vsync, enabled.

> Oh, I wasn't bugging you about those again, they're years away from
> feasible.


Just stemming off the inevitable. I do wish it was quick and easy to
add those, like with the other chips. So far the Cx4 has been the
worst (thanks to Andreas Naive and neviksti's awesome S-DD1, SPC7110
and DSP-1 libraries, and Overload's DSP page for the rest.) And I even
had at least half of the Cx4 done by Nach.

> I'll just focus on the next two versions before I ask you if you're
> interested in contributing to something on the game management end
> of things.


I hear game-specific settings are in high-demand. But that's a
difficult thing to get working right. But yeah, thanks; we'll cover
that in a future release.

> 1. I noticed that you may have forgotten to remove video sync from
> the advanced section after it was added as a functional menu option.


Kay, we'll add that to the list.

> 2. What happens when someone uses multiple mice? You currently don't
> list the mapping as mouse00, just mouse. Will this ever pose a
> problem?


Both DirectInput and Xlib only support one mouse. If you plug in two,
they both return input to the same device. You'd need something like
ManyMouse to support multiple mice. I didn't bother as I didn't want
to add another library dependency, and really -- how many people
really have multiple mice on one PC?

It's definitely a really neat feature in ZSNES, and the library itself
is definitely awesome. But I think the analog joystick mapping should
cover people who really want to use dual justifiers / mice for bsnes.

If not, we can always add it in a future release. The guy's license is
really permissive (zlib), which is awesome.

EDIT: this _may_ pose some problems, too ...

> On Windows, ManyMouse requires Windows XP or later to function,
> since it
> relies on APIs that are new to XP...it uses LoadLibrary() on
> User32.dll and
> GetProcAddress() to get all the Windows entry points it uses, so on
> pre-XP
> systems, it will run, but fail to find any mice in ManyMouse_Init().

> ...

> Please note that using DirectInput at the same time
> as ManyMouse can cause problems; ManyMouse does not use DirectInput,
> due
> to DI8's limitations, but its parallel use seems to prevent
> ManyMouse from
> getting mouse input anyhow.

> ...

> (XInput code isn't finished yet, but in the future this note will be
> true.)


Mmm ... those are what I use now. But I think ZSNES uses DirectInput,
too; so who knows.

[No archive available]
2008-10-20 03:23:00 +00:00
byuu
f748a34e49 Update to bsnes v036r14? release.
New WIP. Couple of changes here.

Ran into that damn char *argv[] crushing Unicode on Windows thing
again with the MOTHER 3 patcher. Before I had to #ifdef the main()
entry point and add all kinds of magic to rebuild the command-line
string as UTF-8. So I moved all of that inside of hiro. Linux users
can now use GTK+ command-line arguments as a result, too. And
ui/main.cpp loses a bunch of platform-specific wrappers.

Moved realpath(), userpath() and mkdir() wrappers inside hiro; as they
all need UTF-8 <> UTF-16 stuff anyway. That cuts bbase.h to ~1.5kb.
Very close to killing it off now.

And probably most importantly, added VG's scaling changes. But I redid
the code to support the same effect in windowed mode. I also made sure
it works on portrait monitors, too (eg width is too big; scale height
instead). That was a messy section before. Please test it out and let
me know if it doesn't work as you guys were wanting.

I want to get a new release out shortly. Release-stoppers right now
are:
- axis sensitivity sucks; mouse maps too fast, joypad axes don't map
at all on Windows.
- need to swap mouse.button01 with mouse.button02 so Linux and Windows
use the same IDs; then I need to set defaults for the mouse / SS /
Justifiers.
- need to hide expansion port / region in simple UI mode.
- still need to add that skew help message to the audio settings
panel.

If I'm missing anything serious in the above, eg you know of some
critical bug or something, please let me know now.

I'm going to put off the video panel discussion and ROM PCB mapping
stuff until the next release or so. Too much to cover, and they'd take
too long at this point.

> That saddens me a little, not because I don't think you'd do a great
> job, but because there are far more people rom hacking than there
> are writing emulators or improving emulation.


And what have we been improving for the last two years? :/
It's been 95% GUI polishing and minor bug fixes. The only major change
I can think of off-hand was the HDMA timing improvements.

I'm really starting to doubt that it's possible to simultaneously
allow both the scanline and cycle-based PPUs. I try and come up with
something every other week, and nothing I think of will avoid a major
speed hit to the scanline renderer.

And I really don't personally care about the SuperFX / SA-1. Yes, I
know a lot of you do, and I'll hopefully get around to adding them.
But if I'm going to start a months-long RE task, it's going to be the
PPU first, sorry. And I'm at a major impasse there.

[No archive available]
2008-10-19 08:49:00 +00:00
byuu
0af5703c47 Update to bsnes v036r13? release.
New WIP finally adds non-ANSI filename support for GZ and ZIP
archives. That plus the existing support for uncompressed filenames
means it works with everything now but JMA archives. Compression
support was enabled with this WIP for testing.

I used Nach's suggestion with gzdOpen() for GZ, but I had to modify
ioapi.c for ZIP support, as there was no unzOpen() that took a file
descriptor. No big deal, it was only a four-line change and it works
great.

I noticed that the Windows hiro port wasn't sending the -1 position
for when no items in a listbox were selected. That turned out to an
absolutely major pain in the ass to support, thanks to the way Windows
works. Say you switch from item #3 to no item, it will send "item 3
lost focus", but nothing for the fact that no item has focus. Easy
enough, but then if you switch from item #3 to item #4, it sends "item
3 lost focus", followed by "item 4 gained focus." Since you can't tell
after the first message if a second message will occur, you don't know
whether or not to send a "no items selected" message; and if you try
and wait and there is no message, you won't get a chance to send it
again.

Took a lot of evil state tricks, but I got it working. That'll make
the input config, cheat editor and advanced panel buttons gray out
when nothing in the list is selected. Please let me know if you spot
any oddities with that.

That ate up nearly all of my time ... with only an hour left, I fixed
the input mapping once a cart was loaded; but I didn't have time to
fix the Windows joypad axis mapping bug, which should be the only bug
left at this point.

> Your website got foobared somehow, I can't navigate to places.


I knew what it was before even looking, based on your description.
Derrick's host turned off PHP register globals. Apparently we can't
have nice things because a few dumb fucks can't remember to initialize
variables. Whatever, it's fixed now.

[No archive available]
2008-10-17 14:02:00 +00:00
byuu
f73d0908c4 Update to bsnes v036r12? release.
New WIP, doesn't do much.

The core no longer scales axis values at all; and the platform input
manager scales joypad axes only by 4096. Mice are unscaled here.
Meaning you can use joypads and mice together at the same time now.

Also updated the input config panel to add all the new input devices.
Assignment is still sketchy. My idea is to separate axis movement from
button movement, and allow fast mouse movements (+/- 20 in a given
direction) or strong joypad axis movements (~50% tolerance+) to assign
axis stuff. For buttons, they'd work as before, but you can also click
a mouse button with the mouse over the input capture window.

Disabled Xlib mouse acceleration during capture mode. I don't notice a
difference, but I may as well leave it in case it matters somewhere.
Sadly, it looks like buttons 4/5 are never set via XQueryPointer(),
and you can only get buttons 6-9 with event callbacks. Since the input
wrapper doesn't own the window (in actuality, GTK+ does), I can't
safely bind the XEvents to capture those. So left, middle, right click
only on Linux.

After that's done, we should start polishing for the next release.

> gtk_tree_selection_get_selected() returns items from the underlying
> unsorted list rather than indexes into the sorted list.


Really? That's interesting. Not sure I like that. If I call
listbox.set_selection(0), I would expect it to select the first entry,
not the eleventh.

It does sound very convenient 99.9% of the time, though; I agree.

> (imagine porting to Mac OS X's Cocoa GUI which tries to do even more
> work for you...)


Oh geez, let me guess. You can drag a listbox item out of one app, and
drop it into another, and the other app can now invoke your callback
functions for activate / change with it? :P

> Since the X11 protocol only really supports three buttons, two
> button mice generally have buttons 0 and 2, and button 1 is emulated
> by clicking both 0 and 2 together (this is controlled by the
> Emulate3Buttons option in xorg.conf).


Excellent, very good to know, thank you. You sir, are a treasure trove
of knowledge! :D

So, should I go the Windows way for the majority; or the Xlib way
since it's a bit cleaner? At least, when you consider most mice have
three buttons these days.

[No archive available]
2008-10-14 12:45:00 +00:00
byuu
18389cb8f7 Update to bsnes v036r11? release.
Another WIP.

A few changes here; I added on_change notifications to both Windows
and Linux textboxes. I use that to only enable the "Add Code" button
on the cheat code screen when a valid GG/PAR code is entered. A bit
nicer than just not doing anything when you click "Add Code". Also
disabled toggle / delete code when one is not selected. Minor touches.

Added on_input mouse capture to the canvas widget for Linux. Needed
for the input.acquire() mouse capture hook.

Tried to use SDL_WM_GrabInput and SDL_GetRelativeMouseState ...
doesn't work at all. Unless SDL creates the window itself, it doesn't
give you any mouse info. SDL_WINDOWID hack doesn't work here either,
same issue with the keyboard input and why I had to use raw Xlib
there.

So, I use XGrabPointer + XQueryPointer + XWarpPointer and some magic
to make my own invisible cursor. Major pain in the ass. It works okay,
but it feels a bit too jumpy ... I'm going to try screwing around with
the acceleration controls to see if I can smooth it out a bit.

And hooray, more fucking cross-platform headache:
Windows: button 1 = right, 2 = middle
Linux: button 1 = middle, 2 = right

I had to completely disable the scale for this build to get the mouse
to work well on Linux, so no joypad axes for this one. I'd be
interested to see how the mouse performs for FitzRoy; where the last
one was too slow, this should be 5x faster. Surprisingly still
playable for me, but a bit too fast for my tastes.

The scalar of 1 feels great for Windows with the cheapo 400dpi mouse
here, too. I think this is a reasonable default.

-----

Detecting listbox column header clicks was easy enough on Windows:

    if(((LPNMHDR)lparam)->code == LVN_COLUMNCLICK) {
      printf("%d\n", ((LPNMLISTVIEW)lparam)->iSubItem);
    }


And of course, there's no obvious way to do the same with GTK+:

http://www.gtk.org/api/2.6/gtk/GtkTreeView.html
http://www.gtk.org/api/2.6/gtk/GtkTreeViewColumn.html
http://www.gtk.org/api/2.6/gtk/TreeWidget.html

I have a couple of hangups about a column sort click, anyway.

1) there's no logical reason to sort by code (they're technically
gibberish, especially encoded Game Genie codes), status (you want the
list to change around when you toggle the status? yuck), or by reverse
description (scroll to the bottom and read up, same thing.)
2) it won't save the setting across runs; each time you load a new
game, you'll have to re-click to sort the list.
3) there'd be no way to stop sorting completely.

But again, we can make this a hidden option like deep filetype
detection if it's too obscure.

[No archive available]
2008-10-13 13:31:00 +00:00
byuu
448a8336b1 Update to bsnes v036r10? release.
Sorry, was a bit under the weather lately.

Anyway, new WIP, very little changed.

Updated nall::sort from insertion sort to merge sort* [O(n log n)],
and then used that to add a "Keep cheat code list sorted by
description" checkbox to the cheat code editor. I'll admit this
probably isn't very useful, I really just wanted an excuse to
implement a proper sorting algorithm and get rid of the embarassing
O(n^2) sorting code I had in my template library. It's actually the
first time in 11 years of programming that I've ever used a sort
function in an application, believe it or not. I'll make it an
advanced mode option if it really bothers people (eg as feature
bloat.) It was only ~12 extra lines of code.
(* not using quick sort as I need a stable sort for my purposes (eg
two descriptions that are the same, but with different codes -- it
shouldn't bounce around every time the list changes or you toggle the
sort option), and it's nice avoiding the worst-case O(n^2) issue with
quick sort.)

Updated the mouse acquired check to work, but only on mouse input. Not
that it matters much since I still don't have a method for
distinguishing between mouse and joypad movement deltas. Eg this build
only works with joypads, not mice.

Moved the endian stuff from bsnes/src/lib/bbase.h to nall/endian.hpp.
I've been trying to eliminate bbase.h for quite a while now. Getting
pretty close, just some Windows POSIX wrappers and typedefs left.

Hid a bunch of the new config file options from the advanced panel.
The idea, of course, is to hide anything that can already be
controlled from the GUI anyway.

Sigh, no way I can make an October 14th release this year. Way too
much stuff is broken.

Dullaron, no, that's not the problem at all. See the input driver
thread for more info.

FitzRoy, wow, 1800dpi. Yeah, my mouse can do that, too; but I leave it
at 1000dpi. That's odd, the work mouse is only 400dpi and its slower
there than my 1000dpi. I'd have expected 1800dpi to be way too fast
for you. I'm at a loss, maybe I'll take a look at how other emulators
handle mouse movement ...

[No archive available]
2008-10-12 10:27:00 +00:00
byuu
233e645772 Update to bsnes v036r09? release.
I fixed up the SDL and X input drivers to work with the new model, so
the Linux port builds again.

For the sake of testing, this WIP disables the "mouse acquired"
requirement, and raises the divider on motion to 5000 from 5. In other
words, this release will work with gamepad thumb sticks, but not with
mice.

Having a _lot_ of trouble coming up with a way to get both working
cleanly. But yeah, you can at least see how it works now.

You want to set the X axes to "joypad00.axis00", and Y axes to
"joypad00.axis01". Use the config file, input assignment is still
screwed.

> I can't get bsnes to recognize thumbstick 2.


DIJOYSTATE2 has lX and lY, but that's it. I guess making that an array
would be too easy. I'll have to dig through and hope one of the 20
other oddly named variables (lHX, lRX, lRLX, etc) refer to the other
analog stick.

You think that's stupid ... the scroll wheel increments in ticks of
120 per one physical tick of the mouse. Always 120, it's a fixed
constant. Using DIPROP_GRANULARITY to get it from the mouse tells you
the driver doesn't support that operation, but there's a Windows
#define called WHEEL_DELTA for it.

Seriously, what's the point of an arbitrary, fixed-value multipler for
something, anyway?

> An idea that I had that would get these things working for everyone
> and every platform, would be to create 4 mappable directions that
> could be assigned to a dpad


If we could come up with some way to map both analog bi-directional
inputs and single push button controls together, then yes we could do
something like that. I think it would be too difficult to play like
that, but whatever. The flexibility would be nice at any rate.

[No archive available]
2008-10-09 17:00:00 +00:00
byuu
f0627239bb Update to bsnes v036r08? release.
New WIP. Not really worth grabbing if you have a previous one,
progress is very slow but steady here.

First, I kept the just-in-time cycle-accurate Super Scope / Justifier
latching support; but optimized things to reduce the overhead even
more. It's now ~0.5% speed hit with no light gun, and ~1.2-1.5% with.

Next, I rewrote ruby::input and the DirectInput driver to scan at O(1)
instead of O(n). With that, I increased the max # of joypad buttons
per controller to 128 (the # doesn't affect speed anymore -- 128 is
just a hard limit with DirectInput), and gained a ~2% speedup over the
old method.

Renamed the mouse axes again, to just "mouse.x" and "mouse.y", sorry.

Added a blocker for mouse.button00, but as the new input system merges
key_down/key_up/axis into one single-pass scan, it's now mapping mouse
motions, and if not that, lousy analog joypads that return sporadic
values.

Hey, it's a WIP release for a reason, right? Getting there, my idea is
to have the input driver return information about what "type" of input
each symcode is, and then pass masks from the input configuration
mapping to control which types of input are considered valid for each
of the different types of controls.

Not sure if I want to allow the Mouse/SS/Justifier axes to be mapped
by swinging the mouse fast in a given direction (the threshold now is
any movement at all, I'd make mapping it require +100/-100 in any
direction so you have to move it fast to map it), or use a dropdown
box for that.

Oh, and I added the glow shadow I was talking about earlier to the
light gun cursors. If you do decide to try out the WIP, let me know
what you think of that.

The Linux port is pretty much 100% busted at this point. I have to
port all of the SDL / X input drivers over to the new system.

Ah, and if anyone's bored and has a five button mouse, try mapping top
thumb to left, bottom thumb to right, left click to B, right click to
Y, and middle click to start; and then play Super Mario All Stars -
Mario 1. 100% control via mouse alone = good times :D
I made it to 4-2 on my first life.

> The speed at which the mouse moves is so slow


The scale is based on my gaming optical mouse (it was the only
5-button mouse I could find without a tilt wheel; fuck those things),
so the DPI scaling I use is pretty high. I'm having trouble getting it
to move at the speed of your regular mouse universally, because I
don't know what the speed of the mouse is to interpret the mouse
movement results.

[No archive available]
2008-10-08 11:14:00 +00:00
byuu
ae67f268a8 Update to bsnes v036r07? release.
New WIP.

This adds all the aforementioned fixes. I got the speed hit to ~1%
with no light gun, and ~7% with.

All three light gun modes allow you to go offscreen by 16 pixels in
either direction, and Super Scope's offscreen flag is now supported.
Mouse still needs the speed bits supported.

I also modified the cursor just a bit by adding dots to each side of
the circle. Makes it look a lot better. Not sure if I should add a
shadow around the cursor or not. It really helps on red screens, but
it seems kind of obtrusive to the view everywhere else.

Oh, and the cursor works as expected in hires and/or interlace modes
now.

Also, x_axis, y_axis, button_NN is now mouse.x_axis, mouse.y_axis,
mouse.buttonNN. joypadNN.button_NN and joypadNN.axis_NN are now
joypadNN.buttonNN and joypadNN.axisNN. So be sure to update the config
file again. Hopefully for the last time.

I have not added the new input changes just yet, so the mouse button 0
still auto-assigns in the GUI. Use the spacebar or enter to bring up
the assignment window for now. That also means that joypad analog axes
won't work well for mouse simulation still.

Other than what I mentioned above, please let me know if you spot any
bugs this time around. Especially regarding the shots not going where
you expect them to. I didn't test Yoshi's Safari myself, but it should
be fine now.

[No archive available]
2008-10-07 10:41:00 +00:00
byuu
b2331ddb85 Update to bsnes v036r06? release.
New WIP. About 12 hours of non-stop programming ...

I've added full mouse support to nall::input, hiro and
ruby::DirectInput. With that, I added some really hacked-together
support for the mouse, super scope and justifiers. Yes, all there --
now _please_ stop bugging me about this already.

Caveats:
- Mouse support doesn't honor the speed setting.
- Super Scope doesn't currently let you go offscreen, which I should
allow by at least a few pixels to allow the offscreen flag to be set
for any games that might need it.
- Dual Justifier mode is fucked. I don't understand where PIO is
supposed to be raised, and I used a hack to get the "shoot offscreen
to reload" thing to work for the single Justifier mode for now. The
dual one tends to desync when you go offscreen and stuff, not very
pleasant.
- I'm not going to support SS / Justifiers in port 1. Since they can't
latch counters anyway, and no games make use of them, I don't see much
point in cluttering the menu more and confusing new people. Both
multitap and mouse have games that can use port 1, so they stay.
- There's no input config panel to map buttons. You have to edit the
config file directly.
- The mouse delta absolutely sucks. It's just a simple div 5, so
moving the mouse really slowly won't even register, and moving it fast
has only a linear curve. This one's going to be a real pain in the ass
to get right on everyone's system, as the ranges DirectInput gives for
mice tends to vary based on resolution, software and hardware mouse
speed settings.
- Joystick delta range is -32768 to +32767, so div 5 means it'll be
pretty much unplayable with the joystick.
- Input capture window binds mouse clicks now. This needs to be
expanded quite a lot to support selective axis and mouse assignment.
- The software-rendered cursor doesn't work right in hires / interlace
modes.
- To get the PIO latching behavior 100% correct without a dead spot
during DRAM refresh, I'd have to test the cursor coordinates every
single clock cycle. That would be way too damn slow, so I used a huge
hack instead. I just test once per scanline and fake the latch
counters to the cursor position. This is really shitty, and some
timing-sensitive code that was looking for this could easily detect
the emulator because of this, but it's either a ~10-20% speed hit, or
no speed hit at all and hacky SS / Justifier support. Since it seems
to work with all the games anyway, I'll go with the latter for now.
- No Linux support for any of this stuff yet, sorry.

If you want to try it, the config file keysyms are:
"x_axis" - mouse x axis
"y_axis" - ...
"button_00" - "button_07" - mouse buttons; hope you have the side
buttons on your mouse for the Super Scope, otherwise have fun using a
keyboard + mouse at the same time.
"joypad00.axis_00" - "joypad00.axis_03" - joypad axes (only 0,1 work
with DirectInput; 0-3 for SDL.)

Yes, I'll rename the mouse ones to "mouse.foo" in the future.

Aside from all that, not really looking for bug reports at the moment.
Way too preliminary for that.

Oh, and you have to click inside the video output to acquire the
mouse. You'll know as the mouse cursor goes away. You can release the
mouse by pressing escape on the keyboard.

If the mouse is acquired, escape overrides any GUI key assignment to
that button. You can also toggle fullscreen mode and the mouse will
stay acquired.

You can't acquire the mouse unless you have a mouse/SS/justifier
attached to a controller port, and a game loaded.

[No archive available]
2008-10-05 15:08:00 +00:00
byuu
2a2f50a8bc Update to bsnes v036r05? release.
New WIP.

I was really hesitant to even do this much, but ... biggest feature:
Image

Lots of caveats here. The biggest one being that it isn't controlled
via the mouse, as I don't have any mouse driver code written; and I
really have no idea how to bind the mouse to the bsnes window region,
nor do I really want to do that.

I also can't map it to standard on/off keys, as there's no delta
response to them. It would be uncontrollable like that. Instead, I've
mapped it to the analog axis sticks on gamepads. The further you press
the gamepad axis stick, the faster the mouse moves in said direction.
Mouse left+right can be mapped to keyboard or gamepad buttons.

I know, I know, not everyone has analog gamepads. Sorry, this is the
best I can do for now.

Does it work well? Honestly ... not so much. I can clear the first
stage of the fly swatter game in Mario Paint, but that's about it. The
only real advantage is you don't need ManyMouse to emulate two mice at
the same time. It also works pretty good in the text games, like
Tokimeki Memorial.

Also, the documentation out there for the mouse absolutely _sucks_. I
have no idea how the speed bits are supposed to work, so they aren't
emulated at all. Thus, the mouse speed settings in games do nothing.
It also fails the SNES mouse electronics test. But it is usable.

Anyway, how to use it ... run the new WIP, then edit the config file.
You have to manually set it up as there's no GUI for configuring it
yet.

Look for "input.mouse(1, 2).(x, y, l, r)". Here, you want to set x, y
to axes, eg "joypad00.axis_00", and l, r to buttons, eg
"joypad00.button_00". This only maps four axes for now, so limit the
axis range from 0-3. Buttons can be 0-15.

**Please do not bug me to improve this!** This was just a functional
demonstration. It's going to be many months before proper mouse
support is added, it may never even be added, who knows ... I have a
_ton_ of complicated problems that must be overcome before I can get
real mouse support in there. If you want to actually help with the
programming side of things, then we can certainly talk about that.

Also, **please do not bug me to add the Super Scope / Justifier
next!** I can't even do it with the gamepad trick, because these two
are supposed to trip interrupts at exact points, which is really
difficult for me to do at this time. The SS would also require a
software cursor to be drawn on-screen, another technical challenge.

[No archive available]
2008-10-02 07:28:00 +00:00
byuu
30b19613d5 Update to bsnes v036r04? release.
New WIP. Quite a bit of neat stuff this time.

First, BS-X and ST BIOS detection is in. Attempting to load them will
bring up the multi-cart loader window with the BIOS fields filled in.
So now it doesn't matter what image the user tries to load, it'll just
work.

Next, added the expansion menu per FitzRoy. You can choose between
"None" and "Satellaview BS-X". I also added a new menu there, for
region selection. There's "Auto-detect" (base off the cart type),
"NTSC" and "PAL". Admittedly not very useful, but I figure since we
aren't automatically selecting the expansion unit, we should make it
possible to manually specify the SNES type. Looks like some games work
in either region, eg the SNES Test Program - Electronics Test. That
kind of surprised me.

I was thinking it might be best to hide expansion port + region when
advanced mode is disabled, since it's something I imagine 99% of users
will never need to touch.

Also, it's set up so that you can only change the settings when the
power is off, or no cart is loaded. This is very much intentional!
It's impossible to change the SNES console without a mod-switch while
it's on, and it'd be really stupid to try hot-swapping the BS-X base
unit while it's running. You can still expand the menu to see what is
currently selected, unlike power. I figured there wasn't much point in
seeing the power-on state with no cart loaded. It's obviously off in
that case.

Speaking of which, updated hiro to support MenuGroup::disable()
properly on Windows.

Fixed the minor cosmetic Y start offset on the drivers panel.

And I cleaned up the cart loading a bit more. Still need to do a bit
more work on that, but it's looking pretty good so far.

[No archive available]
2008-09-26 10:30:00 +00:00
byuu
98fc865130 Update to bsnes v036r03? release.
New WIP.

This one adds BS-X flash cart detection (please let me know if you get
any false-positives or false-negatives), the redesigned System menu
suggested by FitzRoy sans it still saying "Load Cartridge ..." (still
open to suggestions at this point, of course), Power on/off in place
of power cycle, henke37's fix for hiding the "Read Only" checkbox on
WinXP file dialog boxes, and henke37's suggestion to add ellipses to
form buttons that open new windows. Thanks to everyone for their help
with this.

Please note that Windows isn't disabling the "Power >" group as it
should. I'll work on that tomorrow, got tired of screwing with it.
It's ignoring MF_GRAYED and MF_DISABLED on group items for some
reason. It works fine on Linux, and nothing bad will happen if you
swap power states with no cart inserted.

I won't release a new version until it's fixed properly, or until I
find out I can't fix it properly (hopefully the former), of course.

I'm also open to suggestions for improving the layout of the advanced
mode audio panel. Note that it needs to be text boxes to enter values.
Spinboxes aren't going to work there.

[No archive available]
2008-09-25 03:13:00 +00:00
byuu
f6a04682f5 Update to bsnes v036r02? release.
Finally got belegdol's Polish locale up. Thank you again for that!

New WIP. The main thing is that all of the "Load N Cartridge ..."
options have been merged into one. Here's how it works:

- Load a normal cart, and the game starts right away.
- Load a BS-X slotted cart, and you get a window with the slotted cart
set to base, and the slot section empty. You can use Same Game + SG-
FEoEZ or whatever to test.
- Load a Sufami Turbo cart, and you get a window with the BIOS set to
whatever was used last (blank for the first time), the ST cart
assigned to slot A, and slot B blank. The ST won't actually play any
games with a cart only in slot B ... but it does display a unique
error message if you try. You can always clear slot A and then assign
again to slot B if you want.

Another benefit is this works with command-line loading, too. Before,
it was impossible to load BS-X / ST games from the console / bsnes
executable association. There is a bit of a lag in startup, as always,
so that's a bit noticeable.

Right now, I'm missing the algorithm for BS-X flash cart detection ...
Nach, I don't suppose you'd mind posting that for me, please?

Further, in the future I'd like to also detect the BS-X and ST BIOS
files, and assign those and show windows with all slots empty.

FitzRoy, if you want to mess around with the System menu layout again,
that's cool. Just keep in mind that "Power Cycle" is still there in
advanced mode. It looks tacky with load+unload+reset+powercycle with
no separator.

Unload cart does appear to have limited use, so if necessary, we can
consider removing that, I suppose :/

[No archive available]
2008-09-23 10:11:00 +00:00
byuu
87b91f0ace Update to bsnes v036r01? release.
Posted a new WIP.

The biggest change was that I rewrote nearly all of the cheat code
system, so heavy testing on that would be appreciated.

Someone was mentioning over at Snes9X that it was limited to 300
cheats or something, so someone bumped it to 3,000. Not to be outdone
(v036 is limited to 1,024), I vectorized the cheat table, meaning you
can have infinite cheats now (limited only to available memory.)
Actually cleans up the code quite a bit, too. Removed all the ugly
strlcpy() stuff, the limitations on description text length, etc.

Looks like I had a bug with deleting codes, too. I wasn't copying the
actual cheat codes. That would corrupt the descriptions on every code
after the one you deleted, I think. Strange nobody caught that.

I also cleaned up the OBC-1 code, and added a "Fullscreen" checkbox
after "Correct Aspect Ratio". Sorry for the delay with that, FitzRoy.
Hopefully the checkbox is good enough for now, as I can't change the
text to "Switch to ..." just yet.

[No archive available]
2008-09-16 15:28:00 +00:00
byuu
0114e10ede Update to bsnes v036 release.
This release fixes a somewhat serious bug introduced in v035, and also vastly improves Windows support for non-ANSI filenames.
The bug was triggered when HDMA would occur during DMA. If the DMA were long enough, subsequent HDMA transfers would be blocked. This caused graphical glitches in Star Ocean, Super Mario Kart, and possible more games. If you noticed any regressions from v034 to v035, this was almost certainly the cause. Once again, we're operating under the assumption that there are no known bugs currently, so please let us know here if you find any.
I've also rewritten the file handling for the emulator. On Windows, attempting to load a file with non-ANSI characters (eg Russian, Japanese, etc) would cause these characters to be removed. This meant that no version of bsnes thus far could load these files. This problem was exacerbated when I ported the user interface to Unicode (UTF-16), this caused even config and locale file loading to crash the emulator.
The root of the problem is that Windows only accepts non-ANSI strings in UTF-16 format, whereas bsnes' UI wrapper converts strings to UTF-8 interally. When passing these file names to the standard file functions (fopen(), std::ifstream, etc), file loading would fail. To fix this, I replaced all file access functions with a new version that would convert the UTF-8 filenames back to UTF-16, and use appropriate access functions (_wfopen(), _wmkdir(), etc.)
... but there is still one limitation to this: ZIP and GZ support use zlib, and JMA support uses libjma. Neither of these libraries convert UTF-8 strings to UTF-16 before attempting to open files. Due to licensing issues, as well as technical issues, I am unable to correct this at this time. What this means is that loading ZIP, GZ and JMA files; on Windows only; and with Unicode characters in the file name only; will cause the image load to fail. Loading uncompressed images (SMC, SFC, etc) will work with or without Unicode on all platforms.
I tried to be as thorough as possible with this fix: command-line arguments (via CommandLineToArvW + GetCommandLineW), user path (via SHGetFolderPathW), real path (via _wfullpath),folder creation (via _wmkdir) and file access/existence checks (via _wfopen) were updated in all cases. I also updated file loading for ROMs (SMC, SFC, etc), save RAM (SRM), real-time clock save (RTC), cheat files (CHT), UPS patches (UPS) and both configuration files (bsnes.cfg and locale.cfg.) Configuration file loading should work even if your username contains non-ANSI characters, and it should also detect config files put in the same folder as the bsnes executable, even if the path to the executable contains non-ANSI characters.
Still, if you spot any bugs, aside from the ZIP/GZ/JMA loading issue, please let me know via e-mail at setsunakun0; at hotmail.
Lastly, I'd like to apologize for the poor support for non-ANSI filenames in the past. Using an English version of Windows didn't expose the problems to me. I'll be more thorough in the future with this.
2008-09-15 05:29:14 +00:00
byuu
8c591ce44a Update to bsnes v035 release.
Changelog:
    - Added video synchronization support at long last [blargg, byuu].
    - Added audio panel to control volume, latency, frequency and SNES input frequency settings.
    - Added driver panel to select APIs to use for video, audio and input.
    - Added crash handler for driver initialization.
    - Xv and SDL video drivers now work with compositing enabled on Linux/Xorg.
    - Improved ALSA audio driver for Linux.
    - Now using a fixed output frequency, along with a 4-tap hermite resampler.
    - Improved header detection; fixes Batman: Revenge of The Joker and a few fan translations.
    - Frameskip will now randomly choose a frame in each set to display; helps with animations.
    - Locales now support meta-data, which allows for unique translations of the same English input.
2008-08-22 22:28:00 +00:00
byuu
e2cc164f70 Update to bsnes v034r06 release.
This will probably be the last public WIP, so get it now if you want
it.

    http://byuu.cinnamonpirate.com/temp/bsnes_v034_wip06.zip


I used the same "create a child window inside the output window" trick
for Xv that I used for OpenGL, so Xv will now work even with a
compositor enabled.

I also added Video::Synchronize support to OpenGL for Windows. My card
seems to force it on regardless of my driver settings, but maybe
you'll have better luck. That driver had the same issue with
allocating 16MB of memory instead of 4MB (that was due to copy and
pasting of code), so that's fixed too.

This version lowers the CPU<>SMP drifting by an order of magnitude.
You shouldn't notice the speed hit. I can't really get any lower
latency with that, though.

I also restricted the latency range to 25 - 175, with the default
being in the center, 100ms. Quite conservative, given the average we
see is 70-80ms. But you won't notice the difference, and this way we
ensure no popping even in exceptional circumstances by default. 25ms
is doable without video sync and with OSS4+cooked mode, but I
seriously doubt any Windows user will get lower without something
crazy going on with the sound card drivers.

Lastly, I've replaced the 2-tap linear resampler with a 4-tap hermite
resampler. You won't be able to tell the difference, but it's quite
pronounced if you use a waveform analyzer on much higher output
frequencies:

Linear:
Image

Hermite:
Image

Hermite is essentially better than cubic (for which cubic spline is an
optimized version of), as it is better at not going too far away from
the points, so you get a bit less clamping in the extreme cases. But
the difference isn't audible to humans anyway. It's still clearly
inferior to band-limited interpolation, as it will still have
noticeable aliasing of things like square waves and such, but it's
orders of magnitude less complex to implement.

Keep in mind that nobody could tell the difference even with linear
interpolation from the last few WIPs.

----------

Aside from that, I'm pretty much ready to release a new version. If
anyone has any show stoppers, _now_ is the time to say something.
Otherwise I'll probably post something tomorrow or Friday.
2008-08-20 20:36:54 +00:00
byuu
d09e54149b Update to bsnes v034r05 release.
http://byuu.org/temp/bsnes_v034_wip05.zip


OpenGL/Linux now destroys the window and colormap it creates, and it
also avoids allocating 16MB of memory when only 4MB are actually
needed. Forgot to remove the * sizeof(uint32_t) from the buffer
allocation after changing it from malloc to new. I use 4MB because the
internal buffer size is 1024x1024@32bpp. I make it larger than needed
to support both present and future filter requirements (eg HQ4x would
need 1024x960 minimum.)

The X-Video driver will now look for XV_SYNC_TO_VBLANK and add the
video synchronize option when it exists. Unfortunately, that doesn't
stop the binary nvidia driver from ignoring the setting anyway, but it
should be nice for those using the nv driver or somesuch, especially
as it lacks OpenGL support.

For whatever reason, I was able to get my latency in DirectSound down
to 70ms. Not sure if it's related to these changes or not, but I won't
complain. I also needed to set 32150hz / -50 for the input frequency
adjustment. Probably just differences between the monitor timings on
Windows and Linux.

That said, let's get some averages. With the new WIP, be sure to reset
all of your audio and driver settings. It may even default to no
driver at all if you were using a custom one before.

From there, please post the video driver, audio driver, latency and
SNES input adjustment values that work best for you.

> BTW, were you able to look into that status bar bug?


Thanks for pointing that out. The status bar properly restored its
state, but the menu bar did not. Rather than save the menubar state (I
wanted to avoid that for people who accidentally hide the menubar and
then close the app, and don't remember how to re-enable it), I just
made it not save the status bar state at all. Apologies to those who
hate the status bar, you'll have to turn it off more frequently now.
Direct your pitchforks at FirebrandX :P

[No archive available]
2008-08-19 13:55:00 +00:00
byuu
8e4f1be189 Update to bsnes v034r04 release.
14 hours of straight programming brings you this:
    http://byuu.cinnamonpirate.com/temp/bsnes_v034_wip04.zip


Windows binary and source included, binary does not have ZIP+JMA
support enabled, as it's a WIP release.

Yes, vsync works both on Windows and Linux. In fact, it actually seems
to work better on Linux, in that it requires lower audio latencies and
has no troubles at full 5x scale on my 1920x1200 monitor.

Overview of new features:

Most importantly, I've added a new menu group to the settings menu
group, "Synchronize", containing "Synchronize Video" and "Synchronize
Audio" checkboxes. You can have neither, one or both checked. Up to
you. That made the "Uncapped" speed setting redundant, so that was
removed.

Next, there's a new audio configuration panel with lots of new
goodies.

Volume lets you scale audio from 10% to 200%. Note that going over
100% will obviously cause aliasing. It's a much better idea to turn up
your speakers first. But who knows, it could come in handy. On one
machine with OSS4, I couldn't adjust volume in Audacious, and it
always bothered me that it was so much louder than bsnes, so I saw no
reason to cap the volume to 100% here.

Latency lets you control the number of milliseconds between adding
data to the sound buffer and it being played. Note that this is _not_
the absolute latency. Any sound servers and resamplers will obviously
add to this. It increments in steps of 5ms, because I don't want
people wasting their time trying to get it absolutely perfect. 5ms is
a small enough increment that no human being will notice. I also have
to re-create all the buffers and/or device itself when that changes,
so I want to keep it from changing too frequently. Not that there's a
memory / resource leak, but just in case.

PC output frequency let's you control the master frequency for the
sound card output. You can set this to 22050hz (not a good idea, loses
precision, there as a last resort), 32000hz (for purists), 44100hz
(for most cards), 48000hz (for higher end cards -- set as default
because it's a nicer multiple of 32000 than 44100 is) and, yes,
96000hz. And I'm sure all the audiophiles will remark how much better
it sounds, right?

Believe it or not, there's actually some value to higher frequencies
for the vsync. Higher rates lower the rounding errors with
interpolation and such, so you can use lower SNES input rates. And
speaking of which ...

SNES input frequency is what the base SNES input is skewed to. The
basic idea is that you want to get the value as low as possible
without sound crackling. The lower it is, the less video frames
duplicated, the less jerkiness of the video. The higher it is, the
less likely an audio breakup is.

Once again, Linux seems to come out on top here. Because of it's non-
ring buffer approach to audio, both ALSA and OpenAL can insert blank
samples in a way that DirectSound simply cannot. Whatever it does to
BS underflows, it works really well, because you can barely even
notice it.

The default is a tad on the dangerous side. If anything, you may need
to increase it.

Get the right values for everything, and you can easily play games and
never notice any video tearing or audio crackling whatsoever.

Lastly, I removed the "Show Statusbar" option from the misc menu, per
FitzRoy.

Oh, also note that with Linux (both for OpenGL and Xv) and Win/OpenGL,
you have to toggle the vsync enable in your video driver's control
panel. Pain in the ass, that. Linux/SDL and Win/GDI do not vsync. No,
I'm not even going to bother trying to add that to them.

My settings:

Hardware:
nVidia 8800 GTS 320, Intel HDA audio, 24" LG @ 1920x1200x24bpp@60hz

Windows:
Direct3D, DirectSound, Latency = 120ms, PC freq = 48000hz, SNES freq =
32050hz; 4x scale always works, 5x scale misses vblank every few
seconds

Linux:
OpenGL, ALSA, Latency = 60ms, PC freq = 48000hz, SNES freq = 32050hz;
4x and 5x scale always works

I'd be interested in hearing what works best for you guys. I'm
especially interested in how PAL works on a monitor running at 50hz. I
don't have any that can handle that resolution, nor 100hz. I don't
expect scrolling to look great at 100/120hz, as I have no special
handling for it.

> Even if it is wondows-only, you may want to add the option of using
> a short sleep in the advanced options panel.


No, I really can't :P
I tried just to see what would happen, calling Sleep(1) a single time
is enough to jump over the entire vblank period. In the worst case
scenario, you get stuck in a loop, never hitting vblank, and the
framerate drops to 1fps. Trust me, you don't want a sleep in there.

Now, I know you're thinking, "why not let the video card do the sync
for you?" -- well, one, some drivers still eat up all the CPU time in
their loops, and two, by polling the vblank status repeatedly, I
actually get better results with 5x scale in D3D on my system. And I
don't have to destroy the video device to toggle the video sync
enable.

[No archive available]
2008-08-17 20:22:00 +00:00
byuu
f529a84fd1 Update to bsnes v034r03v release.
For Windows / Direct3D / DirectSound _only_.

    http://byuu.cinnamonpirate.com/temp/bsnes_v034_wip03v.zip


Leave it at 100% speed, play NTSC games, leave frameskip off. I don't
care if any of that is broken or not right now.

There are two special variables this time: system.vsync_magic and
system.latency_magic.

The former is the skew for the resampler, you create that many samples
per 32000 samples of output. The latter is the latency in samples. It
will tell you how much total latency you'll end up getting when you
start the emulator.

Note that the system requirements are much greater with the CPU<>SMP
desync trick disabled. It's something like 10-20% slower. So leave off
the filters, please.

If vsync_magic is too low / high, it will tell you on the terminal by
printing an underflow warning. If latency_magic is too low, you'll
hear crackling.

The bad news: no matter what values I plug in, I still get crackling.
I can get it to be pretty rare, but I'm completely unable to get
smooth audio. Maybe you'll have better luck, who knows.

For me at least, the vsync_magic value that sounds best keeps varying
every few minutes between 32100 and 32250. The latency is through the
fucking roof. I've got it over 120ms and it's still not enough to
prevent occasional audio crackling. It's already much too high to be
practical for a release.

Note that without vsync, it only needed to be 60ms, and that was a
conservative number. We could get it down to 20-40ms with the right
hardware.

[No archive available]
2008-08-15 13:27:00 +00:00
byuu
567d415290 Update to bsnes v034r03 release.
New WIP, with _major_ changes to internal header detection.

This should get everything working, if we're lucky. It does get
Batman: RotJ working for the first time, as well as all the fan
translations.

I'm releasing it publicly, as I need all the help I can get with this
one. Windows binary with ZIP+JMA support included along with source
for the penguins.

    byuu.org/temp/bsnes_v034_wip03.zip


Do note that I left the console enabled in the binary. It's not a
release-grade version, anyway. But the main reason was to print the
scoring information. If any games fail, I'd like that information
posted. Might be good to note really close passes, as well, so we can
keep an eye on them for future changes. Right now, I'm only aware of
SFA2 that gets really really close.

Basically, it prints the address it tests for a header at, the score
it ended up getting, and the reset vector's first opcode. If the
values are equal, it defaults to LoROM, then HiROM, then ExHiROM. If
the reset vector is invalid, or the ROM is too small to contain a
header at a certain offset, you won't see any output for that line!
That means a lot of times, you'll only see one line output, and
sometimes you'll see two or three. No worries, just assume missing
means total fail. It only prints output for "possible" header
locations.

If you do test, you don't have to play in-game or anything. The second
you see any visible output whatsoever, that's good enough.

Many thanks to everyone who tests in advance :D

----------

Hunter and tukuyomi, thank you for the kind words and localizations :)

I really hate that table on the download page, and I need to go
through and get names out of all of the locales, but I'd like to get
an "Author:" field in that table on the download page. Sorry it's not
there just yet.

----------

Fes, thanks for the feedback.

> Apparently it has a limit of 65535 bytes for string literals.


I don't have a workaround for that. For whatever reason, ISO didn't
add an "incbin"-style command, and I need a platform-agnostic way of
encoding binary data.

Not for v035, but maybe a while after that, I'll use a more advanced
compressor to get the controller below 64kb of string data. Maybe I
can rig my order-0 arithmetic coder onto the end of LZSS for a quick
and dirty size cut. The reason I don't use 0xnn, 0xnn, is because that
takes 5 bytes of source to encode one byte of input, whereas base-64
strings only take ~1.25 bytes. I didn't want those files to slow down
compilation much.

> # Next, in dictionary.hpp, the first for loop uses 'i' as its
> counter, then declares 'i' again inside the loop body for additional
> work.


Oops, sorry. Didn't get a warning on GCC, so I overlooked it. This is
now fixed.

> # Cartridge::get_base_filename and Cartridge::apply_patch both claim
> to return a value, but don't seem to do so.


First should return the filename, it's just a convenience thing to
allow chaining commands. The second should return result of patching.
I've fixed both now, thanks.

> # spc_dsp.h, nal/file.hpp, and ups.hpp all attempted to include
> stdint.h, which isn't part of vc++. Are those files perhaps meant to
> include nall/stdint.h instead of the standard one?


Microsoft really pisses me off by intentionally ignoring stdint.h.
nall/stdint.hpp was meant as a workaround, so that I didn't have to
special case Visual C++. The idea was to not require you to get one of
those third-party add-ons.

So yes, two of those were a mistake on my part, I used stdint.h on
them before I created my own stdint wrapper. I've corrected both.

As for spc_dsp.h, that shouldn't be compiled. That is for blargg's
reference, unmodified S-DSP emulator. The ones modified to work in
bsnes do not require it. And in fact, only src/dsp/sdsp will compile
at the moment due to memory map changes.

> # pEditbox::get_text seems to declare a dynamically sized stack
> array, which CL balked at.


Hahah, yeah, that would be C99 syntax. Very nice, that.

Looks like I was allocating length*2 wchars, too. I don't know why I
was doing that ... I don't think Microsoft's system even supports the
extended Unicode symbols that need more than 16-bits, and even if so,
they aren't likely to appear in the emulator.

Dropped that back to length+1, and made it use new[]/delete[],
instead. That's one horribly inefficient routine by the way, but
whatever, it works for now.

The rest I can't do much about, sorry. Hopefully it'll make it easier
for you to compile in the future. Sorry for letting the port slip, I
just don't have the patience to load VS2k5 again. Software takes like
three hours to install >_< and creates slower code than GCC4 anyway.
If they'd fix their damn PGO support, I'd be all over it again,
though.
2008-08-13 21:09:15 +00:00
byuu
435a194ccd Update to bsnes v034r02 release.
New WIP.

First, the internal ROM header detected was enhanced. Nach was right,
so I went ahead and did it the right way ... it'll score all three
regions individually now, and then use some heuristics for those
annoying games that duplicate the header entirely in multiple places.
The hardest games to detect, that I recall, are Double Dragon and
Street Fighter Alpha 2, which seem okay. In fact, all ~50 of the games
I have seem to be working fine.
Please let me know if any games fail to start as of this WIP.

Second, finished updating all of src/memory to convert uint ->
unsigned. Yeah, I like the former more, but the latter is a built-in
type. Did the same to hiro, and converted Event to event_t, looks
nicer in code. Part of namespace libhiro, so no worries about other
things named event_t.

Third, added the frameskip cycling code. It just randomly chooses
which of the set of frames to display (random() % (frameskip + 1)).
Seems to work as expected, you can see Link blink when hit even with
FS=1, but obviously it stutters a bit more.

Fourth, I finally added RedDwarf and Nach's latest ALSA code. ALSA
will now with at 75% speed and with speed uncapped. It has the same
overhead as OpenAL. So, unfortunately, due to OpenAL's issues with
completely destroying echo / reverb for some reason, I'm going to have
to recommend Linux users set system.audio to "alsa" from now on :/
FreeBSD users should rely on "libao".

I'd like to release an update this weekend to address the ToP issue,
as well as a missing string in the translate[] hooks and to distribute
the new ALSA updates. I'm worried about the header detection changes
breaking some other games, though. So if you guys wouldn't mind
throwing a bunch of random games at it, I'd appreciate it.

It _should_ be fine, though. In theory, the LoROM / HiROM detection is
identical to the last release still, but I did restructure it, so you
never know ...

Oh, and I updated the website with new locales from Hatsuyuki, Itol,
khiav and wushu. Thanks, guys!

[No archive available]
2008-08-12 09:53:00 +00:00
byuu
df9de289b9 Update to bsnes v034r01 release.
New WIP (yes, already.)
Nothing that affects emulation, just a bunch of core changes I didn't
want to make last-minute before the release.

All of the APURAM / VRAM / OAM / CGRAM memory blocks have been moved
to the Memory class, and I've added operator[] bindings and such so
that I don't have to add .read(), .write() around everything. Required
several dozen individual changes, and I was afraid of introducing a
new bug. Everything looks good so far, anyway.

I also missed the translate[] call around "Paused", so it's not
possible to localize that in the new version. Oops.

> edit and thanks to Jonas Quinn for the $4810 register/Super Power
> League 4 fix.


Definitely, I wasn't going to release a new version this week because
of that bug.

Speaking of which, I just tried SPL4 on the Windows port. Holy hell,
that completely changed my opinion of OpenAL.

Seriously, those on Linux ... compare that game with OpenAL and ALSA.
With DirectSound / ALSA, the game actually has echo / reverb. It's
_completely_ missing with OpenAL. The woman announcer sounds like
she's speaking over a megaphone, but OpenAL makes her sound like she's
two feet away from you. Wild stuff.

And SDL video is going crazy on me now, it seems to be setting each
pixel's alpha value to some sort of inverse of chroma. Eg you can see
the background through the emulator window, and it's completely
transparent on full white / black screens. Really trippy looking.
Definitely be sure to set system.video to "glx" or "xv" if you use the
Linux port.

[No archive available]
2008-08-11 07:24:00 +00:00
byuu
dd83559786 Update to bsnes v034 release.
For this release: SPC7110 emulation speed has been greatly optimized, massive improvements to HDMA timing have been implemented, Multitap support was added, and the user interface was polished a bit more.
Changelog:
    - SPC7110 decompression code updated to latest version by neviksti and converted to a state machine; SPC7110 overhead is now identical to S-DD1 overhead (eg ~5% speed hit over standard games)
    - Fixed a major bug in SPC7110 data port emulation that was crashing Super Power League 4 [Jonas Quinn]
    - HDMA trigger point corrected to H=1104, bus sync timing corrected
    - All illegal DMA A-bus accesses should now be properly blocked
    - DMA state machine rewritten, greatly simplified
    - Major corrections to HDMA run timing; fixes flickering bugs in Mecarobot Golf and Super Mario Kart
    - Emulator now defaults to 2/1/3 SNES (CPU/PPU1/PPU2 revision numbers)
    - Multitap emulation added, can be attached to either or both controller ports; user interface updated to reflect this
    - Status messages (cartridge loaded / unloaded, UPS patch applied, etc) now appear in status bar
    - Added advanced configuration option, "input.analog_axis_resistance", to control gamepad analog stick sensitivity
Also, the SPC7110 emulator download link below was removed: if you are looking for this, please download the bsnes v034 source code, which has the most up-to-date version in the src/chip/spc7110 folder.
2008-08-11 11:33:54 +00:00
byuu
100ef3a271 Update to bsnes v033r09? release.
New WIP, probably not worth downloading.

For the sake of completeness, I finished optimizing the SPC7110 code.
I've converted the pixel buffer rotation from swaps to moves, which
should double the speed of the slowest part. I've also added reverse
morton lookup tables (2x8-bit and 4x-8-bit deinterleaving), which are
8-10x faster than doing it using pure bit logic, I removed the
redundant comparisons from the pixel context lookup (though a compiler
would've done the same anyway), and lastly I've cut the mode2 context
table in half, since the refcon add bit was only set on context 1
anyway. I could've replaced the other half with 5-6 if/else
statements, but I didn't see much of a point in that since it'd only
make the code harder to understand.

That results in a 1-2fps speedup, at best. Really, the code is simply
not a bottleneck. It's pointless to optimize anymore, as any changes
from this point on will just make it harder to understand what's
happening. I only added the morton tables because it does seem to aid
readability.

Also added translate[] wraps around all the new status messages, and
moved the two checkbox options on the paths window to the advanced
options list. No sense cluttering up the UI with near-useless
settings.

> It's hard going back to "Are you sure you'd like to exit?", no
> multiplier eyeball stretching, etc.


Heh, yeah. I never understood the floating point multiplier setups in
some emulators. I guess it's useful if you want your video output size
to be π x _e_.

I thought about the "Are you sure?" thing, it'd be nice if you
accidentally close the emulator, so you don't lose your save. But I
quickly realized that despite using emulators for ten years, I've
never _once_ actually done that. The only point where it might be
appropriate is if I add mouse / SS support, since you may want to have
the cursor near the top right of the window with the menubar off in
windowed mode (though you're just asking for trouble at that point,
honestly.)

To be fair though, you helped design at least half the bsnes GUI, so
obviously you should like it :P

> I should offer a bounty at this point to anyone who can find another
> bug that isn't PPU based.


Super Power League 4 seems to die after an inning or two with a S-SMP
crash. I still need to try screwing with the CPU/SMP scalars and try
substituting with anomie's DSP core to see if it still dies. If
neither of those affect it, it could very well be due to a timing
issue with not emulating the delays of the SPC7110 chip or something.
If someone wants to rule out the DSP core, they could try playing a
SPC dump from the game in one of the plugins that use blargg's core. I
doubt it's that, personally.

The usual rules about special chips apply, but you can list it as a
bug if you like. I probably will with a note. Maybe I can figure it
out before release. Probably not, but who knows.

Sigh, it's always the god damn baseball and golf games, isn't it? I'd
probably half-ass the game too, if it were my job to work on one.

> Two minor things that have probably been forgotten in all this
> excitement that could make the next release: libui is still not
> changed to "hiro" in the license, both online and text based. And
> mudlord wanted to be added to the contributors for his OpenGL stuff.


Ah, thanks. Updated the license file. Decided against listing all the
libraries there for now, as they're getting quite numerous.

As for credits, mudlord is already listed in the source file, and the
contributors list is for people who have submitted code to the core of
the emulator. It's not a good system, I admit. That obviously excludes
you and tetsuo55, despite the fact that your testing has been one of
the most helpful things I've received.

It's not that I mind listing people, but I don't want that window to
become cluttered with 100+ names of everyone up to and including
people pointing out spelling mistakes in WIPs. That would make the
window really onerous to look at.
I really don't want to come off as rude here, I'm really truly
grateful to everyone who has helped out even a little, and I'm happy
to thank them all in some perpetual fashion (eg website thank yous
tend to disappear as the news falls off the page.)

That's the second time someone's brought that list up. I was afraid
that adding such a list would just end up causing problems. Maybe I
should just remove the contributors list on the about screen, and put
everyone in the readme.txt file, so that everyone who ever contributed
anything is listed?

[No archive available]
2008-08-08 14:22:00 +00:00
byuu
bccc5b5a12 Update to bsnes v033r08? release.
I wish I could post the new WIP, I really need it tested. But it looks
like vstech.net (cinnamonpirate.com's host) got sucked into a black
hole, literally. You can't even nslookup it. So ... sorry.

What I did today was:
- remove an unnecessary ternary condition in HDMA CPUsync (no visible
effect on emulation or speed.)
- move controller ports from settings to system.
- rewrite SPC7110 decompression engine from scratch.

The last one obviously the most important. I took neviksti's most
recent decompressor code, made the essential variables static, added a
bool init parameter you can use to start a new decompression sequence,
and built up a dual-indexed (read+write cursor) ring buffer to stream
byte sequences. I set the buffer to >= 32 bytes at a time. I also
simplified a few parts, like the swap sequence for pixel ordering; and
I took out the end of each function that computes length, since that's
no longer needed (nor is bot.)

The result is you can stream an infinite number of bytes safely from
decompression, and nothing will ever go out of bounds of the data ROM.

Speed results on Core 2 Duo E6600 @ stock 2.4GHz:
FEoEZ cart riding sequence - 91fps (was 40fps)
MDH title screen - 111fps (was 29fps)
SPL4 title screen with players running across screen - 118fps (was
35fps)

For comparison, Star Ocean in-game gets ~95fps.

I didn't think we would need that many optimizations to get SPC7110
support running at full speed (how complex could a low-cost IC from
1995 be?), good to see I was right.

As soon as vstech comes back (hopefully tomorrow), I'll post the PD /
BSDL source, and get it sent over to GIGO. Hopefully he can add it to
SNESGT.

Speaking of which ... neviksti:
In your updated DecompMode0.c file, you declare NUM_CONTEXTS as 15,
but it should be 30. I'm guessing it runs fine in isolation (memory
initializes to zero and all that), but when mode 2 ran and set
contexts up to 32; only clearing 15 was resulting in corrupted
graphics all over. No big deal, just mentioning it.

> I don't really understand your (or byuu's) point. If the game does
> indeed works on 99.9% of units...on what do you base yourself to say
> their programming suck or that the game is "broken"? I mean, it
> works, it works right?


This is the problem I have with the black-and-white "bug" label ... it
implies a game is broken to a casual observer, or there is at least
noticeable corruption on at least one screen.

In truth, bsnes has a few visible bugs. Street Racer will flicker one
frame on the title screen, but only one time, and only once every ~4-8
runs. Adventures of Dr Franken and Winter Olympics show one black
scanline because the games update OBSEL at very unusual points mid-
frame.

And there are countless "anti-bugs", eg Battle Blaze on the fighter
select screen is supposed to show some garble up at the top due to
mid-scanline PPU writes. Because bsnes renders an entire scanline at
once, you don't see this. Lots and lots of games will have 1-16 pixels
on one scanline at the left (usually not even visible on TVs) that
flicker due to writing PPU regs past the end of hblank.

BoF2 German detects emulators by reading the division register early.
Since no emulator supports that, you don't see the anti-piracy splash
screen.

All of those could be considered bugs to varying degrees.

I suppose what would be nice is a bug severity ranking system.
"Severe" if it's game ruining, "Moderate" if it's more than one
scanline / frame that glitches graphics or something, and "Minor" for
the stuff 95% of people probably won't even notice. Or something like
that. My point is that it doesn't make a lot of sense to work on the
minor stuff. Most of that will probably go away with a cycle-based PPU
anyway, and the rest will probably continually appear and disappear
with infinitesimal timing changes.

[No archive available]
2008-08-07 13:39:00 +00:00
byuu
acee547da9 Update to bsnes v033r07? release.
And another one.

I've re-written the DMA state machine. I decided to keep it in one FSM
instead of two separate ones, because they honestly share so much. But
I rewrote it to be a lot cleaner, and to handle some really
exceptional edge cases. Due to the design, I was even able to make the
HDMA during DMA edge case "transparent", eg the same codepath is used
for normal HDMA and for HDMA during DMA :D

New WIP passes the last four tests in test_hdmatiming.smc. The ROM
posted doesn't validate the last four yet, so you have to compare the
SRAM file to the source logged values if you care to.

That should be everything with DMA and HDMA timing now, thankfully.
Really happy with that codepath for the very first time. Such an
improvement from the "don't even worry about HDMA syncing" code I had
a few versions ago.

I also reduced the DRAM refresh rotation from 7-lines of code testing
against the NTSC color burst case to 1-line, using the DMA counter
(dram_refresh_pos = 530 + 8 - dma_counter())

Lastly, I added a flush command to the status bar. Any important
messages will now flush all buffered ones to display the new one. Eg
load 10 games back-to-back and it'll say the name of the new game
immediately, instead of scrolling through the other 9. It will still
buffer lesser important ones, like unsupported chip and UPS patch
applied messages. I also removed config / locale path display, because
it annoyed me.

Nearing a release. I want to state machine neviksti's SPC7110
decompression code, and I should be ready on my end.

FitzRoy, I'll give you the final word. If you want controller port
selection moved to "System", I'll do so.

Any show stoppers should be mentioned now. I can't fix the "crash with
Unicode characters in the executable path" issue just yet, so that'll
have to wait.

[No archive available]
2008-08-05 11:58:00 +00:00
byuu
b1b146fd7d Update to bsnes v033r06? release.
New WIP. Adds some more HDMA timing improvements, DMA bus hold
simulation, and hopefully proper detection for ST011, which should
mean that every unsupported game will now notify you of that fact.

Also, I finally got around to writing that status bar message queue
system I mentioned a long time ago. Should make Deathlike happy. It'll
tell you whenever any UI event occurs (load, unload, reset, power
cycle, UPS patch applied, unsupported chip detected, config file /
locale file load, etc.)
Obviously if you turn off the status bar, you won't see them. Not a
problem for me personally: if you want to see status messages, leave
it on.

With that, I removed the annoyingly bland message window, and muted
the terminal message printing, putting it all inside the statusbar
instead.

I also got rid of some now-unused config variables, misc.status_text
(it was kind of overkill to let that be customizable) and
cpu.hdma_enable (it's always enabled now.)

Opinions on the new status bar system welcome.

I've also set the SNES to report itself as 2/1/3, rather than 1/1/1.
Since I don't emulate things like the HDMA conflict crash, I figured I
may as well set it to the CPU revision that doesn't have it.

> Probably the best it's ever been, but Street Racer's track does
> still flicker on "Head to Head" mode.


With the above changes, I was able to eliminate the flicker in-game in
all modes, as well as get rid of it ~80+% of the time on the title
screen. Only once every ~5 restarts will you see it for _maybe_ one
frame.

That's really the best I can do, I'm afraid. It's so subtle I doubt
anyone will even notice it now. Like Winter Olympics and Adventures of
Dr Franken, I'm not going to consider it an active bug (yes, how
convenient), but I'll watch the game closely with future timing
changes. Hopefully it'll go away entirely with more refinements in the
future.

[No archive available]
2008-08-04 06:35:00 +00:00
byuu
53e913e225 Update to bsnes v033r05? release.
New WIP.

After some more hardware testing, it seems my theory from before was
correct. See the HDMA thread for more info if you care.

With those changes plus a few others, I'm now able to get everything
in my "known troublesome" games list to work properly and with no
flickering:
- Breath of Fire 2 (G)
- Earthworm Jim 2 (U+E)
- Energy Breaker
- Jumbo Osaki no Hole in One
- Mecarobot Golf
- Secret of Mana
- Street Racer
- Super Mario Kart

I still can't get Street Racer to flicker, maybe you guys can?
Hopefully not, such a hard-to-trigger bug will be even harder to
debug.

Image
(ignore the framerate, from a pause/resume screen capture.)

And fucking _hell_ that game is hard.

Note that to get BoF2 (G) to work, I had to modify S-SMP cycle timing
from 32040hz*768 to 32041hz*768. It seems the game is very sensitive
to S-CPU <> S-SMP timing, and the improved HDMA timing was just
unlucky enough to just _barely_ miss the handshake. This was further
compounded by there being no input before the point in question to
vary timing.

It's not really a problem with the game itself -- d4s really pushed
the limits of these two chips to pull off that impressive intro. It
was more that I was hitting an extremely tiny window of time that
caused a deadlock.

This timing change only affects S-CPU <> S-SMP communications (eg
handshakes and such), and not timing inside each individual processor.
Recall that both processors in both regions (NTSC and PAL) have
slightly different timings, and the exact timings vary even on real
hardware, as the crystal clocks used are not perfect.

The NTSC S-SMP has been observed at ~32040hz on an oscilloscope by the
guy at alpha-ii.com, which is faster than the stock speed of ~32000hz.
But we still use stock speeds for the S-CPU because that's all we
have. Changing the S-CPU speed a bit would've fixed this as well.

So yeah, the fix is a bit of a kludge, but it's the best I can do when
the problem is in communication between the two chips.

Keep in mind that the S-SMP clock rates are cached in the config file.
You'll either need to delete it, or reset the values to the default in
the advanced panel. Otherwise the game will hang on first run.

Also, I tightened DMA transfer restrictions even more. A-bus accesses
to $4200-421f and $4016-4017 are now blocked. And I also block these
during HDMA line counter / indirect address fetches (as observed on
hardware.) Further, I was previously allowing invalid B->A transfers
to still write the the MMIO reg specified in A, but ignoring the B-bus
read. This seemed wrong: not being able to access the reg should mean
not being able to access it period, so I swapped that around.
Shouldn't affect any known games, but mentioning it just in case.

> Perfect timing matching isn't needed, the games are broken if they
> can't take a normal sized delay for this.


Mortal Kombat II breaks if you're exactly 6 cycles off from expected
timing (but works if you're more than six cycles off.) Jumbo Osaki was
failing by 20 cycles. Wild Guns fails if off by two cycles. A couple
other games were the same. There are roughly _21 million cycles_ in a
second.

Death Brade and some European racing game break if _uninitialized RAM_
doesn't return the values they like.

Uniracers is quite simply _beyond_ broken.

I wish I could get away with just saying the games themselves were
broken (and they are), but when it runs at least 99% of the time on
hardware, you can't use that as an excuse. Everyone will still call it
an emulation bug :(

> Err, not really. Fixed delay for all operations is as dumb as no
> delay for all operations.


I typically like the idea of emulating as much as we can ("building
blocks" and such), if that means guessing approximate delays, so much
the better. But for the DSP-1, adding any delays is even worse in my
opinion. Why?

First, the delay lengths will no doubt vary depending upon how complex
the transfer is. Second, emulating the delays would force us to
implement the DSP-1 as the dedicated processor that it is: thusly, its
overhead would soar from barely noticeable to nearly as intense as
SuperFX / SA-1 emulation. Third, it may be possible to read partially
computed results before the operations finish. We can't even figure
out the partial computations of mere _unsigned multiplication and
division_ in the S-CPU core, so how the hell would we ever plan to
figure out attitude / altitude calculations?

The only feasible way we're going to get this right is to dump the
program ROM and then emulate the instruction set. Even decapping the
DSP-1 has been no help for that, and even if by some miracle we got
the ROM, we'd have to figure out the instruction set and timing with
no documentation. And all of this to improve emulation of a couple of
lackluster action games. Good luck finding someone willing to do all
that for free, and just to end up getting ~90% of people bitching that
suddenly DSP-1 emulation is as demanding as SFX emulation, yet
provides no visible improvement over existing emulation. And it even
requires another DSP1program.rom file that they didn't need before!

Thus, it's really not worth the effort if our entire model of
emulating the chip is busted in such a manner that we couldn't improve
it more even if we wanted to anyway.

[No archive available]
2008-08-03 12:08:00 +00:00
byuu
0cf16ce784 Update to bsnes v033r04? release.
Posted a new WIP which can pass the test_hdmasync ROM I posted in the
other thread.

Please note that it's currently throwing off Jumbo Osaki exactly 50%
of the time. I'll look into it over the weekend. But the change I've
made is correct, so if I can't fix these, the games stay broken :/

One of the most unfortunate parts of emulation: when a game works
because two things are bad, but no longer when only one thing is bad.

[No archive available]
2008-08-01 13:11:00 +00:00
byuu
ce38d577ef Update to bsnes v033r03? release.
New WIP posted.

It adds my new findings on HDMA, which I've posted here:
http://board.zsnes.com/phpBB2/viewtopic.php?t=11804

This effectively fixes Mecarobot Golf once and for all. Interestingly
enough, it also eliminates the track line flickering in Super Mario
Kart.

Image
What a boring screenshot ...

I've tested for regressions with Battle Blaze, Battletoads,
Battletoads & DD, Breath of Fire 2 German, Circuit USA, Der
Langrisser, Energy Breaker, Earthworm Jim 2 (USA and EUR), F1 Grand-
Prix, FF: Mystic Quest, Mortal Kombat I & II, Jumbo Ozaki no Hole in
One, Secret of Mana and Street Racer. Basically, all the usual HDMA
suspects. Looks good to me.

Let me know if you guys find any new regressions, though.

[No archive available]
2008-07-29 06:24:00 +00:00
byuu
0a87b99370 Update to bsnes v033r02? release.
Alright, then. This was the new feature from the last WIP:

Image

Multitap support for Nach and tetsuo55 :)

New WIP up as well. This one adds Pogo's request, there's a new config
variable named input.analog_axis_resistance. The setting works both
for the DirectInput/Windows and SDL/Linux drivers.

It used to be 75% on Windows, 50% on Linux. Now it defaults to 50% on
both platforms. If any of you guys have an analog stick and want to
come up with a better default value, please feel free. I wasn't able
to pull off Ryu's spinning kick thing very easily at 75%, for
instance.

> The WIPs are private. Most of the people with access got it two
> years ago.


I used to give out access to anyone who found a new emulator bug in a
public release, but that's not working so well anymore ...

Eventually I'd like to get a system set up where anyone can get
access, yet avoid having the WIPs leak. I really don't want to bother
emu news site readers with daily WIP updates that change ~3kb of code.

[No archive available]
2008-07-28 09:56:00 +00:00
byuu
82d5761705 Update to bsnes v033r01? release.
Alright, new WIP. Added a new feature so people will stop _harassing_
me about it :P

Try and guess what it is.

[No archive available]
2008-07-27 14:44:00 +00:00
435 changed files with 14613 additions and 13787 deletions

View File

@@ -1,87 +0,0 @@
bsnes (TM) Reference License
Copyright (C) 2004 - 2008 byuu
All rights reserved
1. Definitions
The terms "reproduce", "reproduction", "distribute" and "distribution" have the
same meaning here as under U.S. copyright law.
"The software" means this software package as a whole, including, but not
limited to, this license, binaries, source code, documentation, and data.
"You" means the licensee of the software.
"The licensor" means the copyright holder of the software, byuu.
2. Grant of Rights
Subject to the terms of this license, the licensor grants you a
non-transferable, non-exclusive, worldwide, royalty-free copyright license to
reproduce the software for non-commercial use only, provided the software
remains unmodified, and there is no charge for the software itself, its' use,
nor for the medium upon which the software is distributed. The reproduction of
modified or derivative works of the software is strictly prohibited, except when
transmitted solely to the licensor.
3. Limitations
This license does not grant you any rights to use the licensor's name, logo or
trademarks.
The software is provided "as is", and any express or implied warranties,
including, but not limited to, the implied warranties of merchantability and
fitness for a particular purpose are disclaimed. In no event shall the licensor
be liable for any direct, indirect, incidental, special, exemplary, or
consequential damages (including, but not limited to, procurement of substitute
goods or services; loss of use, data, or profits; or business interruption)
however caused and on any theory of liability, whether in contract, strict
liability, or tort (including negligence or otherwise) arising in any way out of
the use of the software, even if advised of the possibility of such damage.
In the event that this license is determined to be invalid or unenforceable, the
Grant of Rights will become null and void, and no rights shall be granted to the
licensee, within the scope of U.S. copyright law.
4. Exemptions
The software includes the work of other copyright holders, which is licensed
under different agreements, and exempt from this license. Below is a complete
list of all such software, and their respective copyright holders and licenses.
Further, respective source code files are labeled with their correct licensing
information in the header. The lack of such a header indicates said file falls
under the bsnes license.
HQ2x filter, author: MaxST, license: LGPL
JMA decompressor, author: NSRT Team, license: GPL (*)
NTSC filter, author: blargg, license: LGPL
zlib decompressor, license: zlib license
(*) bsnes has received an exemption from the copyright holder to use this work.
The software also includes works which have been released to the public domain,
which are not bound to any licensing agreements. Below is a complete list of all
such software.
libco, author: byuu
libui, author: byuu
OBC-1 emu, author: byuu
S-DD1 decompressor, author: Andreas Naive
SPC7110 decompressor, author: neviksti
S-RTC emu, author: byuu
Any software listed above as exemptions may be relicensed individually from
bsnes under their respective terms. However, no bsnes licensed portions can be
combined with such a derivative work.
The software also includes the work of other copyright holders, which is
licensed under the terms of the bsnes license, with permission to do so from the
respective authors. Below is a complete list of all such software.
Cx4 emu, authors: anomie, Overload, zsKnight, Nach
DSP-1 emu, authors: Overload, John Weidman, Neviksti, Andreas Naive
DSP-2 emu, author: Overload
DSP-3 emu, authors: John Weidman, Kris Bleakley, Lancer, z80 gaiden
DSP-4 emu, authors: Dreamer Nom, John Weidman, Kris Bleakley, Nach, z80 gaiden
S-DSP emu, author: blargg
ST-010 emu, authors: John Weidman, Matthew Kendora, Overload, Feather

View File

@@ -1,93 +0,0 @@
bsnes
Version: 0.033
Author: byuu
========
General:
========
bsnes is a Super Nintendo / Super Famicom emulator that began on
October 14th, 2004.
The latest version can be downloaded from:
http://byuu.org/
Please see license.txt for important licensing information.
==============
Configuration:
==============
bsnes has two configuration files: bsnes.cfg, for program settings; and
locale.cfg, for localization.
For each file, bsnes will start by looking inside the same folder where the
bsnes executable is located. If said file is not found, it will then check your
user profile folder. On Windows, this is located at "%APPDATA%/.bsnes". On all
other operating systems, this is located at "~/.bsnes". If said file is still
not found, it will automatically be created in your user profile folder.
If you wish to use bsnes in single-user mode, be sure that both files exist
inside the same folder as the bsnes executable. If they do not, you can simply
create new blank files and bsnes will use them in the future.
If you wish to use bsnes in multi-user mode, simply delete these two files from
the bsnes executable directory if they exist.
If you wish to have multiple configuration profiles for the same user, you will
need to make copies of the bsnes executable, and use each one in single-user
mode.
==================
Known Limitations:
==================
S-CPU
- Multiply / divide register delays not implemented
S-PPU
- Uses scanline-based renderer. This is very inaccurate, but few (if any)
games rely on mid-scanline writes to function correctly
- Does not support FirstSprite+Y priority
- OAM / CGRAM accesses during active display not supported correctly
- RTO flags are not calculated on frames that are skipped when frameskipping
is enabled. This provides a major speedup, however it will cause in issues
in games that test these flags, eg the SNES Test Program Electronics Test.
Turning frameskipping off will allow RTO flag calculation on every frame
Hardware Bugs
- S-CPU.r1 HDMA crashing bug not emulated
- S-CPU<>S-SMP communication bus conflicts not emulated
=====================
Unsupported Hardware:
=====================
SA-1
Coprocessor used in many popular games, including:
- Dragon Ball Z Hyper Dimension
- Kirby Super Star
- Kirby's Dreamland 3
- Marvelous
- SD Gundam G-NEXT
- Super Mario RPG
Super FX
Coprocessor used in many popular games, including:
- Doom
- Star Fox
- Star Fox 2 (unreleased beta)
- Super Mario World 2: Yoshi's Island
ST-011
SETA DSP used by Quick-move Shogi Match with Nidan Rank-holder Morita
ST-018
SETA RISC CPU used by Quick-move Shogi Match with Nidan Rank-holder Morita 2
Super Gameboy
Cartridge passthrough used for playing Gameboy games
========================
Unsupported Controllers:
========================
Mouse
Super Scope
Justifier
Multitap (4-port and 5-port)

View File

@@ -16,7 +16,7 @@ ifneq ($(findstring gcc,$(compiler)),) # GCC family
mkdef = -D$1
mklib = -l$1
else ifeq ($(compiler),cl) # Visual C++
flags = /nologo /wd4355 /wd4996 /O2 /EHsc /Ilib
flags = /nologo /wd4355 /wd4805 /wd4996 /Ox /GL /EHsc /Ilib
c = cl $(flags)
cpp = cl $(flags)
obj = obj
@@ -34,7 +34,7 @@ endif
##########
ifeq ($(platform),x) # X11
ruby = video.glx video.xv video.sdl audio.openal audio.oss audio.alsa audio.ao input.sdl input.x
ruby = video.glx video.xv video.sdl audio.alsa audio.openal audio.oss audio.pulseaudio audio.ao input.sdl input.x
link += `pkg-config --libs gtk+-2.0`
link += $(call mklib,Xtst)
delete = rm -f $1
@@ -70,6 +70,7 @@ link += $(if $(findstring audio.alsa,$(ruby)),$(call mklib,asound))
link += $(if $(findstring audio.ao,$(ruby)),$(call mklib,ao))
link += $(if $(findstring audio.directsound,$(ruby)),$(call mklib,dsound))
link += $(if $(findstring audio.openal,$(ruby)),$(if $(call streq,$(platform),x),$(call mklib,openal),$(call mklib,openal32)))
link += $(if $(findstring audio.pulseaudio,$(ruby)),$(call mklib,pulse-simple))
link += $(if $(findstring input.directinput,$(ruby)),$(call mklib,dinput8) $(call mklib,dxguid))
link += $(if $(findstring input.sdl,$(ruby)),`sdl-config --libs`)
@@ -77,7 +78,8 @@ link += $(if $(findstring input.sdl,$(ruby)),`sdl-config --libs`)
### main target and dependencies ###
####################################
objects = main libco hiro ruby libfilter string reader cart cheat \
objects = main libco hiro ruby libfilter string \
reader cart cheat \
memory smemory cpu scpu smp ssmp sdsp ppu bppu snes \
bsx srtc sdd1 spc7110 cx4 dsp1 dsp2 dsp3 dsp4 obc1 st010
@@ -96,11 +98,7 @@ rubydef := $(foreach c,$(subst .,_,$(call strupper,$(ruby))),$(call mkdef,$c))
# Windows resource file
ifeq ($(platform),win)
ifeq ($(compiler),cl)
objects += obj/bsnes.res
else ifneq ($(findstring gcc,$(compiler)),)
objects += obj/bsnesrc.$(obj)
endif
objects += obj/resource.$(obj)
endif
################
@@ -125,22 +123,21 @@ all: build;
### main ###
############
obj/main.$(obj): ui/main.cpp ui/* ui/base/* ui/loader/* ui/settings/*
obj/bsnes.res: ui/bsnes.rc; rc /r /foobj/bsnes.res ui/bsnes.rc
obj/bsnesrc.$(obj): ui/bsnes.rc; windres ui/bsnes.rc obj/bsnesrc.$(obj)
obj/main.$(obj) : ui/main.cpp ui/* ui/base/* ui/event/* ui/loader/* ui/settings/*
obj/resource.$(obj): ui/bsnes.rc; windres ui/bsnes.rc obj/resource.$(obj)
#################
### libraries ###
#################
obj/ruby.$(obj): lib/ruby/ruby.cpp lib/ruby/*
obj/ruby.$(obj): lib/ruby/ruby.cpp lib/ruby/* lib/ruby/video/* lib/ruby/audio/* lib/ruby/input/*
$(call compile,$(rubydef) $(rubyflags))
obj/hiro.$(obj): lib/hiro/hiro.cpp lib/hiro/* lib/hiro/gtk/* lib/hiro/win/*
$(call compile,$(if $(call streq,$(platform),x),`pkg-config --cflags gtk+-2.0`))
obj/libco.$(obj): lib/libco/libco.c lib/libco/*
$(call compile,-static)
obj/libco.$(obj): lib/libco/libco.c lib/libco/*
$(call compile,$(if $(call strne,$(compiler),cl),-static))
obj/libfilter.$(obj): lib/libfilter/libfilter.cpp lib/libfilter/*
obj/string.$(obj): lib/nall/string.cpp lib/nall/*
obj/string.$(obj): lib/nall/string.cpp lib/nall/*
#################
### utilities ###
@@ -176,7 +173,6 @@ obj/ssmp.$(obj): smp/ssmp/ssmp.cpp smp/ssmp/* smp/ssmp/core/* smp/ssmp/memory/*
###########
obj/adsp.$(obj): dsp/adsp/adsp.cpp dsp/adsp/*
obj/bdsp.$(obj): dsp/bdsp/bdsp.cpp dsp/bdsp/*
obj/sdsp.$(obj): dsp/sdsp/sdsp.cpp dsp/sdsp/*
###########

View File

@@ -1,4 +1,4 @@
#define BSNES_VERSION "0.033"
#define BSNES_VERSION "0.039"
#define BSNES_TITLE "bsnes v" BSNES_VERSION
#define BUSCORE sBus
@@ -19,38 +19,31 @@
//game genie + pro action replay code support (~2% speed hit)
#define CHEAT_SYSTEM
#include <libco/libco.h>
#include <nall/algorithm.hpp>
#include <nall/array.hpp>
#include <nall/bit.hpp>
#include <nall/config.hpp>
#include <nall/detect.hpp>
#include <nall/endian.hpp>
#include <nall/file.hpp>
#include <nall/function.hpp>
#include <nall/modulo.hpp>
#include <nall/moduloarray.hpp>
#include <nall/new.hpp>
#include <nall/sort.hpp>
#include <nall/platform.hpp>
#include <nall/stdint.hpp>
#include <nall/string.hpp>
#include <nall/utility.hpp>
#include <nall/vector.hpp>
using namespace nall;
#include <libco/libco.h>
#include <bbase.h>
typedef int8_t int8;
typedef int16_t int16;
typedef int32_t int32;
typedef int64_t int64;
typedef uint8_t uint8;
typedef uint16_t uint16;
typedef uint32_t uint32;
typedef uint64_t uint64;
//platform-specific global functions
void alert(const char*, ...);
void dprintf(const char*, ...);
void dprintf(uint, const char*, ...);
namespace source {
enum {
none = 0,
debug,
cpu,
ppu,
smp,
dsp,
bus,
};
};
#include "interface.h"
#include "interface.hpp"

View File

@@ -1,9 +1,13 @@
#include "../base.h"
#define CART_CPP
#include <nall/crc32.hpp>
#include <../base.hpp>
#include <../chip/chip.hpp>
#include <../reader/reader.hpp>
#define CART_CPP
#include <nall/crc32.hpp>
#include <nall/ups.hpp>
#include "cart.hpp"
#include "cart_load.cpp"
#include "cart_normal.cpp"
#include "cart_bsx.cpp"
#include "cart_bsc.cpp"
@@ -21,12 +25,13 @@ namespace memory {
Cartridge cartridge;
Cartridge::MemoryMapper Cartridge::mapper() { return info.mapper; }
Cartridge::Region Cartridge::region() { return info.region; }
const char* Cartridge::name() const { return info.filename; }
Cartridge::CartridgeMode Cartridge::mode() const { return info.mode; }
Cartridge::MemoryMapper Cartridge::mapper() const { return info.mapper; }
Cartridge::Region Cartridge::region() const { return info.region; }
bool Cartridge::loaded() const { return cart.loaded; }
bool Cartridge::loaded() { return cart.loaded; }
void Cartridge::load_begin(CartridgeType cart_type) {
void Cartridge::load_begin(CartridgeMode mode) {
cart.rom = cart.ram = cart.rtc = 0;
bs.ram = 0;
stA.rom = stA.ram = 0;
@@ -37,38 +42,11 @@ void Cartridge::load_begin(CartridgeType cart_type) {
stA.rom_size = stA.ram_size = 0;
stB.rom_size = stB.ram_size = 0;
info.type = cart_type;
info.mode = mode;
info.patched = false;
info.bsxbase = false;
info.bsxcart = false;
info.bsxflash = false;
info.st = false;
info.superfx = false;
info.sa1 = false;
info.srtc = false;
info.sdd1 = false;
info.spc7110 = false;
info.spc7110rtc = false;
info.cx4 = false;
info.dsp1 = false;
info.dsp2 = false;
info.dsp3 = false;
info.dsp4 = false;
info.obc1 = false;
info.st010 = false;
info.st011 = false;
info.st018 = false;
info.dsp1_mapper = DSP1Unmapped;
info.header_index = 0xffc0;
info.mapper = LoROM;
info.name[0] = 0;
info.region = NTSC;
info.rom_size = 0;
info.ram_size = 0;
}
void Cartridge::load_end() {
@@ -89,7 +67,7 @@ void Cartridge::load_end() {
memory::stBrom.write_protect(true);
memory::stBram.write_protect(false);
if(fexists(get_cheat_filename(cart.fn, "cht"))) {
if(file::exists(get_cheat_filename(cart.fn, "cht"))) {
cheat.clear();
cheat.load(cheatfn);
}
@@ -103,11 +81,11 @@ bool Cartridge::unload() {
bus.unload_cart();
switch(info.type) {
case CartridgeNormal: unload_cart_normal(); break;
case CartridgeBSX: unload_cart_bsx(); break;
case CartridgeBSC: unload_cart_bsc(); break;
case CartridgeSufamiTurbo: unload_cart_st(); break;
switch(info.mode) {
case ModeNormal: unload_cart_normal(); break;
case ModeBSX: unload_cart_bsx(); break;
case ModeBSC: unload_cart_bsc(); break;
case ModeSufamiTurbo: unload_cart_st(); break;
}
if(cart.rom) { delete[] cart.rom; cart.rom = 0; }
@@ -119,10 +97,7 @@ bool Cartridge::unload() {
if(stB.rom) { delete[] stB.rom; stB.rom = 0; }
if(stB.ram) { delete[] stB.ram; stB.ram = 0; }
char fn[PATH_MAX];
strcpy(fn, cart.fn);
modify_extension(fn, "cht");
if(cheat.count() > 0 || fexists(get_cheat_filename(cart.fn, "cht"))) {
if(cheat.count() > 0 || file::exists(get_cheat_filename(cart.fn, "cht"))) {
cheat.save(cheatfn);
cheat.clear();
}
@@ -138,3 +113,87 @@ Cartridge::Cartridge() {
Cartridge::~Cartridge() {
if(cart.loaded == true) unload();
}
//==========
//cartinfo_t
//==========
void Cartridge::cartinfo_t::reset() {
type = TypeUnknown;
mapper = LoROM;
dsp1_mapper = DSP1Unmapped;
region = NTSC;
rom_size = 0;
ram_size = 0;
bsxslot = false;
superfx = false;
sa1 = false;
srtc = false;
sdd1 = false;
spc7110 = false;
spc7110rtc = false;
cx4 = false;
dsp1 = false;
dsp2 = false;
dsp3 = false;
dsp4 = false;
obc1 = false;
st010 = false;
st011 = false;
st018 = false;
}
//apply cart-specific settings to current cartridge mode settings
Cartridge::info_t& Cartridge::info_t::operator=(const Cartridge::cartinfo_t &source) {
mapper = source.mapper;
dsp1_mapper = source.dsp1_mapper;
region = source.region;
bsxslot = source.bsxslot;
superfx = source.superfx;
sa1 = source.sa1;
srtc = source.srtc;
sdd1 = source.sdd1;
spc7110 = source.spc7110;
spc7110rtc = source.spc7110rtc;
cx4 = source.cx4;
dsp1 = source.dsp1;
dsp2 = source.dsp2;
dsp3 = source.dsp3;
dsp4 = source.dsp4;
obc1 = source.obc1;
st010 = source.st010;
st011 = source.st011;
st018 = source.st018;
return *this;
}
//=======
//utility
//=======
string Cartridge::filepath(const char *filename, const char *pathname) {
//if no pathname, return filename as-is
string file(filename);
replace(file, "\\", "/");
if(!pathname || !*pathname) return file;
//ensure path ends with trailing '/'
string path(pathname);
replace(path, "\\", "/");
if(!strend(path, "/")) strcat(path, "/");
//replace relative path with absolute path
if(strbegin(path, "./")) {
ltrim(path, "./");
path = string() << snes.config.path.base << path;
}
//remove folder part of filename
lstring part;
split(part, "/", file);
return path << part[count(part) - 1];
}

View File

@@ -1,159 +0,0 @@
class Cartridge {
public:
enum CartridgeType {
CartridgeNormal,
CartridgeBSX,
CartridgeBSC,
CartridgeSufamiTurbo,
};
enum HeaderField {
CART_NAME = 0x00,
MAPPER = 0x15,
ROM_TYPE = 0x16,
ROM_SIZE = 0x17,
RAM_SIZE = 0x18,
REGION = 0x19,
COMPANY = 0x1a,
VERSION = 0x1b,
ICKSUM = 0x1c,
CKSUM = 0x1e,
RESL = 0x3c,
RESH = 0x3d,
};
enum Region {
NTSC,
PAL,
};
enum MemoryMapper {
LoROM,
HiROM,
ExLoROM,
ExHiROM,
SPC7110ROM,
BSXROM,
BSCLoROM,
BSCHiROM,
STROM,
};
enum DSP1MemoryMapper {
DSP1Unmapped,
DSP1LoROM1MB,
DSP1LoROM2MB,
DSP1HiROM,
};
struct {
bool loaded;
char fn[PATH_MAX];
uint8 *rom, *ram, *rtc;
uint rom_size, ram_size, rtc_size;
} cart;
struct {
char fn[PATH_MAX];
uint8 *ram;
uint ram_size;
} bs;
struct {
char fn[PATH_MAX];
uint8 *rom, *ram;
uint rom_size, ram_size;
} stA, stB;
struct {
CartridgeType type;
uint32 crc32;
char filename[PATH_MAX * 4];
char name[128];
Region region;
MemoryMapper mapper;
uint rom_size;
uint ram_size;
bool bsxbase;
bool bsxcart;
bool bsxflash;
bool st;
bool superfx;
bool sa1;
bool srtc;
bool sdd1;
bool spc7110;
bool spc7110rtc;
bool cx4;
bool dsp1;
bool dsp2;
bool dsp3;
bool dsp4;
bool obc1;
bool st010;
bool st011;
bool st018;
DSP1MemoryMapper dsp1_mapper;
uint header_index;
} info;
MemoryMapper mapper();
Region region();
void load_cart_normal(const char*);
void load_cart_bsx(const char*, const char*);
void load_cart_bsc(const char*, const char*);
void load_cart_st(const char*, const char*, const char*);
void unload_cart_normal();
void unload_cart_bsx();
void unload_cart_bsc();
void unload_cart_st();
bool loaded();
void load_begin(CartridgeType);
void load_end();
bool unload();
void find_header();
void read_header();
void read_extended_header();
enum CompressionMode {
CompressionNone, //always load without compression
CompressionInspect, //use file header inspection
CompressionAuto, //use file extension or file header inspection (configured by user)
};
bool load_file(const char *fn, uint8 *&data, uint &size, CompressionMode compression = CompressionNone);
bool save_file(const char *fn, uint8 *data, uint size);
bool apply_patch(const uint8_t *pdata, unsigned psize, uint8_t *&data, unsigned &size);
char* modify_extension(char *filename, const char *extension);
char* get_base_filename(char *filename);
char* get_path_filename(char *filename, const char *path, const char *source, const char *extension);
char* get_patch_filename(const char *source, const char *extension);
char* get_save_filename(const char *source, const char *extension);
char* get_cheat_filename(const char *source, const char *extension);
Cartridge();
~Cartridge();
private:
char patchfn[PATH_MAX];
char savefn[PATH_MAX];
char rtcfn[PATH_MAX];
char cheatfn[PATH_MAX];
};
namespace memory {
extern MappedRAM cartrom, cartram, cartrtc;
extern MappedRAM bscram;
extern MappedRAM stArom, stAram;
extern MappedRAM stBrom, stBram;
};
extern Cartridge cartridge;

205
src/cart/cart.hpp Normal file
View File

@@ -0,0 +1,205 @@
class Cartridge {
public:
enum CartridgeMode {
ModeNormal,
ModeBSC,
ModeBSX,
ModeSufamiTurbo,
};
enum CartridgeType {
TypeNormal,
TypeBSC,
TypeBSXBIOS,
TypeBSX,
TypeSufamiTurboBIOS,
TypeSufamiTurbo,
TypeUnknown,
};
enum HeaderField {
CartName = 0x00,
Mapper = 0x15,
RomType = 0x16,
RomSize = 0x17,
RamSize = 0x18,
CartRegion = 0x19,
Company = 0x1a,
Version = 0x1b,
Complement = 0x1c, //inverse checksum
Checksum = 0x1e,
ResetVector = 0x3c,
};
enum Region {
NTSC,
PAL,
};
enum MemoryMapper {
LoROM,
HiROM,
ExLoROM,
ExHiROM,
SPC7110ROM,
BSCLoROM,
BSCHiROM,
BSXROM,
STROM,
};
enum DSP1MemoryMapper {
DSP1Unmapped,
DSP1LoROM1MB,
DSP1LoROM2MB,
DSP1HiROM,
};
const char* name() const;
CartridgeMode mode() const;
MemoryMapper mapper() const;
Region region() const;
struct {
bool loaded;
char fn[PATH_MAX];
uint8 *rom, *ram, *rtc;
unsigned rom_size, ram_size, rtc_size;
} cart;
struct {
char fn[PATH_MAX];
uint8 *ram;
unsigned ram_size;
} bs;
struct {
char fn[PATH_MAX];
uint8 *rom, *ram;
unsigned rom_size, ram_size;
} stA, stB;
struct cartinfo_t {
CartridgeType type;
MemoryMapper mapper;
DSP1MemoryMapper dsp1_mapper;
Region region;
unsigned rom_size;
unsigned ram_size;
bool bsxslot;
bool superfx;
bool sa1;
bool srtc;
bool sdd1;
bool spc7110;
bool spc7110rtc;
bool cx4;
bool dsp1;
bool dsp2;
bool dsp3;
bool dsp4;
bool obc1;
bool st010;
bool st011;
bool st018;
void reset();
};
struct info_t {
char filename[PATH_MAX * 4];
bool patched;
CartridgeMode mode;
MemoryMapper mapper;
DSP1MemoryMapper dsp1_mapper;
Region region;
bool bsxcart; //is BS-X cart inserted?
bool bsxflash; //is BS-X flash cart inserted into BS-X cart?
bool bsxslot;
bool superfx;
bool sa1;
bool srtc;
bool sdd1;
bool spc7110;
bool spc7110rtc;
bool cx4;
bool dsp1;
bool dsp2;
bool dsp3;
bool dsp4;
bool obc1;
bool st010;
bool st011;
bool st018;
info_t& operator=(const cartinfo_t&);
} info;
struct {
char fn[PATH_MAX];
uint8_t *data;
unsigned size;
} image;
bool load_image(const char*);
bool inspect_image(cartinfo_t &cartinfo, const char *filename);
bool load_ram(const char *filename, uint8_t *&data, unsigned size, uint8_t init);
void load_cart_normal(const char*);
void load_cart_bsc(const char*, const char*);
void load_cart_bsx(const char*, const char*);
void load_cart_st(const char*, const char*, const char*);
void unload_cart_normal();
void unload_cart_bsx();
void unload_cart_bsc();
void unload_cart_st();
bool loaded() const;
void load_begin(CartridgeMode);
void load_end();
bool unload();
void read_header(cartinfo_t &info, const uint8_t *data, unsigned size);
unsigned find_header(const uint8_t *data, unsigned size);
unsigned score_header(const uint8_t *data, unsigned size, unsigned addr);
enum CompressionMode {
CompressionNone, //always load without compression
CompressionInspect, //use file header inspection
CompressionAuto, //use file extension or file header inspection (configured by user)
};
bool load_file(const char *fn, uint8 *&data, unsigned &size, CompressionMode compression = CompressionNone);
bool save_file(const char *fn, uint8 *data, unsigned size);
bool apply_patch(const uint8_t *pdata, unsigned psize, uint8_t *&data, unsigned &size);
char* modify_extension(char *filename, const char *extension);
char* get_base_filename(char *filename);
char* get_path_filename(char *filename, const char *path, const char *source, const char *extension);
char* get_patch_filename(const char *source, const char *extension);
char* get_save_filename(const char *source, const char *extension);
char* get_cheat_filename(const char *source, const char *extension);
static string filepath(const char *filename, const char *pathname);
Cartridge();
~Cartridge();
private:
char patchfn[PATH_MAX];
char savefn[PATH_MAX];
char rtcfn[PATH_MAX];
char cheatfn[PATH_MAX];
};
namespace memory {
extern MappedRAM cartrom, cartram, cartrtc;
extern MappedRAM bscram;
extern MappedRAM stArom, stAram;
extern MappedRAM stBrom, stBram;
};
extern Cartridge cartridge;

View File

@@ -1,57 +1,36 @@
#ifdef CART_CPP
void Cartridge::load_cart_bsc(const char *base, const char *slot) {
if(!base || !*base) return;
strcpy(cart.fn, base);
strcpy(bs.fn, slot ? slot : "");
load_begin(CartridgeBSC);
uint8_t *data = 0;
uint8_t *data;
unsigned size;
load_file(cart.fn, data, size, CompressionAuto);
cart.rom = data, cart.rom_size = size;
strcpy(cart.fn, base);
strcpy(bs.fn, slot);
if(load_file(get_patch_filename(cart.fn, "ups"), data, size, CompressionInspect) == true) {
apply_patch(data, size, cart.rom, cart.rom_size);
delete[] data;
load_begin(ModeBSC);
if(load_image(base) == false) return;
cartinfo_t cartinfo;
read_header(cartinfo, cart.rom = image.data, cart.rom_size = image.size);
info = cartinfo;
if(load_image(slot) == true) {
info.bsxflash = true;
bs.ram = image.data;
bs.ram_size = image.size;
}
if(*bs.fn) {
if(load_file(bs.fn, data, size, CompressionAuto) == true) {
info.bsxflash = true;
bs.ram = data, bs.ram_size = size;
if(load_file(get_patch_filename(bs.fn, "ups"), data, size, CompressionInspect) == true) {
apply_patch(data, size, bs.ram, bs.ram_size);
delete[] data;
}
}
}
find_header();
read_header();
info.mapper = cartridge.info.header_index == 0x7fc0 ? BSCLoROM : BSCHiROM;
info.region = NTSC;
if(info.ram_size > 0) {
cart.ram = new uint8_t[cart.ram_size = info.ram_size];
memset(cart.ram, 0xff, cart.ram_size);
if(load_file(get_save_filename(cart.fn, "srm"), data, size, CompressionNone) == true) {
memcpy(cart.ram, data, min(size, cart.ram_size));
delete[] data;
}
if(cartinfo.ram_size > 0) {
load_ram(get_save_filename(base, "srm"), cart.ram, cart.ram_size = cartinfo.ram_size, 0xff);
}
load_end();
//set base filename
strcpy(info.filename, cart.fn);
strcpy(info.filename, base);
get_base_filename(info.filename);
if(*bs.fn) {
if(*slot) {
char filenameBS[PATH_MAX];
strcpy(filenameBS, bs.fn);
strcpy(filenameBS, slot);
get_base_filename(filenameBS);
strcat(info.filename, " + ");
strcat(info.filename, filenameBS);
@@ -62,4 +41,4 @@ void Cartridge::unload_cart_bsc() {
if(cart.ram) save_file(get_save_filename(cart.fn, "srm"), cart.ram, cart.ram_size);
}
#endif //ifdef CART_CPP
#endif

View File

@@ -1,27 +1,20 @@
#ifdef CART_CPP
void Cartridge::load_cart_bsx(const char *base, const char *slot) {
if(!base || !*base) return;
strcpy(cart.fn, base);
strcpy(bs.fn, slot ? slot : "");
load_begin(CartridgeBSX);
info.bsxbase = true;
info.bsxcart = true;
info.mapper = BSXROM;
info.region = NTSC;
uint8_t *data = 0;
uint8_t *data;
unsigned size;
load_file(cart.fn, data, size, CompressionAuto);
cart.rom = data, cart.rom_size = size;
cart.ram = 0, cart.ram_size = 0;
strcpy(cart.fn, base);
strcpy(bs.fn, slot);
if(load_file(get_patch_filename(cart.fn, "ups"), data, size, CompressionInspect) == true) {
apply_patch(data, size, cart.rom, cart.rom_size);
delete[] data;
}
load_begin(ModeBSX);
if(load_image(base) == false) return;
info.bsxcart = true;
cartinfo_t cartinfo;
read_header(cartinfo, cart.rom = image.data, cart.rom_size = image.size);
info = cartinfo;
cart.ram = 0;
cart.ram_size = 0;
memset(bsxcart.sram.handle (), 0x00, bsxcart.sram.size ());
memset(bsxcart.psram.handle(), 0x00, bsxcart.psram.size());
@@ -36,20 +29,15 @@ void Cartridge::load_cart_bsx(const char *base, const char *slot) {
delete[] data;
}
if(*bs.fn) {
if(load_file(bs.fn, data, size, CompressionAuto) == true) {
info.bsxflash = true;
bs.ram = data, bs.ram_size = size;
if(load_file(get_patch_filename(bs.fn, "ups"), data, size, CompressionInspect) == true) {
apply_patch(data, size, bs.ram, bs.ram_size);
delete[] data;
}
}
if(load_image(slot)) {
info.bsxflash = true;
bs.ram = image.data;
bs.ram_size = image.size;
}
load_end();
strcpy(info.filename, !*bs.fn ? cart.fn : bs.fn);
strcpy(info.filename, !*slot ? base : slot);
get_base_filename(info.filename);
}
@@ -58,4 +46,4 @@ void Cartridge::unload_cart_bsx() {
save_file(get_save_filename(cart.fn, "psr"), bsxcart.psram.handle(), bsxcart.psram.size());
}
#endif //ifdef CART_CPP
#endif

View File

@@ -1,27 +1,27 @@
#ifdef CART_CPP
#include "../reader/filereader.h"
#if defined(GZIP_SUPPORT)
#include "../reader/gzreader.h"
#include "../reader/zipreader.h"
#endif
#if defined(JMA_SUPPORT)
#include "../reader/jmareader.h"
#endif
char* Cartridge::modify_extension(char *filename, const char *extension) {
int i;
for(i = strlen(filename); i >= 0; i--) {
if(filename[i] == '.') break;
if(filename[i] == '/') break;
if(filename[i] == '\\') break;
}
if(i > 0 && filename[i] == '.') filename[i] = 0;
strcat(filename, ".");
strcat(filename, extension);
return filename;
#include "../reader/filereader.hpp"
#if defined(GZIP_SUPPORT)
#include "../reader/gzreader.hpp"
#include "../reader/zipreader.hpp"
#endif
#if defined(JMA_SUPPORT)
#include "../reader/jmareader.hpp"
#endif
char* Cartridge::modify_extension(char *filename, const char *extension) {
int i;
for(i = strlen(filename); i >= 0; i--) {
if(filename[i] == '.') break;
if(filename[i] == '/') break;
if(filename[i] == '\\') break;
}
if(i > 0 && filename[i] == '.') filename[i] = 0;
strcat(filename, ".");
strcat(filename, extension);
return filename;
}
//remove directory information and file extension ("/foo/bar.ext" -> "bar")
@@ -47,101 +47,74 @@ char* Cartridge::get_base_filename(char *filename) {
break;
}
}
}
char* Cartridge::get_path_filename(char *filename, const char *path, const char *source, const char *extension) {
strcpy(filename, source);
for(char *p = filename; *p; p++) { if(*p == '\\') *p = '/'; }
return filename;
}
char* Cartridge::get_path_filename(char *filename, const char *path, const char *source, const char *extension) {
strcpy(filename, source);
modify_extension(filename, extension);
//override path with user-specified folder, if one was defined
if(*path) {
lstring part;
split(part, "/", filename);
string fn = path;
if(strend(fn, "/") == false) strcat(fn, "/");
strcat(fn, part[count(part) - 1]);
strcpy(filename, fn);
//resolve relative path, if found
if(strbegin(fn, "./") == true) {
ltrim(fn, "./");
strcpy(filename, config::path.base);
strcat(filename, fn);
}
}
return filename;
strcpy(filename, filepath(filename, path));
return filename;
}
char* Cartridge::get_patch_filename(const char *source, const char *extension) {
return get_path_filename(patchfn, config::path.patch, source, extension);
}
return get_path_filename(patchfn, snes.config.path.patch, source, extension);
}
char* Cartridge::get_save_filename(const char *source, const char *extension) {
return get_path_filename(savefn, config::path.save, source, extension);
return get_path_filename(savefn, snes.config.path.save, source, extension);
}
char* Cartridge::get_cheat_filename(const char *source, const char *extension) {
return get_path_filename(cheatfn, config::path.cheat, source, extension);
return get_path_filename(cheatfn, snes.config.path.cheat, source, extension);
}
bool Cartridge::load_file(const char *fn, uint8 *&data, uint &size, CompressionMode compression) {
dprintf("* Loading \"%s\" ...", fn);
if(fexists(fn) == false) return false;
bool Cartridge::load_file(const char *fn, uint8 *&data, unsigned &size, CompressionMode compression) {
if(file::exists(fn) == false) return false;
Reader::Type filetype = Reader::Normal;
if(compression == CompressionInspect) filetype = Reader::detect(fn, true);
if(compression == CompressionAuto) filetype = Reader::detect(fn, config::file.autodetect_type);
switch(filetype) {
default:
dprintf("* Warning: filetype detected as unsupported compression type.");
dprintf("* Will attempt to load as uncompressed file -- may fail.");
case Reader::Normal: {
FileReader ff(fn);
if(!ff.ready()) {
alert("Error loading image file (%s)!", fn);
return false;
}
size = ff.size();
data = ff.read();
} break;
#ifdef GZIP_SUPPORT
case Reader::GZIP: {
GZReader gf(fn);
if(!gf.ready()) {
alert("Error loading image file (%s)!", fn);
return false;
}
size = gf.size();
data = gf.read();
} break;
case Reader::ZIP: {
ZipReader zf(fn);
size = zf.size();
data = zf.read();
} break;
#endif
#ifdef JMA_SUPPORT
case Reader::JMA: {
try {
JMAReader jf(fn);
size = jf.size();
data = jf.read();
} catch(JMA::jma_errors jma_error) {
alert("Error loading image file (%s)!", fn);
return false;
}
} break;
#endif
}
return true;
if(compression == CompressionAuto) filetype = Reader::detect(fn, snes.config.file.autodetect_type);
switch(filetype) { default:
case Reader::Normal: {
FileReader ff(fn);
if(!ff.ready()) return false;
size = ff.size();
data = ff.read();
} break;
#ifdef GZIP_SUPPORT
case Reader::GZIP: {
GZReader gf(fn);
if(!gf.ready()) return false;
size = gf.size();
data = gf.read();
} break;
case Reader::ZIP: {
ZipReader zf(fn);
if(!zf.ready()) return false;
size = zf.size();
data = zf.read();
} break;
#endif
#ifdef JMA_SUPPORT
case Reader::JMA: {
try {
JMAReader jf(fn);
size = jf.size();
data = jf.read();
} catch(JMA::jma_errors jma_error) {
return false;
}
} break;
#endif
}
return true;
}
bool Cartridge::apply_patch(const uint8_t *pdata, const unsigned psize, uint8_t *&data, unsigned &size) {
@@ -152,28 +125,28 @@ bool Cartridge::apply_patch(const uint8_t *pdata, const unsigned psize, uint8_t
bool apply = false;
if(result == ups::ok) apply = true;
if(config::file.bypass_patch_crc32 == true) {
if(snes.config.file.bypass_patch_crc32 == true) {
if(result == ups::input_crc32_invalid) apply = true;
if(result == ups::output_crc32_invalid) apply = true;
}
//if patch application was successful, replace old data, size with new data, size
if(apply == true) {
delete[] data;
data = new uint8_t[size = outsize];
memcpy(data, outdata, outsize);
} else {
dprintf("* Warning: patch application failed!");
}
if(outdata) delete[] outdata;
}
bool Cartridge::save_file(const char *fn, uint8 *data, uint size) {
FILE *fp = fopen(fn, "wb");
if(!fp) return false;
fwrite(data, 1, size, fp);
fclose(fp);
return true;
}
return apply;
}
#endif //ifdef CART_CPP
bool Cartridge::save_file(const char *fn, uint8 *data, unsigned size) {
file fp;
if(!fp.open(fn, file::mode_write)) return false;
fp.write(data, size);
fp.close();
return true;
}
#endif

View File

@@ -1,38 +1,91 @@
#ifdef CART_CPP
void Cartridge::read_header() {
uint8 *rom = cart.rom;
uint index = info.header_index;
uint8 mapper = rom[index + MAPPER];
uint8 rom_type = rom[index + ROM_TYPE];
uint8 company = rom[index + COMPANY];
uint8 region = rom[index + REGION] & 0x7f;
void Cartridge::read_header(cartinfo_t &info, const uint8_t *data, unsigned size) {
info.reset();
unsigned index = find_header(data, size);
//detect presence of BS-X flash cartridge connector (reads extended header information)
bool has_bsxflash = false;
if(rom[index - 14] == 'Z') {
if(rom[index - 11] == 'J') {
uint8 n13 = rom[index - 13];
if((n13 >= 'A' && n13 <= 'Z') || (n13 >= '0' && n13 <= '9')) {
if(company == 0x33 || (rom[index - 10] == 0x00 && rom[index - 4] == 0x00)) {
has_bsxflash = true;
//=======================
//detect BS-X flash carts
//=======================
if(data[index + 0x13] == 0x00 || data[index + 0x13] == 0xff) {
if(data[index + 0x14] == 0x00) {
const uint8_t n15 = data[index + 0x15];
if(n15 == 0x00 || n15 == 0x80 || n15 == 0x84 || n15 == 0x9c || n15 == 0xbc || n15 == 0xfc) {
if(data[index + 0x1a] == 0x33 || data[index + 0x1a] == 0xff) {
info.type = TypeBSX;
info.mapper = BSXROM;
info.region = NTSC; //BS-X only released in Japan
return;
}
}
}
}
if(has_bsxflash == true) {
info.mapper = index == 0x7fc0 ? BSCLoROM : BSCHiROM;
} else if(index == 0x7fc0 && cart.rom_size >= 0x401000) {
info.mapper = ExLoROM;
} else if(index == 0x7fc0 && mapper == 0x32) {
info.mapper = ExLoROM;
} else if(index == 0x7fc0) {
info.mapper = LoROM;
} else if(index == 0xffc0) {
info.mapper = HiROM;
} else { //index == 0x40ffc0
info.mapper = ExHiROM;
//=========================
//detect Sufami Turbo carts
//=========================
if(!memcmp(data, "BANDAI SFC-ADX", 14)) {
if(!memcmp(data + 16, "SFC-ADX BACKUP", 14)) {
info.type = TypeSufamiTurboBIOS;
} else {
info.type = TypeSufamiTurbo;
}
info.mapper = STROM;
info.region = NTSC; //Sufami Turbo only released in Japan
return; //RAM size handled internally by load_cart_st();
}
//=====================
//detect standard carts
//=====================
const uint8 mapper = data[index + Mapper];
const uint8 rom_type = data[index + RomType];
const uint8 rom_size = data[index + RomSize];
const uint8 company = data[index + Company];
const uint8 region = data[index + CartRegion] & 0x7f;
//detect presence of BS-X flash cartridge connector (reads extended header information)
if(data[index - 14] == 'Z') {
if(data[index - 11] == 'J') {
uint8 n13 = data[index - 13];
if((n13 >= 'A' && n13 <= 'Z') || (n13 >= '0' && n13 <= '9')) {
if(company == 0x33 || (data[index - 10] == 0x00 && data[index - 4] == 0x00)) {
info.bsxslot = true;
}
}
}
}
if(info.bsxslot == true) {
if(!memcmp(data + index, "Satellaview BS-X ", 21)) {
//BS-X base cart
info.type = TypeBSXBIOS;
info.mapper = BSXROM;
info.region = NTSC; //BS-X only released in Japan
return; //RAM size handled internally by load_cart_bsx() -> BSXCart class
} else {
//BS-X slotted cart
info.type = TypeBSC;
info.mapper = (index == 0x7fc0 ? BSCLoROM : BSCHiROM);
}
} else {
//standard cart
info.type = TypeNormal;
if(index == 0x7fc0 && size >= 0x401000) {
info.mapper = ExLoROM;
} else if(index == 0x7fc0 && mapper == 0x32) {
info.mapper = ExLoROM;
} else if(index == 0x7fc0) {
info.mapper = LoROM;
} else if(index == 0xffc0) {
info.mapper = HiROM;
} else { //index == 0x40ffc0
info.mapper = ExHiROM;
}
}
if(mapper == 0x20 && (rom_type == 0x13 || rom_type == 0x14 || rom_type == 0x15 || rom_type == 0x1a)) {
@@ -74,7 +127,7 @@ void Cartridge::read_header() {
}
if(info.dsp1 == true) {
if((mapper & 0x2f) == 0x20 && cart.rom_size <= 0x100000) {
if((mapper & 0x2f) == 0x20 && size <= 0x100000) {
info.dsp1_mapper = DSP1LoROM1MB;
} else if((mapper & 0x2f) == 0x20) {
info.dsp1_mapper = DSP1LoROM2MB;
@@ -99,97 +152,122 @@ void Cartridge::read_header() {
info.obc1 = true;
}
if(mapper == 0x30 && rom_type == 0xf6) {
//TODO: both ST010 and ST011 share the same mapper + rom_type.
//need way to determine which is which.
//for now, default to supported ST010.
if(mapper == 0x30 && rom_type == 0xf6 && rom_size >= 10) {
info.st010 = true;
}
if(mapper == 0x30 && rom_type == 0xf6 && rom_size < 10) {
info.st011 = true;
}
if(mapper == 0x30 && rom_type == 0xf5) {
info.st018 = true;
}
if(rom[info.header_index + RAM_SIZE] & 7) {
info.ram_size = 1024 << (rom[info.header_index + RAM_SIZE] & 7);
if(data[index + RamSize] & 7) {
info.ram_size = 1024 << (data[index + RamSize] & 7);
} else {
info.ram_size = 0;
}
//0, 1, 13 = NTSC; 2 - 12 = PAL
info.region = (region <= 1 || region >= 13) ? NTSC : PAL;
memcpy(&info.name, &rom[info.header_index + CART_NAME], 21);
info.name[21] = 0;
trim(info.name);
//convert undisplayable characters (half-width katakana, etc) to '?' characters
for(int i = 0; i < 21; i++) {
if(info.name[i] & 0x80) info.name[i] = '?';
}
//always display something
if(!info.name[0]) strcpy(info.name, "(untitled)");
}
void Cartridge::find_header() {
int32 score_lo = 0, score_hi = 0, score_ex = 0;
uint8_t *rom = cart.rom;
if(cart.rom_size < 0x010000) {
//cart too small to be anything but lorom
info.header_index = 0x007fc0;
return;
}
if((rom[0x7fc0 + MAPPER] & ~0x10) == 0x20) score_lo++;
if((rom[0xffc0 + MAPPER] & ~0x10) == 0x21) score_hi++;
if(rom[0x7fc0 + ROM_TYPE] < 0x08) score_lo++;
if(rom[0xffc0 + ROM_TYPE] < 0x08) score_hi++;
if(rom[0x7fc0 + ROM_SIZE] < 0x10) score_lo++;
if(rom[0xffc0 + ROM_SIZE] < 0x10) score_hi++;
if(rom[0x7fc0 + RAM_SIZE] < 0x08) score_lo++;
if(rom[0xffc0 + RAM_SIZE] < 0x08) score_hi++;
if(rom[0x7fc0 + REGION] < 14) score_lo++;
if(rom[0xffc0 + REGION] < 14) score_hi++;
if(rom[0x7fc0 + COMPANY] < 3) score_lo++;
if(rom[0xffc0 + COMPANY] < 3) score_hi++;
if(rom[0x7fc0 + RESH] & 0x80) score_lo += 2;
if(rom[0xffc0 + RESH] & 0x80) score_hi += 2;
uint16 cksum, icksum;
cksum = rom[0x7fc0 + CKSUM] | (rom[0x7fc0 + CKSUM + 1] << 8);
icksum = rom[0x7fc0 + ICKSUM] | (rom[0x7fc0 + ICKSUM + 1] << 8);
if((cksum + icksum) == 0xffff && (cksum != 0) && (icksum != 0)) {
score_lo += 8;
}
cksum = rom[0xffc0 + CKSUM] | (rom[0xffc0 + CKSUM + 1] << 8);
icksum = rom[0xffc0 + ICKSUM] | (rom[0xffc0 + ICKSUM + 1] << 8);
if((cksum + icksum) == 0xffff && (cksum != 0) && (icksum != 0)) {
score_hi += 8;
}
if(cart.rom_size < 0x401000) {
score_ex = 0;
} else {
if(rom[0x7fc0 + MAPPER] == 0x32) score_lo++;
else score_ex += 12;
}
unsigned Cartridge::find_header(const uint8_t *data, unsigned size) {
unsigned score_lo = score_header(data, size, 0x007fc0);
unsigned score_hi = score_header(data, size, 0x00ffc0);
unsigned score_ex = score_header(data, size, 0x40ffc0);
if(score_ex) score_ex += 4; //favor ExHiROM on images > 32mbits
if(score_lo >= score_hi && score_lo >= score_ex) {
info.header_index = 0x007fc0;
return 0x007fc0;
} else if(score_hi >= score_ex) {
info.header_index = 0x00ffc0;
return 0x00ffc0;
} else {
info.header_index = 0x40ffc0;
return 0x40ffc0;
}
}
#endif //ifdef CART_CPP
unsigned Cartridge::score_header(const uint8_t *data, unsigned size, unsigned addr) {
if(size < addr + 64) return 0; //image too small to contain header at this location?
int score = 0;
uint16 resetvector = data[addr + ResetVector] | (data[addr + ResetVector + 1] << 8);
uint16 checksum = data[addr + Checksum ] | (data[addr + Checksum + 1] << 8);
uint16 complement = data[addr + Complement ] | (data[addr + Complement + 1] << 8);
uint8 resetop = data[(addr & ~0x7fff) | (resetvector & 0x7fff)]; //first opcode executed upon reset
uint8 mapper = data[addr + Mapper] & ~0x10; //mask off irrelevent FastROM-capable bit
//$00:[000-7fff] contains uninitialized RAM and MMIO.
//reset vector must point to ROM at $00:[8000-ffff] to be considered valid.
if(resetvector < 0x8000) return 0;
//some images duplicate the header in multiple locations, and others have completely
//invalid header information that cannot be relied upon.
//below code will analyze the first opcode executed at the specified reset vector to
//determine the probability that this is the correct header.
//most likely opcodes
if(resetop == 0x78 //sei
|| resetop == 0x18 //clc (clc; xce)
|| resetop == 0x38 //sec (sec; xce)
|| resetop == 0x9c //stz $nnnn (stz $4200)
|| resetop == 0x4c //jmp $nnnn
|| resetop == 0x5c //jml $nnnnnn
) score += 8;
//plausible opcodes
if(resetop == 0xc2 //rep #$nn
|| resetop == 0xe2 //sep #$nn
|| resetop == 0xad //lda $nnnn
|| resetop == 0xae //ldx $nnnn
|| resetop == 0xac //ldy $nnnn
|| resetop == 0xaf //lda $nnnnnn
|| resetop == 0xa9 //lda #$nn
|| resetop == 0xa2 //ldx #$nn
|| resetop == 0xa0 //ldy #$nn
|| resetop == 0x20 //jsr $nnnn
|| resetop == 0x22 //jsl $nnnnnn
) score += 4;
//implausible opcodes
if(resetop == 0x40 //rti
|| resetop == 0x60 //rts
|| resetop == 0x6b //rtl
|| resetop == 0xcd //cmp $nnnn
|| resetop == 0xec //cpx $nnnn
|| resetop == 0xcc //cpy $nnnn
) score -= 4;
//least likely opcodes
if(resetop == 0x00 //brk #$nn
|| resetop == 0x02 //cop #$nn
|| resetop == 0xdb //stp
|| resetop == 0x42 //wdm
|| resetop == 0xff //sbc $nnnnnn,x
) score -= 8;
//at times, both the header and reset vector's first opcode will match ...
//fallback and rely on info validity in these cases to determine more likely header.
//a valid checksum is the biggest indicator of a valid header.
if((checksum + complement) == 0xffff && (checksum != 0) && (complement != 0)) score += 4;
if(addr == 0x007fc0 && mapper == 0x20) score += 2; //0x20 is usually LoROM
if(addr == 0x00ffc0 && mapper == 0x21) score += 2; //0x21 is usually HiROM
if(addr == 0x007fc0 && mapper == 0x22) score += 2; //0x22 is usually ExLoROM
if(addr == 0x40ffc0 && mapper == 0x25) score += 2; //0x25 is usually ExHiROM
if(data[addr + Company] == 0x33) score += 2; //0x33 indicates extended header
if(data[addr + RomType] < 0x08) score++;
if(data[addr + RomSize] < 0x10) score++;
if(data[addr + RamSize] < 0x08) score++;
if(data[addr + CartRegion] < 14) score++;
if(score < 0) score = 0;
return score;
}
#endif

50
src/cart/cart_load.cpp Normal file
View File

@@ -0,0 +1,50 @@
#ifdef CART_CPP
bool Cartridge::load_image(const char *filename) {
if(!filename || !*filename) return false;
uint8_t *data;
unsigned size;
if(!load_file(filename, data, size, CompressionAuto)) return false;
if((size & 0x7fff) != 512) {
image.data = data;
image.size = size;
} else {
//remove 512-byte header
image.data = new uint8_t[image.size = size - 512];
memcpy(image.data, data + 512, image.size);
}
if(load_file(get_patch_filename(filename, "ups"), data, size, CompressionInspect) == true) {
apply_patch(data, size, image.data, image.size);
delete[] data;
info.patched = true;
}
return true;
}
bool Cartridge::inspect_image(cartinfo_t &cartinfo, const char *filename) {
cartinfo.reset();
if(!load_image(filename)) return false;
read_header(cartinfo, image.data, image.size);
delete[] image.data;
return true;
}
bool Cartridge::load_ram(const char *filename, uint8_t *&data, unsigned size, uint8_t init) {
data = new uint8_t[size];
memset(data, init, size);
uint8_t *savedata;
unsigned savesize;
if(load_file(filename, savedata, savesize, CompressionNone) == false) return false;
memcpy(data, savedata, min(size, savesize));
delete[] savedata;
return true;
}
#endif

View File

@@ -1,57 +1,29 @@
#ifdef CART_CPP
void Cartridge::load_cart_normal(const char *filename) {
if(!filename || !*filename) return;
uint8_t *data = 0;
void Cartridge::load_cart_normal(const char *base) {
uint8_t *data;
unsigned size;
if(load_file(filename, data, size, CompressionAuto) == false) return;
strcpy(cart.fn, filename);
strcpy(cart.fn, base);
load_begin(CartridgeNormal);
load_begin(ModeNormal);
if(load_image(base) == false) return;
//load ROM data, ignore 512-byte header if detected
if((size & 0x7fff) != 512) {
cart.rom = new uint8_t[cart.rom_size = size];
memcpy(cart.rom, data, size);
} else {
cart.rom = new uint8_t[cart.rom_size = size - 512];
memcpy(cart.rom, data + 512, size - 512);
}
delete[] data;
cartinfo_t cartinfo;
read_header(cartinfo, cart.rom = image.data, cart.rom_size = image.size);
info = cartinfo;
if(load_file(get_patch_filename(cart.fn, "ups"), data, size, CompressionInspect) == true) {
apply_patch(data, size, cart.rom, cart.rom_size);
delete[] data;
if(cartinfo.ram_size > 0) {
load_ram(get_save_filename(base, "srm"), cart.ram, cart.ram_size = cartinfo.ram_size, 0xff);
}
info.crc32 = crc32_calculate(cart.rom, cart.rom_size);
find_header();
read_header();
if(info.ram_size > 0) {
cart.ram = new uint8_t[cart.ram_size = info.ram_size];
memset(cart.ram, 0xff, cart.ram_size);
if(load_file(get_save_filename(cart.fn, "srm"), data, size, CompressionNone) == true) {
memcpy(cart.ram, data, min(size, cart.ram_size));
delete[] data;
}
}
if(info.srtc || info.spc7110rtc) {
cart.rtc = new(zeromemory) uint8_t[cart.rtc_size = 20];
if(load_file(get_save_filename(cart.fn, "rtc"), data, size, CompressionNone) == true) {
memcpy(cart.rtc, data, min(size, cart.rtc_size));
delete[] data;
}
if(cartinfo.srtc || cartinfo.spc7110rtc) {
load_ram(get_save_filename(base, "rtc"), cart.rtc, cart.rtc_size = 20, 0x00);
}
load_end();
//set base filename
strcpy(info.filename, cart.fn);
strcpy(info.filename, base);
get_base_filename(info.filename);
}
@@ -60,4 +32,4 @@ void Cartridge::unload_cart_normal() {
if(cart.rtc) save_file(get_save_filename(cart.fn, "rtc"), cart.rtc, cart.rtc_size);
}
#endif //ifdef CART_CPP
#endif

View File

@@ -1,86 +1,52 @@
#ifdef CART_CPP
void Cartridge::load_cart_st(const char *base, const char *slotA, const char *slotB) {
if(!base || !*base) return;
strcpy(cart.fn, base);
strcpy(stA.fn, slotA ? slotA : "");
strcpy(stB.fn, slotB ? slotB : "");
load_begin(CartridgeSufamiTurbo);
info.st = true;
info.mapper = STROM;
info.region = NTSC;
uint8_t *data = 0;
uint8_t *data;
unsigned size;
if(load_file(cart.fn, data, size, CompressionAuto) == true) {
cart.rom = new(zeromemory) uint8_t[cart.rom_size = 0x040000];
memcpy(cart.rom, data, min(size, cart.rom_size));
delete[] data;
if(load_file(get_patch_filename(cart.fn, "ups"), data, size, CompressionInspect) == true) {
apply_patch(data, size, cart.rom, cart.rom_size);
delete[] data;
}
strcpy(cart.fn, base);
strcpy(stA.fn, slotA);
strcpy(stB.fn, slotB);
load_begin(ModeSufamiTurbo);
if(load_image(base) == false) return;
cartinfo_t cartinfo;
read_header(cartinfo, cart.rom = image.data, cart.rom_size = image.size);
info = cartinfo;
if(load_image(slotA)) {
stA.rom = new(zeromemory) uint8_t[stA.rom_size = 0x100000];
memcpy(stA.rom, image.data, min(image.size, stA.rom_size));
delete[] image.data;
load_ram(get_save_filename(slotA, "srm"), stA.ram, stA.ram_size = 0x020000, 0xff);
}
if(*stA.fn) {
if(load_file(stA.fn, data, size, CompressionAuto) == true) {
stA.rom = new(zeromemory) uint8_t[stA.rom_size = 0x100000];
memcpy(stA.rom, data, min(size, stA.rom_size));
delete[] data;
if(load_file(get_patch_filename(stA.fn, "ups"), data, size, CompressionInspect) == true) {
apply_patch(data, size, stA.rom, stA.rom_size);
delete[] data;
}
if(load_image(slotB)) {
stB.rom = new(zeromemory) uint8_t[stB.rom_size = 0x100000];
memcpy(stB.rom, image.data, min(image.size, stB.rom_size));
delete[] image.data;
stA.ram = new uint8_t[stA.ram_size = 0x020000];
memset(stA.ram, 0xff, stA.ram_size);
if(load_file(get_save_filename(stA.fn, "srm"), data, size, CompressionNone) == true) {
memcpy(stA.ram, data, min(size, 0x020000U));
delete[] data;
}
}
}
if(*stB.fn) {
if(load_file(stB.fn, data, size, CompressionAuto) == true) {
stB.rom = new(zeromemory) uint8_t[stB.rom_size = 0x100000];
memcpy(stB.rom, data, min(size, stB.rom_size));
delete[] data;
if(load_file(get_patch_filename(stB.fn, "ups"), data, size, CompressionInspect) == true) {
apply_patch(data, size, stB.rom, stB.rom_size);
delete[] data;
}
stB.ram = new uint8_t[stB.ram_size = 0x020000];
memset(stB.ram, 0xff, stB.ram_size);
if(load_file(get_save_filename(stB.fn, "srm"), data, size, CompressionNone) == true) {
memcpy(stB.ram, data, min(size, 0x020000U));
delete[] data;
}
}
load_ram(get_save_filename(slotB, "srm"), stB.ram, stB.ram_size = 0x020000, 0xff);
}
load_end();
//set base filename
if(!*stA.fn && !*stB.fn) {
if(!*slotA && !*slotB) {
strcpy(info.filename, cart.fn);
get_base_filename(info.filename);
} else if(*stA.fn && !*stB.fn) {
strcpy(info.filename, stA.fn);
} else if(*slotA && !*slotB) {
strcpy(info.filename, slotA);
get_base_filename(info.filename);
} else if(!*stA.fn && *stB.fn) {
strcpy(info.filename, stB.fn);
} else if(!*slotA && *slotB) {
strcpy(info.filename, slotB);
get_base_filename(info.filename);
} else {
char filenameA[PATH_MAX], filenameB[PATH_MAX];
strcpy(filenameA, stA.fn);
strcpy(filenameA, slotA);
get_base_filename(filenameA);
strcpy(filenameB, stB.fn);
strcpy(filenameB, slotB);
get_base_filename(filenameB);
strcpy(info.filename, filenameA);
strcat(info.filename, " + ");
@@ -93,4 +59,4 @@ void Cartridge::unload_cart_st() {
if(stB.ram) save_file(get_save_filename(stB.fn, "srm"), stB.ram, stB.ram_size);
}
#endif //ifdef CART_CPP
#endif

View File

@@ -1,3 +1,3 @@
@make platform=win compiler=mingw32-gcc
::@make platform=win compiler=mingw32-gcc enable_gzip=true enable_jma=true
@mingw32-make platform=win compiler=mingw32-gcc
::@mingw32-make platform=win compiler=mingw32-gcc enable_gzip=true enable_jma=true
@pause

View File

@@ -1,98 +1,339 @@
#include "../base.h"
#include "../reader/filereader.h"
#include <../base.hpp>
#include <nall/sort.hpp>
Cheat cheat;
/*****
* string <> binary code translation routines
* decode() "7e1234:56" -> 0x7e123456
* encode() 0x7e123456 -> "7e1234:56"
*****/
Cheat::cheat_t& Cheat::cheat_t::operator=(const Cheat::cheat_t& source) {
enabled = source.enabled;
code = source.code;
desc = source.desc;
count = source.count;
addr.reset();
data.reset();
for(unsigned n = 0; n < count; n++) {
addr[n] = source.addr[n];
data[n] = source.data[n];
}
return *this;
}
//used to sort cheat code list by description
bool Cheat::cheat_t::operator<(const Cheat::cheat_t& source) {
return strcmp(desc, source.desc) < 0;
}
//parse item ("0123-4567+89AB-CDEF"), return cheat_t item
//return true if code is valid, false otherwise
bool Cheat::decode(const char *s, Cheat::cheat_t &item) const {
item.enabled = false;
item.count = 0;
lstring list;
split(list, "+", s);
for(unsigned n = 0; n < list.size(); n++) {
unsigned addr;
uint8_t data;
type_t type;
if(decode(list[n], addr, data, type) == false) return false;
item.addr[item.count] = addr;
item.data[item.count] = data;
item.count++;
}
return true;
}
//read() is used by MemBus::read() if Cheat::enabled(addr) returns true to look up cheat code.
//returns true if cheat code was found, false if it was not.
//when true, cheat code substitution value is stored in data.
bool Cheat::read(unsigned addr, uint8_t &data) const {
addr = mirror_address(addr);
for(unsigned i = 0; i < code.size(); i++) {
if(enabled(i) == false) continue;
for(unsigned n = 0; n < code[i].count; n++) {
if(addr == mirror_address(code[i].addr[n])) {
data = code[i].data[n];
return true;
}
}
}
//code not found, or code is disabled
return false;
}
//================================
//cheat list manipulation routines
//================================
bool Cheat::add(bool enable, const char *code_, const char *desc_) {
cheat_t item;
if(decode(code_, item) == false) return false;
unsigned i = code.size();
code[i] = item;
code[i].enabled = enable;
code[i].desc = desc_;
code[i].code = code_;
encode_description(code[i].desc);
update(code[i]);
update_cheat_status();
return true;
}
bool Cheat::edit(unsigned i, bool enable, const char *code_, const char *desc_) {
cheat_t item;
if(decode(code_, item) == false) return false;
//disable current code and clear from code lookup table
code[i].enabled = false;
update(code[i]);
code[i] = item;
code[i].enabled = enable;
code[i].desc = desc_;
code[i].code = code_;
encode_description(code[i].desc);
update(code[i]);
update_cheat_status();
return true;
}
bool Cheat::remove(unsigned i) {
unsigned size = code.size();
if(i >= size) return false; //also verifies size cannot be < 1
for(unsigned n = i; n < size - 1; n++) code[n] = code[n + 1];
code.resize(size - 1);
update_cheat_status();
return true;
}
bool Cheat::get(unsigned i, cheat_t &item) const {
if(i >= code.size()) return false;
item = code[i];
decode_description(item.desc);
return true;
}
//==============================
//cheat status modifier routines
//==============================
bool Cheat::enabled(unsigned i) const {
return (i < code.size() ? code[i].enabled : false);
}
void Cheat::enable(unsigned i) {
if(i >= code.size()) return;
code[i].enabled = true;
update(code[i]);
update_cheat_status();
}
void Cheat::disable(unsigned i) {
if(i >= code.size()) return;
code[i].enabled = false;
update(code[i]);
update_cheat_status();
}
//===============================
//cheat file load / save routines
//
//file format:
//"description", status, nnnn-nnnn[+nnnn-nnnn...]\r\n
//...
//===============================
bool Cheat::load(const char *fn) {
string data;
if(!fread(data, fn)) return false;
replace(data, "\r\n", "\n");
qreplace(data, " ", "");
lstring line;
split(line, "\n", data);
for(unsigned i = 0; i < line.size(); i++) {
lstring part;
qsplit(part, ",", line[i]);
if(part.size() != 3) continue;
trim(part[0], "\"");
add(part[1] == "enabled", /* code = */ part[2], /* desc = */ part[0]);
}
return true;
}
bool Cheat::save(const char *fn) const {
file fp;
if(!fp.open(fn, file::mode_write)) return false;
for(unsigned i = 0; i < code.size(); i++) {
fp.print(string()
<< "\"" << code[i].desc << "\", "
<< (code[i].enabled ? "enabled, " : "disabled, ")
<< code[i].code << "\r\n");
}
fp.close();
return true;
}
void Cheat::sort() {
if(code.size() <= 1) return; //nothing to sort?
cheat_t *buffer = new cheat_t[code.size()];
for(unsigned i = 0; i < code.size(); i++) buffer[i] = code[i];
nall::sort(buffer, code.size());
for(unsigned i = 0; i < code.size(); i++) code[i] = buffer[i];
delete[] buffer;
}
void Cheat::clear() {
cheat_system_enabled = false;
memset(mask, 0, 0x200000);
code.reset();
}
Cheat::Cheat() {
clear();
}
//==================
//internal functions
//==================
//string <> binary code translation routines
//decode() "7e123456" -> 0x7e123456
//encode() 0x7e123456 -> "7e123456"
bool Cheat::decode(const char *s, unsigned &addr, uint8_t &data, type_t &type) const {
string t = s;
strlower(t);
#define ischr(n) ((n >= '0' && n <= '9') || (n >= 'a' && n <= 'f'))
if(strlen(t) == 8 || (strlen(t) == 9 && t[6] == ':')) {
//strip ':'
if(strlen(t) == 9 && t[6] == ':') t = string() << substr(t, 0, 6) << substr(t, 7);
//validate input
for(unsigned i = 0; i < 8; i++) if(!ischr(t[i])) return false;
bool Cheat::decode(char *str, uint32 &addr, uint8 &data, uint8 &type) {
string t, part;
strcpy(t, str);
strlower(t());
if(strlen(t) == 8 || (strlen(t) == 9 && t()[6] == ':')) {
type = ProActionReplay;
replace(t, ":", "");
uint32 r = strhex((const char*)t);
unsigned r = strhex((const char*)t);
addr = r >> 8;
data = r & 0xff;
return true;
} else if(strlen(t) == 9 && t()[4] == '-') {
} else if(strlen(t) == 9 && t[4] == '-') {
//strip '-'
t = string() << substr(t, 0, 4) << substr(t, 5);
//validate input
for(unsigned i = 0; i < 8; i++) if(!ischr(t[i])) return false;
type = GameGenie;
replace(t, "-", "");
strtr(t, "df4709156bc8a23e", "0123456789abcdef");
uint32 r = strhex((const char*)t);
unsigned r = strhex((const char*)t);
//8421 8421 8421 8421 8421 8421
//abcd efgh ijkl mnop qrst uvwx
//ijkl qrst opab cduv wxef ghmn
addr = (!!(r & 0x002000) << 23) | (!!(r & 0x001000) << 22) |
(!!(r & 0x000800) << 21) | (!!(r & 0x000400) << 20) |
(!!(r & 0x000020) << 19) | (!!(r & 0x000010) << 18) |
(!!(r & 0x000008) << 17) | (!!(r & 0x000004) << 16) |
(!!(r & 0x800000) << 15) | (!!(r & 0x400000) << 14) |
(!!(r & 0x200000) << 13) | (!!(r & 0x100000) << 12) |
(!!(r & 0x000002) << 11) | (!!(r & 0x000001) << 10) |
(!!(r & 0x008000) << 9) | (!!(r & 0x004000) << 8) |
(!!(r & 0x080000) << 7) | (!!(r & 0x040000) << 6) |
(!!(r & 0x020000) << 5) | (!!(r & 0x010000) << 4) |
(!!(r & 0x000200) << 3) | (!!(r & 0x000100) << 2) |
(!!(r & 0x000080) << 1) | (!!(r & 0x000040) << 0);
addr = (!!(r & 0x002000) << 23) | (!!(r & 0x001000) << 22)
| (!!(r & 0x000800) << 21) | (!!(r & 0x000400) << 20)
| (!!(r & 0x000020) << 19) | (!!(r & 0x000010) << 18)
| (!!(r & 0x000008) << 17) | (!!(r & 0x000004) << 16)
| (!!(r & 0x800000) << 15) | (!!(r & 0x400000) << 14)
| (!!(r & 0x200000) << 13) | (!!(r & 0x100000) << 12)
| (!!(r & 0x000002) << 11) | (!!(r & 0x000001) << 10)
| (!!(r & 0x008000) << 9) | (!!(r & 0x004000) << 8)
| (!!(r & 0x080000) << 7) | (!!(r & 0x040000) << 6)
| (!!(r & 0x020000) << 5) | (!!(r & 0x010000) << 4)
| (!!(r & 0x000200) << 3) | (!!(r & 0x000100) << 2)
| (!!(r & 0x000080) << 1) | (!!(r & 0x000040) << 0);
data = r >> 24;
return true;
} else {
return false;
}
return false;
}
bool Cheat::encode(char *str, uint32 addr, uint8 data, uint8 type) {
bool Cheat::encode(string &s, unsigned addr, uint8_t data, type_t type) const {
char t[16];
if(type == ProActionReplay) {
sprintf(str, "%0.6x:%0.2x", addr, data);
sprintf(t, "%.6x%.2x", addr, data);
s = t;
return true;
} else if(type == GameGenie) {
uint32 r = addr;
addr = (!!(r & 0x008000) << 23) | (!!(r & 0x004000) << 22) |
(!!(r & 0x002000) << 21) | (!!(r & 0x001000) << 20) |
(!!(r & 0x000080) << 19) | (!!(r & 0x000040) << 18) |
(!!(r & 0x000020) << 17) | (!!(r & 0x000010) << 16) |
(!!(r & 0x000200) << 15) | (!!(r & 0x000100) << 14) |
(!!(r & 0x800000) << 13) | (!!(r & 0x400000) << 12) |
(!!(r & 0x200000) << 11) | (!!(r & 0x100000) << 10) |
(!!(r & 0x000008) << 9) | (!!(r & 0x000004) << 8) |
(!!(r & 0x000002) << 7) | (!!(r & 0x000001) << 6) |
(!!(r & 0x080000) << 5) | (!!(r & 0x040000) << 4) |
(!!(r & 0x020000) << 3) | (!!(r & 0x010000) << 2) |
(!!(r & 0x000800) << 1) | (!!(r & 0x000400) << 0);
sprintf(str, "%0.2x%0.2x-%0.4x", data, addr >> 16, addr & 0xffff);
strtr(str, "0123456789abcdef", "df4709156bc8a23e");
unsigned r = addr;
addr = (!!(r & 0x008000) << 23) | (!!(r & 0x004000) << 22)
| (!!(r & 0x002000) << 21) | (!!(r & 0x001000) << 20)
| (!!(r & 0x000080) << 19) | (!!(r & 0x000040) << 18)
| (!!(r & 0x000020) << 17) | (!!(r & 0x000010) << 16)
| (!!(r & 0x000200) << 15) | (!!(r & 0x000100) << 14)
| (!!(r & 0x800000) << 13) | (!!(r & 0x400000) << 12)
| (!!(r & 0x200000) << 11) | (!!(r & 0x100000) << 10)
| (!!(r & 0x000008) << 9) | (!!(r & 0x000004) << 8)
| (!!(r & 0x000002) << 7) | (!!(r & 0x000001) << 6)
| (!!(r & 0x080000) << 5) | (!!(r & 0x040000) << 4)
| (!!(r & 0x020000) << 3) | (!!(r & 0x010000) << 2)
| (!!(r & 0x000800) << 1) | (!!(r & 0x000400) << 0);
sprintf(t, "%.2x%.2x-%.4x", data, addr >> 16, addr & 0xffff);
strtr(t, "0123456789abcdef", "df4709156bc8a23e");
s = t;
return true;
} else {
return false;
}
return false;
}
/*****
* address lookup table manipulation and mirroring
* mirror_address() 0x000000 -> 0x7e0000
* set() enable specified address, mirror accordingly
* clear() disable specified address, mirror accordingly
*****/
//update_cheat_status() will scan to see if any codes are
//enabled. if any are, make sure the cheat system is on.
//otherwise, turn cheat system off to speed up emulation.
void Cheat::update_cheat_status() {
for(unsigned i = 0; i < code.size(); i++) {
if(code[i].enabled) {
cheat_system_enabled = true;
return;
}
}
cheat_system_enabled = false;
}
uint Cheat::mirror_address(uint addr) {
//address lookup table manipulation and mirroring
//mirror_address() 0x000000 -> 0x7e0000
//set() enable specified address, mirror accordingly
//clear() disable specified address, mirror accordingly
unsigned Cheat::mirror_address(unsigned addr) const {
if((addr & 0x40e000) != 0x0000) return addr;
//8k WRAM mirror
//$[00-3f|80-bf]:[0000-1fff] -> $7e:[0000-1fff]
return (0x7e0000 + (addr & 0x1fff));
}
void Cheat::set(uint32 addr) {
//updates mask[] table enabled bits;
//must be called after modifying item.enabled state.
void Cheat::update(const cheat_t &item) {
for(unsigned n = 0; n < item.count; n++) {
(item.enabled) ? set(item.addr[n]) : clear(item.addr[n]);
}
}
void Cheat::set(unsigned addr) {
addr = mirror_address(addr);
mask[addr >> 3] |= 1 << (addr & 7);
if((addr & 0xffe000) == 0x7e0000) {
//mirror $7e:[0000-1fff] to $[00-3f|80-bf]:[0000-1fff]
uint mirror;
for(int x = 0; x <= 0x3f; x++) {
unsigned mirror;
for(unsigned x = 0; x <= 0x3f; x++) {
mirror = ((0x00 + x) << 16) + (addr & 0x1fff);
mask[mirror >> 3] |= 1 << (mirror & 7);
mirror = ((0x80 + x) << 16) + (addr & 0x1fff);
@@ -101,20 +342,20 @@ void Cheat::set(uint32 addr) {
}
}
void Cheat::clear(uint32 addr) {
void Cheat::clear(unsigned addr) {
addr = mirror_address(addr);
//is there more than one cheat code using the same address
//(and likely a different override value) that is enabled?
//if so, do not clear code lookup table entry for this address.
uint8 r;
if(read(addr, r) == true)return;
//if there is more than one cheat code using the same address,
//(eg with a different override value) then do not clear code
//lookup table entry.
uint8_t r;
if(read(addr, r) == true) return;
mask[addr >> 3] &= ~(1 << (addr & 7));
if((addr & 0xffe000) == 0x7e0000) {
//mirror $7e:[0000-1fff] to $[00-3f|80-bf]:[0000-1fff]
uint mirror;
for(int x = 0; x <= 0x3f; x++) {
unsigned mirror;
for(unsigned x = 0; x <= 0x3f; x++) {
mirror = ((0x00 + x) << 16) + (addr & 0x1fff);
mask[mirror >> 3] &= ~(1 << (mirror & 7));
mirror = ((0x80 + x) << 16) + (addr & 0x1fff);
@@ -123,207 +364,16 @@ void Cheat::clear(uint32 addr) {
}
}
/*****
* read() is used by MemBus::read() if Cheat::enabled(addr)
* returns true to look up cheat code.
* returns true if cheat code was found, false if it was not.
* when true, cheat code substitution value is stored in data.
*****/
//these two functions are used to safely store description text inside .cfg file format.
bool Cheat::read(uint32 addr, uint8 &data) {
addr = mirror_address(addr);
for(int i = 0; i < cheat_count; i++) {
if(enabled(i) == false) continue;
if(addr == mirror_address(index[i].addr)) {
data = index[i].data;
return true;
}
}
//code not found, or code is disabled
return false;
string& Cheat::encode_description(string &desc) const {
replace(desc, "\"", "\\q");
replace(desc, "\n", "\\n");
return desc;
}
/*****
* update_cheat_status() will scan to see if any codes are
* enabled. if any are, make sure the cheat system is on.
* otherwise, turn cheat system off to speed up emulation.
*****/
void Cheat::update_cheat_status() {
for(unsigned i = 0; i < cheat_count; i++) {
if(index[i].enabled) {
cheat_enabled = true;
return;
}
}
cheat_enabled = false;
}
/*****
* cheat list manipulation routines
*****/
bool Cheat::add(bool enable, char *code, char *desc) {
if(cheat_count >= CheatLimit) return false;
uint32 addr, len;
uint8 data, type;
if(decode(code, addr, data, type) == false) return false;
index[cheat_count].enabled = enable;
index[cheat_count].addr = addr;
index[cheat_count].data = data;
len = strlen(code);
len = len > 16 ? 16 : len;
memcpy(index[cheat_count].code, code, len);
index[cheat_count].code[len] = 0;
len = strlen(desc);
len = len > 128 ? 128 : len;
memcpy(index[cheat_count].desc, desc, len);
index[cheat_count].desc[len] = 0;
cheat_count++;
(enable) ? set(addr) : clear(addr);
update_cheat_status();
return true;
}
bool Cheat::edit(uint32 n, bool enable, char *code, char *desc) {
if(n >= cheat_count) return false;
uint32 addr, len;
uint8 data, type;
if(decode(code, addr, data, type) == false) return false;
//disable current code and clear from code lookup table
index[n].enabled = false;
clear(index[n].addr);
//update code and enable in code lookup table
index[n].enabled = enable;
index[n].addr = addr;
index[n].data = data;
len = strlen(code);
len = len > 16 ? 16 : len;
memcpy(index[n].code, code, len);
index[n].code[len] = 0;
len = strlen(desc);
len = len > 128 ? 128 : len;
memcpy(index[n].desc, desc, len);
index[n].desc[len] = 0;
set(addr);
update_cheat_status();
return true;
}
bool Cheat::remove(uint32 n) {
if(n >= cheat_count) return false;
for(unsigned i = n; i < cheat_count; i++) {
index[i].enabled = index[i + 1].enabled;
index[i].addr = index[i + 1].addr;
index[i].data = index[i + 1].data;
strcpy(index[i].desc, index[i + 1].desc);
}
cheat_count--;
update_cheat_status();
return true;
}
bool Cheat::get(uint32 n, bool &enable, uint32 &addr, uint8 &data, char *code, char *desc) {
if(n >= cheat_count) return false;
enable = index[n].enabled;
addr = index[n].addr;
data = index[n].data;
strcpy(code, index[n].code);
strcpy(desc, index[n].desc);
return true;
}
/*****
* code status modifier routines
*****/
bool Cheat::enabled(uint32 n) {
if(n >= cheat_count) return false;
return index[n].enabled;
}
void Cheat::enable(uint32 n) {
if(n >= cheat_count) return;
index[n].enabled = true;
set(index[n].addr);
update_cheat_status();
}
void Cheat::disable(uint32 n) {
if(n >= cheat_count) return;
index[n].enabled = false;
clear(index[n].addr);
update_cheat_status();
}
/*****
* cheat file manipulation routines
*****/
/* file format: */
/* nnnn-nnnn = status, "description" \r\n */
/* ... */
bool Cheat::load(const char *fn) {
string data;
if(!fread(data, fn)) return false;
replace(data, "\r\n", "\n");
qreplace(data, "=", ",");
qreplace(data, " ", "");
lstring line;
split(line, "\n", data);
for(unsigned i = 0; i < ::count(line); i++) {
lstring part;
split(part, ",", line[i]);
if(::count(part) != 3) continue;
trim(part[2], "\"");
add(part[1] == "enabled", part[0](), part[2]());
}
return true;
}
bool Cheat::save(const char *fn) {
FILE *fp = fopen(fn, "wb");
if(!fp) return false;
for(unsigned i = 0; i < cheat_count; i++) {
fprintf(fp, "%9s = %8s, \"%s\"\r\n",
index[i].code,
index[i].enabled ? "enabled" : "disabled",
index[i].desc);
}
fclose(fp);
return true;
}
/*****
* initialization routines
*****/
void Cheat::clear() {
cheat_enabled = false;
cheat_count = 0;
memset(mask, 0, 0x200000);
for(unsigned i = 0; i <= CheatLimit; i++) {
index[i].enabled = false;
index[i].addr = 0x000000;
index[i].data = 0x00;
strcpy(index[i].code, "");
strcpy(index[i].desc, "");
}
}
Cheat::Cheat() {
clear();
string& Cheat::decode_description(string &desc) const {
replace(desc, "\\q", "\"");
replace(desc, "\\n", "\n");
return desc;
}

View File

@@ -1,51 +0,0 @@
class Cheat {
public:
enum { CheatLimit = 1024 };
enum Type {
ProActionReplay,
GameGenie,
};
struct CheatIndex {
bool enabled;
uint32 addr;
uint8 data;
char code[ 16 + 1];
char desc[128 + 1];
} index[CheatLimit + 1];
bool cheat_enabled;
uint32 cheat_count;
uint8 mask[0x200000];
inline bool enabled() { return cheat_enabled; }
inline uint count() { return cheat_count; }
inline bool exists(uint32 addr) { return bool(mask[addr >> 3] & 1 << (addr & 7)); }
bool decode(char *str, uint32 &addr, uint8 &data, uint8 &type);
bool encode(char *str, uint32 addr, uint8 data, uint8 type);
bool read(uint32 addr, uint8 &data);
void update_cheat_status();
bool add(bool enable, char *code, char *desc);
bool edit(uint32 n, bool enable, char *code, char *desc);
bool get(uint32 n, bool &enable, uint32 &addr, uint8 &data, char *code, char *desc);
bool remove(uint32 n);
bool enabled(uint32 n);
void enable(uint32 n);
void disable(uint32 n);
bool load(const char *fn);
bool save(const char *fn);
void clear();
Cheat();
private:
uint mirror_address(uint addr);
void set(uint32 addr);
void clear(uint32 addr);
};
extern Cheat cheat;

64
src/cheat/cheat.hpp Normal file
View File

@@ -0,0 +1,64 @@
class Cheat {
public:
enum type_t {
ProActionReplay,
GameGenie,
};
struct cheat_t {
bool enabled;
string code;
string desc;
unsigned count;
array<unsigned> addr;
array<uint8_t> data;
cheat_t& operator=(const cheat_t&);
bool operator<(const cheat_t&);
};
bool decode(const char *s, cheat_t &item) const;
bool read(unsigned addr, uint8_t &data) const;
inline bool enabled() const { return cheat_system_enabled; }
inline unsigned count() const { return code.size(); }
inline bool exists(unsigned addr) const { return mask[addr >> 3] & 1 << (addr & 7); }
bool add(bool enable, const char *code, const char *desc);
bool edit(unsigned i, bool enable, const char *code, const char *desc);
bool remove(unsigned i);
bool get(unsigned i, cheat_t &item) const;
bool enabled(unsigned i) const;
void enable(unsigned i);
void disable(unsigned i);
bool load(const char *fn);
bool save(const char *fn) const;
void sort();
void clear();
Cheat();
private:
bool cheat_system_enabled;
uint8_t mask[0x200000];
vector<cheat_t> code;
bool decode(const char *str, unsigned &addr, uint8_t &data, type_t &type) const;
bool encode(string &str, unsigned addr, uint8_t data, type_t type) const;
void update_cheat_status();
unsigned mirror_address(unsigned addr) const;
void update(const cheat_t& item);
void set(unsigned addr);
void clear(unsigned addr);
string& encode_description(string &desc) const;
string& decode_description(string &desc) const;
};
extern Cheat cheat;

View File

@@ -1,6 +1,8 @@
#include "../../base.h"
#include <../base.hpp>
#include <../cart/cart.hpp>
#define BSX_CPP
#include "bsx.hpp"
#include "bsx_base.cpp"
#include "bsx_cart.cpp"
#include "bsx_flash.cpp"

View File

@@ -5,8 +5,8 @@ public:
void power();
void reset();
uint8 mmio_read(uint addr);
void mmio_write(uint addr, uint8 data);
uint8 mmio_read(unsigned addr);
void mmio_write(unsigned addr, uint8 data);
private:
struct {
@@ -29,8 +29,8 @@ public:
void power();
void reset();
uint8 mmio_read(uint addr);
void mmio_write(uint addr, uint8 data);
uint8 mmio_read(unsigned addr);
void mmio_write(unsigned addr, uint8 data);
MappedRAM sram;
MappedRAM psram;
@@ -56,13 +56,13 @@ public:
void power();
void reset();
uint size();
uint8 read(uint addr);
void write(uint addr, uint8 data);
unsigned size();
uint8 read(unsigned addr);
void write(unsigned addr, uint8 data);
private:
struct {
uint command;
unsigned command;
uint8 write_old;
uint8 write_new;

View File

@@ -15,7 +15,7 @@ void BSXBase::reset() {
memset(&regs, 0x00, sizeof regs);
}
uint8 BSXBase::mmio_read(uint addr) {
uint8 BSXBase::mmio_read(unsigned addr) {
addr &= 0xffff;
switch(addr) {
@@ -28,7 +28,7 @@ uint8 BSXBase::mmio_read(uint addr) {
case 0x2190: return regs.r2190;
case 0x2192: {
uint counter = regs.r2192_counter++;
unsigned counter = regs.r2192_counter++;
if(regs.r2192_counter >= 18) regs.r2192_counter = 0;
if(counter == 0) {
@@ -73,7 +73,7 @@ uint8 BSXBase::mmio_read(uint addr) {
return cpu.regs.mdr;
}
void BSXBase::mmio_write(uint addr, uint8 data) {
void BSXBase::mmio_write(unsigned addr, uint8 data) {
addr &= 0xffff;
switch(addr) {
@@ -134,4 +134,4 @@ void BSXBase::mmio_write(uint addr, uint8 data) {
}
}
#endif //ifdef BSX_CPP
#endif

View File

@@ -12,7 +12,7 @@ void BSXCart::power() {
}
void BSXCart::reset() {
for(uint i = 0; i < 16; i++) regs.r[i] = 0x00;
for(unsigned i = 0; i < 16; i++) regs.r[i] = 0x00;
regs.r[0x07] = 0x80;
regs.r[0x08] = 0x80;
@@ -57,7 +57,7 @@ void BSXCart::update_memory_map() {
bus.map(Bus::MapLinear, 0x70, 0x77, 0x0000, 0xffff, psram);
}
uint8 BSXCart::mmio_read(uint addr) {
uint8 BSXCart::mmio_read(unsigned addr) {
if((addr & 0xf0ffff) == 0x005000) { //$[00-0f]:5000 MMIO
uint8 n = (addr >> 16) & 15;
return regs.r[n];
@@ -70,7 +70,7 @@ uint8 BSXCart::mmio_read(uint addr) {
return 0x00;
}
void BSXCart::mmio_write(uint addr, uint8 data) {
void BSXCart::mmio_write(unsigned addr, uint8 data) {
if((addr & 0xf0ffff) == 0x005000) { //$[00-0f]:5000 MMIO
uint8 n = (addr >> 16) & 15;
regs.r[n] = data;
@@ -96,4 +96,4 @@ BSXCart::~BSXCart() {
delete[] psram_data;
}
#endif //ifdef BSX_CPP
#endif

View File

@@ -17,11 +17,11 @@ void BSXFlash::reset() {
regs.write_enable = false;
}
uint BSXFlash::size() {
unsigned BSXFlash::size() {
return memory::bscram.size();
}
uint8 BSXFlash::read(uint addr) {
uint8 BSXFlash::read(unsigned addr) {
if(addr == 0x0002) {
if(regs.flash_enable) return 0x80;
}
@@ -48,7 +48,7 @@ uint8 BSXFlash::read(uint addr) {
return memory::bscram.read(addr);
}
void BSXFlash::write(uint addr, uint8 data) {
void BSXFlash::write(unsigned addr, uint8 data) {
//there exist both read-only and read-write BS-X flash cartridges ...
//unfortunately, the vendor info is not stored inside memory dumps
//of BS-X flashcarts, so it is impossible to determine whether a
@@ -110,4 +110,4 @@ void BSXFlash::write(uint addr, uint8 data) {
}
}
#endif //ifdef BSX_CPP
#endif

View File

@@ -1,11 +0,0 @@
#include "bsx/bsx.h"
#include "srtc/srtc.h"
#include "sdd1/sdd1.h"
#include "spc7110/spc7110.h"
#include "cx4/cx4.h"
#include "dsp1/dsp1.h"
#include "dsp2/dsp2.h"
#include "dsp3/dsp3.h"
#include "dsp4/dsp4.h"
#include "obc1/obc1.h"
#include "st010/st010.h"

11
src/chip/chip.hpp Normal file
View File

@@ -0,0 +1,11 @@
#include "bsx/bsx.hpp"
#include "srtc/srtc.hpp"
#include "sdd1/sdd1.hpp"
#include "spc7110/spc7110.hpp"
#include "cx4/cx4.hpp"
#include "dsp1/dsp1.hpp"
#include "dsp2/dsp2.hpp"
#include "dsp3/dsp3.hpp"
#include "dsp4/dsp4.hpp"
#include "obc1/obc1.hpp"
#include "st010/st010.hpp"

View File

@@ -5,9 +5,10 @@
Portions (c) anomie, Overload, zsKnight, Nach, byuu
*/
#include "../../base.h"
#include <../base.hpp>
#define CX4_CPP
#include "cx4.hpp"
#include "cx4data.cpp"
#include "cx4fn.cpp"
#include "cx4oam.cpp"
@@ -78,7 +79,7 @@ uint16 dest, count;
}
}
void Cx4::write(uint addr, uint8 data) {
void Cx4::write(unsigned addr, uint8 data) {
addr &= 0x1fff;
if(addr < 0x0c00) {
@@ -160,7 +161,7 @@ void Cx4::writel(uint16 addr, uint32 data) {
write(addr + 2, data >> 16);
}
uint8 Cx4::read(uint addr) {
uint8 Cx4::read(unsigned addr) {
addr &= 0x1fff;
if(addr < 0x0c00) {

View File

@@ -90,8 +90,8 @@ public:
void power();
void reset();
uint8 read (uint addr);
void write(uint addr, uint8 data);
uint8 read (unsigned addr);
void write(unsigned addr, uint8 data);
};
extern Cx4 cx4;

View File

@@ -184,4 +184,4 @@ const int16 Cx4::CosTable[512] = {
32610, 32647, 32679, 32706, 32728, 32745, 32758, 32765
};
#endif //ifdef CX4_CPP
#endif

View File

@@ -243,4 +243,4 @@ uint8 bit = 0x80;
}
}
#endif //ifdef CX4_CPP
#endif

View File

@@ -220,4 +220,4 @@ uint16 mask2 = 0x3f3f;
}
}
#endif //ifdef CX4_CPP
#endif

View File

@@ -223,4 +223,4 @@ void Cx4::op89() {
str(1, 0xffffff);
}
#endif //ifdef CX4_CPP
#endif

View File

@@ -1,6 +1,8 @@
#include "../../base.h"
#include <../base.hpp>
#include <../cart/cart.hpp>
#define DSP1_CPP
#include "dsp1.hpp"
#include "dsp1emu.cpp"
void DSP1::init() {}
@@ -46,11 +48,11 @@ bool DSP1::addr_decode(uint16 addr) {
return 0;
}
uint8 DSP1::read(uint addr) {
uint8 DSP1::read(unsigned addr) {
return (addr_decode(addr) == 0) ? dsp1.getDr() : dsp1.getSr();
}
void DSP1::write(uint addr, uint8 data) {
void DSP1::write(unsigned addr, uint8 data) {
if(addr_decode(addr) == 0) {
dsp1.setDr(data);
}

View File

@@ -1,4 +1,4 @@
#include "dsp1emu.h"
#include "dsp1emu.hpp"
class DSP1 : public Memory {
private:
@@ -11,8 +11,8 @@ public:
void power();
void reset();
uint8 read(uint addr);
void write(uint addr, uint8 data);
uint8 read(unsigned addr);
void write(unsigned addr, uint8 data);
};
extern DSP1 dsp1;

View File

@@ -1622,4 +1622,4 @@ const int16 Dsp1::SinTable[256] = {
//////////////////////////////////////////////////////////////////
#endif //ifdef DSP1_CPP
#endif

View File

@@ -1,6 +1,7 @@
#include "../../base.h"
#include <../base.hpp>
#define DSP2_CPP
#include "dsp2.hpp"
#include "dsp2_op.cpp"
void DSP2::init() {}
@@ -29,8 +30,8 @@ void DSP2::reset() {
status.op0dinlen = 0;
}
uint8 DSP2::read(uint addr) {
uint8 r = 0xff;
uint8 DSP2::read(unsigned addr) {
uint8 r = 0xff;
if(status.out_count) {
r = status.output[status.out_index++];
status.out_index &= 511;
@@ -41,7 +42,7 @@ uint8 r = 0xff;
return r;
}
void DSP2::write(uint addr, uint8 data) {
void DSP2::write(unsigned addr, uint8 data) {
if(status.waiting_for_command) {
status.command = data;
status.in_index = 0;

View File

@@ -1,10 +1,10 @@
class DSP2 : public Memory {
public:
struct {
bool waiting_for_command;
uint command;
uint in_count, in_index;
uint out_count, out_index;
bool waiting_for_command;
unsigned command;
unsigned in_count, in_index;
unsigned out_count, out_index;
uint8 parameters[512];
uint8 output[512];
@@ -26,8 +26,8 @@ public:
void power();
void reset();
uint8 read(uint addr);
void write(uint addr, uint8 data);
uint8 read(unsigned addr);
void write(unsigned addr, uint8 data);
DSP2();
~DSP2();

View File

@@ -174,4 +174,4 @@ uint8 pixelarray[512];
}
}
#endif //ifdef DSP2_CPP
#endif

View File

@@ -1,6 +1,7 @@
#include "../../base.h"
#include <../base.hpp>
#define DSP3_CPP
#include "dsp3.hpp"
namespace DSP3i {
#define bool8 uint8
#include "dsp3emu.c"
@@ -21,13 +22,13 @@ void DSP3::reset() {
DSP3i::DSP3_Reset();
}
uint8 DSP3::read(uint addr) {
uint8 DSP3::read(unsigned addr) {
DSP3i::dsp3_address = addr & 0xffff;
DSP3i::DSP3GetByte();
return DSP3i::dsp3_byte;
}
void DSP3::write(uint addr, uint8 data) {
void DSP3::write(unsigned addr, uint8 data) {
DSP3i::dsp3_address = addr & 0xffff;
DSP3i::dsp3_byte = data;
DSP3i::DSP3SetByte();

View File

@@ -5,8 +5,8 @@ public:
void power();
void reset();
uint8 read (uint addr);
void write(uint addr, uint8 data);
uint8 read (unsigned addr);
void write(unsigned addr, uint8 data);
};
extern DSP3 dsp3;

View File

@@ -1143,4 +1143,4 @@ void InitDSP3()
DSP3_Reset();
}
#endif //ifdef DSP3_CPP
#endif

View File

@@ -1,6 +1,7 @@
#include "../../base.h"
#include <../base.hpp>
#define DSP4_CPP
#include "dsp4.hpp"
namespace DSP4i {
inline uint16 READ_WORD(uint8 *addr) {
return (addr[0]) + (addr[1] << 8);
@@ -34,7 +35,7 @@ void DSP4::reset() {
DSP4i::InitDSP4();
}
uint8 DSP4::read(uint addr) {
uint8 DSP4::read(unsigned addr) {
addr &= 0xffff;
if(addr < 0xc000) {
DSP4i::dsp4_address = addr;
@@ -44,7 +45,7 @@ uint8 DSP4::read(uint addr) {
return 0x80;
}
void DSP4::write(uint addr, uint8 data) {
void DSP4::write(unsigned addr, uint8 data) {
addr &= 0xffff;
if(addr < 0xc000) {
DSP4i::dsp4_address = addr;

View File

@@ -5,8 +5,8 @@ public:
void power();
void reset();
uint8 read (uint addr);
void write(uint addr, uint8 data);
uint8 read (unsigned addr);
void write(unsigned addr, uint8 data);
};
extern DSP4 dsp4;

View File

@@ -2147,4 +2147,4 @@ void DSP4GetByte()
}
}
#endif //ifdef DSP4_CPP
#endif

View File

@@ -1,4 +1,6 @@
#include "../../base.h"
#include <../base.hpp>
#include <../cart/cart.hpp>
#include "obc1.hpp"
void OBC1::init() {}
void OBC1::enable() {}
@@ -8,80 +10,61 @@ void OBC1::power() {
}
void OBC1::reset() {
for(uint i = 0x0000; i <= 0x1fff; i++) ram_write(i, 0xff);
for(unsigned i = 0x0000; i <= 0x1fff; i++) ram_write(i, 0xff);
status.baseptr = (ram_read(0x1ff5) & 1) ? 0x1800 : 0x1c00;
status.address = (ram_read(0x1ff6) & 0x7f);
status.shift = (ram_read(0x1ff6) & 3) << 1;
}
uint8 OBC1::read(uint addr) {
uint8 OBC1::read(unsigned addr) {
addr &= 0x1fff;
if((addr & 0x1ff8) != 0x1ff0) return ram_read(addr);
switch(addr) {
case 0x1ff0:
return ram_read(status.baseptr + (status.address << 2) + 0);
case 0x1ff1:
return ram_read(status.baseptr + (status.address << 2) + 1);
case 0x1ff2:
return ram_read(status.baseptr + (status.address << 2) + 2);
case 0x1ff3:
return ram_read(status.baseptr + (status.address << 2) + 3);
case 0x1ff4:
return ram_read(status.baseptr + (status.address >> 2) + 0x200);
case 0x1ff5:
case 0x1ff6:
case 0x1ff7:
return ram_read(addr);
switch(addr) { default: //never used, avoids compiler warning
case 0x1ff0: return ram_read(status.baseptr + (status.address << 2) + 0);
case 0x1ff1: return ram_read(status.baseptr + (status.address << 2) + 1);
case 0x1ff2: return ram_read(status.baseptr + (status.address << 2) + 2);
case 0x1ff3: return ram_read(status.baseptr + (status.address << 2) + 3);
case 0x1ff4: return ram_read(status.baseptr + (status.address >> 2) + 0x200);
case 0x1ff5: case 0x1ff6: case 0x1ff7: return ram_read(addr);
}
return 0x00; //never used, avoids compiler warning
}
void OBC1::write(uint addr, uint8 data) {
void OBC1::write(unsigned addr, uint8 data) {
addr &= 0x1fff;
if((addr & 0x1ff8) != 0x1ff0) return ram_write(addr, data);
switch(addr) {
case 0x1ff0:
ram_write(status.baseptr + (status.address << 2) + 0, data);
break;
case 0x1ff1:
ram_write(status.baseptr + (status.address << 2) + 1, data);
break;
case 0x1ff2:
ram_write(status.baseptr + (status.address << 2) + 2, data);
break;
case 0x1ff3:
ram_write(status.baseptr + (status.address << 2) + 3, data);
break;
case 0x1ff4: {
uint8 temp;
temp = ram_read(status.baseptr + (status.address >> 2) + 0x200);
temp = (temp & ~(3 << status.shift)) | ((data & 3) << status.shift);
ram_write(status.baseptr + (status.address >> 2) + 0x200, temp);
} break;
case 0x1ff5:
status.baseptr = (data & 1) ? 0x1800 : 0x1c00;
ram_write(addr, data);
break;
case 0x1ff6:
status.address = (data & 0x7f);
status.shift = (data & 3) << 1;
ram_write(addr, data);
break;
case 0x1ff7:
ram_write(addr, data);
break;
case 0x1ff0: ram_write(status.baseptr + (status.address << 2) + 0, data); break;
case 0x1ff1: ram_write(status.baseptr + (status.address << 2) + 1, data); break;
case 0x1ff2: ram_write(status.baseptr + (status.address << 2) + 2, data); break;
case 0x1ff3: ram_write(status.baseptr + (status.address << 2) + 3, data); break;
case 0x1ff4: {
uint8 temp = ram_read(status.baseptr + (status.address >> 2) + 0x200);
temp = (temp & ~(3 << status.shift)) | ((data & 3) << status.shift);
ram_write(status.baseptr + (status.address >> 2) + 0x200, temp);
} break;
case 0x1ff5: {
status.baseptr = (data & 1) ? 0x1800 : 0x1c00;
ram_write(addr, data);
} break;
case 0x1ff6: {
status.address = (data & 0x7f);
status.shift = (data & 3) << 1;
ram_write(addr, data);
} break;
case 0x1ff7: {
ram_write(addr, data);
} break;
}
}
uint8 OBC1::ram_read(uint addr) {
uint8 OBC1::ram_read(unsigned addr) {
return memory::cartram.read(addr & 0x1fff);
}
void OBC1::ram_write(uint addr, uint8 data) {
void OBC1::ram_write(unsigned addr, uint8 data) {
memory::cartram.write(addr & 0x1fff, data);
}

View File

@@ -5,15 +5,15 @@ public:
void power();
void reset();
uint8 read(uint addr);
void write(uint addr, uint8 data);
uint8 read(unsigned addr);
void write(unsigned addr, uint8 data);
OBC1();
~OBC1();
private:
uint8 ram_read(uint addr);
void ram_write(uint addr, uint8 data);
uint8 ram_read(unsigned addr);
void ram_write(unsigned addr, uint8 data);
struct {
uint16 address;

View File

@@ -1,12 +1,24 @@
#include "../../base.h"
#include <../base.hpp>
#include <../cart/cart.hpp>
#define SDD1_CPP
#include "sdd1.hpp"
#include "sdd1emu.cpp"
void SDD1::init() {}
void SDD1::enable() {
for(int i = 0x4800; i <= 0x4807; i++) memory::mmio.map(i, *this);
//hook S-CPU DMA MMIO registers to gather information for struct dma[];
//buffer address and transfer size information for use in SDD1::read()
for(unsigned i = 0x4300; i <= 0x437f; i++) {
cpu_mmio[i & 0x7f] = memory::mmio.get(i);
memory::mmio.map(i, *this);
}
//hook S-DD1 MMIO registers
for(unsigned i = 0x4800; i <= 0x4807; i++) {
memory::mmio.map(i, *this);
}
}
void SDD1::power() {
@@ -14,97 +26,133 @@ void SDD1::power() {
}
void SDD1::reset() {
sdd1.dma_active = false;
sdd1_enable = 0x00;
xfer_enable = 0x00;
regs.r4800 = 0x00;
regs.r4801 = 0x00;
mmc[0] = 0 << 20;
mmc[1] = 1 << 20;
mmc[2] = 2 << 20;
mmc[3] = 3 << 20;
regs.r4804 = 0x00;
regs.r4805 = 0x01;
regs.r4806 = 0x02;
regs.r4807 = 0x03;
for(unsigned i = 0; i < 8; i++) {
dma[i].addr = 0;
dma[i].size = 0;
}
bus.map(Bus::MapLinear, 0xc0, 0xcf, 0x0000, 0xffff, memory::cartrom, (regs.r4804 & 7) << 20);
bus.map(Bus::MapLinear, 0xd0, 0xdf, 0x0000, 0xffff, memory::cartrom, (regs.r4805 & 7) << 20);
bus.map(Bus::MapLinear, 0xe0, 0xef, 0x0000, 0xffff, memory::cartrom, (regs.r4806 & 7) << 20);
bus.map(Bus::MapLinear, 0xf0, 0xff, 0x0000, 0xffff, memory::cartrom, (regs.r4807 & 7) << 20);
buffer.ready = false;
bus.map(Bus::MapDirect, 0xc0, 0xff, 0x0000, 0xffff, *this);
}
uint8 SDD1::mmio_read(uint addr) {
switch(addr & 0xffff) {
case 0x4804: return regs.r4804;
case 0x4805: return regs.r4805;
case 0x4806: return regs.r4806;
case 0x4807: return regs.r4807;
uint8 SDD1::mmio_read(unsigned addr) {
addr &= 0xffff;
if((addr & 0x4380) == 0x4300) {
return cpu_mmio[addr & 0x7f]->mmio_read(addr);
}
switch(addr) {
case 0x4804: return (mmc[0] >> 20) & 7;
case 0x4805: return (mmc[1] >> 20) & 7;
case 0x4806: return (mmc[2] >> 20) & 7;
case 0x4807: return (mmc[3] >> 20) & 7;
}
return cpu.regs.mdr;
}
void SDD1::mmio_write(uint addr, uint8 data) {
switch(addr & 0xffff) {
case 0x4800: {
regs.r4800 = data;
} break;
void SDD1::mmio_write(unsigned addr, uint8 data) {
addr &= 0xffff;
case 0x4801: {
regs.r4801 = data;
} break;
if((addr & 0x4380) == 0x4300) {
unsigned channel = (addr >> 4) & 7;
switch(addr & 15) {
case 2: dma[channel].addr = (dma[channel].addr & 0xffff00) + (data << 0); break;
case 3: dma[channel].addr = (dma[channel].addr & 0xff00ff) + (data << 8); break;
case 4: dma[channel].addr = (dma[channel].addr & 0x00ffff) + (data << 16); break;
case 0x4804: {
if(regs.r4804 != data) {
regs.r4804 = data;
bus.map(Bus::MapLinear, 0xc0, 0xcf, 0x0000, 0xffff,
memory::cartrom, (regs.r4804 & 7) << 20);
}
} break;
case 5: dma[channel].size = (dma[channel].size & 0xff00) + (data << 0); break;
case 6: dma[channel].size = (dma[channel].size & 0x00ff) + (data << 8); break;
}
return cpu_mmio[addr & 0x7f]->mmio_write(addr, data);
}
case 0x4805: {
if(regs.r4805 != data) {
regs.r4805 = data;
bus.map(Bus::MapLinear, 0xd0, 0xdf, 0x0000, 0xffff,
memory::cartrom, (regs.r4805 & 7) << 20);
}
} break;
switch(addr) {
case 0x4800: sdd1_enable = data; break;
case 0x4801: xfer_enable = data; break;
case 0x4806: {
if(regs.r4806 != data) {
regs.r4806 = data;
bus.map(Bus::MapLinear, 0xe0, 0xef, 0x0000, 0xffff,
memory::cartrom, (regs.r4806 & 7) << 20);
}
} break;
case 0x4807: {
if(regs.r4807 != data) {
regs.r4807 = data;
bus.map(Bus::MapLinear, 0xf0, 0xff, 0x0000, 0xffff,
memory::cartrom, (regs.r4807 & 7) << 20);
}
} break;
case 0x4804: mmc[0] = (data & 7) << 20; break;
case 0x4805: mmc[1] = (data & 7) << 20; break;
case 0x4806: mmc[2] = (data & 7) << 20; break;
case 0x4807: mmc[3] = (data & 7) << 20; break;
}
}
void SDD1::dma_begin(uint8 channel, uint32 addr, uint16 length) {
if(regs.r4800 & (1 << channel) && regs.r4801 & (1 << channel)) {
regs.r4801 &= ~(1 << channel);
sdd1.dma_active = true;
sdd1.buffer_index = 0;
sdd1.buffer_size = length;
sdd1emu.decompress(addr, (length) ? length : 65536, sdd1.buffer);
}
//SDD1::read() is mapped to $[c0-ff]:[0000-ffff]
//the design is meant to be as close to the hardware design as possible, thus this code
//avoids adding S-DD1 hooks inside S-CPU::DMA emulation.
//
//the real S-DD1 cannot see $420b (DMA enable) writes, as they are not placed on the bus.
//however, $43x0-$43xf writes (DMAx channel settings) most likely do appear on the bus.
//the S-DD1 also requires fixed addresses for transfers, which wouldn't be necessary if
//it could see $420b writes (eg it would know when the transfer should begin.)
//
//the hardware needs a way to distinguish program code after $4801 writes from DMA
//decompression that follows soon after.
//
//the only plausible design for hardware would be for the S-DD1 to spy on DMAx settings,
//and begin spooling decompression on writes to $4801 that activate a channel. after that,
//it feeds decompressed data only when the ROM read address matches the DMA channel address.
//
//the actual S-DD1 transfer can occur on any channel, but it is most likely limited to
//one transfer per $420b write (for spooling purposes). however, this is not known for certain.
uint8 SDD1::read(unsigned addr) {
if(sdd1_enable & xfer_enable) {
//at least one channel has S-DD1 decompression enabled ...
for(unsigned i = 0; i < 8; i++) {
if(sdd1_enable & xfer_enable & (1 << i)) {
//S-DD1 always uses fixed transfer mode, so address will not change during transfer
if(addr == dma[i].addr) {
if(!buffer.ready) {
//first byte read for channel performs full decompression.
//this really should stream byte-by-byte, but it's not necessary since the size is known
buffer.offset = 0;
buffer.size = dma[i].size ? dma[i].size : 65536;
//sdd1emu calls this function; it needs to access uncompressed data;
//so temporarily disable decompression mode for decompress() call.
uint8 temp = sdd1_enable;
sdd1_enable = false;
sdd1emu.decompress(addr, buffer.size, buffer.data);
sdd1_enable = temp;
buffer.ready = true;
}
//fetch a decompressed byte; once buffer is depleted, disable channel and invalidate buffer
uint8 data = buffer.data[(uint16)buffer.offset++];
if(buffer.offset >= buffer.size) {
buffer.ready = false;
xfer_enable &= ~(1 << i);
}
return data;
} //address matched
} //channel enabled
} //channel loop
} //S-DD1 decompressor enabled
//S-DD1 decompression mode inactive; return ROM data
return memory::cartrom.read(mmc[(addr >> 20) & 3] + (addr & 0x0fffff));
}
bool SDD1::dma_active() {
return sdd1.dma_active;
void SDD1::write(unsigned addr, uint8 data) {
}
uint8 SDD1::dma_read() {
if(--sdd1.buffer_size == 0) sdd1.dma_active = false;
//sdd1.buffer[] is 65536 bytes, and sdd1.buffer_index
//is of type uint16, so no buffer overflow is possible
return sdd1.buffer[sdd1.buffer_index++];
SDD1::SDD1() {
buffer.data = new uint8[65536];
}
SDD1::SDD1() {}
SDD1::~SDD1() {
delete[] buffer.data;
}

View File

@@ -1,39 +0,0 @@
#include "sdd1emu.h"
class SDD1 : public MMIO {
public:
void init();
void enable();
void power();
void reset();
uint8 mmio_read (uint addr);
void mmio_write(uint addr, uint8 data);
void dma_begin(uint8 channel, uint32 addr, uint16 length);
bool dma_active();
uint8 dma_read();
SDD1();
private:
SDD1emu sdd1emu;
struct {
uint8 buffer[65536]; //pointer to decompressed S-DD1 data, max DMA length is 65536
uint16 buffer_index; //DMA read index into S-DD1 decompression buffer
uint16 buffer_size;
bool dma_active;
} sdd1;
struct {
uint8 r4800;
uint8 r4801;
uint8 r4804;
uint8 r4805;
uint8 r4806;
uint8 r4807;
} regs;
};
extern SDD1 sdd1;

40
src/chip/sdd1/sdd1.hpp Normal file
View File

@@ -0,0 +1,40 @@
#include "sdd1emu.hpp"
class SDD1 : public MMIO, public Memory {
public:
void init();
void enable();
void power();
void reset();
uint8 mmio_read(unsigned addr);
void mmio_write(unsigned addr, uint8 data);
uint8 read(unsigned addr);
void write(unsigned addr, uint8 data);
SDD1();
~SDD1();
private:
MMIO *cpu_mmio[0x80]; //bus spying hooks to glean information for struct dma[]
uint8 sdd1_enable; //channel bit-mask
uint8 xfer_enable; //channel bit-mask
unsigned mmc[4]; //memory map controller ROM indices
struct {
unsigned addr; //$43x2-$43x4 -- DMA transfer address
uint16 size; //$43x5-$43x6 -- DMA transfer size
} dma[8];
SDD1emu sdd1emu;
struct {
uint8 *data; //pointer to decompressed S-DD1 data (65536 bytes)
uint16 offset; //read index into S-DD1 decompression buffer
unsigned size; //length of data buffer; reads decrement counter, set ready to false at 0
bool ready; //true when data[] is valid; false to invoke sdd1emu.decompress()
} buffer;
};
extern SDD1 sdd1;

View File

@@ -30,7 +30,7 @@ understood.
************************************************************************/
#define SDD1_read(__addr) (bus.read(__addr))
#define SDD1_read(__addr) (sdd1.read(__addr))
////////////////////////////////////////////////////
@@ -448,4 +448,4 @@ SDD1emu::SDD1emu() :
///////////////////////////////////////////////////////////
#endif //ifdef SDD1_CPP
#endif

View File

@@ -1,697 +0,0 @@
const uint8_t SPC7110Codec::EvolutionTable[53][4] = {
//prob, nextlps, nextmps, toggle invert
{0x5a, 1, 1,1}, //0 l,m
{0x25, 6, 2,0}, //1 l,m
{0x11, 8, 3,0}, //2 l,m
{0x08, 10, 4,0}, //3 ,m
{0x03, 12, 5,0}, //4 ,m
{0x01, 15, 5,0}, //5 ,m
{0x5a, 7, 7,1}, //6 l,
{0x3f, 19, 8,0}, //7 l,m
{0x2c, 21, 9,0}, //8 l,m
{0x20, 22, 10,0}, //9 ,m
{0x17, 23, 11,0}, //10 ,m
{0x11, 25, 12,0}, //11 ,m
{0x0c, 26, 13,0}, //12 ,m
{0x09, 28, 14,0}, //13 ,m
{0x07, 29, 15,0}, //14 ,m
{0x05, 31, 16,0}, //15 ,m
{0x04, 32, 17,0}, //16 ,m
{0x03, 34, 18,0}, //17 ,m
{0x02, 35, 5,0}, //18 ,m
{0x5a, 20, 20,1}, //19 l,m
{0x48, 39, 21,0}, //20 l,m
{0x3a, 40, 22,0}, //21 l,m
{0x2e, 42, 23,0}, //22 l,m
{0x26, 44, 24,0}, //23 l,m
{0x1f, 45, 25,0}, //24 l,m
{0x19, 46, 26,0}, //25 l,m
{0x15, 25, 27,0}, //26 l,m
{0x11, 26, 28,0}, //27 l,m
{0x0e, 26, 29,0}, //28 l,m
{0x0b, 27, 30,0}, //29 ,m
{0x09, 28, 31,0}, //30 ,m
{0x08, 29, 32,0}, //31 l,m
{0x07, 30, 33,0}, //32 l,m
{0x05, 31, 34,0}, //33 l,m <--- changed lps
{0x04, 33, 35,0}, //34 ,m ... this is NOT skipped
{0x04, 33, 36,0}, //35 ,m
{0x03, 34, 37,0}, //36 ,m
{0x02, 35, 38,0}, //37 ,m ... this is NOT skipped
{0x02, 36, 5,0}, //38 ,m
{0x58, 39, 40,1}, //39 l,m
{0x4d, 47, 41,0}, //40 l,m
{0x43, 48, 42,0}, //41 ,m
{0x3b, 49, 43,0}, //42 ,m
{0x34, 50, 44,0}, //43 l,m
{0x2e, 51, 45,0}, //44 l,m
{0x29, 44, 46,0}, //45 l,m
{0x25, 45, 24,0}, //46 ,m
{0x56, 47, 48,1}, //47 l,m
{0x4f, 47, 49,0}, //48 l,m
{0x47, 48, 50,0}, //49 l,m
{0x41, 49, 51,0}, //50 l,m
{0x3c, 50, 52,0}, //51 l,m
{0x37, 51, 43,0} //52 ,m
};
const uint8_t SPC7110Codec::Mode2ContextTable[32][4] = {
// "bit" = (lps^invert)
//next_0, use ref pixel, next_1, use ref pixel
// if use ref pixel, then add on the 0-4 bell number grouping
{1, 0, 2, 0}, //0
{3, 1, 8, 1}, //1 prev bit 0
{13,0, 14,0}, //2 prev bit 1
{15,0, 16,0}, //3 prev bit 00
{17,0, 18,0}, //4
{19,0, 20,0}, //5
{21,0, 22,0}, //6
{23,0, 24,0}, //7
{25,0, 26,0}, //8 prev bit 01
{25,0, 26,0}, //9
{25,0, 26,0}, //10
{25,0, 26,0}, //11
{25,0, 26,0}, //12
{27,0, 28,0}, //13 prev bit 10
{29,0, 30,0}, //14 prev bit 11
{31,0, 31,0}, //15 000 ref group 0
{31,0, 31,0}, //16 001 ref group 0
{31,0, 31,0}, //17 000 ref group 1
{31,0, 31,0}, //18 001 ref group 1
{31,0, 31,0}, //19 000 ref group 2
{31,0, 31,0}, //20 001 ref group 2
{31,0, 31,0}, //21 000 ref group 3
{31,0, 31,0}, //22 001 ref group 3
{31,0, 31,0}, //23 000 ref group 4
{31,0, 31,0}, //24 001 ref group 4
{31,0, 31,0}, //25 010
{31,0, 31,0}, //26 011
{31,0, 31,0}, //27 100
{31,0, 31,0}, //28 101
{31,0, 31,0}, //29 110
{31,0, 31,0}, //30 111
{31,0, 31,0} //31 -- used as a trap for testing purposes --
};
#define PROB(x) EvolutionTable[Contexts[x].index][0]
#define NEXT_LPS(x) EvolutionTable[Contexts[x].index][1]
#define NEXT_MPS(x) EvolutionTable[Contexts[x].index][2]
#define TOGGLE_INVERT(x) EvolutionTable[Contexts[x].index][3]
#define BIT(x,y) ((x>>y)&1)
void SPC7110Codec::decomp_mode0(int len) {
uint8_t *datain = buffer;
uint8_t *dataout = output;
static const unsigned NUM_CONTEXTS = 30;
uint8 top,val;
uint8 con,mps,prob;
uint8 flag_lps,shift,mask;
int out=0;
int inverts=0;
int lps=0;
unsigned char in;
int in_count;
int i,bit;
//setup
top=0xFF;
val=*datain;
datain++;
in=*datain;
datain++;
in_count=8;
//reset context states
for(i=0;i<NUM_CONTEXTS;i++)
{
Contexts[i].index=0;
Contexts[i].invert=0;
}
for(i=0;i<len;i++)
{
if(i==-1800)
{
int k;
printf("\nEvolution table:\n");
//for(k=0;k<53;k++)
//printf(" %d,%d //%d\n",SeenEvolution[k][0],SeenEvolution[k][1],k);
}
for(bit=0;bit<8;bit++)
{
//get context
mask = (1<<(bit&3)) - 1;
con = mask + ((inverts&mask)^(lps&mask));
if(bit>3)
con+=15;
//get PROB and MPS
prob = PROB(con);
mps = (BIT(out,15) ^ Contexts[con].invert);
if(i>=15 && i<=18 && 0)
printf("byte %d bit %d: val=%.2X top=%.2X prob=%.2X mps=%d con=%d state=%d\n",
i,bit,val,top,prob,mps,con,Contexts[con].index);
//get bit
if (val <= top-prob)
{
//mps
top = top - prob;
out = (out << 1) + mps;
flag_lps=0;
}
else
{
//lps
val = val - (top - (prob - 1));
top = prob - 1;
out = (out << 1) + 1-mps;
flag_lps=1;
}
// renormalize
shift=0;
while(top<0x7F) // NOTE: not 0x80, it's a strange border case
{
shift++;
top = (top<<1)+1;
val = (val<<1)+(in>>7);
in = (in<<1);
if(--in_count==0)
{
in=*datain;
datain++;
in_count=8;
}
}
//update processing info
lps = (lps<<1) + flag_lps;
inverts = (inverts<<1) + Contexts[con].invert;
//update context state
if(flag_lps & TOGGLE_INVERT(con))
Contexts[con].invert ^= 1;
if(flag_lps)
{
//SeenEvolution[Contexts[con].index][0]=1;
Contexts[con].index = NEXT_LPS(con);
}
else if(shift)
{
//SeenEvolution[Contexts[con].index][1]=1;
Contexts[con].index = NEXT_MPS(con);
}
}
//save byte
*dataout = (out & 0xFF);
dataout++;
}
}
void SPC7110Codec::decomp_mode1(int len) {
uint8_t *datain = buffer;
uint8_t *dataout = output;
static const unsigned NUM_CONTEXTS = 15;
int pixelorder[4]={0,1,2,3};
int realorder[4];
int a,b,c;
int m,n;
uint8 top,val;
uint8 con,prob;
uint8 flag_lps,shift;
int out=0;
int inverts=0;
int lps=0;
unsigned char in;
int in_count;
int in_len=0;
int i,j,pixel;
//setup
top=0xFF;
val=datain[in_len++];
in=datain[in_len++];
in_count=8;
//reset context states
for(i=0;i<NUM_CONTEXTS;i++)
{
Contexts[i].index=0;
Contexts[i].invert=0;
}
for(i=0;i<len;i+=2)
{
if(i!=0)
{
//turn pixel data into bitplanes
//and save as output
*dataout = (BIT(out,15)<<7) + (BIT(out,13)<<6) + (BIT(out,11)<<5) + (BIT(out,9)<<4)
+ (BIT(out,7)<<3) + (BIT(out,5)<<2) + (BIT(out,3)<<1) + BIT(out,1);
dataout++;
*dataout = (BIT(out,14)<<7) + (BIT(out,12)<<6) + (BIT(out,10)<<5) + (BIT(out,8)<<4)
+ (BIT(out,6)<<3) + (BIT(out,4)<<2) + (BIT(out,2)<<1) + BIT(out,0);
dataout++;
}
for(pixel=0;pixel<8;pixel++)
{
//get first symbol context
a = ((out >> (1*2)) & 0x3);
b = ((out >> (7*2)) & 0x3);
c = ((out >> (8*2)) & 0x3);
if(a==b && b==c)
con=0;
else if (a==b && b!=c)
con=1;
else if (a!=b && b==c)
con=2;
else if (a==c && b!=c)
con=3;
else
con=4;
//update pixel order
for(m=0;m<4;m++)
if(pixelorder[m]==a)
break;
for(n=m;n>0;n--)
{
j=pixelorder[n-1];
pixelorder[n-1]=pixelorder[n];
pixelorder[n]=j;
}
//get PROB
prob = PROB(con);
//get symbol
if (val <= top-prob)
{
//mps
top = top - prob;
flag_lps=0;
}
else
{
//lps
val = val - (top - (prob - 1));
top = prob - 1;
flag_lps=1;
}
// renormalize
shift=0;
while(top<0x7F)
{
shift++;
top = (top<<1)+1;
val = (val<<1)+(in>>7);
in = (in<<1);
if(--in_count==0)
{
in=datain[in_len++];
in_count=8;
}
}
//update processing info
lps = (lps<<1) + flag_lps;
inverts = (inverts<<1) + Contexts[con].invert;
//update context state
if(flag_lps & TOGGLE_INVERT(con))
Contexts[con].invert ^= 1;
if(flag_lps)
Contexts[con].index = NEXT_LPS(con);
else if(shift)
Contexts[con].index = NEXT_MPS(con);
//get context of second symbol
con = 5 + con*2 + ((lps^inverts)&1);
//get PROB
prob = PROB(con);
//get symbol
if (val <= top-prob)
{
//mps
top = top - prob;
flag_lps=0;
}
else
{
//lps
val = val - (top - (prob - 1));
top = prob - 1;
flag_lps=1;
}
// renormalize
shift=0;
while(top<0x7F)
{
shift++;
top = (top<<1)+1;
val = (val<<1)+(in>>7);
in = (in<<1);
if(--in_count==0)
{
in=datain[in_len++];
in_count=8;
}
}
//calculate the real pixel order
for(m=0;m<4;m++)
realorder[m]=pixelorder[m];
//shift refence pixel c value to top
for(m=0;m<4;m++)
if(realorder[m]==c)
break;
for(n=m;n>0;n--)
{
j=realorder[n-1];
realorder[n-1]=realorder[n];
realorder[n]=j;
}
//shift refence pixel b value to top
for(m=0;m<4;m++)
if(realorder[m]==b)
break;
for(n=m;n>0;n--)
{
j=realorder[n-1];
realorder[n-1]=realorder[n];
realorder[n]=j;
}
//shift refence pixel a value to top
for(m=0;m<4;m++)
if(realorder[m]==a)
break;
for(n=m;n>0;n--)
{
j=realorder[n-1];
realorder[n-1]=realorder[n];
realorder[n]=j;
}
//update processing info
lps = (lps<<1) + flag_lps;
inverts = (inverts<<1) + Contexts[con].invert;
//update context state
if(flag_lps & TOGGLE_INVERT(con))
Contexts[con].invert ^= 1;
if(flag_lps)
Contexts[con].index = NEXT_LPS(con);
else if(shift)
Contexts[con].index = NEXT_MPS(con);
//get pixel
b=realorder[(lps^inverts)&3];
out = (out<<2) + b;
}
}
//turn pixel data into bitplanes
//and save as output.. BUT don't save second byte unless asked to
*dataout = (BIT(out,15)<<7) + (BIT(out,13)<<6) + (BIT(out,11)<<5) + (BIT(out,9)<<4)
+ (BIT(out,7)<<3) + (BIT(out,5)<<2) + (BIT(out,3)<<1) + BIT(out,1);
dataout++;
if((len&1)==0)
{
*dataout = (BIT(out,14)<<7) + (BIT(out,12)<<6) + (BIT(out,10)<<5) + (BIT(out,8)<<4)
+ (BIT(out,6)<<3) + (BIT(out,4)<<2) + (BIT(out,2)<<1) + BIT(out,0);
dataout++;
}
if(in_count==8)
in_len--;
//printf("Used %d bytes of input.\n",in_len);
//return in_len;
}
void SPC7110Codec::decomp_mode2(int len) {
uint8_t *datain = buffer;
uint8_t *dataout = output;
static const unsigned NUM_CONTEXTS = 32;
int pixelorder[16]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int realorder[16];
int a,b,c;
int m,n;
uint8 bitplanebuffer[16];
uint8 buf_idx=0;
uint8 top,val,prob;
uint8 con,refcon;
uint8 flag_lps,invertbit,shift;
int out=0;
int out2=0;
int inverts=0;
int lps=0;
unsigned char in;
int in_count;
int in_len=0;
int i,j,pixel,bit;
//setup
top=0xFF;
val=datain[in_len++];
in=datain[in_len++];
in_count=8;
//reset context states
for(i=0;i<NUM_CONTEXTS;i++)
{
Contexts[i].index=0;
Contexts[i].invert=0;
}
for(i=0;i<len;i+=2)
{
for(pixel=0;pixel<8;pixel++)
{
//get first symbol context
a = ((out >> (0*4)) & 0x0F);
b = ((out >> (7*4)) & 0x0F);
c = ((out2>> (0*4)) & 0x0F);
if(a==b && b==c)
refcon=0;
else if (a==b && b!=c)
refcon=1;
else if (a!=b && b==c)
refcon=2;
else if (a==c && b!=c)
refcon=3;
else
refcon=4;
con=0;
//update pixel order
for(m=0;m<16;m++)
if(pixelorder[m]==a)
break;
for(n=m;n>0;n--)
{
j=pixelorder[n-1];
pixelorder[n-1]=pixelorder[n];
pixelorder[n]=j;
}
//calculate the real pixel order
for(m=0;m<16;m++)
realorder[m]=pixelorder[m];
//shift refence pixel c value to top
for(m=0;m<16;m++)
if(realorder[m]==c)
break;
for(n=m;n>0;n--)
{
j=realorder[n-1];
realorder[n-1]=realorder[n];
realorder[n]=j;
}
//shift refence pixel b value to top
for(m=0;m<16;m++)
if(realorder[m]==b)
break;
for(n=m;n>0;n--)
{
j=realorder[n-1];
realorder[n-1]=realorder[n];
realorder[n]=j;
}
//shift refence pixel a value to top
for(m=0;m<16;m++)
if(realorder[m]==a)
break;
for(n=m;n>0;n--)
{
j=realorder[n-1];
realorder[n-1]=realorder[n];
realorder[n]=j;
}
//get 4 symbols
for(bit=0;bit<4;bit++)
{
//get PROB
prob = PROB(con);
//get symbol
if (val <= top-prob)
{
//mps
top = top - prob;
flag_lps=0;
}
else
{
//lps
val = val - (top - (prob - 1));
top = prob - 1;
flag_lps=1;
}
// renormalize
shift=0;
while(top<0x7F)
{
shift++;
top = (top<<1)+1;
val = (val<<1)+(in>>7);
in = (in<<1);
if(--in_count==0)
{
in=datain[in_len++];
in_count=8;
}
}
//update processing info
lps = (lps<<1) + flag_lps;
invertbit = Contexts[con].invert;
inverts = (inverts<<1) + Contexts[con].invert;
//update context state
if(flag_lps & TOGGLE_INVERT(con))
Contexts[con].invert ^= 1;
if(flag_lps)
Contexts[con].index = NEXT_LPS(con);
else if(shift)
Contexts[con].index = NEXT_MPS(con);
//get next context
if(Mode2ContextTable[con][2*(flag_lps^invertbit)+1])
con=Mode2ContextTable[con][2*(flag_lps^invertbit)]+refcon;
else
con=Mode2ContextTable[con][2*(flag_lps^invertbit)];
}
//get pixel
b=realorder[(lps^inverts)&0x0F];
out2 = (out2<<4) + ((out>>28)&0x0F);
out = (out<<4) + b;
}
//cludge to convert pixel data into bitplanes and respect len parameter for output buf
*dataout = (BIT(out,31)<<7) + (BIT(out,27)<<6) + (BIT(out,23)<<5) + (BIT(out,19)<<4)
+ (BIT(out,15)<<3) + (BIT(out,11)<<2) + (BIT(out,7)<<1) + BIT(out,3);
dataout++;
if((i+1)<len)
{
*dataout = (BIT(out,30)<<7) + (BIT(out,26)<<6) + (BIT(out,22)<<5) + (BIT(out,18)<<4)
+ (BIT(out,14)<<3) + (BIT(out,10)<<2) + (BIT(out,6)<<1) + BIT(out,2);
dataout++;
}
bitplanebuffer[buf_idx++] =
(BIT(out,29)<<7) + (BIT(out,25)<<6) + (BIT(out,21)<<5) + (BIT(out,17)<<4)
+ (BIT(out,13)<<3) + (BIT(out,9)<<2) + (BIT(out,5)<<1) + BIT(out,1);
bitplanebuffer[buf_idx++] =
(BIT(out,28)<<7) + (BIT(out,24)<<6) + (BIT(out,20)<<5) + (BIT(out,16)<<4)
+ (BIT(out,12)<<3) + (BIT(out,8)<<2) + (BIT(out,4)<<1) + BIT(out,0);
if(buf_idx==16)
{
for(m=0;m<16 && i+2<len;m++,i++)
{
*dataout = bitplanebuffer[m];
dataout++;
}
buf_idx=0;
}
}
if(in_count==8)
in_len--;
//printf("Used %d bytes of input.\n",in_len);
//return in_len;
}
#undef PROB
#undef NEXT_LPS
#undef NEXT_MPS
#undef TOGGLE_INVERT
#undef BIT
SPC7110Codec::SPC7110Codec() {
buffer = new(zeromemory) uint8_t[65536];
output = new(zeromemory) uint8_t[65536];
}
SPC7110Codec::~SPC7110Codec() {
delete[] buffer;
delete[] output;
}

View File

@@ -1,20 +0,0 @@
class SPC7110Codec {
public:
uint8_t *buffer;
uint8_t *output;
void decomp_mode0(int len);
void decomp_mode1(int len);
void decomp_mode2(int len);
SPC7110Codec();
~SPC7110Codec();
private:
static const uint8_t EvolutionTable[53][4];
static const uint8_t Mode2ContextTable[32][4];
struct ContextState {
uint8_t index;
uint8_t invert;
} Contexts[32];
};

511
src/chip/spc7110/decomp.cpp Normal file
View File

@@ -0,0 +1,511 @@
#ifdef SPC7110_CPP
uint8 SPC7110Decomp::read() {
if(decomp_buffer_length == 0) {
//decompress at least (decomp_buffer_size / 2) bytes to the buffer
switch(decomp_mode) {
case 0: mode0(false); break;
case 1: mode1(false); break;
case 2: mode2(false); break;
default: return 0x00;
}
}
uint8 data = decomp_buffer[decomp_buffer_rdoffset++];
decomp_buffer_rdoffset &= decomp_buffer_size - 1;
decomp_buffer_length--;
return data;
}
void SPC7110Decomp::write(uint8 data) {
decomp_buffer[decomp_buffer_wroffset++] = data;
decomp_buffer_wroffset &= decomp_buffer_size - 1;
decomp_buffer_length++;
}
uint8 SPC7110Decomp::dataread() {
unsigned size = memory::cartrom.size() - 0x100000;
while(decomp_offset >= size) decomp_offset -= size;
return memory::cartrom.read(0x100000 + decomp_offset++);
}
void SPC7110Decomp::init(unsigned mode, unsigned offset, unsigned index) {
decomp_mode = mode;
decomp_offset = offset;
decomp_buffer_rdoffset = 0;
decomp_buffer_wroffset = 0;
decomp_buffer_length = 0;
//reset context states
for(unsigned i = 0; i < 32; i++) {
context[i].index = 0;
context[i].invert = 0;
}
switch(decomp_mode) {
case 0: mode0(true); break;
case 1: mode1(true); break;
case 2: mode2(true); break;
}
//decompress up to requested output data index
while(index--) read();
}
//
void SPC7110Decomp::mode0(bool init) {
static uint8 val, in, span;
static int out, inverts, lps, in_count;
if(init == true) {
out = inverts = lps = 0;
span = 0xff;
val = dataread();
in = dataread();
in_count = 8;
return;
}
while(decomp_buffer_length < (decomp_buffer_size >> 1)) {
for(unsigned bit = 0; bit < 8; bit++) {
//get context
uint8 mask = (1 << (bit & 3)) - 1;
uint8 con = mask + ((inverts & mask) ^ (lps & mask));
if(bit > 3) con += 15;
//get prob and mps
unsigned prob = probability(con);
unsigned mps = (((out >> 15) & 1) ^ context[con].invert);
//get bit
unsigned flag_lps;
if(val <= span - prob) { //mps
span = span - prob;
out = (out << 1) + mps;
flag_lps = 0;
} else { //lps
val = val - (span - (prob - 1));
span = prob - 1;
out = (out << 1) + 1 - mps;
flag_lps = 1;
}
//renormalize
unsigned shift = 0;
while(span < 0x7f) {
shift++;
span = (span << 1) + 1;
val = (val << 1) + (in >> 7);
in <<= 1;
if(--in_count == 0) {
in = dataread();
in_count = 8;
}
}
//update processing info
lps = (lps << 1) + flag_lps;
inverts = (inverts << 1) + context[con].invert;
//update context state
if(flag_lps & toggle_invert(con)) context[con].invert ^= 1;
if(flag_lps) context[con].index = next_lps(con);
else if(shift) context[con].index = next_mps(con);
}
//save byte
write(out);
}
}
void SPC7110Decomp::mode1(bool init) {
static int pixelorder[4], realorder[4];
static uint8 in, val, span;
static int out, inverts, lps, in_count;
if(init == true) {
for(unsigned i = 0; i < 4; i++) pixelorder[i] = i;
out = inverts = lps = 0;
span = 0xff;
val = dataread();
in = dataread();
in_count = 8;
return;
}
while(decomp_buffer_length < (decomp_buffer_size >> 1)) {
for(unsigned pixel = 0; pixel < 8; pixel++) {
//get first symbol context
unsigned a = ((out >> (1 * 2)) & 3);
unsigned b = ((out >> (7 * 2)) & 3);
unsigned c = ((out >> (8 * 2)) & 3);
unsigned con = (a == b) ? (b != c) : (b == c) ? 2 : 4 - (a == c);
//update pixel order
unsigned m, n;
for(m = 0; m < 4; m++) if(pixelorder[m] == a) break;
for(n = m; n > 0; n--) pixelorder[n] = pixelorder[n - 1];
pixelorder[0] = a;
//calculate the real pixel order
for(m = 0; m < 4; m++) realorder[m] = pixelorder[m];
//rotate reference pixel c value to top
for(m = 0; m < 4; m++) if(realorder[m] == c) break;
for(n = m; n > 0; n--) realorder[n] = realorder[n - 1];
realorder[0] = c;
//rotate reference pixel b value to top
for(m = 0; m < 4; m++) if(realorder[m] == b) break;
for(n = m; n > 0; n--) realorder[n] = realorder[n - 1];
realorder[0] = b;
//rotate reference pixel a value to top
for(m = 0; m < 4; m++) if(realorder[m] == a) break;
for(n = m; n > 0; n--) realorder[n] = realorder[n - 1];
realorder[0] = a;
//get 2 symbols
for(unsigned bit = 0; bit < 2; bit++) {
//get prob
unsigned prob = probability(con);
//get symbol
unsigned flag_lps;
if(val <= span - prob) { //mps
span = span - prob;
flag_lps = 0;
} else { //lps
val = val - (span - (prob - 1));
span = prob - 1;
flag_lps = 1;
}
//renormalize
unsigned shift = 0;
while(span < 0x7f) {
shift++;
span = (span << 1) + 1;
val = (val << 1) + (in >> 7);
in <<= 1;
if(--in_count == 0) {
in = dataread();
in_count = 8;
}
}
//update processing info
lps = (lps << 1) + flag_lps;
inverts = (inverts << 1) + context[con].invert;
//update context state
if(flag_lps & toggle_invert(con)) context[con].invert ^= 1;
if(flag_lps) context[con].index = next_lps(con);
else if(shift) context[con].index = next_mps(con);
//get next context
con = 5 + (con << 1) + ((lps ^ inverts) & 1);
}
//get pixel
b = realorder[(lps ^ inverts) & 3];
out = (out << 2) + b;
}
//turn pixel data into bitplanes
unsigned data = morton_2x8(out);
write(data >> 8);
write(data >> 0);
}
}
void SPC7110Decomp::mode2(bool init) {
static int pixelorder[16], realorder[16];
static uint8 bitplanebuffer[16], buffer_index;
static uint8 in, val, span;
static int out0, out1, inverts, lps, in_count;
if(init == true) {
for(unsigned i = 0; i < 16; i++) pixelorder[i] = i;
buffer_index = 0;
out0 = out1 = inverts = lps = 0;
span = 0xff;
val = dataread();
in = dataread();
in_count = 8;
return;
}
while(decomp_buffer_length < (decomp_buffer_size >> 1)) {
for(unsigned pixel = 0; pixel < 8; pixel++) {
//get first symbol context
unsigned a = ((out0 >> (0 * 4)) & 15);
unsigned b = ((out0 >> (7 * 4)) & 15);
unsigned c = ((out1 >> (0 * 4)) & 15);
unsigned con = 0;
unsigned refcon = (a == b) ? (b != c) : (b == c) ? 2 : 4 - (a == c);
//update pixel order
unsigned m, n;
for(m = 0; m < 16; m++) if(pixelorder[m] == a) break;
for(n = m; n > 0; n--) pixelorder[n] = pixelorder[n - 1];
pixelorder[0] = a;
//calculate the real pixel order
for(m = 0; m < 16; m++) realorder[m] = pixelorder[m];
//rotate reference pixel c value to top
for(m = 0; m < 16; m++) if(realorder[m] == c) break;
for(n = m; n > 0; n--) realorder[n] = realorder[n - 1];
realorder[0] = c;
//rotate reference pixel b value to top
for(m = 0; m < 16; m++) if(realorder[m] == b) break;
for(n = m; n > 0; n--) realorder[n] = realorder[n - 1];
realorder[0] = b;
//rotate reference pixel a value to top
for(m = 0; m < 16; m++) if(realorder[m] == a) break;
for(n = m; n > 0; n--) realorder[n] = realorder[n - 1];
realorder[0] = a;
//get 4 symbols
for(unsigned bit = 0; bit < 4; bit++) {
//get prob
unsigned prob = probability(con);
//get symbol
unsigned flag_lps;
if(val <= span - prob) { //mps
span = span - prob;
flag_lps = 0;
} else { //lps
val = val - (span - (prob - 1));
span = prob - 1;
flag_lps = 1;
}
//renormalize
unsigned shift = 0;
while(span < 0x7f) {
shift++;
span = (span << 1) + 1;
val = (val << 1) + (in >> 7);
in <<= 1;
if(--in_count == 0) {
in = dataread();
in_count = 8;
}
}
//update processing info
lps = (lps << 1) + flag_lps;
unsigned invertbit = context[con].invert;
inverts = (inverts << 1) + invertbit;
//update context state
if(flag_lps & toggle_invert(con)) context[con].invert ^= 1;
if(flag_lps) context[con].index = next_lps(con);
else if(shift) context[con].index = next_mps(con);
//get next context
con = mode2_context_table[con][flag_lps ^ invertbit] + (con == 1 ? refcon : 0);
}
//get pixel
b = realorder[(lps ^ inverts) & 0x0f];
out1 = (out1 << 4) + ((out0 >> 28) & 0x0f);
out0 = (out0 << 4) + b;
}
//convert pixel data into bitplanes
unsigned data = morton_4x8(out0);
write(data >> 24);
write(data >> 16);
bitplanebuffer[buffer_index++] = data >> 8;
bitplanebuffer[buffer_index++] = data >> 0;
if(buffer_index == 16) {
for(unsigned i = 0; i < 16; i++) write(bitplanebuffer[i]);
buffer_index = 0;
}
}
}
//
const uint8 SPC7110Decomp::evolution_table[53][4] = {
//{ prob, nextlps, nextmps, toggle invert },
{ 0x5a, 1, 1, 1 },
{ 0x25, 6, 2, 0 },
{ 0x11, 8, 3, 0 },
{ 0x08, 10, 4, 0 },
{ 0x03, 12, 5, 0 },
{ 0x01, 15, 5, 0 },
{ 0x5a, 7, 7, 1 },
{ 0x3f, 19, 8, 0 },
{ 0x2c, 21, 9, 0 },
{ 0x20, 22, 10, 0 },
{ 0x17, 23, 11, 0 },
{ 0x11, 25, 12, 0 },
{ 0x0c, 26, 13, 0 },
{ 0x09, 28, 14, 0 },
{ 0x07, 29, 15, 0 },
{ 0x05, 31, 16, 0 },
{ 0x04, 32, 17, 0 },
{ 0x03, 34, 18, 0 },
{ 0x02, 35, 5, 0 },
{ 0x5a, 20, 20, 1 },
{ 0x48, 39, 21, 0 },
{ 0x3a, 40, 22, 0 },
{ 0x2e, 42, 23, 0 },
{ 0x26, 44, 24, 0 },
{ 0x1f, 45, 25, 0 },
{ 0x19, 46, 26, 0 },
{ 0x15, 25, 27, 0 },
{ 0x11, 26, 28, 0 },
{ 0x0e, 26, 29, 0 },
{ 0x0b, 27, 30, 0 },
{ 0x09, 28, 31, 0 },
{ 0x08, 29, 32, 0 },
{ 0x07, 30, 33, 0 },
{ 0x05, 31, 34, 0 },
{ 0x04, 33, 35, 0 },
{ 0x04, 33, 36, 0 },
{ 0x03, 34, 37, 0 },
{ 0x02, 35, 38, 0 },
{ 0x02, 36, 5, 0 },
{ 0x58, 39, 40, 1 },
{ 0x4d, 47, 41, 0 },
{ 0x43, 48, 42, 0 },
{ 0x3b, 49, 43, 0 },
{ 0x34, 50, 44, 0 },
{ 0x2e, 51, 45, 0 },
{ 0x29, 44, 46, 0 },
{ 0x25, 45, 24, 0 },
{ 0x56, 47, 48, 1 },
{ 0x4f, 47, 49, 0 },
{ 0x47, 48, 50, 0 },
{ 0x41, 49, 51, 0 },
{ 0x3c, 50, 52, 0 },
{ 0x37, 51, 43, 0 },
};
const uint8 SPC7110Decomp::mode2_context_table[32][2] = {
//{ next 0, next 1 },
{ 1, 2 },
{ 3, 8 },
{ 13, 14 },
{ 15, 16 },
{ 17, 18 },
{ 19, 20 },
{ 21, 22 },
{ 23, 24 },
{ 25, 26 },
{ 25, 26 },
{ 25, 26 },
{ 25, 26 },
{ 25, 26 },
{ 27, 28 },
{ 29, 30 },
{ 31, 31 },
{ 31, 31 },
{ 31, 31 },
{ 31, 31 },
{ 31, 31 },
{ 31, 31 },
{ 31, 31 },
{ 31, 31 },
{ 31, 31 },
{ 31, 31 },
{ 31, 31 },
{ 31, 31 },
{ 31, 31 },
{ 31, 31 },
{ 31, 31 },
{ 31, 31 },
{ 31, 31 },
};
uint8 SPC7110Decomp::probability (unsigned n) { return evolution_table[context[n].index][0]; }
uint8 SPC7110Decomp::next_lps (unsigned n) { return evolution_table[context[n].index][1]; }
uint8 SPC7110Decomp::next_mps (unsigned n) { return evolution_table[context[n].index][2]; }
bool SPC7110Decomp::toggle_invert(unsigned n) { return evolution_table[context[n].index][3]; }
unsigned SPC7110Decomp::morton_2x8(unsigned data) {
//reverse morton lookup: de-interleave two 8-bit values
//15, 13, 11, 9, 7, 5, 3, 1 -> 15- 8
//14, 12, 10, 8, 6, 4, 2, 0 -> 7- 0
return morton16[0][(data >> 0) & 255] + morton16[1][(data >> 8) & 255];
}
unsigned SPC7110Decomp::morton_4x8(unsigned data) {
//reverse morton lookup: de-interleave four 8-bit values
//31, 27, 23, 19, 15, 11, 7, 3 -> 31-24
//30, 26, 22, 18, 14, 10, 6, 2 -> 23-16
//29, 25, 21, 17, 13, 9, 5, 1 -> 15- 8
//28, 24, 20, 16, 12, 8, 4, 0 -> 7- 0
return morton32[0][(data >> 0) & 255] + morton32[1][(data >> 8) & 255]
+ morton32[2][(data >> 16) & 255] + morton32[3][(data >> 24) & 255];
}
//
void SPC7110Decomp::reset() {
//mode 3 is invalid; this is treated as a special case to always return 0x00
//set to mode 3 so that reading decomp port before starting first decomp will return 0x00
decomp_mode = 3;
decomp_buffer_rdoffset = 0;
decomp_buffer_wroffset = 0;
decomp_buffer_length = 0;
}
SPC7110Decomp::SPC7110Decomp() {
decomp_buffer = new uint8_t[decomp_buffer_size];
reset();
//initialize reverse morton lookup tables
for(unsigned i = 0; i < 256; i++) {
#define map(x, y) (((i >> x) & 1) << y)
//2x8-bit
morton16[1][i] = map(7, 15) + map(6, 7) + map(5, 14) + map(4, 6)
+ map(3, 13) + map(2, 5) + map(1, 12) + map(0, 4);
morton16[0][i] = map(7, 11) + map(6, 3) + map(5, 10) + map(4, 2)
+ map(3, 9) + map(2, 1) + map(1, 8) + map(0, 0);
//4x8-bit
morton32[3][i] = map(7, 31) + map(6, 23) + map(5, 15) + map(4, 7)
+ map(3, 30) + map(2, 22) + map(1, 14) + map(0, 6);
morton32[2][i] = map(7, 29) + map(6, 21) + map(5, 13) + map(4, 5)
+ map(3, 28) + map(2, 20) + map(1, 12) + map(0, 4);
morton32[1][i] = map(7, 27) + map(6, 19) + map(5, 11) + map(4, 3)
+ map(3, 26) + map(2, 18) + map(1, 10) + map(0, 2);
morton32[0][i] = map(7, 25) + map(6, 17) + map(5, 9) + map(4, 1)
+ map(3, 24) + map(2, 16) + map(1, 8) + map(0, 0);
#undef map
}
}
SPC7110Decomp::~SPC7110Decomp() {
delete[] decomp_buffer;
}
#endif

View File

@@ -0,0 +1,45 @@
class SPC7110Decomp {
public:
uint8 read();
void init(unsigned mode, unsigned offset, unsigned index);
void reset();
SPC7110Decomp();
~SPC7110Decomp();
private:
unsigned decomp_mode;
unsigned decomp_offset;
//read() will spool chunks half the size of decomp_buffer_size
enum { decomp_buffer_size = 64 }; //must be >= 64, and must be a power of two
uint8 *decomp_buffer;
unsigned decomp_buffer_rdoffset;
unsigned decomp_buffer_wroffset;
unsigned decomp_buffer_length;
void write(uint8 data);
uint8 dataread();
void mode0(bool init);
void mode1(bool init);
void mode2(bool init);
static const uint8 evolution_table[53][4];
static const uint8 mode2_context_table[32][2];
struct ContextState {
uint8 index;
uint8 invert;
} context[32];
uint8 probability(unsigned n);
uint8 next_lps(unsigned n);
uint8 next_mps(unsigned n);
bool toggle_invert(unsigned n);
unsigned morton16[2][256];
unsigned morton32[4][256];
unsigned morton_2x8(unsigned data);
unsigned morton_4x8(unsigned data);
};

View File

@@ -1,7 +1,9 @@
#include "../../base.h"
#include <../base.hpp>
#include <../cart/cart.hpp>
#define SPC7110_CPP
#include "codec.cpp"
#include "spc7110.hpp"
#include "decomp.cpp"
const unsigned SPC7110::months[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
@@ -30,9 +32,7 @@ void SPC7110::reset() {
r480b = 0x00;
r480c = 0x00;
memset(codec.output, 0, 65536);
memset(codec.buffer, 0, 65536);
decomp_offset = 0;
decomp.reset();
r4811 = 0x00;
r4812 = 0x00;
@@ -94,18 +94,30 @@ void SPC7110::set_data_pointer(unsigned addr) { r4811 = addr; r4812 = addr >> 8;
void SPC7110::set_data_adjust(unsigned addr) { r4814 = addr; r4815 = addr >> 8; }
void SPC7110::update_time(int offset) {
time_t rtc_time;
rtc_time = memory::cartrtc.read(16);
rtc_time |= memory::cartrtc.read(17) << 8;
rtc_time |= memory::cartrtc.read(18) << 16;
rtc_time |= memory::cartrtc.read(19) << 24;
time_t rtc_time
= (memory::cartrtc.read(16) << 0)
| (memory::cartrtc.read(17) << 8)
| (memory::cartrtc.read(18) << 16)
| (memory::cartrtc.read(19) << 24);
time_t current_time = time(0);
//sizeof(time_t) is platform-dependent; though memory::cartrtc needs to be platform-agnostic.
//yet platforms with 32-bit signed time_t will overflow every ~68 years. handle this by
//accounting for overflow at the cost of 1-bit precision (to catch underflow). this will allow
//memory::cartrtc timestamp to remain valid for up to ~34 years from the last update, even if
//time_t overflows. calculation should be valid regardless of number representation, time_t size,
//or whether time_t is signed or unsigned.
time_t diff
= (current_time >= rtc_time)
? (current_time - rtc_time)
: (std::numeric_limits<time_t>::max() - rtc_time + current_time + 1); //compensate for overflow
if(diff > std::numeric_limits<time_t>::max() / 2) diff = 0; //compensate for underflow
bool update = true;
if(memory::cartrtc.read(13) & 1) update = false; //do not update if CR0 timer disable flag is set
if(memory::cartrtc.read(15) & 3) update = false; //do not update if CR2 timer disable flags are set
if(memory::cartrtc.read(13) & 1) update = false; //do not update if CR0 timer disable flag is set
if(memory::cartrtc.read(15) & 3) update = false; //do not update if CR2 timer disable flags are set
time_t current_time = time(0) - offset;
if(update && current_time > rtc_time) {
if(diff > 0 && update == true) {
unsigned second = memory::cartrtc.read( 0) + memory::cartrtc.read( 1) * 10;
unsigned minute = memory::cartrtc.read( 2) + memory::cartrtc.read( 3) * 10;
unsigned hour = memory::cartrtc.read( 4) + memory::cartrtc.read( 5) * 10;
@@ -116,9 +128,9 @@ void SPC7110::update_time(int offset) {
day--;
month--;
year += (year >= 90) ? 1900 : 2000; //range = 1990-2089
year += (year >= 90) ? 1900 : 2000; //range = 1990-2089
second += (unsigned)(current_time - rtc_time);
second += diff;
while(second >= 60) {
second -= 60;
@@ -170,13 +182,13 @@ void SPC7110::update_time(int offset) {
memory::cartrtc.write(12, weekday % 7);
}
memory::cartrtc.write(16, current_time);
memory::cartrtc.write(17, current_time >> 8);
memory::cartrtc.write(16, current_time >> 0);
memory::cartrtc.write(17, current_time >> 8);
memory::cartrtc.write(18, current_time >> 16);
memory::cartrtc.write(19, current_time >> 24);
}
uint8 SPC7110::mmio_read(uint addr) {
uint8 SPC7110::mmio_read(unsigned addr) {
addr &= 0xffff;
switch(addr) {
@@ -189,7 +201,7 @@ uint8 SPC7110::mmio_read(uint addr) {
counter--;
r4809 = counter;
r480a = counter >> 8;
return codec.output[(decomp_offset++) & 0xffff];
return decomp.read();
}
case 0x4801: return r4801;
case 0x4802: return r4802;
@@ -213,11 +225,11 @@ uint8 SPC7110::mmio_read(uint addr) {
//==============
case 0x4810: {
if(r481x != 0x1f) return 0x00;
if(r481x != 0x07) return 0x00;
unsigned addr = data_pointer();
unsigned adjust = data_adjust();
if(r4818 & 8) adjust = (int16)adjust; //16-bit sign extend
if(r4818 & 8) adjust = (int16)adjust; //16-bit sign extend
unsigned adjustaddr = addr;
if(r4818 & 2) {
@@ -228,7 +240,7 @@ uint8 SPC7110::mmio_read(uint addr) {
uint8 data = memory::cartrom.read(datarom_addr(adjustaddr));
if(!(r4818 & 2)) {
unsigned increment = (r4818 & 1) ? data_increment() : 1;
if(r4818 & 4) increment = (int16)increment; //16-bit sign extend
if(r4818 & 4) increment = (int16)increment; //16-bit sign extend
if((r4818 & 16) == 0) {
set_data_pointer(addr + increment);
@@ -248,11 +260,11 @@ uint8 SPC7110::mmio_read(uint addr) {
case 0x4817: return r4817;
case 0x4818: return r4818;
case 0x481a: {
if(r481x != 0x1f) return 0x00;
if(r481x != 0x07) return 0x00;
unsigned addr = data_pointer();
unsigned adjust = data_adjust();
if(r4818 & 8) adjust = (int16)adjust; //16-bit sign extend
if(r4818 & 8) adjust = (int16)adjust; //16-bit sign extend
uint8 data = memory::cartrom.read(datarom_addr(addr + adjust));
if((r4818 & 0x60) == 0x60) {
@@ -324,7 +336,7 @@ uint8 SPC7110::mmio_read(uint addr) {
return cpu.regs.mdr;
}
void SPC7110::mmio_write(uint addr, uint8 data) {
void SPC7110::mmio_write(unsigned addr, uint8 data) {
addr &= 0xffff;
switch(addr) {
@@ -349,27 +361,7 @@ void SPC7110::mmio_write(uint addr, uint8 data) {
+ (memory::cartrom.read(addr + 2) << 8)
+ (memory::cartrom.read(addr + 3) << 0);
//this can technically be 65536, but it has never been observed higher than 32768 ...
//really need a way to determine both compressed and decompressed lengths, though.
static const unsigned max_length = 32768;
offset = datarom_addr(offset);
for(unsigned i = 0; i < max_length; i++) codec.buffer[i] = memory::cartrom.read(offset + i);
#if 0
printf("decompression: 4805=$%0.2x,4806=$%0.2x,4807=$%0.2x,4808=$%0.2x,480b=$%0.2x\n",
r4805, r4806, r4807, r4808, r480b);
printf("table=$%0.6x,index=%3d,length=%5d,mode=%d,offset=$%0.6x\n",
table, r4804, length, mode, offset);
#endif
switch(mode) {
case 0: codec.decomp_mode0(max_length); break;
case 1: codec.decomp_mode1(max_length); break;
case 2: codec.decomp_mode2(max_length); break;
}
decomp_offset = (r4805 + (r4806 << 8)) << mode;
decomp.init(mode, offset, (r4805 + (r4806 << 8)) << mode);
r480c = 0x80;
} break;
@@ -388,7 +380,6 @@ void SPC7110::mmio_write(uint addr, uint8 data) {
case 0x4813: r4813 = data; r481x |= 0x04; break;
case 0x4814: {
r4814 = data;
r481x |= 0x08;
r4814_latch = true;
if(!r4815_latch) break;
if(!(r4818 & 2)) break;
@@ -396,17 +387,16 @@ void SPC7110::mmio_write(uint addr, uint8 data) {
if((r4818 & 0x60) == 0x20) {
unsigned increment = data_adjust() & 0xff;
if(r4818 & 8) increment = (int8)increment; //8-bit sign extend
if(r4818 & 8) increment = (int8)increment; //8-bit sign extend
set_data_pointer(data_pointer() + increment);
} else if((r4818 & 0x60) == 0x40) {
unsigned increment = data_adjust();
if(r4818 & 8) increment = (int16)increment; //16-bit sign extend
if(r4818 & 8) increment = (int16)increment; //16-bit sign extend
set_data_pointer(data_pointer() + increment);
}
} break;
case 0x4815: {
r4815 = data;
r481x |= 0x10;
r4815_latch = true;
if(!r4814_latch) break;
if(!(r4818 & 2)) break;
@@ -414,18 +404,18 @@ void SPC7110::mmio_write(uint addr, uint8 data) {
if((r4818 & 0x60) == 0x20) {
unsigned increment = data_adjust() & 0xff;
if(r4818 & 8) increment = (int8)increment; //8-bit sign extend
if(r4818 & 8) increment = (int8)increment; //8-bit sign extend
set_data_pointer(data_pointer() + increment);
} else if((r4818 & 0x60) == 0x40) {
unsigned increment = data_adjust();
if(r4818 & 8) increment = (int16)increment; //16-bit sign extend
if(r4818 & 8) increment = (int16)increment; //16-bit sign extend
set_data_pointer(data_pointer() + increment);
}
} break;
case 0x4816: r4816 = data; break;
case 0x4817: r4817 = data; break;
case 0x4818: {
if(r481x != 0x1f) break;
if(r481x != 0x07) break;
r4818 = data;
r4814_latch = r4815_latch = false;
@@ -639,27 +629,19 @@ void SPC7110::mmio_write(uint addr, uint8 data) {
}
}
uint8 SPC7110::read(uint addr) {
uint8 SPC7110::read(unsigned addr) {
//$[00-0f|80-8f]:[8000-ffff], $[c0-cf]:[0000-ffff] mapped directly to memory::cartrom
if((addr & 0xffe000) == 0x006000 || (addr & 0xffe000) == 0x306000) {
//$[00|30]:[6000-7fff]
return memory::cartram.read(addr & 0x1fff);
}
if((addr & 0x708000) == 0x008000) {
//$[00-0f|80-8f]:[8000-ffff]
return memory::cartrom.read(addr & 0x0fffff);
}
if((addr & 0xff0000) == 0x500000) {
//$[50]:[0000-ffff]
return mmio_read(0x4800);
}
if((addr & 0xf00000) == 0xc00000) {
//$[c0-cf]:[0000-ffff]
return memory::cartrom.read(addr & 0x0fffff);
}
if((addr & 0xf00000) == 0xd00000) {
//$[d0-df]:[0000-ffff]
return memory::cartrom.read(dx_offset + (addr & 0x0fffff));
@@ -678,7 +660,7 @@ uint8 SPC7110::read(uint addr) {
return cpu.regs.mdr;
}
void SPC7110::write(uint addr, uint8 data) {
void SPC7110::write(unsigned addr, uint8 data) {
if((addr & 0xffe000) == 0x006000 || (addr & 0xffe000) == 0x306000) {
//$[00|30]:[6000-7fff]
if(r4830 & 0x80) memory::cartram.write(addr & 0x1fff, data);

View File

@@ -1,5 +1,5 @@
/*****
* SPC7110 emulator - version 0.1 (2008-07-19)
* SPC7110 emulator - version 0.03 (2008-08-10)
* Copyright (c) 2008, byuu and neviksti
*
* Permission to use, copy, modify, and/or distribute this software for any
@@ -15,7 +15,7 @@
* or in connection with the use or performance of this software.
*****/
#include "codec.h"
#include "decomp.hpp"
class SPC7110 : public MMIO, public Memory {
public:
@@ -35,11 +35,15 @@ public:
void update_time(int offset = 0);
time_t create_time();
uint8 mmio_read (uint addr);
void mmio_write(uint addr, uint8 data);
uint8 mmio_read (unsigned addr);
void mmio_write(unsigned addr, uint8 data);
uint8 read (uint addr);
void write(uint addr, uint8 data);
uint8 read (unsigned addr);
void write(unsigned addr, uint8 data);
//spc7110decomp
void decomp_init();
uint8 decomp_read();
SPC7110();
@@ -60,8 +64,7 @@ private:
uint8 r480b; //decompression control register
uint8 r480c; //decompression status
SPC7110Codec codec;
uint16 decomp_offset;
SPC7110Decomp decomp;
//==============
//data port unit

View File

@@ -1,4 +1,6 @@
#include "../../base.h"
#include <../base.hpp>
#include <../cart/cart.hpp>
#include "srtc.hpp"
const unsigned SRTC::months[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
@@ -21,14 +23,26 @@ void SRTC::reset() {
}
void SRTC::update_time() {
time_t rtc_time;
rtc_time = memory::cartrtc.read(16);
rtc_time |= memory::cartrtc.read(17) << 8;
rtc_time |= memory::cartrtc.read(18) << 16;
rtc_time |= memory::cartrtc.read(19) << 24;
time_t rtc_time
= (memory::cartrtc.read(16) << 0)
| (memory::cartrtc.read(17) << 8)
| (memory::cartrtc.read(18) << 16)
| (memory::cartrtc.read(19) << 24);
time_t current_time = time(0);
if(current_time > rtc_time) {
//sizeof(time_t) is platform-dependent; though memory::cartrtc needs to be platform-agnostic.
//yet platforms with 32-bit signed time_t will overflow every ~68 years. handle this by
//accounting for overflow at the cost of 1-bit precision (to catch underflow). this will allow
//memory::cartrtc timestamp to remain valid for up to ~34 years from the last update, even if
//time_t overflows. calculation should be valid regardless of number representation, time_t size,
//or whether time_t is signed or unsigned.
time_t diff
= (current_time >= rtc_time)
? (current_time - rtc_time)
: (std::numeric_limits<time_t>::max() - rtc_time + current_time + 1); //compensate for overflow
if(diff > std::numeric_limits<time_t>::max() / 2) diff = 0; //compensate for underflow
if(diff > 0) {
unsigned second = memory::cartrtc.read( 0) + memory::cartrtc.read( 1) * 10;
unsigned minute = memory::cartrtc.read( 2) + memory::cartrtc.read( 3) * 10;
unsigned hour = memory::cartrtc.read( 4) + memory::cartrtc.read( 5) * 10;
@@ -41,8 +55,7 @@ void SRTC::update_time() {
month--;
year += 1000;
second += (unsigned)(current_time - rtc_time);
second += diff;
while(second >= 60) {
second -= 60;
@@ -94,8 +107,8 @@ void SRTC::update_time() {
memory::cartrtc.write(12, weekday % 7);
}
memory::cartrtc.write(16, current_time);
memory::cartrtc.write(17, current_time >> 8);
memory::cartrtc.write(16, current_time >> 0);
memory::cartrtc.write(17, current_time >> 8);
memory::cartrtc.write(18, current_time >> 16);
memory::cartrtc.write(19, current_time >> 24);
}
@@ -104,8 +117,8 @@ void SRTC::update_time() {
//eg 0 = Sunday, 1 = Monday, ... 6 = Saturday
//usage: weekday(2008, 1, 1) returns weekday of January 1st, 2008
unsigned SRTC::weekday(unsigned year, unsigned month, unsigned day) {
unsigned y = 1900, m = 1; //epoch is 1900-01-01
unsigned sum = 0; //number of days passed since epoch
unsigned y = 1900, m = 1; //epoch is 1900-01-01
unsigned sum = 0; //number of days passed since epoch
year = max(1900, year);
month = max(1, min(12, month));
@@ -136,10 +149,10 @@ unsigned SRTC::weekday(unsigned year, unsigned month, unsigned day) {
}
sum += day - 1;
return (sum + 1) % 7; //1900-01-01 was a Monday
return (sum + 1) % 7; //1900-01-01 was a Monday
}
uint8 SRTC::mmio_read(uint addr) {
uint8 SRTC::mmio_read(unsigned addr) {
addr &= 0xffff;
if(addr == 0x2800) {
@@ -160,11 +173,11 @@ uint8 SRTC::mmio_read(uint addr) {
return cpu.regs.mdr;
}
void SRTC::mmio_write(uint addr, uint8 data) {
void SRTC::mmio_write(unsigned addr, uint8 data) {
addr &= 0xffff;
if(addr == 0x2801) {
data &= 0x0f; //only the low four bits are used
data &= 0x0f; //only the low four bits are used
if(data == 0x0d) {
rtc_mode = RTCM_Read;
@@ -177,7 +190,7 @@ void SRTC::mmio_write(uint addr, uint8 data) {
return;
}
if(data == 0x0f) return; //unknown behavior
if(data == 0x0f) return; //unknown behavior
if(rtc_mode == RTCM_Write) {
if(rtc_index >= 0 && rtc_index < 12) {

View File

@@ -8,8 +8,8 @@ public:
void power();
void reset();
uint8 mmio_read (uint addr);
void mmio_write(uint addr, uint8 data);
uint8 mmio_read (unsigned addr);
void mmio_write(unsigned addr, uint8 data);
SRTC();

View File

@@ -1,7 +1,8 @@
#include "../../base.h"
#include <../base.hpp>
#define ST010_CPP
#include "st010_data.h"
#include "st010.hpp"
#include "st010_data.hpp"
#include "st010_op.cpp"
int16 ST010::sin(int16 theta) {
@@ -62,11 +63,11 @@ void ST010::reset() {
//
uint8 ST010::read(uint addr) {
uint8 ST010::read(unsigned addr) {
return readb(addr);
}
void ST010::write(uint addr, uint8 data) {
void ST010::write(unsigned addr, uint8 data) {
writeb(addr, data);
if((addr & 0xfff) == 0x0021 && (data & 0x80)) {

View File

@@ -5,8 +5,8 @@ public:
void power();
void reset();
uint8 read (uint addr);
void write(uint addr, uint8 data);
uint8 read (unsigned addr);
void write(unsigned addr, uint8 data);
private:
uint8 ram[0x1000];

View File

@@ -258,4 +258,4 @@ int16 x1, y1;
writew(0x0012, y1);
}
#endif //ifdef ST010_CPP
#endif

View File

@@ -1 +1 @@
@make platform=win compiler=mingw32-gcc clean
@mingw32-make platform=win compiler=mingw32-gcc clean

View File

@@ -1,130 +0,0 @@
namespace config {
configuration& config() {
static configuration config;
return config;
}
integral_setting File::autodetect_type(config(), "file.autodetect_type",
"Auto-detect file type by inspecting file header, rather than by file extension.\n"
"In other words, if a .zip file is renamed to .smc, it will still be correctly\n"
"identified as a .zip file. However, there is an infinitesimal (1:~500,000,000)\n"
"chance of a false detection when loading an uncompressed image file, if this\n"
"option is enabled.",
integral_setting::boolean, false);
integral_setting File::bypass_patch_crc32(config(), "file.bypass_patch_crc32",
"UPS patches contain CRC32s to validate that a patch was applied successfully.\n"
"By default, if this validation fails, said patch will not be applied.\n"
"Setting this option to true will bypass the validation,\n"
"which may or may not result in a working image.\n"
"Enabling this option is strongly discouraged.",
integral_setting::boolean, false);
string file_updatepath(const char *req_file, const char *req_path) {
string file(req_file);
replace(file, "\\", "/");
if(!req_path || strlen(req_path) == 0) { return file; }
string path(req_path);
replace(path, "\\", "/");
if(!strend(path, "/")) { strcat(path, "/"); }
if(strbegin(path, "./")) {
ltrim(path(), "./");
string temp;
strcpy(temp, config::path.base);
strcat(temp, path);
strcpy(path, temp);
}
lstring part;
split(part, "/", file);
strcat(path, part[count(part) - 1]);
return path;
}
string_setting Path::base("path.base", "Path that bsnes resides in", "");
string_setting Path::user("path.user", "Path to user folder", "");
string_setting Path::rom(config(), "path.rom",
"Default path to look for ROM files in (\"\" = use default directory)", "");
string_setting Path::patch(config(), "path.patch",
"Default path for all UPS patch files (\"\" = use current directory)", "");
string_setting Path::save(config(), "path.save",
"Default path for all save RAM files (\"\" = use current directory)", "");
string_setting Path::cheat(config(), "path.cheat",
"Default path for all cheat files (\"\" = use current directory)", "");
string_setting Path::bsx(config(), "path.bsx", "", "");
string_setting Path::st(config(), "path.st", "", "");
integral_setting SNES::controller_port0(config(), "snes.controller_port_1",
"Controller attached to SNES port 1", integral_setting::decimal, ::SNES::Input::DeviceIDJoypad1);
integral_setting SNES::controller_port1(config(), "snes.controller_port_2",
"Controller attached to SNES port 2", integral_setting::decimal, ::SNES::Input::DeviceIDJoypad2);
integral_setting CPU::ntsc_clock_rate(config(), "cpu.ntsc_clock_rate",
"NTSC S-CPU clock rate (in hz)", integral_setting::decimal, 21477272);
integral_setting CPU::pal_clock_rate(config(), "cpu.pal_clock_rate",
"PAL S-CPU clock rate (in hz)", integral_setting::decimal, 21281370);
integral_setting CPU::wram_init_value(config(), "cpu.wram_init_value",
"Value to initialize 128k WRAM to upon power cycle.\n"
"Note that on real hardware, this value is undefined; meaning it can vary\n"
"per power-on, and per SNES unit. Such randomness is undesirable for an\n"
"emulator, so a static value is needed. There is also some form of pattern\n"
"to the randomness that has yet to be determined, which some games rely upon.\n"
"A value of 0x55 is safe for all known commercial software, and should be used.\n"
"However, some software written for SNES copiers, or backup units, relies on\n"
"WRAM being initialized to 0x00; which was a side-effect of the BIOS program\n"
"which executed on these copiers. Using 0x00 will therefore fix many homebrew\n"
"programs, but *will* break some poorly programmed commercial software titles,\n"
"which do not properly initialize WRAM upon power cycle.\n",
integral_setting::hex, 0x55);
integral_setting CPU::hdma_enable("cpu.hdma_enable",
"Enable HDMA effects", integral_setting::boolean, true);
integral_setting SMP::ntsc_clock_rate(config(), "smp.ntsc_clock_rate",
"NTSC S-SMP clock rate (in hz)", integral_setting::decimal, 24606720);
integral_setting SMP::pal_clock_rate(config(), "smp.pal_clock_rate",
"PAL S-SMP clock rate (in hz)", integral_setting::decimal, 24606720);
integral_setting PPU::Hack::render_scanline_position(config(), "ppu.hack.render_scanline_position",
"Approximate HCLOCK position to render at for scanline-based renderers",
integral_setting::decimal, 512);
integral_setting PPU::Hack::obj_cache(config(), "ppu.hack.obj_cache",
"Cache OAM OBJ attributes one scanline before rendering\n"
"This is technically closer to the actual operation of the SNES,\n"
"but can cause problems in some games if enabled",
integral_setting::boolean, false);
integral_setting PPU::Hack::oam_address_invalidation(config(), "ppu.hack.oam_address_invalidation",
"OAM access address changes during active display, as the S-PPU reads\n"
"data to render the display. Thusly, the address retrieved when accessing\n"
"OAM during active display is unpredictable. Unfortunately, the exact\n"
"algorithm for this is completely unknown at this time. It is more hardware\n"
"accurate to enable this setting, but one must *not* rely on the actual\n"
"address to match hardware under emulation.",
integral_setting::boolean, true);
integral_setting PPU::Hack::cgram_address_invalidation(config(), "ppu.hack.cgram_address_invalidation",
"CGRAM access address changes during active display (excluding hblank), as\n"
"the S-PPU reads data to render the display. Thusly, as with OAM, the access\n"
"address is unpredictable. Again, enabling this setting is more hardware\n"
"accurate, but one must *not* rely on the actual address to match hardware\n"
"under emulation.",
integral_setting::boolean, true);
integral_setting PPU::opt_enable("ppu.opt_enable", "Enable offset-per-tile effects", integral_setting::boolean, true);
integral_setting PPU::bg1_pri0_enable("ppu.bg1_pri0_enable", "Enable BG1 Priority 0", integral_setting::boolean, true);
integral_setting PPU::bg1_pri1_enable("ppu.bg1_pri1_enable", "Enable BG1 Priority 1", integral_setting::boolean, true);
integral_setting PPU::bg2_pri0_enable("ppu.bg2_pri0_enable", "Enable BG2 Priority 0", integral_setting::boolean, true);
integral_setting PPU::bg2_pri1_enable("ppu.bg2_pri1_enable", "Enable BG2 Priority 1", integral_setting::boolean, true);
integral_setting PPU::bg3_pri0_enable("ppu.bg3_pri0_enable", "Enable BG3 Priority 0", integral_setting::boolean, true);
integral_setting PPU::bg3_pri1_enable("ppu.bg3_pri1_enable", "Enable BG3 Priority 1", integral_setting::boolean, true);
integral_setting PPU::bg4_pri0_enable("ppu.bg4_pri0_enable", "Enable BG4 Priority 0", integral_setting::boolean, true);
integral_setting PPU::bg4_pri1_enable("ppu.bg4_pri1_enable", "Enable BG4 Priority 1", integral_setting::boolean, true);
integral_setting PPU::oam_pri0_enable("ppu.oam_pri0_enable", "Enable OAM Priority 0", integral_setting::boolean, true);
integral_setting PPU::oam_pri1_enable("ppu.oam_pri1_enable", "Enable OAM Priority 1", integral_setting::boolean, true);
integral_setting PPU::oam_pri2_enable("ppu.oam_pri2_enable", "Enable OAM Priority 2", integral_setting::boolean, true);
integral_setting PPU::oam_pri3_enable("ppu.oam_pri3_enable", "Enable OAM Priority 3", integral_setting::boolean, true);
} //namespace config

View File

@@ -1,49 +0,0 @@
namespace config {
extern configuration& config();
string file_updatepath(const char*, const char*);
extern struct File {
static integral_setting autodetect_type;
static integral_setting bypass_patch_crc32;
} file;
extern struct Path {
static string_setting base, user, rom, patch, save, cheat;
static string_setting bsx, st;
} path;
extern struct SNES {
static integral_setting controller_port0;
static integral_setting controller_port1;
} snes;
extern struct CPU {
static integral_setting ntsc_clock_rate, pal_clock_rate;
static integral_setting wram_init_value;
static integral_setting hdma_enable;
} cpu;
extern struct SMP {
static integral_setting ntsc_clock_rate, pal_clock_rate;
} smp;
extern struct PPU {
struct Hack {
static integral_setting render_scanline_position;
static integral_setting obj_cache;
static integral_setting oam_address_invalidation;
static integral_setting cgram_address_invalidation;
} hack;
static integral_setting opt_enable;
static integral_setting bg1_pri0_enable, bg1_pri1_enable;
static integral_setting bg2_pri0_enable, bg2_pri1_enable;
static integral_setting bg3_pri0_enable, bg3_pri1_enable;
static integral_setting bg4_pri0_enable, bg4_pri1_enable;
static integral_setting oam_pri0_enable, oam_pri1_enable;
static integral_setting oam_pri2_enable, oam_pri3_enable;
} ppu;
};

View File

@@ -1,10 +1,10 @@
#include "../base.h"
#include <../base.hpp>
#define CPU_CPP
#include "dcpu.cpp"
CPU::CPU() {
cpu_version = 1;
cpu_version = 2;
}
CPU::~CPU() {

View File

@@ -1,5 +1,3 @@
#include "cpuregs.h"
class CPU : public MMIO {
public:
virtual void enter() = 0;
@@ -7,28 +5,18 @@ public:
//CPU version number
//* 1 and 2 are known
//* reported by $4210
//* affects DRAM refresh behavior
//* affects timing (DRAM refresh, HDMA init, etc)
uint8 cpu_version;
//timing
virtual uint16 vcounter() = 0;
virtual uint16 hcounter() = 0;
virtual uint16 hdot() = 0;
virtual uint8 pio_status() = 0;
virtual uint8 pio() = 0;
virtual bool joylatch() = 0;
virtual uint8 port_read(uint8 port) = 0;
virtual void port_write(uint8 port, uint8 value) = 0;
CPURegs regs;
enum {
FLAG_N = 0x80, FLAG_V = 0x40,
FLAG_M = 0x20, FLAG_X = 0x10,
FLAG_D = 0x08, FLAG_I = 0x04,
FLAG_Z = 0x02, FLAG_C = 0x01
};
#include "cpuregs.hpp"
regs_t regs;
virtual void scanline() = 0;
virtual void frame() = 0;
virtual void power() = 0;
virtual void reset() = 0;

View File

@@ -1,88 +0,0 @@
template<int mask>
struct CPUFlag {
uint8 &data;
inline operator bool() const { return data & mask; }
inline CPUFlag& operator=(bool i) { data = (data & ~mask) | (-i & mask); return *this; }
CPUFlag(uint8 &data_) : data(data_) {}
};
class CPURegFlags {
public:
uint8 data;
CPUFlag<0x80> n;
CPUFlag<0x40> v;
CPUFlag<0x20> m;
CPUFlag<0x10> x;
CPUFlag<0x08> d;
CPUFlag<0x04> i;
CPUFlag<0x02> z;
CPUFlag<0x01> c;
inline operator unsigned() const { return data; }
inline unsigned operator = (unsigned i) { data = i; return data; }
inline unsigned operator |= (unsigned i) { data |= i; return data; }
inline unsigned operator ^= (unsigned i) { data ^= i; return data; }
inline unsigned operator &= (unsigned i) { data &= i; return data; }
CPURegFlags() : data(0), n(data), v(data), m(data), x(data), d(data), i(data), z(data), c(data) {}
};
class CPUReg16 {
public:
union {
uint16 w;
struct { uint8 order_lsb2(l, h); };
};
inline operator unsigned() const { return w; }
inline unsigned operator = (unsigned i) { w = i; return w; }
inline unsigned operator |= (unsigned i) { w |= i; return w; }
inline unsigned operator ^= (unsigned i) { w ^= i; return w; }
inline unsigned operator &= (unsigned i) { w &= i; return w; }
inline unsigned operator <<= (unsigned i) { w <<= i; return w; }
inline unsigned operator >>= (unsigned i) { w >>= i; return w; }
inline unsigned operator += (unsigned i) { w += i; return w; }
inline unsigned operator -= (unsigned i) { w -= i; return w; }
inline unsigned operator *= (unsigned i) { w *= i; return w; }
inline unsigned operator /= (unsigned i) { w /= i; return w; }
inline unsigned operator %= (unsigned i) { w %= i; return w; }
CPUReg16() : w(0) {}
};
class CPUReg24 {
public:
union {
uint32 d;
struct { uint16 order_lsb2(w, wh); };
struct { uint8 order_lsb4(l, h, b, bh); };
};
inline operator unsigned() const { return d; }
inline unsigned operator = (unsigned i) { d = uclip<24>(i); return d; }
inline unsigned operator |= (unsigned i) { d = uclip<24>(d | i); return d; }
inline unsigned operator ^= (unsigned i) { d = uclip<24>(d ^ i); return d; }
inline unsigned operator &= (unsigned i) { d = uclip<24>(d & i); return d; }
inline unsigned operator <<= (unsigned i) { d = uclip<24>(d << i); return d; }
inline unsigned operator >>= (unsigned i) { d = uclip<24>(d >> i); return d; }
inline unsigned operator += (unsigned i) { d = uclip<24>(d + i); return d; }
inline unsigned operator -= (unsigned i) { d = uclip<24>(d - i); return d; }
inline unsigned operator *= (unsigned i) { d = uclip<24>(d * i); return d; }
inline unsigned operator /= (unsigned i) { d = uclip<24>(d / i); return d; }
inline unsigned operator %= (unsigned i) { d = uclip<24>(d % i); return d; }
CPUReg24() : d(0) {}
};
class CPURegs {
public:
CPUReg24 pc;
CPUReg16 a, x, y, s, d;
CPURegFlags p;
uint8 db;
uint8 mdr;
bool e;
CPURegs() : db(0), mdr(0), e(false) {}
};

74
src/cpu/cpuregs.hpp Normal file
View File

@@ -0,0 +1,74 @@
struct flag_t {
bool n, v, m, x, d, i, z, c;
inline operator unsigned() const {
return (n << 7) + (v << 6) + (m << 5) + (x << 4)
+ (d << 3) + (i << 2) + (z << 1) + (c << 0);
}
inline unsigned operator=(uint8_t data) {
n = data & 0x80; v = data & 0x40; m = data & 0x20; x = data & 0x10;
d = data & 0x08; i = data & 0x04; z = data & 0x02; c = data & 0x01;
return data;
}
inline unsigned operator|=(unsigned data) { return operator=(operator unsigned() | data); }
inline unsigned operator^=(unsigned data) { return operator=(operator unsigned() ^ data); }
inline unsigned operator&=(unsigned data) { return operator=(operator unsigned() & data); }
flag_t() : n(0), v(0), m(0), x(0), d(0), i(0), z(0), c(0) {}
};
struct reg16_t {
union {
uint16 w;
struct { uint8 order_lsb2(l, h); };
};
inline operator unsigned() const { return w; }
inline unsigned operator = (unsigned i) { return w = i; }
inline unsigned operator |= (unsigned i) { return w |= i; }
inline unsigned operator ^= (unsigned i) { return w ^= i; }
inline unsigned operator &= (unsigned i) { return w &= i; }
inline unsigned operator <<= (unsigned i) { return w <<= i; }
inline unsigned operator >>= (unsigned i) { return w >>= i; }
inline unsigned operator += (unsigned i) { return w += i; }
inline unsigned operator -= (unsigned i) { return w -= i; }
inline unsigned operator *= (unsigned i) { return w *= i; }
inline unsigned operator /= (unsigned i) { return w /= i; }
inline unsigned operator %= (unsigned i) { return w %= i; }
reg16_t() : w(0) {}
};
struct reg24_t {
union {
uint32 d;
struct { uint16 order_lsb2(w, wh); };
struct { uint8 order_lsb4(l, h, b, bh); };
};
inline operator unsigned() const { return d; }
inline unsigned operator = (unsigned i) { return d = uclip<24>(i); }
inline unsigned operator |= (unsigned i) { return d = uclip<24>(d | i); }
inline unsigned operator ^= (unsigned i) { return d = uclip<24>(d ^ i); }
inline unsigned operator &= (unsigned i) { return d = uclip<24>(d & i); }
inline unsigned operator <<= (unsigned i) { return d = uclip<24>(d << i); }
inline unsigned operator >>= (unsigned i) { return d = uclip<24>(d >> i); }
inline unsigned operator += (unsigned i) { return d = uclip<24>(d + i); }
inline unsigned operator -= (unsigned i) { return d = uclip<24>(d - i); }
inline unsigned operator *= (unsigned i) { return d = uclip<24>(d * i); }
inline unsigned operator /= (unsigned i) { return d = uclip<24>(d / i); }
inline unsigned operator %= (unsigned i) { return d = uclip<24>(d % i); }
reg24_t() : d(0) {}
};
struct regs_t {
reg24_t pc;
reg16_t a, x, y, s, d;
flag_t p;
uint8_t db, mdr;
bool e;
regs_t() : db(0), mdr(0), e(false) {}
};

View File

@@ -2,22 +2,22 @@
uint8 CPU::dreadb(uint32 addr) {
if((addr & 0x40ffff) >= 0x2000 && (addr & 0x40ffff) <= 0x5fff) {
//$[00-3f|80-bf]:[2000-5fff]
//do not read MMIO registers within debugger
//$[00-3f|80-bf]:[2000-5fff]
//do not read MMIO registers within debugger
return 0x00;
}
return bus.read(addr);
}
uint16 CPU::dreadw(uint32 addr) {
uint16 r;
uint16 r;
r = dreadb((addr + 0) & 0xffffff) << 0;
r |= dreadb((addr + 1) & 0xffffff) << 8;
return r;
}
uint32 CPU::dreadl(uint32 addr) {
uint32 r;
uint32 r;
r = dreadb((addr + 0) & 0xffffff) << 0;
r |= dreadb((addr + 1) & 0xffffff) << 8;
r |= dreadb((addr + 2) & 0xffffff) << 16;
@@ -25,87 +25,89 @@ uint32 r;
}
uint32 CPU::decode(uint8 offset_type, uint32 addr) {
uint32 r = 0;
uint32 r = 0;
switch(offset_type) {
case OPTYPE_DP:
r = (regs.d + (addr & 0xffff)) & 0xffff;
break;
case OPTYPE_DPX:
r = (regs.d + regs.x + (addr & 0xffff)) & 0xffff;
break;
case OPTYPE_DPY:
r = (regs.d + regs.y + (addr & 0xffff)) & 0xffff;
break;
case OPTYPE_IDP:
addr = (regs.d + (addr & 0xffff)) & 0xffff;
r = (regs.db << 16) + dreadw(addr);
break;
case OPTYPE_IDPX:
addr = (regs.d + regs.x + (addr & 0xffff)) & 0xffff;
r = (regs.db << 16) + dreadw(addr);
break;
case OPTYPE_IDPY:
addr = (regs.d + (addr & 0xffff)) & 0xffff;
r = (regs.db << 16) + dreadw(addr) + regs.y;
break;
case OPTYPE_ILDP:
addr = (regs.d + (addr & 0xffff)) & 0xffff;
r = dreadl(addr);
break;
case OPTYPE_ILDPY:
addr = (regs.d + (addr & 0xffff)) & 0xffff;
r = dreadl(addr) + regs.y;
break;
case OPTYPE_ADDR:
r = (regs.db << 16) + (addr & 0xffff);
break;
case OPTYPE_ADDR_PC:
r = (regs.pc.b << 16) + (addr & 0xffff);
break;
case OPTYPE_ADDRX:
r = (regs.db << 16) + (addr & 0xffff) + regs.x;
break;
case OPTYPE_ADDRY:
r = (regs.db << 16) + (addr & 0xffff) + regs.y;
break;
case OPTYPE_IADDR_PC:
r = (regs.pc.b << 16) + (addr & 0xffff);
break;
case OPTYPE_IADDRX:
r = (regs.pc.b << 16) + ((addr + regs.x) & 0xffff);
break;
case OPTYPE_ILADDR:
r = addr;
break;
case OPTYPE_LONG:
r = addr;
break;
case OPTYPE_LONGX:
r = (addr + regs.x);
break;
case OPTYPE_SR:
r = (regs.s + (addr & 0xff)) & 0xffff;
break;
case OPTYPE_ISRY:
addr = (regs.s + (addr & 0xff)) & 0xffff;
r = (regs.db << 16) + dreadw(addr) + regs.y;
break;
case OPTYPE_RELB:
r = (regs.pc.b << 16) + ((regs.pc.w + 2) & 0xffff);
r += int8(addr);
break;
case OPTYPE_RELW:
r = (regs.pc.b << 16) + ((regs.pc.w + 3) & 0xffff);
r += int16(addr);
break;
case OPTYPE_DP:
r = (regs.d + (addr & 0xffff)) & 0xffff;
break;
case OPTYPE_DPX:
r = (regs.d + regs.x + (addr & 0xffff)) & 0xffff;
break;
case OPTYPE_DPY:
r = (regs.d + regs.y + (addr & 0xffff)) & 0xffff;
break;
case OPTYPE_IDP:
addr = (regs.d + (addr & 0xffff)) & 0xffff;
r = (regs.db << 16) + dreadw(addr);
break;
case OPTYPE_IDPX:
addr = (regs.d + regs.x + (addr & 0xffff)) & 0xffff;
r = (regs.db << 16) + dreadw(addr);
break;
case OPTYPE_IDPY:
addr = (regs.d + (addr & 0xffff)) & 0xffff;
r = (regs.db << 16) + dreadw(addr) + regs.y;
break;
case OPTYPE_ILDP:
addr = (regs.d + (addr & 0xffff)) & 0xffff;
r = dreadl(addr);
break;
case OPTYPE_ILDPY:
addr = (regs.d + (addr & 0xffff)) & 0xffff;
r = dreadl(addr) + regs.y;
break;
case OPTYPE_ADDR:
r = (regs.db << 16) + (addr & 0xffff);
break;
case OPTYPE_ADDR_PC:
r = (regs.pc.b << 16) + (addr & 0xffff);
break;
case OPTYPE_ADDRX:
r = (regs.db << 16) + (addr & 0xffff) + regs.x;
break;
case OPTYPE_ADDRY:
r = (regs.db << 16) + (addr & 0xffff) + regs.y;
break;
case OPTYPE_IADDR_PC:
r = (regs.pc.b << 16) + (addr & 0xffff);
break;
case OPTYPE_IADDRX:
r = (regs.pc.b << 16) + ((addr + regs.x) & 0xffff);
break;
case OPTYPE_ILADDR:
r = addr;
break;
case OPTYPE_LONG:
r = addr;
break;
case OPTYPE_LONGX:
r = (addr + regs.x);
break;
case OPTYPE_SR:
r = (regs.s + (addr & 0xff)) & 0xffff;
break;
case OPTYPE_ISRY:
addr = (regs.s + (addr & 0xff)) & 0xffff;
r = (regs.db << 16) + dreadw(addr) + regs.y;
break;
case OPTYPE_RELB:
r = (regs.pc.b << 16) + ((regs.pc.w + 2) & 0xffff);
r += int8(addr);
break;
case OPTYPE_RELW:
r = (regs.pc.b << 16) + ((regs.pc.w + 3) & 0xffff);
r += int16(addr);
break;
}
return(r & 0xffffff);
}
void CPU::disassemble_opcode(char *output) {
static CPUReg24 pc;
char t[256];
char *s = output;
static reg24_t pc;
char t[256];
char *s = output;
if(in_opcode() == true) {
strcpy(s, "?????? <CPU within opcode>");
@@ -113,367 +115,369 @@ char *s = output;
}
pc.d = regs.pc.d;
sprintf(s, "%0.6x ", uint32(pc.d));
sprintf(s, "%.6x ", (uint32)pc.d);
uint8 op = dreadb(pc.d); pc.w++;
uint8 op0 = dreadb(pc.d); pc.w++;
uint8 op1 = dreadb(pc.d); pc.w++;
uint8 op2 = dreadb(pc.d);
uint8 op = dreadb(pc.d); pc.w++;
uint8 op0 = dreadb(pc.d); pc.w++;
uint8 op1 = dreadb(pc.d); pc.w++;
uint8 op2 = dreadb(pc.d);
#define op8 ((op0))
#define op16 ((op0) | (op1 << 8))
#define op24 ((op0) | (op1 << 8) | (op2 << 16))
#define a8 (regs.e || regs.p.m)
#define x8 (regs.e || regs.p.x)
#define op8 ((op0))
#define op16 ((op0) | (op1 << 8))
#define op24 ((op0) | (op1 << 8) | (op2 << 16))
#define a8 (regs.e || regs.p.m)
#define x8 (regs.e || regs.p.x)
switch(op) {
case 0x00: sprintf(t, "brk #$%0.2x ", op8); break;
case 0x01: sprintf(t, "ora ($%0.2x,x) [$%0.6x]", op8, decode(OPTYPE_IDPX, op8)); break;
case 0x02: sprintf(t, "cop #$%0.2x ", op8); break;
case 0x03: sprintf(t, "ora $%0.2x,s [$%0.6x]", op8, decode(OPTYPE_SR, op8)); break;
case 0x04: sprintf(t, "tsb $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x05: sprintf(t, "ora $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x06: sprintf(t, "asl $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x07: sprintf(t, "ora [$%0.2x] [$%0.6x]", op8, decode(OPTYPE_ILDP, op8)); break;
case 0x08: sprintf(t, "php "); break;
case 0x09: if(a8)sprintf(t, "ora #$%0.2x ", op8);
else sprintf(t, "ora #$%0.4x ", op16); break;
case 0x0a: sprintf(t, "asl a "); break;
case 0x0b: sprintf(t, "phd "); break;
case 0x0c: sprintf(t, "tsb $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x0d: sprintf(t, "ora $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x0e: sprintf(t, "asl $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x0f: sprintf(t, "ora $%0.6x [$%0.6x]", op24, decode(OPTYPE_LONG, op24)); break;
case 0x10: sprintf(t, "bpl $%0.4x [$%0.6x]", uint16(decode(OPTYPE_RELB, op8)), decode(OPTYPE_RELB, op8)); break;
case 0x11: sprintf(t, "ora ($%0.2x),y [$%0.6x]", op8, decode(OPTYPE_IDPY, op8)); break;
case 0x12: sprintf(t, "ora ($%0.2x) [$%0.6x]", op8, decode(OPTYPE_IDP, op8)); break;
case 0x13: sprintf(t, "ora ($%0.2x,s),y [$%0.6x]", op8, decode(OPTYPE_ISRY, op8)); break;
case 0x14: sprintf(t, "trb $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x15: sprintf(t, "ora $%0.2x,x [$%0.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x16: sprintf(t, "asl $%0.2x,x [$%0.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x17: sprintf(t, "ora [$%0.2x],y [$%0.6x]", op8, decode(OPTYPE_ILDPY, op8)); break;
case 0x18: sprintf(t, "clc "); break;
case 0x19: sprintf(t, "ora $%0.4x,y [$%0.6x]", op16, decode(OPTYPE_ADDRY, op16)); break;
case 0x1a: sprintf(t, "inc "); break;
case 0x1b: sprintf(t, "tcs "); break;
case 0x1c: sprintf(t, "trb $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x1d: sprintf(t, "ora $%0.4x,x [$%0.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x1e: sprintf(t, "asl $%0.4x,x [$%0.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x1f: sprintf(t, "ora $%0.6x,x [$%0.6x]", op24, decode(OPTYPE_LONGX, op24)); break;
case 0x20: sprintf(t, "jsr $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR_PC, op16)); break;
case 0x21: sprintf(t, "and ($%0.2x,x) [$%0.6x]", op8, decode(OPTYPE_IDPX, op8)); break;
case 0x22: sprintf(t, "jsl $%0.6x [$%0.6x]", op24, decode(OPTYPE_LONG, op24)); break;
case 0x23: sprintf(t, "and $%0.2x,s [$%0.6x]", op8, decode(OPTYPE_SR, op8)); break;
case 0x24: sprintf(t, "bit $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x25: sprintf(t, "and $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x26: sprintf(t, "rol $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x27: sprintf(t, "and [$%0.2x] [$%0.6x]", op8, decode(OPTYPE_ILDP, op8)); break;
case 0x28: sprintf(t, "plp "); break;
case 0x29: if(a8)sprintf(t, "and #$%0.2x ", op8);
else sprintf(t, "and #$%0.4x ", op16); break;
case 0x2a: sprintf(t, "rol a "); break;
case 0x2b: sprintf(t, "pld "); break;
case 0x2c: sprintf(t, "bit $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x2d: sprintf(t, "and $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x2e: sprintf(t, "rol $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x2f: sprintf(t, "and $%0.6x [$%0.6x]", op24, decode(OPTYPE_LONG, op24)); break;
case 0x30: sprintf(t, "bmi $%0.4x [$%0.6x]", uint16(decode(OPTYPE_RELB, op8)), decode(OPTYPE_RELB, op8)); break;
case 0x31: sprintf(t, "and ($%0.2x),y [$%0.6x]", op8, decode(OPTYPE_IDPY, op8)); break;
case 0x32: sprintf(t, "and ($%0.2x) [$%0.6x]", op8, decode(OPTYPE_IDP, op8)); break;
case 0x33: sprintf(t, "and ($%0.2x,s),y [$%0.6x]", op8, decode(OPTYPE_ISRY, op8)); break;
case 0x34: sprintf(t, "bit $%0.2x,x [$%0.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x35: sprintf(t, "and $%0.2x,x [$%0.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x36: sprintf(t, "rol $%0.2x,x [$%0.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x37: sprintf(t, "and [$%0.2x],y [$%0.6x]", op8, decode(OPTYPE_ILDPY, op8)); break;
case 0x38: sprintf(t, "sec "); break;
case 0x39: sprintf(t, "and $%0.4x,y [$%0.6x]", op16, decode(OPTYPE_ADDRY, op16)); break;
case 0x3a: sprintf(t, "dec "); break;
case 0x3b: sprintf(t, "tsc "); break;
case 0x3c: sprintf(t, "bit $%0.4x,x [$%0.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x3d: sprintf(t, "and $%0.4x,x [$%0.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x3e: sprintf(t, "rol $%0.4x,x [$%0.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x3f: sprintf(t, "and $%0.6x,x [$%0.6x]", op24, decode(OPTYPE_LONGX, op24)); break;
case 0x40: sprintf(t, "rti "); break;
case 0x41: sprintf(t, "eor ($%0.2x,x) [$%0.6x]", op8, decode(OPTYPE_IDPX, op8)); break;
case 0x42: sprintf(t, "wdm "); break;
case 0x43: sprintf(t, "eor $%0.2x,s [$%0.6x]", op8, decode(OPTYPE_SR, op8)); break;
case 0x44: sprintf(t, "mvp $%0.2x,$%0.2x ", op1, op8); break;
case 0x45: sprintf(t, "eor $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x46: sprintf(t, "lsr $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x47: sprintf(t, "eor [$%0.2x] [$%0.6x]", op8, decode(OPTYPE_ILDP, op8)); break;
case 0x48: sprintf(t, "pha "); break;
case 0x49: if(a8)sprintf(t, "eor #$%0.2x ", op8);
else sprintf(t, "eor #$%0.4x ", op16); break;
case 0x4a: sprintf(t, "lsr a "); break;
case 0x4b: sprintf(t, "phk "); break;
case 0x4c: sprintf(t, "jmp $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR_PC, op16)); break;
case 0x4d: sprintf(t, "eor $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x4e: sprintf(t, "lsr $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x4f: sprintf(t, "eor $%0.6x [$%0.6x]", op24, decode(OPTYPE_LONG, op24)); break;
case 0x50: sprintf(t, "bvc $%0.4x [$%0.6x]", uint16(decode(OPTYPE_RELB, op8)), decode(OPTYPE_RELB, op8)); break;
case 0x51: sprintf(t, "eor ($%0.2x),y [$%0.6x]", op8, decode(OPTYPE_IDPY, op8)); break;
case 0x52: sprintf(t, "eor ($%0.2x) [$%0.6x]", op8, decode(OPTYPE_IDP, op8)); break;
case 0x53: sprintf(t, "eor ($%0.2x,s),y [$%0.6x]", op8, decode(OPTYPE_ISRY, op8)); break;
case 0x54: sprintf(t, "mvn $%0.2x,$%0.2x ", op1, op8); break;
case 0x55: sprintf(t, "eor $%0.2x,x [$%0.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x56: sprintf(t, "lsr $%0.2x,x [$%0.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x57: sprintf(t, "eor [$%0.2x],y [$%0.6x]", op8, decode(OPTYPE_ILDPY, op8)); break;
case 0x58: sprintf(t, "cli "); break;
case 0x59: sprintf(t, "eor $%0.4x,y [$%0.6x]", op16, decode(OPTYPE_ADDRY, op16)); break;
case 0x5a: sprintf(t, "phy "); break;
case 0x5b: sprintf(t, "tcd "); break;
case 0x5c: sprintf(t, "jml $%0.6x [$%0.6x]", op24, decode(OPTYPE_LONG, op24)); break;
case 0x5d: sprintf(t, "eor $%0.4x,x [$%0.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x5e: sprintf(t, "lsr $%0.4x,x [$%0.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x5f: sprintf(t, "eor $%0.6x,x [$%0.6x]", op24, decode(OPTYPE_LONGX, op24)); break;
case 0x60: sprintf(t, "rts "); break;
case 0x61: sprintf(t, "adc ($%0.2x,x) [$%0.6x]", op8, decode(OPTYPE_IDPX, op8)); break;
case 0x62: sprintf(t, "per $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x63: sprintf(t, "adc $%0.2x,s [$%0.6x]", op8, decode(OPTYPE_SR, op8)); break;
case 0x64: sprintf(t, "stz $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x65: sprintf(t, "adc $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x66: sprintf(t, "ror $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x67: sprintf(t, "adc [$%0.2x] [$%0.6x]", op8, decode(OPTYPE_ILDP, op8)); break;
case 0x68: sprintf(t, "pla "); break;
case 0x69: if(a8)sprintf(t, "adc #$%0.2x ", op8);
else sprintf(t, "adc #$%0.4x ", op16); break;
case 0x6a: sprintf(t, "ror a "); break;
case 0x6b: sprintf(t, "rtl "); break;
case 0x6c: sprintf(t, "jmp ($%0.4x) [$%0.6x]", op16, decode(OPTYPE_IADDR_PC, op16)); break;
case 0x6d: sprintf(t, "adc $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x6e: sprintf(t, "ror $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x6f: sprintf(t, "adc $%0.6x [$%0.6x]", op24, decode(OPTYPE_LONG, op24)); break;
case 0x70: sprintf(t, "bvs $%0.4x [$%0.6x]", uint16(decode(OPTYPE_RELB, op8)), decode(OPTYPE_RELB, op8)); break;
case 0x71: sprintf(t, "adc ($%0.2x),y [$%0.6x]", op8, decode(OPTYPE_IDPY, op8)); break;
case 0x72: sprintf(t, "adc ($%0.2x) [$%0.6x]", op8, decode(OPTYPE_IDP, op8)); break;
case 0x73: sprintf(t, "adc ($%0.2x,s),y [$%0.6x]", op8, decode(OPTYPE_ISRY, op8)); break;
case 0x74: sprintf(t, "stz $%0.2x,x [$%0.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x75: sprintf(t, "adc $%0.2x,x [$%0.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x76: sprintf(t, "ror $%0.2x,x [$%0.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x77: sprintf(t, "adc [$%0.2x],y [$%0.6x]", op8, decode(OPTYPE_ILDPY, op8)); break;
case 0x78: sprintf(t, "sei "); break;
case 0x79: sprintf(t, "adc $%0.4x,y [$%0.6x]", op16, decode(OPTYPE_ADDRY, op16)); break;
case 0x7a: sprintf(t, "ply "); break;
case 0x7b: sprintf(t, "tdc "); break;
case 0x7c: sprintf(t, "jmp ($%0.4x,x) [$%0.6x]", op16, decode(OPTYPE_IADDRX, op16)); break;
case 0x7d: sprintf(t, "adc $%0.4x,x [$%0.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x7e: sprintf(t, "ror $%0.4x,x [$%0.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x7f: sprintf(t, "adc $%0.6x,x [$%0.6x]", op24, decode(OPTYPE_LONGX, op24)); break;
case 0x80: sprintf(t, "bra $%0.4x [$%0.6x]", uint16(decode(OPTYPE_RELB, op8)), decode(OPTYPE_RELB, op8)); break;
case 0x81: sprintf(t, "sta ($%0.2x,x) [$%0.6x]", op8, decode(OPTYPE_IDPX, op8)); break;
case 0x82: sprintf(t, "brl $%0.4x [$%0.6x]", uint16(decode(OPTYPE_RELW, op16)), decode(OPTYPE_RELW, op16)); break;
case 0x83: sprintf(t, "sta $%0.2x,s [$%0.6x]", op8, decode(OPTYPE_SR, op8)); break;
case 0x84: sprintf(t, "sty $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x85: sprintf(t, "sta $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x86: sprintf(t, "stx $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x87: sprintf(t, "sta [$%0.2x] [$%0.6x]", op8, decode(OPTYPE_ILDP, op8)); break;
case 0x88: sprintf(t, "dey "); break;
case 0x89: if(a8)sprintf(t, "bit #$%0.2x ", op8);
else sprintf(t, "bit #$%0.4x ", op16); break;
case 0x8a: sprintf(t, "txa "); break;
case 0x8b: sprintf(t, "phb "); break;
case 0x8c: sprintf(t, "sty $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x8d: sprintf(t, "sta $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x8e: sprintf(t, "stx $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x8f: sprintf(t, "sta $%0.6x [$%0.6x]", op24, decode(OPTYPE_LONG, op24)); break;
case 0x90: sprintf(t, "bcc $%0.4x [$%0.6x]", uint16(decode(OPTYPE_RELB, op8)), decode(OPTYPE_RELB, op8)); break;
case 0x91: sprintf(t, "sta ($%0.2x),y [$%0.6x]", op8, decode(OPTYPE_IDPY, op8)); break;
case 0x92: sprintf(t, "sta ($%0.2x) [$%0.6x]", op8, decode(OPTYPE_IDP, op8)); break;
case 0x93: sprintf(t, "sta ($%0.2x,s),y [$%0.6x]", op8, decode(OPTYPE_ISRY, op8)); break;
case 0x94: sprintf(t, "sty $%0.2x,x [$%0.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x95: sprintf(t, "sta $%0.2x,x [$%0.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x96: sprintf(t, "stx $%0.2x,y [$%0.6x]", op8, decode(OPTYPE_DPY, op8)); break;
case 0x97: sprintf(t, "sta [$%0.2x],y [$%0.6x]", op8, decode(OPTYPE_ILDPY, op8)); break;
case 0x98: sprintf(t, "tya "); break;
case 0x99: sprintf(t, "sta $%0.4x,y [$%0.6x]", op16, decode(OPTYPE_ADDRY, op16)); break;
case 0x9a: sprintf(t, "txs "); break;
case 0x9b: sprintf(t, "txy "); break;
case 0x9c: sprintf(t, "stz $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x9d: sprintf(t, "sta $%0.4x,x [$%0.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x9e: sprintf(t, "stz $%0.4x,x [$%0.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x9f: sprintf(t, "sta $%0.6x,x [$%0.6x]", op24, decode(OPTYPE_LONGX, op24)); break;
case 0xa0: if(x8)sprintf(t, "ldy #$%0.2x ", op8);
else sprintf(t, "ldy #$%0.4x ", op16); break;
case 0xa1: sprintf(t, "lda ($%0.2x,x) [$%0.6x]", op8, decode(OPTYPE_IDPX, op8)); break;
case 0xa2: if(x8)sprintf(t, "ldx #$%0.2x ", op8);
else sprintf(t, "ldx #$%0.4x ", op16); break;
case 0xa3: sprintf(t, "lda $%0.2x,s [$%0.6x]", op8, decode(OPTYPE_SR, op8)); break;
case 0xa4: sprintf(t, "ldy $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0xa5: sprintf(t, "lda $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0xa6: sprintf(t, "ldx $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0xa7: sprintf(t, "lda [$%0.2x] [$%0.6x]", op8, decode(OPTYPE_ILDP, op8)); break;
case 0xa8: sprintf(t, "tay "); break;
case 0xa9: if(a8)sprintf(t, "lda #$%0.2x ", op8);
else sprintf(t, "lda #$%0.4x ", op16); break;
case 0xaa: sprintf(t, "tax "); break;
case 0xab: sprintf(t, "plb "); break;
case 0xac: sprintf(t, "ldy $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0xad: sprintf(t, "lda $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0xae: sprintf(t, "ldx $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0xaf: sprintf(t, "lda $%0.6x [$%0.6x]", op24, decode(OPTYPE_LONG, op24)); break;
case 0xb0: sprintf(t, "bcs $%0.4x [$%0.6x]", uint16(decode(OPTYPE_RELB, op8)), decode(OPTYPE_RELB, op8)); break;
case 0xb1: sprintf(t, "lda ($%0.2x),y [$%0.6x]", op8, decode(OPTYPE_IDPY, op8)); break;
case 0xb2: sprintf(t, "lda ($%0.2x) [$%0.6x]", op8, decode(OPTYPE_IDP, op8)); break;
case 0xb3: sprintf(t, "lda ($%0.2x,s),y [$%0.6x]", op8, decode(OPTYPE_ISRY, op8)); break;
case 0xb4: sprintf(t, "ldy $%0.2x,x [$%0.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0xb5: sprintf(t, "lda $%0.2x,x [$%0.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0xb6: sprintf(t, "ldx $%0.2x,y [$%0.6x]", op8, decode(OPTYPE_DPY, op8)); break;
case 0xb7: sprintf(t, "lda [$%0.2x],y [$%0.6x]", op8, decode(OPTYPE_ILDPY, op8)); break;
case 0xb8: sprintf(t, "clv "); break;
case 0xb9: sprintf(t, "lda $%0.4x,y [$%0.6x]", op16, decode(OPTYPE_ADDRY, op16)); break;
case 0xba: sprintf(t, "tsx "); break;
case 0xbb: sprintf(t, "tyx "); break;
case 0xbc: sprintf(t, "ldy $%0.4x,x [$%0.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0xbd: sprintf(t, "lda $%0.4x,x [$%0.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0xbe: sprintf(t, "ldx $%0.4x,y [$%0.6x]", op16, decode(OPTYPE_ADDRY, op16)); break;
case 0xbf: sprintf(t, "lda $%0.6x,x [$%0.6x]", op24, decode(OPTYPE_LONGX, op24)); break;
case 0xc0: if(x8)sprintf(t, "cpy #$%0.2x ", op8);
else sprintf(t, "cpy #$%0.4x ", op16); break;
case 0xc1: sprintf(t, "cmp ($%0.2x,x) [$%0.6x]", op8, decode(OPTYPE_IDPX, op8)); break;
case 0xc2: sprintf(t, "rep #$%0.2x ", op8); break;
case 0xc3: sprintf(t, "cmp $%0.2x,s [$%0.6x]", op8, decode(OPTYPE_SR, op8)); break;
case 0xc4: sprintf(t, "cpy $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0xc5: sprintf(t, "cmp $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0xc6: sprintf(t, "dec $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0xc7: sprintf(t, "cmp [$%0.2x] [$%0.6x]", op8, decode(OPTYPE_ILDP, op8)); break;
case 0xc8: sprintf(t, "iny "); break;
case 0xc9: if(a8)sprintf(t, "cmp #$%0.2x ", op8);
else sprintf(t, "cmp #$%0.4x ", op16); break;
case 0xca: sprintf(t, "dex "); break;
case 0xcb: sprintf(t, "wai "); break;
case 0xcc: sprintf(t, "cpy $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0xcd: sprintf(t, "cmp $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0xce: sprintf(t, "dec $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0xcf: sprintf(t, "cmp $%0.6x [$%0.6x]", op24, decode(OPTYPE_LONG, op24)); break;
case 0xd0: sprintf(t, "bne $%0.4x [$%0.6x]", uint16(decode(OPTYPE_RELB, op8)), decode(OPTYPE_RELB, op8)); break;
case 0xd1: sprintf(t, "cmp ($%0.2x),y [$%0.6x]", op8, decode(OPTYPE_IDPY, op8)); break;
case 0xd2: sprintf(t, "cmp ($%0.2x) [$%0.6x]", op8, decode(OPTYPE_IDP, op8)); break;
case 0xd3: sprintf(t, "cmp ($%0.2x,s),y [$%0.6x]", op8, decode(OPTYPE_ISRY, op8)); break;
case 0xd4: sprintf(t, "pei ($%0.2x) [$%0.6x]", op8, decode(OPTYPE_IDP, op8)); break;
case 0xd5: sprintf(t, "cmp $%0.2x,x [$%0.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0xd6: sprintf(t, "dec $%0.2x,x [$%0.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0xd7: sprintf(t, "cmp [$%0.2x],y [$%0.6x]", op8, decode(OPTYPE_ILDPY, op8)); break;
case 0xd8: sprintf(t, "cld "); break;
case 0xd9: sprintf(t, "cmp $%0.4x,y [$%0.6x]", op16, decode(OPTYPE_ADDRY, op16)); break;
case 0xda: sprintf(t, "phx "); break;
case 0xdb: sprintf(t, "stp "); break;
case 0xdc: sprintf(t, "jmp [$%0.4x] [$%0.6x]", op16, decode(OPTYPE_ILADDR, op16)); break;
case 0xdd: sprintf(t, "cmp $%0.4x,x [$%0.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0xde: sprintf(t, "dec $%0.4x,x [$%0.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0xdf: sprintf(t, "cmp $%0.6x,x [$%0.6x]", op24, decode(OPTYPE_LONGX, op24)); break;
case 0xe0: if(x8)sprintf(t, "cpx #$%0.2x ", op8);
else sprintf(t, "cpx #$%0.4x ", op16); break;
case 0xe1: sprintf(t, "sbc ($%0.2x,x) [$%0.6x]", op8, decode(OPTYPE_IDPX, op8)); break;
case 0xe2: sprintf(t, "sep #$%0.2x ", op8); break;
case 0xe3: sprintf(t, "sbc $%0.2x,s [$%0.6x]", op8, decode(OPTYPE_SR, op8)); break;
case 0xe4: sprintf(t, "cpx $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0xe5: sprintf(t, "sbc $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0xe6: sprintf(t, "inc $%0.2x [$%0.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0xe7: sprintf(t, "sbc [$%0.2x] [$%0.6x]", op8, decode(OPTYPE_ILDP, op8)); break;
case 0xe8: sprintf(t, "inx "); break;
case 0xe9: if(a8)sprintf(t, "sbc #$%0.2x ", op8);
else sprintf(t, "sbc #$%0.4x ", op16); break;
case 0xea: sprintf(t, "nop "); break;
case 0xeb: sprintf(t, "xba "); break;
case 0xec: sprintf(t, "cpx $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0xed: sprintf(t, "sbc $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0xee: sprintf(t, "inc $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0xef: sprintf(t, "sbc $%0.6x [$%0.6x]", op24, decode(OPTYPE_LONG, op24)); break;
case 0xf0: sprintf(t, "beq $%0.4x [$%0.6x]", uint16(decode(OPTYPE_RELB, op8)), decode(OPTYPE_RELB, op8)); break;
case 0xf1: sprintf(t, "sbc ($%0.2x),y [$%0.6x]", op8, decode(OPTYPE_IDPY, op8)); break;
case 0xf2: sprintf(t, "sbc ($%0.2x) [$%0.6x]", op8, decode(OPTYPE_IDP, op8)); break;
case 0xf3: sprintf(t, "sbc ($%0.2x,s),y [$%0.6x]", op8, decode(OPTYPE_ISRY, op8)); break;
case 0xf4: sprintf(t, "pea $%0.4x [$%0.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0xf5: sprintf(t, "sbc $%0.2x,x [$%0.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0xf6: sprintf(t, "inc $%0.2x,x [$%0.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0xf7: sprintf(t, "sbc [$%0.2x],y [$%0.6x]", op8, decode(OPTYPE_ILDPY, op8)); break;
case 0xf8: sprintf(t, "sed "); break;
case 0xf9: sprintf(t, "sbc $%0.4x,y [$%0.6x]", op16, decode(OPTYPE_ADDRY, op16)); break;
case 0xfa: sprintf(t, "plx "); break;
case 0xfb: sprintf(t, "xce "); break;
case 0xfc: sprintf(t, "jsr ($%0.4x,x) [$%0.6x]", op16, decode(OPTYPE_IADDRX, op16)); break;
case 0xfd: sprintf(t, "sbc $%0.4x,x [$%0.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0xfe: sprintf(t, "inc $%0.4x,x [$%0.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0xff: sprintf(t, "sbc $%0.6x,x [$%0.6x]", op24, decode(OPTYPE_LONGX, op24)); break;
case 0x00: sprintf(t, "brk #$%.2x ", op8); break;
case 0x01: sprintf(t, "ora ($%.2x,x) [$%.6x]", op8, decode(OPTYPE_IDPX, op8)); break;
case 0x02: sprintf(t, "cop #$%.2x ", op8); break;
case 0x03: sprintf(t, "ora $%.2x,s [$%.6x]", op8, decode(OPTYPE_SR, op8)); break;
case 0x04: sprintf(t, "tsb $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x05: sprintf(t, "ora $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x06: sprintf(t, "asl $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x07: sprintf(t, "ora [$%.2x] [$%.6x]", op8, decode(OPTYPE_ILDP, op8)); break;
case 0x08: sprintf(t, "php "); break;
case 0x09: if(a8)sprintf(t, "ora #$%.2x ", op8);
else sprintf(t, "ora #$%.4x ", op16); break;
case 0x0a: sprintf(t, "asl a "); break;
case 0x0b: sprintf(t, "phd "); break;
case 0x0c: sprintf(t, "tsb $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x0d: sprintf(t, "ora $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x0e: sprintf(t, "asl $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x0f: sprintf(t, "ora $%.6x [$%.6x]", op24, decode(OPTYPE_LONG, op24)); break;
case 0x10: sprintf(t, "bpl $%.4x [$%.6x]", uint16(decode(OPTYPE_RELB, op8)), decode(OPTYPE_RELB, op8)); break;
case 0x11: sprintf(t, "ora ($%.2x),y [$%.6x]", op8, decode(OPTYPE_IDPY, op8)); break;
case 0x12: sprintf(t, "ora ($%.2x) [$%.6x]", op8, decode(OPTYPE_IDP, op8)); break;
case 0x13: sprintf(t, "ora ($%.2x,s),y [$%.6x]", op8, decode(OPTYPE_ISRY, op8)); break;
case 0x14: sprintf(t, "trb $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x15: sprintf(t, "ora $%.2x,x [$%.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x16: sprintf(t, "asl $%.2x,x [$%.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x17: sprintf(t, "ora [$%.2x],y [$%.6x]", op8, decode(OPTYPE_ILDPY, op8)); break;
case 0x18: sprintf(t, "clc "); break;
case 0x19: sprintf(t, "ora $%.4x,y [$%.6x]", op16, decode(OPTYPE_ADDRY, op16)); break;
case 0x1a: sprintf(t, "inc "); break;
case 0x1b: sprintf(t, "tcs "); break;
case 0x1c: sprintf(t, "trb $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x1d: sprintf(t, "ora $%.4x,x [$%.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x1e: sprintf(t, "asl $%.4x,x [$%.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x1f: sprintf(t, "ora $%.6x,x [$%.6x]", op24, decode(OPTYPE_LONGX, op24)); break;
case 0x20: sprintf(t, "jsr $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR_PC, op16)); break;
case 0x21: sprintf(t, "and ($%.2x,x) [$%.6x]", op8, decode(OPTYPE_IDPX, op8)); break;
case 0x22: sprintf(t, "jsl $%.6x [$%.6x]", op24, decode(OPTYPE_LONG, op24)); break;
case 0x23: sprintf(t, "and $%.2x,s [$%.6x]", op8, decode(OPTYPE_SR, op8)); break;
case 0x24: sprintf(t, "bit $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x25: sprintf(t, "and $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x26: sprintf(t, "rol $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x27: sprintf(t, "and [$%.2x] [$%.6x]", op8, decode(OPTYPE_ILDP, op8)); break;
case 0x28: sprintf(t, "plp "); break;
case 0x29: if(a8)sprintf(t, "and #$%.2x ", op8);
else sprintf(t, "and #$%.4x ", op16); break;
case 0x2a: sprintf(t, "rol a "); break;
case 0x2b: sprintf(t, "pld "); break;
case 0x2c: sprintf(t, "bit $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x2d: sprintf(t, "and $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x2e: sprintf(t, "rol $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x2f: sprintf(t, "and $%.6x [$%.6x]", op24, decode(OPTYPE_LONG, op24)); break;
case 0x30: sprintf(t, "bmi $%.4x [$%.6x]", uint16(decode(OPTYPE_RELB, op8)), decode(OPTYPE_RELB, op8)); break;
case 0x31: sprintf(t, "and ($%.2x),y [$%.6x]", op8, decode(OPTYPE_IDPY, op8)); break;
case 0x32: sprintf(t, "and ($%.2x) [$%.6x]", op8, decode(OPTYPE_IDP, op8)); break;
case 0x33: sprintf(t, "and ($%.2x,s),y [$%.6x]", op8, decode(OPTYPE_ISRY, op8)); break;
case 0x34: sprintf(t, "bit $%.2x,x [$%.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x35: sprintf(t, "and $%.2x,x [$%.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x36: sprintf(t, "rol $%.2x,x [$%.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x37: sprintf(t, "and [$%.2x],y [$%.6x]", op8, decode(OPTYPE_ILDPY, op8)); break;
case 0x38: sprintf(t, "sec "); break;
case 0x39: sprintf(t, "and $%.4x,y [$%.6x]", op16, decode(OPTYPE_ADDRY, op16)); break;
case 0x3a: sprintf(t, "dec "); break;
case 0x3b: sprintf(t, "tsc "); break;
case 0x3c: sprintf(t, "bit $%.4x,x [$%.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x3d: sprintf(t, "and $%.4x,x [$%.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x3e: sprintf(t, "rol $%.4x,x [$%.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x3f: sprintf(t, "and $%.6x,x [$%.6x]", op24, decode(OPTYPE_LONGX, op24)); break;
case 0x40: sprintf(t, "rti "); break;
case 0x41: sprintf(t, "eor ($%.2x,x) [$%.6x]", op8, decode(OPTYPE_IDPX, op8)); break;
case 0x42: sprintf(t, "wdm "); break;
case 0x43: sprintf(t, "eor $%.2x,s [$%.6x]", op8, decode(OPTYPE_SR, op8)); break;
case 0x44: sprintf(t, "mvp $%.2x,$%.2x ", op1, op8); break;
case 0x45: sprintf(t, "eor $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x46: sprintf(t, "lsr $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x47: sprintf(t, "eor [$%.2x] [$%.6x]", op8, decode(OPTYPE_ILDP, op8)); break;
case 0x48: sprintf(t, "pha "); break;
case 0x49: if(a8)sprintf(t, "eor #$%.2x ", op8);
else sprintf(t, "eor #$%.4x ", op16); break;
case 0x4a: sprintf(t, "lsr a "); break;
case 0x4b: sprintf(t, "phk "); break;
case 0x4c: sprintf(t, "jmp $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR_PC, op16)); break;
case 0x4d: sprintf(t, "eor $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x4e: sprintf(t, "lsr $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x4f: sprintf(t, "eor $%.6x [$%.6x]", op24, decode(OPTYPE_LONG, op24)); break;
case 0x50: sprintf(t, "bvc $%.4x [$%.6x]", uint16(decode(OPTYPE_RELB, op8)), decode(OPTYPE_RELB, op8)); break;
case 0x51: sprintf(t, "eor ($%.2x),y [$%.6x]", op8, decode(OPTYPE_IDPY, op8)); break;
case 0x52: sprintf(t, "eor ($%.2x) [$%.6x]", op8, decode(OPTYPE_IDP, op8)); break;
case 0x53: sprintf(t, "eor ($%.2x,s),y [$%.6x]", op8, decode(OPTYPE_ISRY, op8)); break;
case 0x54: sprintf(t, "mvn $%.2x,$%.2x ", op1, op8); break;
case 0x55: sprintf(t, "eor $%.2x,x [$%.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x56: sprintf(t, "lsr $%.2x,x [$%.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x57: sprintf(t, "eor [$%.2x],y [$%.6x]", op8, decode(OPTYPE_ILDPY, op8)); break;
case 0x58: sprintf(t, "cli "); break;
case 0x59: sprintf(t, "eor $%.4x,y [$%.6x]", op16, decode(OPTYPE_ADDRY, op16)); break;
case 0x5a: sprintf(t, "phy "); break;
case 0x5b: sprintf(t, "tcd "); break;
case 0x5c: sprintf(t, "jml $%.6x [$%.6x]", op24, decode(OPTYPE_LONG, op24)); break;
case 0x5d: sprintf(t, "eor $%.4x,x [$%.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x5e: sprintf(t, "lsr $%.4x,x [$%.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x5f: sprintf(t, "eor $%.6x,x [$%.6x]", op24, decode(OPTYPE_LONGX, op24)); break;
case 0x60: sprintf(t, "rts "); break;
case 0x61: sprintf(t, "adc ($%.2x,x) [$%.6x]", op8, decode(OPTYPE_IDPX, op8)); break;
case 0x62: sprintf(t, "per $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x63: sprintf(t, "adc $%.2x,s [$%.6x]", op8, decode(OPTYPE_SR, op8)); break;
case 0x64: sprintf(t, "stz $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x65: sprintf(t, "adc $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x66: sprintf(t, "ror $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x67: sprintf(t, "adc [$%.2x] [$%.6x]", op8, decode(OPTYPE_ILDP, op8)); break;
case 0x68: sprintf(t, "pla "); break;
case 0x69: if(a8)sprintf(t, "adc #$%.2x ", op8);
else sprintf(t, "adc #$%.4x ", op16); break;
case 0x6a: sprintf(t, "ror a "); break;
case 0x6b: sprintf(t, "rtl "); break;
case 0x6c: sprintf(t, "jmp ($%.4x) [$%.6x]", op16, decode(OPTYPE_IADDR_PC, op16)); break;
case 0x6d: sprintf(t, "adc $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x6e: sprintf(t, "ror $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x6f: sprintf(t, "adc $%.6x [$%.6x]", op24, decode(OPTYPE_LONG, op24)); break;
case 0x70: sprintf(t, "bvs $%.4x [$%.6x]", uint16(decode(OPTYPE_RELB, op8)), decode(OPTYPE_RELB, op8)); break;
case 0x71: sprintf(t, "adc ($%.2x),y [$%.6x]", op8, decode(OPTYPE_IDPY, op8)); break;
case 0x72: sprintf(t, "adc ($%.2x) [$%.6x]", op8, decode(OPTYPE_IDP, op8)); break;
case 0x73: sprintf(t, "adc ($%.2x,s),y [$%.6x]", op8, decode(OPTYPE_ISRY, op8)); break;
case 0x74: sprintf(t, "stz $%.2x,x [$%.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x75: sprintf(t, "adc $%.2x,x [$%.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x76: sprintf(t, "ror $%.2x,x [$%.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x77: sprintf(t, "adc [$%.2x],y [$%.6x]", op8, decode(OPTYPE_ILDPY, op8)); break;
case 0x78: sprintf(t, "sei "); break;
case 0x79: sprintf(t, "adc $%.4x,y [$%.6x]", op16, decode(OPTYPE_ADDRY, op16)); break;
case 0x7a: sprintf(t, "ply "); break;
case 0x7b: sprintf(t, "tdc "); break;
case 0x7c: sprintf(t, "jmp ($%.4x,x) [$%.6x]", op16, decode(OPTYPE_IADDRX, op16)); break;
case 0x7d: sprintf(t, "adc $%.4x,x [$%.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x7e: sprintf(t, "ror $%.4x,x [$%.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x7f: sprintf(t, "adc $%.6x,x [$%.6x]", op24, decode(OPTYPE_LONGX, op24)); break;
case 0x80: sprintf(t, "bra $%.4x [$%.6x]", uint16(decode(OPTYPE_RELB, op8)), decode(OPTYPE_RELB, op8)); break;
case 0x81: sprintf(t, "sta ($%.2x,x) [$%.6x]", op8, decode(OPTYPE_IDPX, op8)); break;
case 0x82: sprintf(t, "brl $%.4x [$%.6x]", uint16(decode(OPTYPE_RELW, op16)), decode(OPTYPE_RELW, op16)); break;
case 0x83: sprintf(t, "sta $%.2x,s [$%.6x]", op8, decode(OPTYPE_SR, op8)); break;
case 0x84: sprintf(t, "sty $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x85: sprintf(t, "sta $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x86: sprintf(t, "stx $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0x87: sprintf(t, "sta [$%.2x] [$%.6x]", op8, decode(OPTYPE_ILDP, op8)); break;
case 0x88: sprintf(t, "dey "); break;
case 0x89: if(a8)sprintf(t, "bit #$%.2x ", op8);
else sprintf(t, "bit #$%.4x ", op16); break;
case 0x8a: sprintf(t, "txa "); break;
case 0x8b: sprintf(t, "phb "); break;
case 0x8c: sprintf(t, "sty $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x8d: sprintf(t, "sta $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x8e: sprintf(t, "stx $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x8f: sprintf(t, "sta $%.6x [$%.6x]", op24, decode(OPTYPE_LONG, op24)); break;
case 0x90: sprintf(t, "bcc $%.4x [$%.6x]", uint16(decode(OPTYPE_RELB, op8)), decode(OPTYPE_RELB, op8)); break;
case 0x91: sprintf(t, "sta ($%.2x),y [$%.6x]", op8, decode(OPTYPE_IDPY, op8)); break;
case 0x92: sprintf(t, "sta ($%.2x) [$%.6x]", op8, decode(OPTYPE_IDP, op8)); break;
case 0x93: sprintf(t, "sta ($%.2x,s),y [$%.6x]", op8, decode(OPTYPE_ISRY, op8)); break;
case 0x94: sprintf(t, "sty $%.2x,x [$%.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x95: sprintf(t, "sta $%.2x,x [$%.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0x96: sprintf(t, "stx $%.2x,y [$%.6x]", op8, decode(OPTYPE_DPY, op8)); break;
case 0x97: sprintf(t, "sta [$%.2x],y [$%.6x]", op8, decode(OPTYPE_ILDPY, op8)); break;
case 0x98: sprintf(t, "tya "); break;
case 0x99: sprintf(t, "sta $%.4x,y [$%.6x]", op16, decode(OPTYPE_ADDRY, op16)); break;
case 0x9a: sprintf(t, "txs "); break;
case 0x9b: sprintf(t, "txy "); break;
case 0x9c: sprintf(t, "stz $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0x9d: sprintf(t, "sta $%.4x,x [$%.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x9e: sprintf(t, "stz $%.4x,x [$%.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0x9f: sprintf(t, "sta $%.6x,x [$%.6x]", op24, decode(OPTYPE_LONGX, op24)); break;
case 0xa0: if(x8)sprintf(t, "ldy #$%.2x ", op8);
else sprintf(t, "ldy #$%.4x ", op16); break;
case 0xa1: sprintf(t, "lda ($%.2x,x) [$%.6x]", op8, decode(OPTYPE_IDPX, op8)); break;
case 0xa2: if(x8)sprintf(t, "ldx #$%.2x ", op8);
else sprintf(t, "ldx #$%.4x ", op16); break;
case 0xa3: sprintf(t, "lda $%.2x,s [$%.6x]", op8, decode(OPTYPE_SR, op8)); break;
case 0xa4: sprintf(t, "ldy $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0xa5: sprintf(t, "lda $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0xa6: sprintf(t, "ldx $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0xa7: sprintf(t, "lda [$%.2x] [$%.6x]", op8, decode(OPTYPE_ILDP, op8)); break;
case 0xa8: sprintf(t, "tay "); break;
case 0xa9: if(a8)sprintf(t, "lda #$%.2x ", op8);
else sprintf(t, "lda #$%.4x ", op16); break;
case 0xaa: sprintf(t, "tax "); break;
case 0xab: sprintf(t, "plb "); break;
case 0xac: sprintf(t, "ldy $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0xad: sprintf(t, "lda $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0xae: sprintf(t, "ldx $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0xaf: sprintf(t, "lda $%.6x [$%.6x]", op24, decode(OPTYPE_LONG, op24)); break;
case 0xb0: sprintf(t, "bcs $%.4x [$%.6x]", uint16(decode(OPTYPE_RELB, op8)), decode(OPTYPE_RELB, op8)); break;
case 0xb1: sprintf(t, "lda ($%.2x),y [$%.6x]", op8, decode(OPTYPE_IDPY, op8)); break;
case 0xb2: sprintf(t, "lda ($%.2x) [$%.6x]", op8, decode(OPTYPE_IDP, op8)); break;
case 0xb3: sprintf(t, "lda ($%.2x,s),y [$%.6x]", op8, decode(OPTYPE_ISRY, op8)); break;
case 0xb4: sprintf(t, "ldy $%.2x,x [$%.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0xb5: sprintf(t, "lda $%.2x,x [$%.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0xb6: sprintf(t, "ldx $%.2x,y [$%.6x]", op8, decode(OPTYPE_DPY, op8)); break;
case 0xb7: sprintf(t, "lda [$%.2x],y [$%.6x]", op8, decode(OPTYPE_ILDPY, op8)); break;
case 0xb8: sprintf(t, "clv "); break;
case 0xb9: sprintf(t, "lda $%.4x,y [$%.6x]", op16, decode(OPTYPE_ADDRY, op16)); break;
case 0xba: sprintf(t, "tsx "); break;
case 0xbb: sprintf(t, "tyx "); break;
case 0xbc: sprintf(t, "ldy $%.4x,x [$%.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0xbd: sprintf(t, "lda $%.4x,x [$%.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0xbe: sprintf(t, "ldx $%.4x,y [$%.6x]", op16, decode(OPTYPE_ADDRY, op16)); break;
case 0xbf: sprintf(t, "lda $%.6x,x [$%.6x]", op24, decode(OPTYPE_LONGX, op24)); break;
case 0xc0: if(x8)sprintf(t, "cpy #$%.2x ", op8);
else sprintf(t, "cpy #$%.4x ", op16); break;
case 0xc1: sprintf(t, "cmp ($%.2x,x) [$%.6x]", op8, decode(OPTYPE_IDPX, op8)); break;
case 0xc2: sprintf(t, "rep #$%.2x ", op8); break;
case 0xc3: sprintf(t, "cmp $%.2x,s [$%.6x]", op8, decode(OPTYPE_SR, op8)); break;
case 0xc4: sprintf(t, "cpy $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0xc5: sprintf(t, "cmp $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0xc6: sprintf(t, "dec $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0xc7: sprintf(t, "cmp [$%.2x] [$%.6x]", op8, decode(OPTYPE_ILDP, op8)); break;
case 0xc8: sprintf(t, "iny "); break;
case 0xc9: if(a8)sprintf(t, "cmp #$%.2x ", op8);
else sprintf(t, "cmp #$%.4x ", op16); break;
case 0xca: sprintf(t, "dex "); break;
case 0xcb: sprintf(t, "wai "); break;
case 0xcc: sprintf(t, "cpy $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0xcd: sprintf(t, "cmp $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0xce: sprintf(t, "dec $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0xcf: sprintf(t, "cmp $%.6x [$%.6x]", op24, decode(OPTYPE_LONG, op24)); break;
case 0xd0: sprintf(t, "bne $%.4x [$%.6x]", uint16(decode(OPTYPE_RELB, op8)), decode(OPTYPE_RELB, op8)); break;
case 0xd1: sprintf(t, "cmp ($%.2x),y [$%.6x]", op8, decode(OPTYPE_IDPY, op8)); break;
case 0xd2: sprintf(t, "cmp ($%.2x) [$%.6x]", op8, decode(OPTYPE_IDP, op8)); break;
case 0xd3: sprintf(t, "cmp ($%.2x,s),y [$%.6x]", op8, decode(OPTYPE_ISRY, op8)); break;
case 0xd4: sprintf(t, "pei ($%.2x) [$%.6x]", op8, decode(OPTYPE_IDP, op8)); break;
case 0xd5: sprintf(t, "cmp $%.2x,x [$%.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0xd6: sprintf(t, "dec $%.2x,x [$%.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0xd7: sprintf(t, "cmp [$%.2x],y [$%.6x]", op8, decode(OPTYPE_ILDPY, op8)); break;
case 0xd8: sprintf(t, "cld "); break;
case 0xd9: sprintf(t, "cmp $%.4x,y [$%.6x]", op16, decode(OPTYPE_ADDRY, op16)); break;
case 0xda: sprintf(t, "phx "); break;
case 0xdb: sprintf(t, "stp "); break;
case 0xdc: sprintf(t, "jmp [$%.4x] [$%.6x]", op16, decode(OPTYPE_ILADDR, op16)); break;
case 0xdd: sprintf(t, "cmp $%.4x,x [$%.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0xde: sprintf(t, "dec $%.4x,x [$%.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0xdf: sprintf(t, "cmp $%.6x,x [$%.6x]", op24, decode(OPTYPE_LONGX, op24)); break;
case 0xe0: if(x8)sprintf(t, "cpx #$%.2x ", op8);
else sprintf(t, "cpx #$%.4x ", op16); break;
case 0xe1: sprintf(t, "sbc ($%.2x,x) [$%.6x]", op8, decode(OPTYPE_IDPX, op8)); break;
case 0xe2: sprintf(t, "sep #$%.2x ", op8); break;
case 0xe3: sprintf(t, "sbc $%.2x,s [$%.6x]", op8, decode(OPTYPE_SR, op8)); break;
case 0xe4: sprintf(t, "cpx $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0xe5: sprintf(t, "sbc $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0xe6: sprintf(t, "inc $%.2x [$%.6x]", op8, decode(OPTYPE_DP, op8)); break;
case 0xe7: sprintf(t, "sbc [$%.2x] [$%.6x]", op8, decode(OPTYPE_ILDP, op8)); break;
case 0xe8: sprintf(t, "inx "); break;
case 0xe9: if(a8)sprintf(t, "sbc #$%.2x ", op8);
else sprintf(t, "sbc #$%.4x ", op16); break;
case 0xea: sprintf(t, "nop "); break;
case 0xeb: sprintf(t, "xba "); break;
case 0xec: sprintf(t, "cpx $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0xed: sprintf(t, "sbc $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0xee: sprintf(t, "inc $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0xef: sprintf(t, "sbc $%.6x [$%.6x]", op24, decode(OPTYPE_LONG, op24)); break;
case 0xf0: sprintf(t, "beq $%.4x [$%.6x]", uint16(decode(OPTYPE_RELB, op8)), decode(OPTYPE_RELB, op8)); break;
case 0xf1: sprintf(t, "sbc ($%.2x),y [$%.6x]", op8, decode(OPTYPE_IDPY, op8)); break;
case 0xf2: sprintf(t, "sbc ($%.2x) [$%.6x]", op8, decode(OPTYPE_IDP, op8)); break;
case 0xf3: sprintf(t, "sbc ($%.2x,s),y [$%.6x]", op8, decode(OPTYPE_ISRY, op8)); break;
case 0xf4: sprintf(t, "pea $%.4x [$%.6x]", op16, decode(OPTYPE_ADDR, op16)); break;
case 0xf5: sprintf(t, "sbc $%.2x,x [$%.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0xf6: sprintf(t, "inc $%.2x,x [$%.6x]", op8, decode(OPTYPE_DPX, op8)); break;
case 0xf7: sprintf(t, "sbc [$%.2x],y [$%.6x]", op8, decode(OPTYPE_ILDPY, op8)); break;
case 0xf8: sprintf(t, "sed "); break;
case 0xf9: sprintf(t, "sbc $%.4x,y [$%.6x]", op16, decode(OPTYPE_ADDRY, op16)); break;
case 0xfa: sprintf(t, "plx "); break;
case 0xfb: sprintf(t, "xce "); break;
case 0xfc: sprintf(t, "jsr ($%.4x,x) [$%.6x]", op16, decode(OPTYPE_IADDRX, op16)); break;
case 0xfd: sprintf(t, "sbc $%.4x,x [$%.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0xfe: sprintf(t, "inc $%.4x,x [$%.6x]", op16, decode(OPTYPE_ADDRX, op16)); break;
case 0xff: sprintf(t, "sbc $%.6x,x [$%.6x]", op24, decode(OPTYPE_LONGX, op24)); break;
}
#undef op8
#undef op16
#undef op24
#undef a8
#undef x8
#undef op8
#undef op16
#undef op24
#undef a8
#undef x8
strcat(s, t);
strcat(s, " ");
sprintf(t, "A:%0.4x X:%0.4x Y:%0.4x S:%0.4x D:%0.4x DB:%0.2x ",
sprintf(t, "A:%.4x X:%.4x Y:%.4x S:%.4x D:%.4x DB:%.2x ",
regs.a.w, regs.x.w, regs.y.w, regs.s.w, regs.d.w, regs.db);
strcat(s, t);
if(regs.e) {
sprintf(t, "%c%c%c%c%c%c%c%c",
(regs.p.n) ? 'N' : 'n', (regs.p.v) ? 'V' : 'v',
(regs.p.m) ? '1' : '0', (regs.p.x) ? 'B' : 'b',
(regs.p.d) ? 'D' : 'd', (regs.p.i) ? 'I' : 'i',
(regs.p.z) ? 'Z' : 'z', (regs.p.c) ? 'C' : 'c');
regs.p.n ? 'N' : 'n', regs.p.v ? 'V' : 'v',
regs.p.m ? '1' : '0', regs.p.x ? 'B' : 'b',
regs.p.d ? 'D' : 'd', regs.p.i ? 'I' : 'i',
regs.p.z ? 'Z' : 'z', regs.p.c ? 'C' : 'c');
} else {
sprintf(t, "%c%c%c%c%c%c%c%c",
(regs.p.n) ? 'N' : 'n', (regs.p.v) ? 'V' : 'v',
(regs.p.m) ? 'M' : 'm', (regs.p.x) ? 'X' : 'x',
(regs.p.d) ? 'D' : 'd', (regs.p.i) ? 'I' : 'i',
(regs.p.z) ? 'Z' : 'z', (regs.p.c) ? 'C' : 'c');
regs.p.n ? 'N' : 'n', regs.p.v ? 'V' : 'v',
regs.p.m ? 'M' : 'm', regs.p.x ? 'X' : 'x',
regs.p.d ? 'D' : 'd', regs.p.i ? 'I' : 'i',
regs.p.z ? 'Z' : 'z', regs.p.c ? 'C' : 'c');
}
strcat(s, t);
strcat(s, " ");
sprintf(t, "V:%3d H:%4d", vcounter(), hcounter());
sprintf(t, "V:%3d H:%4d", ppu.vcounter(), ppu.hcounter());
strcat(s, t);
}
/*****
* opcode_length() retrieves the length of the next opcode
* to be executed. It is used by the debugger to step over,
* disable and proceed cpu opcodes.
*
* 5 and 6 are special cases, 5 is used for #consts based on
* the A register size, 6 for the X/Y register size. the
* rest are literal sizes. There's no need to test for
* emulation mode, as regs.p.m/regs.p.x should *always* be
* set in emulation mode.
*****/
//opcode_length() retrieves the length of the next opcode
//to be executed. It is used by the debugger to step over,
//disable and proceed cpu opcodes.
//
//5 and 6 are special cases, 5 is used for #consts based on
//the A register size, 6 for the X/Y register size. the
//rest are literal sizes. There's no need to test for
//emulation mode, as regs.p.m/regs.p.x should *always* be
//set in emulation mode.
uint8 CPU::opcode_length() {
uint8 op, len;
static uint8 op_len_tbl[256] = {
//0,1,2,3, 4,5,6,7, 8,9,a,b, c,d,e,f
uint8 op, len;
static uint8 op_len_tbl[256] = {
//0,1,2,3, 4,5,6,7, 8,9,a,b, c,d,e,f
2,2,2,2, 2,2,2,2, 1,5,1,1, 3,3,3,4, //0x0n
2,2,2,2, 2,2,2,2, 1,3,1,1, 3,3,3,4, //0x1n
3,2,4,2, 2,2,2,2, 1,5,1,1, 3,3,3,4, //0x2n
2,2,2,2, 2,2,2,2, 1,3,1,1, 3,3,3,4, //0x3n
2,2,2,2, 2,2,2,2, 1,5,1,1, 3,3,3,4, //0x0n
2,2,2,2, 2,2,2,2, 1,3,1,1, 3,3,3,4, //0x1n
3,2,4,2, 2,2,2,2, 1,5,1,1, 3,3,3,4, //0x2n
2,2,2,2, 2,2,2,2, 1,3,1,1, 3,3,3,4, //0x3n
1,2,2,2, 3,2,2,2, 1,5,1,1, 3,3,3,4, //0x4n
2,2,2,2, 3,2,2,2, 1,3,1,1, 4,3,3,4, //0x5n
1,2,3,2, 2,2,2,2, 1,5,1,1, 3,3,3,4, //0x6n
2,2,2,2, 2,2,2,2, 1,3,1,1, 3,3,3,4, //0x7n
1,2,2,2, 3,2,2,2, 1,5,1,1, 3,3,3,4, //0x4n
2,2,2,2, 3,2,2,2, 1,3,1,1, 4,3,3,4, //0x5n
1,2,3,2, 2,2,2,2, 1,5,1,1, 3,3,3,4, //0x6n
2,2,2,2, 2,2,2,2, 1,3,1,1, 3,3,3,4, //0x7n
2,2,3,2, 2,2,2,2, 1,5,1,1, 3,3,3,4, //0x8n
2,2,2,2, 2,2,2,2, 1,3,1,1, 3,3,3,4, //0x9n
6,2,6,2, 2,2,2,2, 1,5,1,1, 3,3,3,4, //0xan
2,2,2,2, 2,2,2,2, 1,3,1,1, 3,3,3,4, //0xbn
2,2,3,2, 2,2,2,2, 1,5,1,1, 3,3,3,4, //0x8n
2,2,2,2, 2,2,2,2, 1,3,1,1, 3,3,3,4, //0x9n
6,2,6,2, 2,2,2,2, 1,5,1,1, 3,3,3,4, //0xan
2,2,2,2, 2,2,2,2, 1,3,1,1, 3,3,3,4, //0xbn
6,2,2,2, 2,2,2,2, 1,5,1,1, 3,3,3,4, //0xcn
2,2,2,2, 2,2,2,2, 1,3,1,1, 3,3,3,4, //0xdn
6,2,2,2, 2,2,2,2, 1,5,1,1, 3,3,3,4, //0xen
2,2,2,2, 3,2,2,2, 1,3,1,1, 3,3,3,4 //0xfn
};
6,2,2,2, 2,2,2,2, 1,5,1,1, 3,3,3,4, //0xcn
2,2,2,2, 2,2,2,2, 1,3,1,1, 3,3,3,4, //0xdn
6,2,2,2, 2,2,2,2, 1,5,1,1, 3,3,3,4, //0xen
2,2,2,2, 3,2,2,2, 1,3,1,1, 3,3,3,4 //0xfn
};
if(in_opcode() == true) {
return 0;
}
op = dreadb(regs.pc.d);
len = op_len_tbl[op];
if(len == 5)return (regs.e || regs.p.m) ? 2 : 3;
if(len == 6)return (regs.e || regs.p.x) ? 2 : 3;
if(len == 5) return (regs.e || regs.p.m) ? 2 : 3;
if(len == 6) return (regs.e || regs.p.x) ? 2 : 3;
return len;
}
#endif //ifdef CPU_CPP
#endif //ifdef CPU_CPP

View File

@@ -2,15 +2,22 @@
#include "opfn.cpp"
void sCPU::enter() { loop:
if(event.irq) {
event.irq = false;
if(status.nmi_pending == true) {
void sCPU::enter() {
initialize:
//initial latch values for $213c/$213d
//[x]0035 : [y]0000 (53.0 -> 212) [lda $2137]
//[x]0038 : [y]0000 (56.5 -> 226) [nop : lda $2137]
add_clocks(186);
loop:
if(status.interrupt_pending) {
status.interrupt_pending = false;
if(status.nmi_pending) {
status.nmi_pending = false;
event.irq_vector = (regs.e == false) ? 0xffea : 0xfffa;
} else if(status.irq_pending == true) {
status.interrupt_vector = (regs.e == false ? 0xffea : 0xfffa);
} else if(status.irq_pending) {
status.irq_pending = false;
event.irq_vector = (regs.e == false) ? 0xffee : 0xfffe;
status.interrupt_vector = (regs.e == false ? 0xffee : 0xfffe);
}
op_irq();
}
@@ -33,15 +40,15 @@ void sCPU::enter() { loop:
void sCPU::op_irq() {
op_read(regs.pc.d);
op_io();
if(!regs.e)op_writestack(regs.pc.b);
if(!regs.e) op_writestack(regs.pc.b);
op_writestack(regs.pc.h);
op_writestack(regs.pc.l);
op_writestack(regs.e ? (regs.p & ~0x10) : regs.p);
rd.l = op_read(event.irq_vector + 0);
rd.l = op_read(status.interrupt_vector + 0);
regs.pc.b = 0x00;
regs.p.i = 1;
regs.p.d = 0;
rd.h = op_read(event.irq_vector + 1);
rd.h = op_read(status.interrupt_vector + 1);
regs.pc.w = rd.w;
}
@@ -50,11 +57,11 @@ void sCPU::op_irq() {
//this affects the following opcodes:
// clc, cld, cli, clv, sec, sed, sei,
// tax, tay, txa, txy, tya, tyx,
// tcd, tcs, tdc, tsc, tsx, tcs,
// tcd, tcs, tdc, tsc, tsx, txs,
// inc, inx, iny, dec, dex, dey,
// asl, lsr, rol, ror, nop, xce.
alwaysinline void sCPU::op_io_irq() {
if(event.irq) {
if(status.interrupt_pending) {
//IRQ pending, modify I/O cycle to bus read cycle, do not increment PC
op_read(regs.pc.d);
} else {
@@ -80,4 +87,4 @@ alwaysinline void sCPU::op_io_cond6(uint16 addr) {
}
}
#endif //ifdef SCPU_CPP
#endif

View File

@@ -1,4 +1,4 @@
CPUReg24 aa, rd;
reg24_t aa, rd;
uint8_t dp, sp;
void op_irq();

View File

@@ -62,9 +62,9 @@ stp(0xdb) {
}
wai(0xcb) {
//last_cycle() will clear event.wai once an NMI / IRQ edge is reached
1:event.wai = true;
while(event.wai) {
//last_cycle() will clear status.wai_lock once an NMI / IRQ edge is reached
1:status.wai_lock = true;
while(status.wai_lock) {
last_cycle();
op_io();
}

View File

@@ -1,3 +1,5 @@
#ifdef SCPU_CPP
//nop
case 0xea: {
last_cycle();
@@ -103,9 +105,9 @@ case 0xdb: {
//wai
case 0xcb: {
//last_cycle() will clear event.wai once an NMI / IRQ edge is reached
event.wai = true;
while(event.wai) {
//last_cycle() will clear status.wai_lock once an NMI / IRQ edge is reached
status.wai_lock = true;
while(status.wai_lock) {
last_cycle();
op_io();
}
@@ -534,3 +536,4 @@ case 0x62: {
if(regs.e) regs.s.h = 0x01;
} break;
#endif

View File

@@ -1,3 +1,5 @@
#ifdef SCPU_CPP
//bcc
case 0x90: {
if(!!regs.p.c) last_cycle();
@@ -274,3 +276,4 @@ case 0x6b: {
if(regs.e) regs.s.h = 0x01;
} break;
#endif

View File

@@ -1,3 +1,5 @@
#ifdef SCPU_CPP
//adc_const
case 0x69: {
if(regs.p.m) last_cycle();
@@ -1649,3 +1651,4 @@ case 0x89: {
regs.p.z = ((rd.w & regs.a.w) == 0);
} break;
#endif

View File

@@ -1,3 +1,5 @@
#ifdef SCPU_CPP
//inc
case 0x1a: {
last_cycle();
@@ -568,3 +570,4 @@ case 0x76: {
op_writedp(dp + regs.x.w, rd.l);
} break;
#endif

View File

@@ -1,3 +1,5 @@
#ifdef SCPU_CPP
//sta_addr
case 0x8d: {
aa.l = op_readpc();
@@ -288,3 +290,4 @@ case 0x93: {
op_writedbr(aa.w + regs.y.w + 1, regs.a.h);
} break;
#endif

View File

@@ -1,56 +1,55 @@
#ifdef SCPU_CPP
void sCPU::dma_add_clocks(uint clocks) {
void sCPU::dma_add_clocks(unsigned clocks) {
status.dma_clocks += clocks;
add_clocks(clocks);
}
/*****
* used by both DMA and HDMA
*
* DMA address bus A cannot read from or write to the following addresses :
* $[00-3f|80-bf]:43[00-7f] <DMA control registers>
* $[00-3f|80-bf]:420b <DMA enable register>
* $[00-3f|80-bf]:420c <HDMA enable register>
*
* WRAM<>WRAM transfers via $2180 are also illegal
*****/
bool sCPU::dma_addr_valid(uint32 abus) {
//reads from B-bus or S-CPU registers are invalid
if((abus & 0x40ff00) == 0x2100) return false; //$[00-3f|80-bf]:[2100-21ff]
if((abus & 0x40fe00) == 0x4000) return false; //$[00-3f|80-bf]:[4000-41ff]
if((abus & 0x40ffe0) == 0x4200) return false; //$[00-3f|80-bf]:[4200-421f]
if((abus & 0x40ff80) == 0x4300) return false; //$[00-3f|80-bf]:[4300-437f]
return true;
}
uint8 sCPU::dma_read(uint32 abus) {
if(dma_addr_valid(abus) == false) return 0x00; //does not return S-CPU MDR
return bus.read(abus);
}
void sCPU::dma_transfer(bool direction, uint8 bbus, uint32 abus) {
if(direction == 0) {
//a->b transfer (to $21xx)
if(bbus == 0x80 && ((abus & 0xfe0000) == 0x7e0000 || (abus & 0x40e000) == 0x0000)) {
//illegal WRAM->WRAM transfer
//illegal WRAM->WRAM transfer (bus conflict)
//read most likely occurs; no write occurs
//read is irrelevant, as it has no observable effect on emulation
} else if((abus & 0x40ff00) == 0x2100 || (abus & 0x40ff80) == 0x4300
|| (abus & 0x40ffff) == 0x420b || (abus & 0x40ffff) == 0x420c) {
//illegal register access
bus.write(0x2100 | bbus, regs.mdr); //TODO: verify if MDR is written here
//read is irrelevent, as it cannot be observed by software
dma_add_clocks(8);
} else {
//valid transfer
bus.write(0x2100 | bbus, bus.read(abus));
dma_add_clocks(4);
uint8 data = dma_read(abus);
dma_add_clocks(4);
bus.write(0x2100 | bbus, data);
}
} else {
//b->a transfer (from $21xx)
if(bbus == 0x80 && ((abus & 0xfe0000) == 0x7e0000 || (abus & 0x40e000) == 0x0000)) {
//illegal WRAM->WRAM transfer
//illegal WRAM->WRAM transfer (bus conflict)
//no read occurs; write does occur
//does not write MDR as expected
//TODO: 0x00 was observed on hardware; verify if other values are possible
bus.write(abus, 0x00);
} else if((abus & 0x40ff00) == 0x2100 || (abus & 0x40ff80) == 0x4300
|| (abus & 0x40ffff) == 0x420b || (abus & 0x40ffff) == 0x420c) {
//illegal register access
bus.write(abus, regs.mdr); //TODO: verify if MDR is written here
dma_add_clocks(8);
bus.write(abus, 0x00); //does not write S-CPU MDR
} else {
//valid transfer
bus.write(abus, bus.read(0x2100 | bbus));
dma_add_clocks(4);
uint8 data = bus.read(0x2100 | bbus);
dma_add_clocks(4);
if(dma_addr_valid(abus) == true) {
bus.write(abus, data);
}
}
}
//each byte *always* consumes 8 clocks, even if transfer is invalid and no read and/or write occurs
dma_add_clocks(8);
cycle_edge();
}
@@ -60,14 +59,14 @@ void sCPU::dma_transfer(bool direction, uint8 bbus, uint32 abus) {
uint8 sCPU::dma_bbus(uint8 i, uint8 index) {
switch(channel[i].xfermode) { default:
case 0: return (channel[i].destaddr); //0
case 1: return (channel[i].destaddr + (index & 1)); //0,1
case 2: return (channel[i].destaddr); //0,0
case 3: return (channel[i].destaddr + ((index >> 1) & 1)); //0,0,1,1
case 4: return (channel[i].destaddr + (index & 3)); //0,1,2,3
case 5: return (channel[i].destaddr + (index & 1)); //0,1,0,1
case 6: return (channel[i].destaddr); //0,0 [2]
case 7: return (channel[i].destaddr + ((index >> 1) & 1)); //0,0,1,1 [3]
case 0: return (channel[i].destaddr); //0
case 1: return (channel[i].destaddr + (index & 1)); //0,1
case 2: return (channel[i].destaddr); //0,0
case 3: return (channel[i].destaddr + ((index >> 1) & 1)); //0,0,1,1
case 4: return (channel[i].destaddr + (index & 3)); //0,1,2,3
case 5: return (channel[i].destaddr + (index & 1)); //0,1,0,1
case 6: return (channel[i].destaddr); //0,0 [2]
case 7: return (channel[i].destaddr + ((index >> 1) & 1)); //0,0,1,1 [3]
}
}
@@ -97,56 +96,33 @@ inline uint32 sCPU::hdma_iaddr(uint8 i) {
* DMA functions
*****/
void sCPU::dma_transfertobusb(uint8 i, uint8 bbus) {
if(cartridge.info.sdd1 == true && sdd1.dma_active() == true) {
bus.write(0x2100 | bbus, sdd1.dma_read());
} else {
dma_transfer(0, bbus, dma_addr(i));
}
channel[i].xfersize--;
}
void sCPU::dma_transfertobusa(uint8 i, uint8 bbus) {
dma_transfer(1, bbus, dma_addr(i));
channel[i].xfersize--;
}
inline void sCPU::dma_write(uint8 i, uint8 index) {
//cannot use dma_transfer() directly, due to current S-DD1 implementation
if(channel[i].direction == 0) {
dma_transfertobusb(i, index);
} else {
dma_transfertobusa(i, index);
uint8 sCPU::dma_enabled_channels() {
uint8 r = 0;
for(unsigned i = 0; i < 8; i++) {
if(channel[i].dma_enabled) r++;
}
return r;
}
void sCPU::dma_run() {
for(int i = 0; i < 8; i++) {
dma_add_clocks(8);
cycle_edge();
for(unsigned i = 0; i < 8; i++) {
if(channel[i].dma_enabled == false) continue;
dma_add_clocks(8);
cycle_edge();
if(cartridge.info.sdd1 == true) {
sdd1.dma_begin(i, (channel[i].srcbank << 16) | (channel[i].srcaddr), channel[i].xfersize);
}
if(tracer.enabled() == true && tracer.cpudma_enabled() == true) {
tprintf("[DMA] channel:%d direction:%s reverse:%c fixed:%c mode:%d b_addr:$21%0.2x "
"a_addr:$%0.2x%0.4x length:$%0.4x (%5d)",
i, channel[i].direction ? "b->a" : "a->b", channel[i].reversexfer ? '1' : '0',
channel[i].fixedxfer ? '1' : '0', channel[i].xfermode, channel[i].destaddr,
channel[i].srcbank, channel[i].srcaddr,
channel[i].xfersize, channel[i].xfersize ? channel[i].xfersize : 65536);
}
uint index = 0;
unsigned index = 0;
do {
dma_write(i, dma_bbus(i, index++));
} while(channel[i].dma_enabled && channel[i].xfersize);
dma_transfer(channel[i].direction, dma_bbus(i, index++), dma_addr(i));
} while(channel[i].dma_enabled && --channel[i].xfersize);
channel[i].dma_enabled = false;
}
counter.set(counter.irq_delay, 2);
status.irq_lock = true;
event.enqueue(2, EventIrqLockRelease);
}
/*****
@@ -158,7 +134,7 @@ inline bool sCPU::hdma_active(uint8 i) {
}
inline bool sCPU::hdma_active_after(uint8 i) {
for(int n = i + 1; n < 8; n++) {
for(unsigned n = i + 1; n < 8; n++) {
if(hdma_active(n) == true) return true;
}
return false;
@@ -166,7 +142,7 @@ inline bool sCPU::hdma_active_after(uint8 i) {
inline uint8 sCPU::hdma_enabled_channels() {
uint8 r = 0;
for(int i = 0; i < 8; i++) {
for(unsigned i = 0; i < 8; i++) {
if(channel[i].hdma_enabled) r++;
}
return r;
@@ -174,78 +150,84 @@ inline uint8 sCPU::hdma_enabled_channels() {
inline uint8 sCPU::hdma_active_channels() {
uint8 r = 0;
for(int i = 0; i < 8; i++) {
for(unsigned i = 0; i < 8; i++) {
if(hdma_active(i) == true) r++;
}
return r;
}
void sCPU::hdma_update(uint8 i) {
channel[i].hdma_line_counter = bus.read(hdma_addr(i));
channel[i].hdma_line_counter = dma_read(hdma_addr(i));
dma_add_clocks(8);
channel[i].hdma_completed = (channel[i].hdma_line_counter == 0);
channel[i].hdma_do_transfer = !channel[i].hdma_completed;
if(channel[i].hdma_indirect) {
channel[i].hdma_iaddr = bus.read(hdma_addr(i)) << 8;
channel[i].hdma_iaddr = dma_read(hdma_addr(i)) << 8;
dma_add_clocks(8);
if(!channel[i].hdma_completed || hdma_active_after(i)) {
channel[i].hdma_iaddr >>= 8;
channel[i].hdma_iaddr |= bus.read(hdma_addr(i)) << 8;
channel[i].hdma_iaddr |= dma_read(hdma_addr(i)) << 8;
dma_add_clocks(8);
}
}
}
void sCPU::hdma_run() {
static uint8 hdma_xferlen[8] = { 1, 2, 2, 4, 4, 4, 2, 4 };
for(int i = 0; i < 8; i++) {
dma_add_clocks(8);
for(unsigned i = 0; i < 8; i++) {
if(hdma_active(i) == false) continue;
channel[i].dma_enabled = false; //HDMA run during DMA will stop DMA mid-transfer
dma_add_clocks(8);
channel[i].dma_enabled = false; //HDMA run during DMA will stop DMA mid-transfer
if(channel[i].hdma_do_transfer) {
int xferlen = hdma_xferlen[channel[i].xfermode];
for(int index = 0; index < xferlen; index++) {
if(bool(config::cpu.hdma_enable) == true) {
dma_transfer(channel[i].direction, dma_bbus(i, index),
!channel[i].hdma_indirect ? hdma_addr(i) : hdma_iaddr(i));
} else {
dma_add_clocks(8);
cycle_edge();
}
static const unsigned transfer_length[8] = { 1, 2, 2, 4, 4, 4, 2, 4 };
unsigned length = transfer_length[channel[i].xfermode];
for(unsigned index = 0; index < length; index++) {
unsigned addr = !channel[i].hdma_indirect ? hdma_addr(i) : hdma_iaddr(i);
dma_transfer(channel[i].direction, dma_bbus(i, index), addr);
}
}
}
for(unsigned i = 0; i < 8; i++) {
if(hdma_active(i) == false) continue;
channel[i].hdma_line_counter--;
channel[i].hdma_do_transfer = bool(channel[i].hdma_line_counter & 0x80);
if((channel[i].hdma_line_counter & 0x7f) == 0) {
hdma_update(i);
} else {
dma_add_clocks(8);
}
}
counter.set(counter.irq_delay, 2);
status.irq_lock = true;
event.enqueue(2, EventIrqLockRelease);
}
void sCPU::hdma_init_reset() {
for(int i = 0; i < 8; i++) {
for(unsigned i = 0; i < 8; i++) {
channel[i].hdma_completed = false;
channel[i].hdma_do_transfer = false;
}
}
void sCPU::hdma_init() {
for(int i = 0; i < 8; i++) {
if(!channel[i].hdma_enabled)continue;
channel[i].dma_enabled = false; //HDMA init during DMA will stop DMA mid-transfer
dma_add_clocks(8);
for(unsigned i = 0; i < 8; i++) {
if(!channel[i].hdma_enabled) continue;
channel[i].dma_enabled = false; //HDMA init during DMA will stop DMA mid-transfer
channel[i].hdma_addr = channel[i].srcaddr;
hdma_update(i);
}
counter.set(counter.irq_delay, 2);
status.irq_lock = true;
event.enqueue(2, EventIrqLockRelease);
}
/*****
@@ -253,7 +235,7 @@ void sCPU::hdma_init() {
*****/
void sCPU::dma_power() {
for(int i = 0; i < 8; i++) {
for(unsigned i = 0; i < 8; i++) {
channel[i].dmap = 0xff;
channel[i].direction = 1;
channel[i].hdma_indirect = true;
@@ -267,7 +249,7 @@ void sCPU::dma_power() {
channel[i].srcbank = 0xff;
channel[i].xfersize = 0xffff;
//channel[i].hdma_iaddr = 0xffff; //union with xfersize
//channel[i].hdma_iaddr = 0xffff; //union with xfersize
channel[i].hdma_ibank = 0xff;
channel[i].hdma_addr = 0xffff;
@@ -277,7 +259,7 @@ void sCPU::dma_power() {
}
void sCPU::dma_reset() {
for(int i = 0; i < 8; i++) {
for(unsigned i = 0; i < 8; i++) {
channel[i].dma_enabled = false;
channel[i].hdma_enabled = false;

View File

@@ -45,7 +45,9 @@
bool hdma_do_transfer;
} channel[8];
void dma_add_clocks(uint clocks);
void dma_add_clocks(unsigned clocks);
bool dma_addr_valid(uint32 abus);
uint8 dma_read(uint32 abus);
void dma_transfer(bool direction, uint8 bbus, uint32 abus);
uint8 dma_bbus(uint8 i, uint8 index);
@@ -53,9 +55,7 @@
uint32 hdma_addr(uint8 i);
uint32 hdma_iaddr(uint8 i);
void dma_transfertobusb(uint8 i, uint8 bbus);
void dma_transfertobusa(uint8 i, uint8 bbus);
void dma_write(uint8 i, uint8 index);
uint8 dma_enabled_channels();
void dma_run();
bool hdma_active(uint8 i);

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,10 @@
void mmio_power();
void mmio_reset();
uint8 mmio_read(uint addr);
void mmio_write(uint addr, uint8 data);
uint8 mmio_read(unsigned addr);
void mmio_write(unsigned addr, uint8 data);
uint8 pio_status();
uint8 pio();
bool joylatch();
uint8 mmio_r2180();
uint8 mmio_r4016();

View File

@@ -1,6 +1,9 @@
#include "../../base.h"
#include <../base.hpp>
#define SCPU_CPP
#include <nall/priorityqueue.hpp>
priority_queue<unsigned> event(512, bind(&sCPU::queue_event, &cpu));
#include "core/core.cpp"
#include "dma/dma.cpp"
#include "memory/memory.cpp"
@@ -33,9 +36,9 @@ void sCPU::reset() {
regs.e = 1;
regs.mdr = 0x00;
event.wai = false;
event.irq = false;
event.irq_vector = 0xfffc; //reset vector address
status.wai_lock = false;
status.interrupt_pending = false;
status.interrupt_vector = 0xfffc; //reset vector address
mmio_reset();
dma_reset();

View File

@@ -1,133 +0,0 @@
class sCPU : public CPU {
public:
void enter();
#include "core/core.h"
#include "dma/dma.h"
#include "memory/memory.h"
#include "mmio/mmio.h"
#include "timing/timing.h"
struct {
bool wai;
bool irq;
uint16 irq_vector;
} event;
struct {
uint nmi_hold;
uint irq_hold;
uint nmi_fire;
uint irq_fire;
uint irq_delay;
uint hw_math;
alwaysinline void set(uint &ctr, uint clocks) {
if(clocks >= ctr) { ctr = clocks; }
}
alwaysinline void sub(uint &ctr, uint clocks) {
if(ctr >= clocks) {
ctr -= clocks;
} else {
ctr = 0;
}
}
} counter;
enum {
DMASTATE_INACTIVE,
DMASTATE_DMASYNC,
DMASTATE_RUN,
DMASTATE_CPUSYNC,
};
struct {
//core
uint8 opcode;
bool in_opcode;
uint clock_count;
//timing
uint16 vcounter, hcounter;
uint16 field_lines, line_clocks;
bool line_rendered;
uint16 line_render_position;
bool dram_refreshed;
uint16 dram_refresh_position;
bool hdmainit_triggered;
uint16 hdmainit_trigger_position;
bool hdma_triggered;
uint16 irq_delay;
bool nmi_valid;
bool nmi_line;
bool nmi_transition;
bool nmi_pending;
uint16 virq_trigger_pos, hirq_trigger_pos;
bool irq_valid;
bool irq_line;
bool irq_transition;
bool irq_pending;
//dma
uint dma_counter;
uint dma_clocks;
uint dma_state;
bool dma_pending;
bool hdma_pending;
bool hdmainit_pending;
//mmio
//$2181-$2183
uint32 wram_addr;
//$4016-$4017
bool joypad_strobe_latch;
uint32 joypad1_bits;
uint32 joypad2_bits;
//$4200
bool nmi_enabled;
bool hirq_enabled, virq_enabled;
bool auto_joypad_poll;
//$4201
uint8 pio;
//$4202-$4203
uint8 mul_a, mul_b;
//$4204-$4206
uint16 div_a;
uint8 div_b;
//$4207-$420a
uint16 hirq_pos, virq_pos;
//$4214-$4217
uint16 r4214;
uint16 r4216;
//$4218-$421f
uint8 joy1l, joy1h;
uint8 joy2l, joy2h;
uint8 joy3l, joy3h;
uint8 joy4l, joy4h;
} status;
void power();
void reset();
sCPU();
~sCPU();
};

94
src/cpu/scpu/scpu.hpp Normal file
View File

@@ -0,0 +1,94 @@
class sCPU : public CPU {
public:
void enter();
#include "core/core.hpp"
#include "dma/dma.hpp"
#include "memory/memory.hpp"
#include "mmio/mmio.hpp"
#include "timing/timing.hpp"
enum DmaState { DmaInactive, DmaRun, DmaCpuSync };
struct {
//core
uint8 opcode;
bool in_opcode;
bool wai_lock;
bool interrupt_pending;
uint16 interrupt_vector;
unsigned clock_count;
unsigned line_clocks;
//timing
bool irq_lock;
bool alu_lock;
unsigned dram_refresh_position;
bool nmi_valid;
bool nmi_line;
bool nmi_transition;
bool nmi_pending;
bool nmi_hold;
bool irq_valid;
bool irq_line;
bool irq_transition;
bool irq_pending;
bool irq_hold;
//DMA
unsigned dma_counter;
unsigned dma_clocks;
bool dma_pending;
bool hdma_pending;
bool hdma_mode; //0 = init, 1 = run
DmaState dma_state;
//MMIO
//$2181-$2183
uint32 wram_addr;
//$4016-$4017
bool joypad_strobe_latch;
uint32 joypad1_bits;
uint32 joypad2_bits;
//$4200
bool nmi_enabled;
bool hirq_enabled, virq_enabled;
bool auto_joypad_poll;
//$4201
uint8 pio;
//$4202-$4203
uint8 mul_a, mul_b;
//$4204-$4206
uint16 div_a;
uint8 div_b;
//$4207-$420a
uint16 hirq_pos, virq_pos;
//$4214-$4217
uint16 r4214;
uint16 r4216;
//$4218-$421f
uint8 joy1l, joy1h;
uint8 joy2l, joy2h;
uint8 joy3l, joy3h;
uint8 joy4l, joy4h;
} status;
void power();
void reset();
sCPU();
~sCPU();
};

View File

@@ -0,0 +1,35 @@
#ifdef SCPU_CPP
void sCPU::queue_event(unsigned id) {
switch(id) {
//interrupts triggered during (H)DMA do not trigger immediately after
case EventIrqLockRelease: {
status.irq_lock = false;
} break;
//ALU multiplication / division results are not immediately calculated;
//the exact formula for the calculations are unknown, but this lock at least
//allows emulation to avoid returning to fully computed results too soon.
case EventAluLockRelease: {
status.alu_lock = false;
} break;
//S-CPU WRAM consists of two 64kbyte DRAM chips, which must be refreshed
//once per scanline to avoid memory decay.
case EventDramRefresh: {
add_clocks(40);
} break;
//HDMA init routine; occurs once per frame
case EventHdmaInit: {
cycle_edge_state |= EventFlagHdmaInit;
} break;
//HDMA run routine; occurs once per scanline
case EventHdmaRun: {
cycle_edge_state |= EventFlagHdmaRun;
} break;
}
}
#endif

View File

@@ -1,56 +1,47 @@
#ifdef SCPU_CPP
void sCPU::update_interrupts() {
if(irq_pos_valid() == true) {
status.virq_trigger_pos = status.virq_pos;
status.hirq_trigger_pos = 4 * ((status.hirq_enabled) ? (status.hirq_pos + 1) : 0);
} else {
status.virq_trigger_pos = IRQ_TRIGGER_NEVER;
status.hirq_trigger_pos = IRQ_TRIGGER_NEVER;
}
}
alwaysinline void sCPU::poll_interrupts() {
uint16_t vpos, hpos;
#ifdef SCPU_CPP
//called once every four clock cycles;
//as NMI steps by scanlines (divisible by 4) and IRQ by PPU 4-cycle dots.
//
//ppu.(vh)counter(n) returns the value of said counters n-clocks before current time;
//it is used to emulate hardware communication delay between opcode and interrupt units.
void sCPU::poll_interrupts() {
//NMI hold
if(counter.nmi_hold) {
counter.nmi_hold -= 2;
if(counter.nmi_hold == 0) {
if(status.nmi_enabled == true) status.nmi_transition = true;
}
if(status.nmi_hold) {
status.nmi_hold = false;
if(status.nmi_enabled) status.nmi_transition = true;
}
//NMI test
history.query(2, vpos, hpos);
bool nmi_valid = (vpos >= (!ppu.overscan() ? 225 : 240));
if(status.nmi_valid == false && nmi_valid == true) {
bool nmi_valid = (ppu.vcounter(2) >= (!ppu.overscan() ? 225 : 240));
if(!status.nmi_valid && nmi_valid) {
//0->1 edge sensitive transition
status.nmi_line = true;
counter.nmi_hold = 4;
} else if(status.nmi_valid == true && nmi_valid == false) {
status.nmi_hold = true; //hold /NMI for four cycles
} else if(status.nmi_valid && !nmi_valid) {
//1->0 edge sensitive transition
status.nmi_line = false;
}
status.nmi_valid = nmi_valid;
//IRQ hold
if(counter.irq_hold) counter.irq_hold -= 2;
if(status.irq_line == true && counter.irq_hold == 0) {
if(status.virq_enabled == true || status.hirq_enabled == true) status.irq_transition = true;
status.irq_hold = false;
if(status.irq_line) {
if(status.virq_enabled || status.hirq_enabled) status.irq_transition = true;
}
//IRQ test
history.query(10, vpos, hpos);
bool irq_valid = (status.virq_enabled == true || status.hirq_enabled == true);
if(irq_valid == true) {
if(status.virq_enabled == true && vpos != status.virq_trigger_pos) irq_valid = false;
if(status.hirq_enabled == true && hpos != status.hirq_trigger_pos) irq_valid = false;
bool irq_valid = (status.virq_enabled || status.hirq_enabled);
if(irq_valid) {
if((status.virq_enabled && ppu.vcounter(10) != (status.virq_pos))
|| (status.hirq_enabled && ppu.hcounter(10) != (status.hirq_pos + 1) * 4)
|| (status.virq_pos && ppu.vcounter(6) == 0) //IRQs cannot trigger on last dot of field
) irq_valid = false;
}
if(status.irq_valid == false && irq_valid == true) {
if(!status.irq_valid && irq_valid) {
//0->1 edge sensitive transition
status.irq_line = true;
counter.irq_hold = 4;
status.irq_hold = true; //hold /IRQ for four cycles
}
status.irq_valid = irq_valid;
}
@@ -59,36 +50,32 @@ void sCPU::nmitimen_update(uint8 data) {
bool nmi_enabled = status.nmi_enabled;
bool virq_enabled = status.virq_enabled;
bool hirq_enabled = status.hirq_enabled;
status.nmi_enabled = !!(data & 0x80);
status.virq_enabled = !!(data & 0x20);
status.hirq_enabled = !!(data & 0x10);
status.nmi_enabled = data & 0x80;
status.virq_enabled = data & 0x20;
status.hirq_enabled = data & 0x10;
//0->1 edge sensitive transition
if(nmi_enabled == false && status.nmi_enabled == true && status.nmi_line == true) {
if(!nmi_enabled && status.nmi_enabled && status.nmi_line) {
status.nmi_transition = true;
}
//?->1 level sensitive transition
if(status.virq_enabled == true && status.hirq_enabled == false && status.irq_line == true) {
if(status.virq_enabled && !status.hirq_enabled && status.irq_line) {
status.irq_transition = true;
}
if(status.virq_enabled == false && status.hirq_enabled == false) {
if(!status.virq_enabled && !status.hirq_enabled) {
status.irq_line = false;
status.irq_transition = false;
}
update_interrupts();
counter.set(counter.irq_delay, 2);
}
void sCPU::hvtime_update(uint16 addr) {
update_interrupts();
status.irq_lock = true;
event.enqueue(2, EventIrqLockRelease);
}
bool sCPU::rdnmi() {
bool result = status.nmi_line;
if(counter.nmi_hold == 0) {
if(!status.nmi_hold) {
status.nmi_line = false;
}
return result;
@@ -96,42 +83,25 @@ bool sCPU::rdnmi() {
bool sCPU::timeup() {
bool result = status.irq_line;
if(counter.irq_hold == 0) {
if(!status.irq_hold) {
status.irq_line = false;
status.irq_transition = false;
}
return result;
}
bool sCPU::irq_pos_valid() {
uint vpos = status.virq_pos;
uint hpos = (status.hirq_enabled) ? status.hirq_pos : 0;
uint vlimit = (snes.region() == SNES::NTSC ? 525 : 625) >> 1;
//positions that can never be latched
//vlimit = 262/NTSC, 312/PAL
//PAL results are unverified on hardware
if(vpos == 240 && hpos == 339 && ppu.interlace() == false && ppu.field() == 1) return false;
if(vpos == (vlimit - 1) && hpos == 339 && ppu.interlace() == false) return false;
if(vpos == vlimit && ppu.interlace() == false) return false;
if(vpos == vlimit && hpos == 339) return false;
if(vpos > vlimit) return false;
if(hpos > 339) return false;
return true;
}
alwaysinline bool sCPU::nmi_test() {
if(status.nmi_transition == false) return false;
bool sCPU::nmi_test() {
if(!status.nmi_transition) return false;
status.nmi_transition = false;
event.wai = false;
status.wai_lock = false;
return true;
}
alwaysinline bool sCPU::irq_test() {
if(status.irq_transition == false) return false;
bool sCPU::irq_test() {
if(!status.irq_transition) return false;
status.irq_transition = false;
event.wai = false;
return regs.p.i ? false : true;
status.wai_lock = false;
return !regs.p.i;
}
#endif //ifdef SCPU_CPP
#endif

View File

@@ -1,10 +1,15 @@
#ifdef SCPU_CPP
void sCPU::run_auto_joypad_poll() {
uint16_t joy1 = 0, joy2 = 0;
uint16 joy1 = 0, joy2 = 0, joy3 = 0, joy4 = 0;
for(unsigned i = 0; i < 16; i++) {
joy1 |= (uint16_t)snes.input.port_read(0) ? (0x8000 >> i) : 0;
joy2 |= (uint16_t)snes.input.port_read(1) ? (0x8000 >> i) : 0;
uint8 port0 = snes.input.port_read(0);
uint8 port1 = snes.input.port_read(1);
joy1 |= (port0 & 1) ? (0x8000 >> i) : 0;
joy2 |= (port1 & 1) ? (0x8000 >> i) : 0;
joy3 |= (port0 & 2) ? (0x8000 >> i) : 0;
joy4 |= (port1 & 2) ? (0x8000 >> i) : 0;
}
status.joy1l = joy1;
@@ -13,11 +18,11 @@ void sCPU::run_auto_joypad_poll() {
status.joy2l = joy2;
status.joy2h = joy2 >> 8;
status.joy3l = 0x00;
status.joy3h = 0x00;
status.joy3l = joy3;
status.joy3h = joy3 >> 8;
status.joy4l = 0x00;
status.joy4h = 0x00;
status.joy4l = joy4;
status.joy4h = joy4 >> 8;
}
#endif //ifdef SCPU_CPP
#endif

View File

@@ -1,255 +1,166 @@
#ifdef SCPU_CPP
#define ntsc_color_burst_phase_shift_scanline() ( \
snes.region() == SNES::NTSC && status.vcounter == 240 && \
ppu.interlace() == false && ppu.field() == 1 \
)
#include "irq.cpp"
#include "joypad.cpp"
uint16 sCPU::vcounter() { return status.vcounter; }
uint16 sCPU::hcounter() { return status.hcounter; }
uint sCPU::dma_counter() { return (status.dma_counter + status.hcounter) & 7; }
/*****
* One PPU dot = 4 CPU clocks
*
* PPU dots 323 and 327 are 6 CPU clocks long.
* This does not apply to NTSC non-interlace scanline 240 on odd fields. This is
* because the PPU skips one dot to alter the color burst phase of the video signal.
*
* Dot 323 range = { 1292, 1294, 1296 }
* Dot 327 range = { 1310, 1312, 1314 }
*****/
uint16 sCPU::hdot() {
if(ntsc_color_burst_phase_shift_scanline() == true) return (status.hcounter >> 2);
return (status.hcounter - ((status.hcounter > 1292) << 1) - ((status.hcounter > 1310) << 1)) >> 2;
}
void sCPU::add_clocks(uint clocks) {
if(status.dram_refreshed == false) {
if(status.hcounter + clocks >= status.dram_refresh_position) {
status.dram_refreshed = true;
clocks += 40;
}
}
counter.sub(counter.irq_delay, clocks);
scheduler.addclocks_cpu(clocks);
clocks >>= 1;
while(clocks--) {
history.enqueue(status.vcounter, status.hcounter);
status.hcounter += 2;
if(status.hcounter >= status.line_clocks) scanline();
poll_interrupts();
}
}
void sCPU::scanline() {
status.hcounter = 0;
status.dma_counter = (status.dma_counter + status.line_clocks) & 7;
if(++status.vcounter >= status.field_lines) frame();
status.line_clocks = (ntsc_color_burst_phase_shift_scanline() == false) ? 1364 : 1360;
//dram refresh occurs once every scanline
status.dram_refreshed = false;
if(cpu_version == 2) {
if(ntsc_color_burst_phase_shift_scanline() == false) {
if(status.dram_refresh_position == 534) {
status.dram_refresh_position = 538;
} else {
status.dram_refresh_position = 534;
}
}
}
//hdma triggers once every visible scanline
status.line_rendered = false;
status.hdma_triggered = (status.vcounter <= (ppu.overscan() == false ? 224 : 239)) ? false : true;
ppu.scanline();
snes.scanline();
update_interrupts();
if(status.auto_joypad_poll == true && status.vcounter == (ppu.overscan() == false ? 227 : 242)) {
snes.input.poll();
run_auto_joypad_poll();
}
}
void sCPU::frame() {
ppu.frame();
snes.frame();
status.vcounter = 0;
status.field_lines = (snes.region() == SNES::NTSC ? 525 : 625) >> 1;
//interlaced even fields have one extra scanline
//(263+262=525 NTSC, 313+312=625 PAL)
if(ppu.interlace() == true && ppu.field() == 0) status.field_lines++;
status.hdmainit_triggered = false;
if(cpu_version == 1) {
status.hdmainit_trigger_position = 12 + 8 - dma_counter();
} else {
status.hdmainit_trigger_position = 12 + dma_counter();
}
}
/*****
* precycle_edge()
*
* Used for DMA/HDMA bus synchronization
*****/
alwaysinline void sCPU::precycle_edge() {
if(status.dma_state == DMASTATE_CPUSYNC) {
status.dma_state = DMASTATE_INACTIVE;
uint n = status.clock_count - (status.dma_clocks % status.clock_count);
add_clocks(n ? n : status.clock_count);
}
}
/*****
* cycle_edge()
*
* Used to test for HDMA, which can trigger on the edge of every opcode cycle.
*****/
void sCPU::cycle_edge() {
if(status.line_rendered == false) {
if(status.hcounter >= status.line_render_position) {
status.line_rendered = true;
ppu.render_scanline();
}
}
if(status.hdmainit_triggered == false) {
if(status.hcounter >= status.hdmainit_trigger_position || status.vcounter) {
status.hdmainit_triggered = true;
hdma_init_reset();
if(hdma_enabled_channels()) {
if(status.dma_state == DMASTATE_INACTIVE) {
status.dma_state = DMASTATE_DMASYNC;
status.hdmainit_pending = true;
} else {
hdma_init();
}
}
}
}
if(status.hdma_triggered == false) {
if(status.hcounter >= 1106) {
status.hdma_triggered = true;
if(hdma_active_channels()) {
if(status.dma_state == DMASTATE_INACTIVE) {
status.dma_state = DMASTATE_DMASYNC;
status.hdma_pending = true;
} else {
hdma_run();
}
}
}
#include "event.cpp"
#include "irq.cpp"
#include "joypad.cpp"
unsigned sCPU::dma_counter() {
return (status.dma_counter + ppu.hcounter()) & 7;
}
void sCPU::add_clocks(unsigned clocks) {
event.tick(clocks);
unsigned ticks = clocks >> 1;
while(ticks--) {
ppu.tick();
if((ppu.hcounter() & 2) == 0) {
snes.input.tick();
} else {
poll_interrupts();
}
}
scheduler.addclocks_cpu(clocks);
}
void sCPU::scanline() {
status.dma_counter = (status.dma_counter + status.line_clocks) & 7;
status.line_clocks = ppu.lineclocks();
if(ppu.vcounter() == 0) {
//hdma init triggers once every frame
event.enqueue(cpu_version == 1 ? 12 + 8 - dma_counter() : 12 + dma_counter(), EventHdmaInit);
}
switch(status.dma_state) {
case DMASTATE_INACTIVE: break;
//dram refresh occurs once every scanline
if(cpu_version == 2) status.dram_refresh_position = 530 + 8 - dma_counter();
event.enqueue(status.dram_refresh_position, EventDramRefresh);
case DMASTATE_DMASYNC: {
status.dma_state = DMASTATE_RUN;
} break;
//hdma triggers once every visible scanline
if(ppu.vcounter() <= (ppu.overscan() == false ? 224 : 239)) {
event.enqueue(1104, EventHdmaRun);
}
case DMASTATE_RUN: {
status.dma_state = DMASTATE_CPUSYNC;
status.dma_clocks = 8 - dma_counter() + 8;
add_clocks(status.dma_clocks);
if(status.auto_joypad_poll == true && ppu.vcounter() == (ppu.overscan() == false ? 227 : 242)) {
snes.input.poll();
run_auto_joypad_poll();
}
}
if(status.hdmainit_pending) { hdma_init(); status.hdmainit_pending = false; }
if(status.hdma_pending) { hdma_run(); status.hdma_pending = false; }
if(status.dma_pending) { dma_run(); status.dma_pending = false; }
//used for H/DMA bus synchronization
void sCPU::precycle_edge() {
if(status.dma_state == DmaCpuSync) {
add_clocks(status.clock_count - (status.dma_clocks % status.clock_count));
status.dma_state = DmaInactive;
}
}
} break;
}
}
/*****
* last_cycle()
*
* Used to test for NMI/IRQ, which can trigger on the edge of every opcode.
* Test one cycle early to simulate two-stage pipeline of x816 CPU.
*
* status.irq_delay is used to simulate hardware delay before interrupts can
* trigger during certain events (immediately after DMA, writes to $4200, etc)
*****/
void sCPU::last_cycle() {
if(counter.irq_delay) return;
status.nmi_pending |= nmi_test();
status.irq_pending |= irq_test();
event.irq = (status.nmi_pending || status.irq_pending);
}
void sCPU::timing_power() {
}
void sCPU::timing_reset() {
counter.nmi_hold = 0;
counter.irq_hold = 0;
counter.nmi_fire = 0;
counter.irq_fire = 0;
counter.irq_delay = 0;
counter.hw_math = 0;
status.clock_count = 0;
status.vcounter = 0;
status.hcounter = 0;
status.field_lines = (snes.region() == SNES::NTSC ? 525 : 625) >> 1;
status.line_clocks = 1364;
status.line_rendered = false;
status.line_render_position = min(1112U, (uint)config::ppu.hack.render_scanline_position);
status.dram_refreshed = false;
status.dram_refresh_position = (cpu_version == 1) ? 530 : 538;
status.hdmainit_triggered = false;
status.hdmainit_trigger_position = 0;
status.hdma_triggered = false;
status.irq_delay = 0;
status.nmi_valid = false;
status.nmi_line = false;
status.nmi_transition = false;
status.nmi_pending = false;
status.irq_valid = false;
status.irq_line = false;
status.irq_transition = false;
status.irq_pending = false;
update_interrupts();
status.dma_counter = 0;
status.dma_state = DMASTATE_INACTIVE;
status.dma_pending = false;
status.hdma_pending = false;
status.hdmainit_pending = false;
//used to test for H/DMA, which can trigger on the edge of every opcode cycle.
void sCPU::cycle_edge() {
while(cycle_edge_state) {
switch(bit::lowest(cycle_edge_state)) {
case EventFlagHdmaInit: {
hdma_init_reset();
if(hdma_enabled_channels()) {
status.hdma_pending = true;
status.hdma_mode = 0;
}
} break;
history.reset();
//initial latch values for $213c/$213d
//[x]0035 : [y]0000 (53.0 -> 212) [lda $2137]
//[x]0038 : [y]0000 (56.5 -> 226) [nop : lda $2137]
add_clocks(186);
}
#undef ntsc_color_burst_phase_shift_scanline
case EventFlagHdmaRun: {
if(hdma_active_channels()) {
status.hdma_pending = true;
status.hdma_mode = 1;
}
} break;
}
#endif //ifdef SCPU_CPP
cycle_edge_state = bit::clear_lowest(cycle_edge_state);
}
//H/DMA pending && DMA inactive?
//.. Run one full CPU cycle
//.. HDMA pending && HDMA enabled ? DMA sync + HDMA run
//.. DMA pending && DMA enabled ? DMA sync + DMA run
//.... HDMA during DMA && HDMA enabled ? DMA sync + HDMA run
//.. Run one bus CPU cycle
//.. CPU sync
if(status.dma_state == DmaRun) {
if(status.hdma_pending) {
status.hdma_pending = false;
if(hdma_enabled_channels()) {
dma_add_clocks(8 - dma_counter()); //DMA sync
status.hdma_mode == 0 ? hdma_init() : hdma_run();
if(!dma_enabled_channels()) status.dma_state = DmaCpuSync;
}
}
if(status.dma_pending) {
status.dma_pending = false;
if(dma_enabled_channels()) {
dma_add_clocks(8 - dma_counter()); //DMA sync
dma_run();
status.dma_state = DmaCpuSync;
}
}
}
if(status.dma_state == DmaInactive) {
if(status.dma_pending || status.hdma_pending) {
status.dma_clocks = 0;
status.dma_state = DmaRun;
}
}
}
//used to test for NMI/IRQ, which can trigger on the edge of every opcode.
//test one cycle early to simulate two-stage pipeline of x816 CPU.
//
//status.irq_lock is used to simulate hardware delay before interrupts can
//trigger during certain events (immediately after DMA, writes to $4200, etc)
void sCPU::last_cycle() {
if(!status.irq_lock) {
status.nmi_pending |= nmi_test();
status.irq_pending |= irq_test();
status.interrupt_pending = (status.nmi_pending || status.irq_pending);
}
}
void sCPU::timing_power() {
}
void sCPU::timing_reset() {
event.reset();
status.clock_count = 0;
status.line_clocks = ppu.lineclocks();
status.irq_lock = false;
status.alu_lock = false;
status.dram_refresh_position = (cpu_version == 1 ? 530 : 538);
event.enqueue(status.dram_refresh_position, EventDramRefresh);
status.nmi_valid = false;
status.nmi_line = false;
status.nmi_transition = false;
status.nmi_pending = false;
status.nmi_hold = false;
status.irq_valid = false;
status.irq_line = false;
status.irq_transition = false;
status.irq_pending = false;
status.irq_hold = false;
status.dma_counter = 0;
status.dma_clocks = 0;
status.dma_pending = false;
status.hdma_pending = false;
status.hdma_mode = 0;
status.dma_state = DmaInactive;
cycle_edge_state = 0;
}
#endif

View File

@@ -1,57 +0,0 @@
uint16 vcounter();
uint16 hcounter();
uint16 hdot();
uint dma_counter();
void add_clocks(uint clocks);
void scanline();
void frame();
void precycle_edge();
void cycle_edge();
void last_cycle();
uint32 clocks_executed();
void timing_power();
void timing_reset();
//timeshifting -- needed by NMI and IRQ timing
struct History {
struct Time {
uint16 vcounter;
uint16 hcounter;
} time[32];
unsigned index;
alwaysinline void enqueue(uint16 vcounter, uint16 hcounter) {
Time &t = time[index++];
index &= 31;
t.vcounter = vcounter;
t.hcounter = hcounter;
}
alwaysinline void query(unsigned offset, uint16 &vcounter, uint16 &hcounter) {
Time &t = time[(index - (offset >> 1)) & 31];
vcounter = t.vcounter;
hcounter = t.hcounter;
}
void reset() {
index = 0;
for(unsigned i = 0; i < 32; i++) time[i].vcounter = time[i].hcounter = 0;
}
History() { reset(); }
} history;
//irq.cpp
enum { IRQ_TRIGGER_NEVER = 0x3fff };
void update_interrupts();
void poll_interrupts();
void nmitimen_update(uint8 data);
void hvtime_update(uint16 addr);
bool rdnmi();
bool timeup();
bool irq_pos_valid();
bool nmi_test();
bool irq_test();
//joypad.cpp
void run_auto_joypad_poll();

View File

@@ -0,0 +1,41 @@
enum {
EventNone,
EventIrqLockRelease,
EventAluLockRelease,
EventDramRefresh,
EventHdmaInit,
EventHdmaRun,
//cycle edge
EventFlagHdmaInit = 1 << 0,
EventFlagHdmaRun = 1 << 1,
};
unsigned cycle_edge_state;
//timing.cpp
unsigned dma_counter();
void add_clocks(unsigned clocks);
void scanline();
alwaysinline void precycle_edge();
alwaysinline void cycle_edge();
void last_cycle();
void timing_power();
void timing_reset();
//irq.cpp
alwaysinline void poll_interrupts();
void nmitimen_update(uint8 data);
bool rdnmi();
bool timeup();
alwaysinline bool nmi_test();
alwaysinline bool irq_test();
//joypad.cpp
void run_auto_joypad_poll();
//event.cpp
void queue_event(unsigned); //priorityqueue callback function

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

After

Width:  |  Height:  |  Size: 22 KiB

View File

@@ -1,3 +1,7 @@
#if defined(_MSC_VER)
//TODO: Visual C++ cannot handle strings > 65536 bytes. Need to find workaround.
static char enc_controller[65536 * 2] = { 0 };
#else
static char enc_controller[] = {
"_v8B8AHwAfAB8AHwAfAB8P8B8AHwAfAB8AHwAfAB8AHw_wHwAfAB8AHwAfAB8AHw"
"AfB_AfAB8AHwAfAB8AHwAeD9AP396OjomJiZAHBwcG5ubmpqAGpYWFhLS0tBAEFB"
@@ -1032,3 +1036,4 @@ static char enc_controller[] = {
"AfAB8AHwAfAB8AHw_wHwAfAB8AHwAfAB8AHwAfD_AfAB8AHwAfAB8AHwAfAB8P9G"
"8kbyRvJG8kbyRvJG8kby_0byqPAB8AHwAfAB8AHwAfAPAfAB8AHwATA"
};
#endif

View File

@@ -1,4 +1,4 @@
#include "../../base.h"
#include <../base.hpp>
#define ADSP_CPP
#include "adsp_tables.cpp"

View File

@@ -1,681 +0,0 @@
/* This code is heavily customized for bsnes and requires cothreads.
Original portable snes_spc library available at http://www.slack.net/~ant/
Copyright (C) 2007 Shay Green. See license.txt. */
#include "../../base.h"
int const brr_block_size = 9;
// Accesses global DSP register
#define REG(n) m.regs [r_##n]
// Accesses voice DSP register
#define VREG(r,n) r [v_##n]
// Volume registers and efb are signed! Easy to forget int8 cast.
// Prefixes are to avoid accidental use of locals with same names.
// Gaussian interpolation
static short const gauss [512] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2,
2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5,
6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10,
11, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 15, 16, 16, 17, 17,
18, 19, 19, 20, 20, 21, 21, 22, 23, 23, 24, 24, 25, 26, 27, 27,
28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 36, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
58, 59, 60, 61, 62, 64, 65, 66, 67, 69, 70, 71, 73, 74, 76, 77,
78, 80, 81, 83, 84, 86, 87, 89, 90, 92, 94, 95, 97, 99, 100, 102,
104, 106, 107, 109, 111, 113, 115, 117, 118, 120, 122, 124, 126, 128, 130, 132,
134, 137, 139, 141, 143, 145, 147, 150, 152, 154, 156, 159, 161, 163, 166, 168,
171, 173, 175, 178, 180, 183, 186, 188, 191, 193, 196, 199, 201, 204, 207, 210,
212, 215, 218, 221, 224, 227, 230, 233, 236, 239, 242, 245, 248, 251, 254, 257,
260, 263, 267, 270, 273, 276, 280, 283, 286, 290, 293, 297, 300, 304, 307, 311,
314, 318, 321, 325, 328, 332, 336, 339, 343, 347, 351, 354, 358, 362, 366, 370,
374, 378, 381, 385, 389, 393, 397, 401, 405, 410, 414, 418, 422, 426, 430, 434,
439, 443, 447, 451, 456, 460, 464, 469, 473, 477, 482, 486, 491, 495, 499, 504,
508, 513, 517, 522, 527, 531, 536, 540, 545, 550, 554, 559, 563, 568, 573, 577,
582, 587, 592, 596, 601, 606, 611, 615, 620, 625, 630, 635, 640, 644, 649, 654,
659, 664, 669, 674, 678, 683, 688, 693, 698, 703, 708, 713, 718, 723, 728, 732,
737, 742, 747, 752, 757, 762, 767, 772, 777, 782, 787, 792, 797, 802, 806, 811,
816, 821, 826, 831, 836, 841, 846, 851, 855, 860, 865, 870, 875, 880, 884, 889,
894, 899, 904, 908, 913, 918, 923, 927, 932, 937, 941, 946, 951, 955, 960, 965,
969, 974, 978, 983, 988, 992, 997,1001,1005,1010,1014,1019,1023,1027,1032,1036,
1040,1045,1049,1053,1057,1061,1066,1070,1074,1078,1082,1086,1090,1094,1098,1102,
1106,1109,1113,1117,1121,1125,1128,1132,1136,1139,1143,1146,1150,1153,1157,1160,
1164,1167,1170,1174,1177,1180,1183,1186,1190,1193,1196,1199,1202,1205,1207,1210,
1213,1216,1219,1221,1224,1227,1229,1232,1234,1237,1239,1241,1244,1246,1248,1251,
1253,1255,1257,1259,1261,1263,1265,1267,1269,1270,1272,1274,1275,1277,1279,1280,
1282,1283,1284,1286,1287,1288,1290,1291,1292,1293,1294,1295,1296,1297,1297,1298,
1299,1300,1300,1301,1302,1302,1303,1303,1303,1304,1304,1304,1304,1304,1305,1305,
};
//// Counters
int const simple_counter_range = 2048 * 5 * 3; // 30720
static unsigned const counter_rates [32] =
{
simple_counter_range + 1, // never fires
2048, 1536,
1280, 1024, 768,
640, 512, 384,
320, 256, 192,
160, 128, 96,
80, 64, 48,
40, 32, 24,
20, 16, 12,
10, 8, 6,
5, 4, 3,
2,
1
};
static unsigned const counter_offsets [32] =
{
1, 0, 1040,
536, 0, 1040,
536, 0, 1040,
536, 0, 1040,
536, 0, 1040,
536, 0, 1040,
536, 0, 1040,
536, 0, 1040,
536, 0, 1040,
536, 0, 1040,
0,
0
};
inline unsigned bDSP::read_counter( int rate )
{
return ((unsigned) m.counter + counter_offsets [rate]) % counter_rates [rate];
}
//// Envelope
inline void bDSP::run_envelope( voice_t* const v )
{
int env = v->env;
if ( v->env_mode == env_release )
{
if ( (env -= 0x8) < 0 )
env = 0;
v->env = env;
}
else
{
int rate;
int env_data = VREG(v->regs,adsr1);
if ( m.t_adsr0 & 0x80 ) // ADSR
{
if ( v->env_mode >= env_decay )
{
env--;
env -= asr<8>( env );
rate = env_data & 0x1F;
if ( v->env_mode == env_decay )
rate = (m.t_adsr0 >> 3 & 0x0E) + 0x10;
}
else // env_attack
{
rate = (m.t_adsr0 & 0x0F) * 2 + 1;
env += rate < 31 ? 0x20 : 0x400;
}
}
else // GAIN
{
env_data = VREG(v->regs,gain);
int mode = env_data >> 5;
if ( mode < 4 ) // direct
{
env = env_data * 0x10;
rate = 31;
}
else
{
rate = env_data & 0x1F;
if ( mode == 4 ) // 4: linear decrease
{
env -= 0x20;
}
else if ( mode < 6 ) // 5: exponential decrease
{
env--;
env -= asr<8>( env );
}
else // 6,7: linear increase
{
env += 0x20;
if ( mode > 6 && (unsigned) v->hidden_env >= 0x600 )
env += 0x8 - 0x20; // 7: two-slope linear increase
}
}
}
// Sustain level
if ( (env >> 8) == (env_data >> 5) && v->env_mode == env_decay )
v->env_mode = env_sustain;
v->hidden_env = env;
// unsigned cast because linear decrease going negative also triggers this
if ( (unsigned) env > 0x7FF )
{
env = (env < 0 ? 0 : 0x7FF);
if ( v->env_mode == env_attack )
v->env_mode = env_decay;
}
if ( !read_counter( rate ) )
v->env = env; // nothing else is controlled by the counter
}
}
//// BRR Decoding
inline void bDSP::decode_brr( voice_t* v )
{
// Arrange the four input nybbles in 0xABCD order for easy decoding
int nybbles = m.t_brr_byte * 0x100 + ram [(v->brr_addr + v->brr_offset + 1) & 0xFFFF];
// Write to next four samples in circular buffer
int* pos = &v->buf [v->buf_pos];
if ( (v->buf_pos += 4) >= brr_buf_size )
v->buf_pos = 0;
// Decode four samples
for ( int* end = pos + 4; pos < end; pos++ )
{
// Extract nybble and sign-extend
int s = asr<12>( sclip<16>( nybbles ) );
nybbles <<= 4;
// Shift sample based on header
int const shift = m.t_brr_header >> 4;
s = asr<1>( s << shift );
if ( shift >= 0xD ) // handle invalid range
s = (s < 0 ? -0x800 : 0);
// Apply IIR filter (8 is the most commonly used)
int const p1 = pos [brr_buf_size - 1];
int const p2 = asr<1>( pos [brr_buf_size - 2] );
switch ( m.t_brr_header >> 2 & 3 )
{
case 1: s += asr<1>( p1 ) + asr<5>( -p1 ); break; // s += p1 * 0.4687500
case 2: s += p1 + asr<6>( p1 * -3 ) - p2 + asr<4>( p2 ); break; // s += p1 * 0.9531250 - p2 * 0.46875
case 3: s += p1 + asr<7>( p1 * -13 ) - p2 + asr<4>( p2 * 3 ); break; // s += p1 * 0.8984375 - p2 * 0.40625
}
// Adjust and write sample
s = sclip<16>( sclamp<16>( s ) * 2 );
pos [brr_buf_size] = pos [0] = s; // second copy simplifies wrap-around
}
}
//// Voices
#define VOICE_CLOCK( n ) void bDSP::voice_##n( voice_t* const v )
inline VOICE_CLOCK( V1 )
{
m.t_dir_addr = m.t_dir * 0x100 + m.t_srcn * 4;
m.t_srcn = VREG(v->regs,srcn);
}
inline VOICE_CLOCK( V2 )
{
// Read sample pointer (ignored if not needed)
uint8 const* entry = &ram [m.t_dir_addr];
if ( !v->kon_delay )
entry += 2;
m.t_brr_next_addr = entry [0] | entry [1] << 8;
m.t_adsr0 = VREG(v->regs,adsr0);
// Read pitch, spread over two clocks
m.t_pitch = VREG(v->regs,pitchl);
}
inline VOICE_CLOCK( V3a )
{
m.t_pitch += (VREG(v->regs,pitchh) & 0x3F) << 8;
}
inline VOICE_CLOCK( V3b )
{
// Read BRR header and byte
m.t_brr_byte = ram [(v->brr_addr + v->brr_offset) & 0xFFFF];
m.t_brr_header = ram [v->brr_addr]; // brr_addr doesn't need masking
}
VOICE_CLOCK( V3c )
{
// Pitch modulation using previous voice's output
if ( m.t_pmon & v->vbit )
m.t_pitch += asr<10>( asr<5>( m.t_output ) * m.t_pitch );
if ( v->kon_delay )
{
// Get ready to start BRR decoding on next sample
if ( v->kon_delay == 5 )
{
v->brr_addr = m.t_brr_next_addr;
v->brr_offset = 1;
v->buf_pos = 0;
m.t_brr_header = 0; // header is ignored on this sample
}
// Envelope is never run during KON
v->env = 0;
v->hidden_env = 0;
// Disable BRR decoding until last three samples
v->interp_pos = 0;
if ( --v->kon_delay & 3 )
v->interp_pos = 0x4000;
// Pitch is never added during KON
m.t_pitch = 0;
}
// Gaussian interpolation
{
// Make pointers into gaussian based on fractional position between samples
int offset = v->interp_pos >> 4 & 0xFF;
short const* fwd = gauss + 255 - offset;
short const* rev = gauss + offset; // mirror left half of gaussian
int const* in = &v->buf [(v->interp_pos >> 12) + v->buf_pos];
int out;
out = asr<11>( fwd [ 0] * in [0] );
out += asr<11>( fwd [256] * in [1] );
out += asr<11>( rev [256] * in [2] );
out = sclip<16>( out );
out += asr<11>( rev [ 0] * in [3] );
out = sclamp<16>( out ) & ~1;
// Noise
if ( m.t_non & v->vbit )
out = sclip<16>( m.noise * 2 );
// Apply envelope
m.t_output = asr<11>( out * v->env ) & ~1;
v->t_envx_out = (uint8) (v->env >> 4);
}
// Immediate silence due to end of sample or soft reset
if ( REG(flg) & 0x80 || (m.t_brr_header & 3) == 1 )
{
v->env_mode = env_release;
v->env = 0;
}
if ( m.every_other_sample )
{
// KOFF
if ( m.t_koff & v->vbit )
v->env_mode = env_release;
// KON
if ( m.kon & v->vbit )
{
v->kon_delay = 5;
v->env_mode = env_attack;
}
}
// Run envelope for next sample
if ( !v->kon_delay )
run_envelope( v );
}
inline void bDSP::voice_output( voice_t const* v, int ch )
{
// Apply left/right volume
int amp = asr<7>( m.t_output * (int8) VREG(v->regs,voll + ch) );
// Add to output total
m.t_main_out [ch] = sclamp<16>( m.t_main_out [ch] + amp );
// Optionally add to echo total
if ( m.t_eon & v->vbit )
m.t_echo_out [ch] = sclamp<16>( m.t_echo_out [ch] + amp );
}
VOICE_CLOCK( V4 )
{
// Decode BRR
m.t_looped = 0;
if ( v->interp_pos >= 0x4000 )
{
decode_brr( v );
if ( (v->brr_offset += 2) >= brr_block_size )
{
// Start decoding next BRR block
assert( v->brr_offset == brr_block_size );
v->brr_addr = (v->brr_addr + brr_block_size) & 0xFFFF;
if ( m.t_brr_header & 1 )
{
v->brr_addr = m.t_brr_next_addr;
m.t_looped = v->vbit;
}
v->brr_offset = 1;
}
}
// Apply pitch
v->interp_pos = (v->interp_pos & 0x3FFF) + m.t_pitch;
// Keep from getting too far ahead (when using pitch modulation)
if ( v->interp_pos > 0x7FFF )
v->interp_pos = 0x7FFF;
// Output left
voice_output( v, 0 );
}
inline VOICE_CLOCK( V5 )
{
// Output right
voice_output( v, 1 );
// ENDX, OUTX, and ENVX won't update if you wrote to them 1-2 clocks earlier
int endx_buf = REG(endx) | m.t_looped;
// Clear bit in ENDX if KON just began
if ( v->kon_delay == 5 )
endx_buf &= ~v->vbit;
m.endx_buf = (uint8) endx_buf;
}
inline VOICE_CLOCK( V6 )
{
(void) v; // avoid compiler warning about unused v
m.outx_buf = (uint8) (m.t_output >> 8);
}
inline VOICE_CLOCK( V7 )
{
// Update ENDX
REG(endx) = m.endx_buf;
m.envx_buf = v->t_envx_out;
}
inline VOICE_CLOCK( V8 )
{
// Update OUTX
VREG(v->regs,outx) = m.outx_buf;
}
inline VOICE_CLOCK( V9 )
{
// Update ENVX
VREG(v->regs,envx) = m.envx_buf;
}
// Most voices do all these in one clock, so make a handy composite
inline VOICE_CLOCK( V3 )
{
voice_V3a( v );
voice_V3b( v );
voice_V3c( v );
}
// Common combinations of voice steps on different voices. This greatly reduces
// code size and allows everything to be inlined in these functions.
VOICE_CLOCK(V7_V4_V1) { voice_V7(v); voice_V1(v+3); voice_V4(v+1); }
VOICE_CLOCK(V8_V5_V2) { voice_V8(v); voice_V5(v+1); voice_V2(v+2); }
VOICE_CLOCK(V9_V6_V3) { voice_V9(v); voice_V6(v+1); voice_V3(v+2); }
//// Echo
// Current echo buffer pointer for left/right channel
#define ECHO_PTR( ch ) (&ram [echo_ptr + ch * 2])
// Sample in echo history buffer, where 0 is the oldest
#define ECHO_FIR( i ) (m.echo_hist [(m.echo_hist_pos + (i)) & (echo_hist_size - 1)])
// Calculate FIR point for left/right channel
#define CALC_FIR( i, ch ) asr<6>( ECHO_FIR( i + 1 ) [ch] * (int8) REG(fir + i * 0x10) )
inline int get_echo_sample( void const* p )
{
return ((uint8 const*) p) [0] |
(( int8 const*) p) [1] << 8;
}
inline void set_echo_sample( void* p, unsigned n )
{
((uint8*) p) [0] = (uint8) n;
((uint8*) p) [1] = (uint8) (n >> 8);
}
inline int bDSP::calc_echo_output( int ch, int echo_in )
{
return sclamp<16>(
sclip<16>( asr<7>( m.t_main_out [ch] * (int8) REG(mvoll + ch * 0x10) ) ) +
sclip<16>( asr<7>( echo_in * (int8) REG(evoll + ch * 0x10) ) ) );
}
//// Timing
void bDSP::enter()
{
int t_esa = REG(esa);
while ( 1 )
{
// n is currently ignored
#define NEXT_CLOCK( n ) \
scheduler.addclocks_dsp( 3 * 8 );
// Execute clock for a particular voice
#define V( clock, voice ) voice_##clock( &m.voices [voice] );
/* The most common sequence of clocks uses composite operations
for efficiency. For example, the following are equivalent to the
individual steps on the right:
V(V7_V4_V1,2) -> V(V7,2) V(V4,3) V(V1,5)
V(V8_V5_V2,2) -> V(V8,2) V(V5,3) V(V2,4)
V(V9_V6_V3,2) -> V(V9,2) V(V6,3) V(V3,4) */
NEXT_CLOCK( 0) V(V5,0)V(V2,1)
NEXT_CLOCK( 1) V(V6,0)V(V3,1)
NEXT_CLOCK( 2) V(V7_V4_V1,0)
NEXT_CLOCK( 3) V(V8_V5_V2,0)
NEXT_CLOCK( 4) V(V9_V6_V3,0)
NEXT_CLOCK( 5) V(V7_V4_V1,1)
NEXT_CLOCK( 6) V(V8_V5_V2,1)
NEXT_CLOCK( 7) V(V9_V6_V3,1)
NEXT_CLOCK( 8) V(V7_V4_V1,2)
NEXT_CLOCK( 9) V(V8_V5_V2,2)
NEXT_CLOCK(10) V(V9_V6_V3,2)
NEXT_CLOCK(11) V(V7_V4_V1,3)
NEXT_CLOCK(12) V(V8_V5_V2,3)
NEXT_CLOCK(13) V(V9_V6_V3,3)
NEXT_CLOCK(14) V(V7_V4_V1,4)
NEXT_CLOCK(15) V(V8_V5_V2,4)
NEXT_CLOCK(16) V(V9_V6_V3,4)
NEXT_CLOCK(17) V(V1,0) V(V7,5)V(V4,6)
NEXT_CLOCK(18) V(V8_V5_V2,5)
NEXT_CLOCK(19) V(V9_V6_V3,5)
NEXT_CLOCK(20) V(V1,1) V(V7,6)V(V4,7)
NEXT_CLOCK(21) V(V8,6)V(V5,7) V(V2,0) /* t_brr_next_addr order dependency */
NEXT_CLOCK(22) V(V3a,0) V(V9,6)V(V6,7)
// History
if ( ++m.echo_hist_pos >= echo_hist_size )
m.echo_hist_pos = 0;
int const echo_ptr = (t_esa * 0x100 + m.echo_offset) & 0xFFFF;
// FIR
int echo_in_l = CALC_FIR( 0, 0 );
int echo_in_r = CALC_FIR( 0, 1 );
ECHO_FIR( 0 ) [0] = asr<1>( get_echo_sample( ECHO_PTR( 0 ) ) );
NEXT_CLOCK(23) V(V7,7)
echo_in_l += CALC_FIR( 1, 0 ) + CALC_FIR( 2, 0 );
echo_in_r += CALC_FIR( 1, 1 ) + CALC_FIR( 2, 1 );
ECHO_FIR( 0 ) [1] = asr<1>( get_echo_sample( ECHO_PTR( 1 ) ) );
NEXT_CLOCK(24) V(V8,7)
echo_in_l += CALC_FIR( 3, 0 ) + CALC_FIR( 4, 0 ) + CALC_FIR( 5, 0 );
echo_in_r += CALC_FIR( 3, 1 ) + CALC_FIR( 4, 1 ) + CALC_FIR( 5, 1 );
NEXT_CLOCK(25) V(V3b,0) V(V9,7)
echo_in_l = sclip<16>( echo_in_l + CALC_FIR( 6, 0 ) ) + sclip<16>( CALC_FIR( 7, 0 ) );
echo_in_r = sclip<16>( echo_in_r + CALC_FIR( 6, 1 ) ) + sclip<16>( CALC_FIR( 7, 1 ) );
echo_in_l = sclamp<16>( echo_in_l ) & ~1;
echo_in_r = sclamp<16>( echo_in_r ) & ~1;
NEXT_CLOCK(26)
// Echo feedback
int echo_out_l = m.t_echo_out [0] + sclip<16>( asr<7>( echo_in_l * (int8) REG(efb) ) );
int echo_out_r = m.t_echo_out [1] + sclip<16>( asr<7>( echo_in_r * (int8) REG(efb) ) );
echo_out_l = sclamp<16>( echo_out_l ) & ~1;
echo_out_r = sclamp<16>( echo_out_r ) & ~1;
// Output
int main_out_l = calc_echo_output( 0, echo_in_l );
NEXT_CLOCK(27)
int main_out_r = calc_echo_output( 1, echo_in_r );
// TODO: global muting isn't this simple (turns DAC on and off
// or something, causing small ~37-sample pulse when first muted)
if ( REG(flg) & 0x40 )
{
main_out_l = 0;
main_out_r = 0;
}
// Output sample to DAC
snes.audio.update( main_out_l, main_out_r );
m.t_main_out [0] = 0;
m.t_main_out [1] = 0;
m.t_pmon = REG(pmon) & 0xFE; // voice 0 doesn't support PMON
NEXT_CLOCK(28)
m.t_non = REG(non);
m.t_eon = REG(eon);
m.t_dir = REG(dir);
int echo_disabled = REG(flg);
NEXT_CLOCK(29)
// Write left echo
if ( !(echo_disabled & 0x20) )
set_echo_sample( ECHO_PTR( 0 ), echo_out_l );
m.t_echo_out [0] = 0;
t_esa = REG(esa);
if ( !m.echo_offset )
m.echo_length = (REG(edl) & 0x0F) * 0x800;
m.echo_offset += 4;
if ( m.echo_offset >= m.echo_length )
m.echo_offset = 0;
if ( (m.every_other_sample ^= 1) != 0 )
m.new_kon &= ~m.kon; // clears KON 63 clocks after it was last read
echo_disabled = REG(flg);
NEXT_CLOCK(30)
// Write right echo
if ( !(echo_disabled & 0x20) )
set_echo_sample( ECHO_PTR( 1 ), echo_out_r );
m.t_echo_out [1] = 0;
if ( m.every_other_sample )
{
m.kon = m.new_kon;
m.t_koff = REG(koff);
}
if ( --m.counter < 0 )
m.counter = simple_counter_range - 1;
// Noise
if ( !read_counter( REG(flg) & 0x1F ) )
{
int feedback = (m.noise << 13) ^ (m.noise << 14);
m.noise = (feedback & 0x4000) ^ (m.noise >> 1);
}
V(V3c,0)
NEXT_CLOCK(31) V(V4,0) V(V1,2)
}
}
//// Setup
bDSP::bDSP() { }
bDSP::~bDSP() { }
void bDSP::reset()
{
REG(flg) = 0xE0;
m.noise = 0x4000;
m.echo_hist_pos = 0;
m.every_other_sample = 1;
m.echo_offset = 0;
m.counter = 0;
}
static uint8 const initial_regs [bDSP::register_count] =
{
0x45,0x8B,0x5A,0x9A,0xE4,0x82,0x1B,0x78,0x00,0x00,0xAA,0x96,0x89,0x0E,0xE0,0x80,
0x2A,0x49,0x3D,0xBA,0x14,0xA0,0xAC,0xC5,0x00,0x00,0x51,0xBB,0x9C,0x4E,0x7B,0xFF,
0xF4,0xFD,0x57,0x32,0x37,0xD9,0x42,0x22,0x00,0x00,0x5B,0x3C,0x9F,0x1B,0x87,0x9A,
0x6F,0x27,0xAF,0x7B,0xE5,0x68,0x0A,0xD9,0x00,0x00,0x9A,0xC5,0x9C,0x4E,0x7B,0xFF,
0xEA,0x21,0x78,0x4F,0xDD,0xED,0x24,0x14,0x00,0x00,0x77,0xB1,0xD1,0x36,0xC1,0x67,
0x52,0x57,0x46,0x3D,0x59,0xF4,0x87,0xA4,0x00,0x00,0x7E,0x44,0x9C,0x4E,0x7B,0xFF,
0x75,0xF5,0x06,0x97,0x10,0xC3,0x24,0xBB,0x00,0x00,0x7B,0x7A,0xE0,0x60,0x12,0x0F,
0xF7,0x74,0x1C,0xE5,0x39,0x3D,0x73,0xC1,0x00,0x00,0x7A,0xB3,0xFF,0x4E,0x7B,0xFF
};
void bDSP::power()
{
ram = (uint8*) smp.get_spcram_handle();
memset( &m, 0, sizeof m );
//memcpy( m.regs, initial_regs, sizeof m.regs );
memset(m.regs, 0, sizeof m.regs);
REG(flg) = 0xe0;
// Internal state
for ( int i = voice_count; --i >= 0; )
{
voice_t* v = &m.voices [i];
v->brr_offset = 1;
v->vbit = 1 << i;
v->regs = &m.regs [i * 0x10];
}
m.new_kon = REG(kon);
m.t_dir = REG(dir);
reset();
}

View File

@@ -1,172 +0,0 @@
class bDSP : public DSP {
public:
void enter();
uint8 read( uint8 addr );
void write( uint8 addr, uint8 data );
void power();
void reset();
bDSP();
~bDSP();
template<int n, typename T> inline T asr(const T x) {
enum { bits = (sizeof(T) << 3) - n };
return sclip<bits>(x >> n);
}
public:
enum { echo_hist_size = 8 };
enum { register_count = 128 };
enum { voice_count = 8 };
enum env_mode_t { env_release, env_attack, env_decay, env_sustain };
enum { brr_buf_size = 12 };
struct voice_t
{
int buf [brr_buf_size*2];// decoded samples (twice the size to simplify wrap handling)
int buf_pos; // place in buffer where next samples will be decoded
int interp_pos; // relative fractional position in sample (0x1000 = 1.0)
int brr_addr; // address of current BRR block
int brr_offset; // current decoding offset in BRR block
uint8* regs; // pointer to voice's DSP registers
int vbit; // bitmask for voice: 0x01 for voice 0, 0x02 for voice 1, etc.
int kon_delay; // KON delay/current setup phase
env_mode_t env_mode;
int env; // current envelope level
int hidden_env; // used by GAIN mode 7, very obscure quirk
uint8 t_envx_out;
};
private:
struct state_t
{
uint8 regs [register_count];
// Echo history keeps most recent 8 samples
int echo_hist [echo_hist_size] [2];
int echo_hist_pos;
int every_other_sample; // toggles every sample
int kon; // KON value when last checked
int noise;
int counter;
int echo_offset; // offset from ESA in echo buffer
int echo_length; // number of bytes that echo_offset will stop at
// Hidden registers also written to when main register is written to
int new_kon;
uint8 endx_buf;
uint8 envx_buf;
uint8 outx_buf;
// Temporary state between clocks
// read once per sample
int t_pmon;
int t_non;
int t_eon;
int t_dir;
int t_koff;
// read a few clocks ahead then used
int t_brr_next_addr;
int t_adsr0;
int t_brr_header;
int t_brr_byte;
int t_srcn;
// internal state that is recalculated every sample
int t_dir_addr;
int t_pitch;
int t_output;
int t_looped;
// left/right sums
int t_main_out [2];
int t_echo_out [2];
voice_t voices [voice_count];
};
state_t m;
uint8* ram;
unsigned read_counter( int rate );
void run_envelope( voice_t* const v );
void decode_brr( voice_t* v );
void voice_output( voice_t const* v, int ch );
void voice_V1( voice_t* const );
void voice_V2( voice_t* const );
void voice_V3( voice_t* const );
void voice_V3a( voice_t* const );
void voice_V3b( voice_t* const );
void voice_V3c( voice_t* const );
void voice_V4( voice_t* const );
void voice_V5( voice_t* const );
void voice_V6( voice_t* const );
void voice_V7( voice_t* const );
void voice_V8( voice_t* const );
void voice_V9( voice_t* const );
void voice_V7_V4_V1( voice_t* const );
void voice_V8_V5_V2( voice_t* const );
void voice_V9_V6_V3( voice_t* const );
int calc_echo_output( int ch, int sample );
// Global registers
enum {
r_mvoll = 0x0C, r_mvolr = 0x1C,
r_evoll = 0x2C, r_evolr = 0x3C,
r_kon = 0x4C, r_koff = 0x5C,
r_flg = 0x6C, r_endx = 0x7C,
r_efb = 0x0D, r_pmon = 0x2D,
r_non = 0x3D, r_eon = 0x4D,
r_dir = 0x5D, r_esa = 0x6D,
r_edl = 0x7D,
r_fir = 0x0F // 8 coefficients at 0x0F, 0x1F ... 0x7F
};
// Voice registers
enum {
v_voll = 0x00, v_volr = 0x01,
v_pitchl = 0x02, v_pitchh = 0x03,
v_srcn = 0x04, v_adsr0 = 0x05,
v_adsr1 = 0x06, v_gain = 0x07,
v_envx = 0x08, v_outx = 0x09
};
};
inline uint8 bDSP::read( uint8 addr )
{
return m.regs [addr];
}
inline void bDSP::write( uint8 addr, uint8 data )
{
m.regs [addr] = data;
switch ( addr & 0x0F )
{
case v_envx:
m.envx_buf = data;
break;
case v_outx:
m.outx_buf = data;
break;
case 0x0C:
if ( addr == r_kon )
m.new_kon = data;
if ( addr == r_endx ) // always cleared, regardless of data written
{
m.endx_buf = 0;
m.regs [r_endx] = 0;
}
break;
}
}

View File

@@ -1,32 +0,0 @@
#include "../../base.h"
#include "spc_dsp.h"
void bDSP::power() {
spc_dsp_init(r_smp->get_spcram_handle());
spc_dsp_reset();
}
void bDSP::reset() {
spc_dsp_soft_reset();
}
uint8 bDSP::read(uint8 addr) {
return spc_dsp_read(addr);
}
void bDSP::write(uint8 addr, uint8 data) {
spc_dsp_write(addr, data);
}
#define SPC_DSP_CUSTOM_RUN 1 //causes spc_dsp_run() to not be defined since it's huge and we don't need it
#define SPC_DSP_OUT_HOOK(left, right) snes.audio_update(left, right);
#include "spc_dsp.cpp"
void bDSP::enter() { loop:
#define PHASE(n) scheduler.addclocks_dsp(3);
#include "spc_dsp_timing.h"
goto loop;
}
bDSP::bDSP() {}
bDSP::~bDSP() {}

Some files were not shown because too many files have changed in this diff Show More