Compare commits

...

284 Commits
v015 ... v067

Author SHA1 Message Date
byuu
7b7a95af67 Update to bsnes v067 release.
I apologize, bsnes v066 had a small error in the source that resulted in the PPU not synchronizing properly to the CPU. This bug was not exposed in the images I use to test releases. I have also updated the cheat code database, which is maintained by mightymo.
2010-08-02 00:25:53 +00:00
byuu
a266a2b5e2 Update to bsnes v066 release.
Major features in this release are: serial controller emulation, a brand new scheduler that supports multiple simultaneous coprocessors, and accuracy improvements.
The serial controller is something devised by blargg. With the proper voltage adjustments (5v-9v), it is possible to wire an SNES controller to a serial port, which can then be used for bidirectional communication between the SNES, and (usually, but not only) a PC. The support in bsnes was added so that such programs could be debugged and ran from within an emulator, and not just on real hardware.
The scheduler rewrite was meant to allow the combination of coprocessors. It was specifically meant to allow the serial controller thread to run alongside the SuperFX and SA-1 coprocessor threads, but it also allows fun things like MSU1 support in SuperFX and SA-1 games, and even creating dev cartridges that utilize both the SuperFX and SA-1 at the same time. The one thing not yet allowed is running multiple instances of the exact same coprocessor at the same time, as this is due to design constraints favoring code inlining.
There are two important accuracy updates. The first is that when PAL video mode is used without being in overscan mode, black bars are shown. Emulators have always shown this black bar at the bottom of the screen, but this is actually incorrect. resxto took pictures from his PAL TV that shows the image is in fact vertically centered in the screen. bsnes has been updated to reflect this.
Also interesting is that I have backported some code from the dot-based PPU renderer. In the game Uniracers, it writes to OAM during Hblank, and expects the write to go to a specific address. In previous releases, that address was hard-coded to go to the required memory location. But the way the hardware really works is that the write goes to the extended attribute address for the last sprite that the PPU fetched, as the PPU is still asserting the OAM address bus. Now, due to the precision limitations, I was not able to also port timing access during the active display period. However, this is sufficient to at least remove the last global hack from the older, speed-focused scanline renderer.
2010-08-01 05:46:17 +00:00
byuu
53f03be5a2 Update to bsnes v065r05 release.
Fairly major changes here, I'd appreciate some testing if anyone's not
busy. Note that the save state version has been bumped, so consider
WIP saves unstable until v066 official.

Rewrote the entire scheduling system. Instead of having a global class
that all of the chips call into, each class now contains its own
thread, clock and frequency information. They also implement their own
syncing primitives, but with a tiny bit of standardization.
void step(unsigned clocks) -- add to/subtract from counter based on
master/slave select.
void synchronize_chip() -- make sure chip is caught up to our current
thread before continuing.

So we go from scheduler.sync_copcpu() to sa1.synchronize_cpu(); with
the sa1. being omitted inside the SA1 class itself.

The S-CPU implementation also adds an array<Processor*> coprocessors;
list, and iterates them all. This allows bsnes to have an infinite
number of additional coprocessors at the same time. But there is still
the limitation of only one of each type. So you can use the XML memory
mapping to make a cartridge that contains a SuperFX2 chip, an SA-1
chip, an MSU1 chip and that can be debugged via serial communications.
However, you can't make a cart that has two SA-1 chips. That
limitation probably could be overcome as well, but it's less
important. I mainly wanted to be able to use MSU1 and Serial on
special chip games.

I implemented the synchronization primitives in the chip base classes,
which means that for inlining purposes I had to make it all global, so
you'll have src/cpu/synchronization.hpp, etc now. This was to reduce
some redundancy of having the same exact code inside both bPPU and
sPPU, etc. I'll probably make a Coprocessor : Processor class to
automatically implement the step+synchronize_cpu functions for the
five coprocessors next.

The Scheduler class is actually still around, but it's very trivial
now. It simply saves the program thread and last active emulation
thread for the purpose of entering and exiting emulation. Because I
killed Scheduler::init(), which was responsible for destroying and re-
creating threads, I had to create the threads inside
ChipName::create(), which I call at power and reset. This means that
to load a save state, the system needs to be reset to destroy those
threads.

This caused some troubles with the SA-1, specifically in Kirby's
Dreamland 3, but no other games I tried. I had to move the SA-1 bus
initialization to the power-on event, and only reset when loading a
save state. It would appear that the SA-1 is leaking bus mapping state
information, presumably from the SA-1 MMIO registers that control some
of the mapping layout. If I add remapping of those sections into the
SA1::serialize() function, it should take care of that problem and I
can move sa1bus.init() back into SA1::reset().

All of this results in a 2-3% speed hit for normal games, and a 6-7%
speed hit for special chip games. The former should not have any speed
hit, so I will have to look into what's going on there. The latter we
have no choice on, to allow for more than one coprocessor, the
coprocessor synchronization needs to iterate a list, compared to a
single hard-coded check in the previous builds. If I can figure out
what is happening with the regular game speeds, it should drop the
special chip hit to 4%. Worst part is this hit is in addition to the
10-15% speed hit from v065 official where I wasn't syncing the special
chips up to the CPU except once per scanline and on MMIO accesses.

But that's progress. v065 is definitely going to be the preferred
build for playing SuperFX/SA-1 games for a long time to come.
2010-07-29 16:24:28 +00:00
byuu
77375c3c68 Update to bsnes v065r04 release.
Only posting because the link changed, it's the exact same as r03.
Only difference is some improvements to nall:
- string class gains lower(), upper(), transform(), *trim(_once)
- file::print now accepts variadic arguments like print
Examples:
    strtr(item, "ABCDEF", "abcdef"); -> item.transform("ABCDEF",
    "abcdef");
    strlower(item); -> item.lower();
    fp.print(string("Age: ", age, "\n")); -> fp.print("Age: ", age,
    "\n");
2010-07-16 14:40:08 +00:00
byuu
dce3e61f06 Update to bsnes v065r03 release.
Polishing work. My dlopen wrapper accepts an optional path argument
now, and the basename setting is universal instead of just for MSU1,
so serial-based games can load in a dynamic client library directly.

Still need to update snesserver to accept another argument for the
program library name to load.

Upped the serial polling frequency to 8x UART speed per blargg.

And a very tricky change, I updated nall/string to remove sprint(). At
first, I used:
    string name = string() << path << basename << ".msu";


I then improved upon that with:
    string name = sprint(path, basename, ".msu");


Tonight I went ahead and finished this by taking advantage of variadic
templates for the constructor itself. Very tricky because my
conversion functions created new strings to copy data into, which
would create an infinite loop; then of course I also had to leave the
copy constructor behind even after this. So the end result is the
following:
    string name(path, basename, ".msu");


Oh, and I found a typo in MSU1, it wasn't using the proper extension
when loading a save state for the data file.
2010-07-12 15:56:17 +00:00
byuu
20b44ddfd1 Update to bsnes v065r02 release.
Be warned, this is going to get complicated.

To start out with, serial.tar.bz2 is a simple SNES program that is
right now being used for integrity testing. The important part is
here:

    serial_read:
    lda #$01
    -; bit $4017; bne -
    -; bit $4017; beq -
    nop #24
    pha; lda $4017; eor #$01; ror; pla; ror; nop #18
    pha; lda $4017; eor #$01; ror; pla; ror; nop #18
    pha; lda $4017; eor #$01; ror; pla; ror; nop #18
    pha; lda $4017; eor #$01; ror; pla; ror; nop #18
    pha; lda $4017; eor #$01; ror; pla; ror; nop #18
    pha; lda $4017; eor #$01; ror; pla; ror; nop #18
    pha; lda $4017; eor #$01; ror; pla; ror; nop #18
    pha; lda $4017; eor #$01; ror; pla; ror; rts

    serial_write:
    pha #6; pla #6; wdm #$00; stz $4016; sec
    pha #6; pla #6; wdm #$00; sta $4016; ror
    pha #6; pla #6; wdm #$00; sta $4016; ror
    pha #6; pla #6; wdm #$00; sta $4016; ror
    pha #6; pla #6; wdm #$00; sta $4016; ror
    pha #6; pla #6; wdm #$00; sta $4016; ror
    pha #6; pla #6; wdm #$00; sta $4016; ror
    pha #6; pla #6; wdm #$00; sta $4016; ror
    pha #6; pla #6; wdm #$00; sta $4016; ror
    pha #6; pla #6; wdm #$00; sta $4016; rts


Fairly ugly, but it works.

Next, I needed a way to be able to execute the client in such a way
that it would work with both bsnes and real hardware, with no
recompilation or changes needed. The nice way would be some form of
inter-process communication, but well, I don't really do that. And
it's probably extremely platform-dependent.

So I used what was available to me already, a cross-platform dlopen
wrapper for dynamic library support. The client application is written
and compiled into a shared library that exports a single function,
snesserial_main, which runs as if it is its own program and never
returns. It takes three parameters, the time tick(), read() and
write() function pointers. It can call them to do its work. This
process is put in a folder called snesserial for now. It's the
accompanying program to serial.sfc.

Now I have both bsnes (v065.02 above) and snesserver, they both act
the same way. They load in snesserial, and give it those three
functions and call its main entry point. The difference is that the
read/write functions in bsnes simulate a serial strobe to the
emulator, and the read/write functions in snesserver actually read and
write to the TTY device you specify as the program argument, eg for me
I use: ./snesserver /dev/ttyUSB0
Mmm, USB<>SNES for the win.

There's a limitation in my dlopen wrapper, it adds the libN.so or
N.dll stuff automatically, making it difficult to also specify a path.
That means that for now you have to put libsnesserial.so into
/usr/local/lib. Obviously you don't want to be limited to just one
program. The plan is to have it load the library that matches the game
name:
zelda.sfc + zelda.so/zelda.dll/zelda.dylib (yeah, no libzelda.so.)

Now, the bsnes+serial emulation works on any platform. However,
snesserver only works on Linux. You can blame that one on Microsoft.
They make you require special kernel drivers to be able to access the
serial port. I'm not going through the trouble. OS X can probably use
it if it makes the appropriate /dev/tty device, but I'm not going to
test it.

Activating the module can only be done with a custom XML file, as
before. Still need to work on integration with the controller port
options, as it's not really a special chip.

Lastly, the timing is "pretty good", but not perfect. It accepted a
374 cycle-per-bit loop for serial writes from the SNES to the PC, but
snesserver did not. I had to adjust to 364 cycle-per-bit loop for it
to work on both.

This is really bad, because the goal here is to use the PC as the
testbed to make sure it'll work on the real thing. On the plus side,
you only have to get it working one time, and stick with the
serial_read/serial_write functions like at the top of this post. But I
do need to address this. I'm not entirely sure how to more accurately
simulate a serial port at this point though.

Oh, and I am thinking I need to expand the read/write functions to
process more than one byte at a time. That should greatly speed up
transfer time on the real thing. I also need to add some slowdown so
the emulator more closely matches hardware speeds.
2010-07-11 18:27:42 +00:00
byuu
79f20030a0 Update to bsnes v065r01 release.
In order to fully decode the 16MB address maps, I am going to need to
use blargg's stop-and-swap, which will require a serial-communications
program. To develop this program, and others in the future, as well as
for testing automation, it would be very beneficial to have a way to
debug these programs through bsnes.

So what I'm working on now is emulating a serial port inside bsnes.
The basic premise is to start with a custom XML map that specifies its
presence:

    <?xml version="1.0" encoding="UTF-8"?>
    <cartridge region="NTSC">
    <rom>
    <map mode="linear" address="00-7f:8000-ffff"/>
    <map mode="linear" address="80-ff:8000-ffff"/>
    </rom>

    <ram size="2000">
    <map mode="linear" address="70-7f:0000-7fff"/>
    </ram>

    <serial baud="57600">
    </serial>
    </cartridge>


I am essentially treating the serial communication as a special chip.
One could argue this belongs as an option under controllers, and one
would be right. But as I can't have two coprocessor threads at the
same time, this is how it is for right now. Eventually it'll probably
be under controller port 2, and only enabled in the debugger builds.

So, this pseudo-coprocessor ... it's basically emulating the PC-side
communications program.
Meaning I still need to externalize this somehow so that any program
can be run.
The below program writes 0x96 six times, and then reads in data six
times. Well, technically forever, but the SNES ROM only writes six
times at the end.

    void Serial::enter() {
    scheduler.clock.cop_freq = cartridge.serial_baud_rate() * 2;

    latch = 0;
    add_clocks(512);

    for(unsigned i = 0; i < 6; i++) {
    latch = 1; add_clocks(2);

    latch = 1; add_clocks(2);
    latch = 0; add_clocks(2);
    latch = 0; add_clocks(2);
    latch = 1; add_clocks(2);
    latch = 0; add_clocks(2);
    latch = 1; add_clocks(2);
    latch = 1; add_clocks(2);
    latch = 0; add_clocks(2);

    latch = 0; add_clocks(2);
    }

    while(true) {
    while(cpu.joylatch() == 0) add_clocks(1);
    while(cpu.joylatch() == 1) add_clocks(1);
    add_clocks(1);

    uint8 data = 0;
    for(unsigned i = 0; i < 8; i++) {
    add_clocks(2);
    data = (data << 1) | cpu.joylatch();
    }

    print("Read ", strhex<2>(data), "\n");
    }
    }


The SNES code looks like this:

    //21,477,272hz cpu / 57,600hz serial = ~372.87 clocks/tick

    org $8000
    xce; rep #$10
    ldx #$01ff; txs

    jsr serial_read; sta $700000
    jsr serial_read; sta $700001
    jsr serial_read; sta $700002
    jsr serial_read; sta $700003
    jsr serial_read; sta $700004
    jsr serial_read; sta $700005

    nop #46

    jsr serial_write
    jsr serial_write
    jsr serial_write
    jsr serial_write
    jsr serial_write
    jsr serial_write

    //hang
    -; bra -

    serial_read:
    -; lda $4017; and #$01; bne -
    -; lda $4017; and #$01; beq -
    nop #23; lda $00; nop #10

    lda $4017; and #$01; asl $00; ora $00; sta $00; lda $00; nop #13
    lda $4017; and #$01; asl $00; ora $00; sta $00; lda $00; nop #13
    lda $4017; and #$01; asl $00; ora $00; sta $00; lda $00; nop #13
    lda $4017; and #$01; asl $00; ora $00; sta $00; lda $00; nop #13
    lda $4017; and #$01; asl $00; ora $00; sta $00; lda $00; nop #13
    lda $4017; and #$01; asl $00; ora $00; sta $00; lda $00; nop #13
    lda $4017; and #$01; asl $00; ora $00; sta $00; lda $00; nop #13
    lda $4017; and #$01; asl $00; ora $00; sta $00; lda $00; nop #13

    rts

    serial_write:
    lda #$01; sta $4016; nop #23

    lda #$00; sta $4016; nop #23

    lda #$01; sta $4016; nop #23
    lda #$00; sta $4016; nop #23
    lda #$00; sta $4016; nop #23
    lda #$01; sta $4016; nop #23
    lda #$00; sta $4016; nop #23
    lda #$01; sta $4016; nop #23
    lda #$01; sta $4016; nop #23
    lda #$00; sta $4016; nop #23

    lda #$01; sta $4016; nop #23

    rts


That reads six times, and then writes six times.

I haven't made the test do an infinite PC->SNES transfer, but I have
for SNES->PC. No errors after millions of bytes, even if I stride the
CPU timing.

As this is just an example, it's pretty lousy with actual timing, but
I guess that's a good thing as it still works quite well. More
tolerance = less potential for errors.

**Now, this part is important.**

While debugging this, I noticed that my serial coprocessor was only
running when Vcounter=n,Hcounter=0. In other words, nothing was making
the CPU synchronize back to the coprocessor, except the once-per-
scanline synchronization that was there in case of CPU stalls.

That's ... really bad. MSU1 worked only because it buffers a few
hundred samples for audio mixing. I don't really know why this didn't
cause an issue for SuperFX, SA-1 or Super Game Boy games; but in
theory they were at most 682x less precise than they should have been
in terms of CPU->coprocessor synchronization.

Making it sync after every add_clocks() call results in a 10% speed
hit to SuperFX, SA-1 and Super Game Boy emulation, unfortunately.

I don't notice any quality improvements in emulation, but in theory
the lack of this syncing before effectively eliminated the benefits of
the SuperFX and SA-1 being cycle based.

I'm going to have to look into this more to understand if I was
intentionally not doing this sync before, or if I really did forget
it. I'm thinking it was an oversight right now. The SuperFX and SA-1
don't really talk back and forth a whole hell of a lot, so once a
scanline probably wouldn't be that noticeable.

But holy hell ... now that I'm thinking about it, I wonder if this was
the cause of all that craziness in trying to sync up the Super Game
Boy's VRAM transfers. Yeah, definitely need to look into this more ...
2010-07-09 15:02:23 +00:00
byuu
79b939e1c7 Update to bsnes v065 release.
It's been a while, so here is a new release of bsnes.
Unfortunately I don't have a full changelog this time. Most of the work went into stabilizing libsnes (which is used by the experimental .NET, Cocoa and Python UIs; as well as by Richard Bannister's OS X port).
The Windows binary package now comes with all three variants included: bsnes.exe, the standard version that casual users should run; bsnes-debugger.exe, for SNES programmers and ROM hackers only; and bsnes-accurate.exe, which should not be used by anybody, ever.
In all seriousness, bsnes-accurate.exe is bsnes with the dot-based S-PPU renderer. It's twice as slow as the normal build, and you won't really notice any differences except in Air Strike Patrol. It's there for the curious and for any SNES programmers who want to try making some really awesome video demos.
Changelog:
* OS X port builds once again; now requires gcc44 from Macports
* libsnes API finalized
* fixed a bug with S-CPU debugger breakpoints
* various source cleanup
2010-06-27 12:29:18 +00:00
byuu
3ae74ff5a5 Update to bsnes v064r08 release.
Fixes Super Game Boy save RAM/RTC data.
Fixes a crash when you pass a null pointer for the second Sufami Turbo
cartridge, etc.

[No archive available]
2010-06-14 02:01:12 +00:00
byuu
7351b910c5 Update to bsnes v064r07 release.
Wow, that's probably a record for the longest time between two WIPs.
My priority has obviously shifted to language learning, but as time
goes on things should balance out better.

Okay, changes:
- linear_vector, pointer_vector and array are greatly improved: added
insert and remove (can insert or remove more than one item at a time
for O(n) performance); renamed add to append; improved array::find to
use optional<unsigned> instead of -1 trick ala the new strpos function
- fixed string to floating-point conversion for international systems
that use "," for fractions
- libsnes::snes_get_memory_(size|data) will return 0 if you try and
access: BS-X data without a BS-X cartridge loaded, same for ST, same
for SGB; this is in case someone tries to write a generic function
that writes all memory that is valid instead of special casing based
on the cartridge type they loaded
- libsnes::snes_load_cartridge_* returns a boolean result to indicate
success; always returns true for now, but it's meant to eventually
catch when libgambatte fails to load a GB cartridge -- bsnes itself
will never fail to load an SNES/BSX/ST cartridge
- Linux monospace font changed from "Monospace" to "Liberation Mono",
because the former is not monospaced when your desktop environment is
set to Japanese, etc.
- some other misc. cleanups

[No archive available]
2010-06-06 05:28:35 +00:00
byuu
6bbb609f2f Update to bsnes v064r06 release.
Updated to build using Xcode Snow Leopard+Qt/Cocoa 4.6.2+Macports
gcc44.
2010-05-03 14:04:30 +00:00
byuu
0d19902435 Update to bsnes v064r05 release.
- swaps the video_refresh output from BGR555 to RGB555, for the sake
of direct copying for certain APIs. Not going to do RGB565 because the
G5 bit doesn't exist, and faking it is lame.

[Meanwhile, in bsnesui 2010-04-24...]

bsnes.python:
- adds more icons and stuff.
bsnes.net:
- new port, targets C#, binds every function in libsnes
- targets .NET 3.5 ... I honestly would have went with 4.0 for the
nicer IntPtr addition alone, but the SP3 requirement may put off a lot
of people
- video output that doesn't scale (or clean up when dropping to a
smaller size)
- Port1 joypad input support via keyboard only
bsnes.cocoa:
- stuck in a time/space wormhole until Apple gets their heads out of
their asses and updates GCC

Probably the coolest thing about Python and .NET is that anyone can
now compile these GUIs and modify them just by having the run-times
installed. I really like the way MS is distributing the complete
development chain along with the run-time.
2010-04-25 08:39:41 +00:00
byuu
44bab83d68 Update to bsnes v064r04 release.
Fixes S-CPU debugger breakpoint issue.
libsnes always returns 0 for "no memory present" now, never -1U.

[Meanwhile, in bsnes-python 2010-04-20...]

Won't error if there's no joypad present.
Swaps menu and status bars with a toolbar.
Adds keyboard support - you can use both a keyboard and joypad for
input now.
Won't crash if RAM doesn't exist yet.
Won't crash if game uses no RAM.
2010-04-20 22:33:44 +00:00
byuu
42a4c1d60e Update to bsnes v064r03 release.
Some changes to libsnes. Really hoping the API will be stable from
this point out ...
2010-04-19 17:37:14 +00:00
byuu
645689e683 Update to bsnes v064r02 release.
Nothing interesting, just added bsnes-qt.py to ui_python. No input
handling, but OpenGL-based video resizing and libao audio. Doesn't use
numpy, found a workaround for that. It's obvious that we need
video/audio/input handled by an external library for this to work, so
I'm thinking now about a rewrite of ruby to a C-like interface.
2010-04-18 14:09:17 +00:00
byuu
8b0153daf0 Update to bsnes v064r01 release.
Adds bool snes_get_region(void) to libsnes (permanent).
Adds snes_blit_colortable and snes_blit to libsnes (temporary).
Adds src/ui_python with a basic Python GUI, and abstraction between
the libsnes wrapper and PyGTK (so it can be reused for PyQt, etc.)

The GUI has:
- menubar
- video output (2x scale, supports NTSC/PAL, hires, overscan and
interlace correctly)
- audio output (libao through ALSA)
- input (very lousy key press events, they toggle off and on if you
hold a key down ...)

I'm getting full-speed, so that's good.

Not sure where I want to take all of this stuff yet, but it's kind of
neat for now I suppose. It would be kinda fun to go really out there
with completely new GUI design styles that aren't just your standard
menubar+video. Things like a toolbar, mouse gestures, really deep
platform integration, AVI-based recording, frame analysis shit, game-
specific GUI shit (perhaps map touch-screen input + gyroscope on top
of a simulated gamepad; or perhaps read the contents of RAM and
provide statistical information on the sides of the video output
screen?), I dunno ... whatever. It's there, it's possible, but it's
certainly not good enough to replace the official C++ Qt port, and I
don't really have the time or patience to make it that good myself.
2010-04-16 13:40:27 +00:00
byuu
9ca1e259cb Update to bsnes v064 release.
A thank you to everyone who helped test the RC to ensure stability. I've uploaded the official v064 release to Google Code.
The most important change in this release is the cycle-based PPU renderer; but due to performance reasons the scanline-based renderer remains the default in the Windows binary. If you want to try out the cycle-based renderer, you will need to compile from source for now.
Another major change is the introduction of libsnes, which allows one to build bsnes as a shared library that can be used from other programming languages. It is intended both to create a regression testing framework, and to provide API stability for the various projects that use the bsnes core. While I can't guarantee the API to libsnes won't change, I will properly revision it and do everything I can to avoid changing it if possible.
2010-04-14 15:46:56 +00:00
byuu
7227107d5e Update to bsnes v063r14 release.
- libsnes updated ... should be the official syntax now, I don't
expect any more changes
- added kode54's patch for HQ2x
- NOT going to add the libjma Windows Unicode fix, I want something
more elegant than hijacking all of std::ifstream, so that can wait for
now
- fixed status.irq_lock for Power Rangers
- went back to blargg's 1.024MHz S-DSP for the fast build
- updated mightymo's cheat pack to the latest version
2010-04-13 15:21:37 +00:00
byuu
65ff00e28a Update to bsnes v064rc1 release.
I'm posting a release candidate for v064, for which I am looking for beta testers. If you would like to help out, please give it a try and report any bugs or regressions on the forum. If all goes well, this will be posted as v064 official shortly.
Note that you will need the Qt run-times from bsnes v063 official to use this. Also, this build does not use the new cycle-based PPU. Official builds are going to continue using the scanline-based renderer. This build should be about 10% faster than v063 was, which should lower the system requirements further.
2010-04-12 15:25:39 +00:00
byuu
717aa69d42 Update to bsnes v063r12 release.
Well I really don't want to think about a caching system right now, so
I skipped that.

- added sPPU::Background::get_tile(), which computes its own copies of
mask_xy, screen_xy, tile_size, etc; allows BG3 offset-per-tile to
compute tile correctly
- fixed two V=(start of Vblank) checks that lacked overscan tests
- removed fade stuff from video output, going to rely exclusively on
filters for that stuff now
- modified state. to t. for brevity
- cached regs.overscan for overscan() function
- PPUDebugger uses interlace_enable() and overscan_enable() to avoid
conflicts with the base classes; forgot to move PPUcounter to
PPUCounter
- added controller selection capability to libsnes; still needs cheat
code and save state support

Should fix that Adventure Island thing, confirmation would be
appreciated.

I tried some quick hacks and was able to get mode7 caching (NHL '94)
and OAM caching (Winter Gold) working without breaking anything, but
it's too scanline-PPU for my tastes. There's really no reason to half-
ass this just to get games playable, so I'll wait and do it the right
way later on.

Only worked on this for about an hour today ... I must be burned out.
Think I'll try messing around with Python or something, since Ruby is
a dead-end for using libsnes.
2010-04-11 13:00:48 +00:00
byuu
35fdb71f3d Update to bsnes v063r11 release.
Writing to SETINI will update video mode priorities for EXTBG mode.
Merged pixel output { main, sub { valid, priority } } into just
priority. A priority of zero is considered invalid now.
Merged pixel output { main, sub { palette_index, palette_number } }
into just palette with the tiledata bits for direct color mode at
d8-d10.
This cuts a lot of copying and extra comparisons out of the final
screen rendering pass, though it doesn't really help speed.
Output is always 512x448 now. Having trouble deciding on how to do
video for that, but I'll post more on that later.
Really need to figure out how offset-per-tile fetches in regards to
lores v hires and SC size, tile size and wrapping.
For now, I simplified it to constants; whereas the scanline-renderer
uses the BG3 settings.
I also made it not perform OPT lookup on BG3 and BG4 anymore. Skips a
pointless trickery of setting the OPT valid bit to zero for BG3,BG4
and is faster.
Forgot an overscan check in sprite drawing, should draw sprites
properly to V=225-239 now.
Made the mode7 variable names more consistent.
2010-04-09 16:00:03 +00:00
byuu
c33f70a8c6 Update to bsnes v063r10 release.
With this release, the final last-generation holdout, the scanline-based PPU renderer, has been replaced with a true, accurate, cycle-level PPU that renders one dot at a time. Finally, this fulfills the greatest milestone remaining in the SNES emulation scene. With every processor emulated at the lowest possible level, SNES emulation finally rivals the accuracy levels that NES emulators have offered for years.
Now, please do understand that this release is not a beta, nor is it even an alpha. It is simply a preview of things to come, and as such you can consider it a pre-alpha. There are many caveats at this time.
First, it is very slow. More than twice as slow as v063 official. There have been absolutely no optimizations whatsoever to the new dot-based renderer. I do expect to be able to speed this up significantly in future releases.
Second, this may lock up on Windows Vista and later for unknown reasons. I haven't had a chance to look into it; so stick with Windows XP or Linux for now.
Third, save states are not supported yet. If you try and use them anyway, bad things will happen.
Fourth, and most importantly, this isn't 100% bit-perfect by any stretch of the imagination. Off the top of my head, memory is accessed far too often, the OAM and CGRAM address lines are not controlled by the S-PPU during active display, none of the various glitches are supported, and the OAM renderer does not pre-cache the next scanline's sprites, it happens on the same line for now.
I will obviously be doing my best to improve the accuracy of the aforementioned things. But even with those missing, this is still leaps and bounds above a pure scanline-based renderer. It essentially provides 682 times the parallelism. It is enough to finally properly emulate the shadow effect in Air Strike Patrol, and it finally eliminates the "PPU Hclock render position" hack once and for all.
Lastly, you'll need the DLLs from v063 official. I didn't bother to include them this time.
Enjoy!
2010-04-07 14:40:59 +00:00
byuu
0a3fdc404d Update to bsnes v063r09 release.
So that's about 24 solid hours worth of programming in two days. Holy
fuck am I exhausted. Don't expect the last bits any time soon.

Missing features:
- Mode 7 renderer
- OAM previous-line caching
- offset-per-tile mode
- some edge cases in color add/sub
- hires
- interlace
- overscan
- S-PPU control over VRAM, OAM, CGRAM during active display

Speed hit is about as bad as I had feared. 172fps with scanline
rendering to 80fps with dot rendering. I'm guessing that with
optimizations I can make it to ~100-110fps.
2010-04-05 18:38:43 +00:00
byuu
efa7879c6d Update to bsnes v063r08 release.
No binary, this is just a point release.

I have basic lores BG1-4 rendering with mosaic added. No offset-per-
tile, no windowing, no color math (requires windowing), no sprites, no
hires, no interlace, no mode7.

It's enough to see how powerful the concept is already, though.
- Battle Blaze intro looks just fine (can't beat a battle because I
can't see my sprites or save states yet)
- Dai Kaijuu Monogatari II stat bar looks fine (no duplicated line)
- Super Metroid looks fine (no extra status bar line)
- Air Strike Patrol shows the translucent shadow for your plane (but
the left-hand scrolling is glitchy ... not sure what's up yet)

Speed is ... yeah, it's bad. About 50-60% speed. But it can get
better, I'm being really lazy and completely recomputing everything
for each pixel. A very large number of these operations can be cached.
I'm going to wait until the renderer matches the quality of the
scanline-renderer before optimizing; and I'm not going to push too far
on optimizing this (eg I probably won't bring back the tiledata
planar->packed conversion cache.)

I'm designing this similar to MooglyGuy's N64 renderer, putting each
component in its own class. So far I'm really liking the concept.
2010-04-05 13:28:36 +00:00
byuu
b11f22f517 Update to bsnes v063r07 release.
src/lib is no more, merged libco, nall and ruby into src/.

libsnes has been improved, builds in when you "make library" now.

XML memory map generation happens from a nall template header, so both
libsnes (used by ui_sdl) and ui_qt can run again without snesreader.

ui_sdl improved, can run any game via command-line, but doesn't load
or save RAM yet.

And most importantly, much work has gone into sPPU, the new cycle-
based PPU renderer. It has enough support to be compatible with all
games ($2134-213f are mostly complete, just missing range/time over
flags and VRAM/OAM/CGRAM blocking.) It only renders the back color, as
if you had all BG and OAM layers disabled.

At this point, if you run Air Strike Patrol, thanks to its gradient
fade highlighting, you can see the plane's shadow, just as on real
hardware now. It also runs test_hello and test_noise, which I will
upload shortly.
2010-04-04 18:42:09 +00:00
byuu
9614275b34 Update to bsnes v063r03 release.
Extremely substantial code structure changes this time. Probably the
most in four years.

All of the SNES core now resides in src/snes, and the contents of
system have been unrolled into this directory as well. This folder
gets its own Makefile now, and some special build commands, "make
library" and "make install-library". This creates static and dynamic
link libraries of the core, completely devoid of Qt, ruby, the GUI,
etc.

There's a new module as well, src/snes/libsnes. This is a C interface
that will let you initialize and control the bsnes core without the
need for anything more than a 1KB header file.

To test this, I've created a UI fork, ui_sdl. Very very simple, 2KB,
nothing there at all really, it just boots up Zelda 3 and runs it
directly with keyboard input support and video only. The important
point here is that the ui_sdl project does not reference the core, or
ruby, or Qt, or anything else, and is fully C++98 (though it could
also be C89 if desired.)

Now I'm being a bit lazy and using the compiled objects directly, but
it'd be just as easy to replace them with a library include directive,
or even dynamically link against the shared library and use an
entirely different language.

It's not actually my goal to make a C++ SDL port, what I really want
to do is make a port using Ruby only. May not be so easy, we'll have
to see how one accesses shared libraries in it.

The main src/Makefile was also simplified for the sake of supporting
non-Qt code. All of the Qt and ruby references were moved into the
src/ui_qt/Makefile.

I fixed up aDSP to compile again, but you still have to manually
comment out sDSP and comment in aDSP. Doing so will net you a 6-12%
speedup at the cost of some accuracy.

Lastly, I added a workaround for the Battletech 3050 splash screen.
2010-04-02 15:22:04 +00:00
byuu
9995876bc5 Update to bsnes v063r02 release.
It would be a really good idea to test all of the HDMA-sensitive games
with this WIP, if anyone's up for it.

Rewrote most of sCPU::DMA. It now implements a parallel two-stage
pipeline to more closely model the hardware. Even if it turns out to
be wrong, simply making dma_write() immediate would revert it to the
old behavior. Fixed a bug where HDMA init and run were always syncing
to the DMA counter, even when a DMA was already in progress. Will
speed up the S-CPU in a very, very small number of games, namely
College Football '97. Most games avoid this because it can crash
CPUr1. New DMA variables means new save state version, sorry.

I did not add the MDR override code, because it's too fucking insane.
Speedy Gonzales still works.

Removed the status bar size grip entirely. There's really no point in
it being there in windowed mode since you can already grip the sides
of the window anyway. Added space to each side of the status text so
that it doesn't nail the very edge of the monitor.

Added checks in XML mapping to not map in special chip sections when
you try and load BIOSes directly, which will stop the SGB and BS-X
BIOSes from crashing the emulator. Load it the right way and it'll
work fine, as always.

Fixed the loader window to display screenshots properly when you have
HTML entities in the filename, eg &, < and >.
2010-03-31 13:40:33 +00:00
byuu
43a3991ddf Update to bsnes v063r01 release.
I've had enough of idiots incapable of finding fullscreen settings.
The menubar is enabled in fullscreen mode by default. A new option in
settings->configuration->video will let you hide it as with v063
official. I don't want to hear about how I shouldn't allow any
settings to be configured differently in fullscreen mode, or how it
should be in a GUI panel, or whatever. I will ignore you if you bring
it up.

I've also added the strpos / qstrpos function->class code, as
mentioned in the programming section.
2010-03-29 17:41:11 +00:00
byuu
27c24bc8a6 Update to bsnes v063 release.
Time for another (hopefully) stable release. The changelog has all updates since the last stable release.
Most notably, this release features substantial accuracy improvements all around. Almost all of them represent brand new findings never before seen in any SNES emulator.
Changelog:
    - fixed off-by-one buffer size issue in S-PPU RTO calculations [PiCiJi]
    - added XML parser
    - added XML-based memory mapping system
    - moved header-based memory mapping code into snesreader library
    - added some linker flags for Fedora [belegdol]
    - added cheat code database; with codes for over 1,500 games [mightymo]
    - fixed a bug where S-CPU IRQs were being tested one cycle early on direct page indexed read opcodes
    - added global cheat system enable/disable checkbox to cheat code editor
    - fixed bug in overflow calculation of S-CPU ADC and SBC opcodes in BCD mode [blargg]
    - emulated the S-CPU ALU MUL and DIV hardware delays with partial result calculation steps [blargg]
    - controller port read now returns real-time results of B button when strobe latch is raised
    - major improvements to emulation of the S-SMP TEST register [blargg, byuu]
    - fixed DSP2 memory map [Overload]
    - "Apply Patch" checkbox will now scan UPS patch folder if one is set in the paths section
    - fixed S-CPU TSC negative flag calculation in emulation mode [address]
    - added "make uninstall" command to Makefile for Linux users
    - S-CPU (H)DMA now updates the S-CPU MDR; fixes a freeze in Speedy Gonzales - Stage 6-1
    - very substantial code cleanups and optimizations as a result of moving from C++98 to C++0x
2010-03-28 15:46:44 +00:00
byuu
fac95dfec5 Update to bsnes v062r10 release.
Added make uninstall, and fixed up nall::function to also bind lambdas
that don't yet exist in GCC 4.4.

Spent most of tonight rewriting the standalone UPS patcher.
2010-03-24 14:19:38 +00:00
byuu
362542924e Update to bsnes v062r09 release.
Mostly minor stuff again.

Fixes:
array, linear_vector and pointer_vector need to set source.pool = 0
before calling reset() to avoid destroying the object we're trying to
move.
All of nall::string is inside namespace nall now. No idea what I was
trying to do before with the half-global approach.
nall::function gains a reset() function, more obvious than func =
(void*)0;
The movie file loader wasn't binding the right action when changing
files and clicking load, can't believe nobody noticed that one.
2010-03-23 12:12:10 +00:00
byuu
4179282244 Update to bsnes v062r08 release.
This WIP has bsnes.exe, snesreader.dll, and src/. If you need anything
else, get it from past releases, please.

I fixed TSC negative flag calculation in emulation mode. Will pass
this test now:
http://blargg.parodius.com/snes-tests/snes_test_tsc.zip

_Way_ too obscure to affect anything, but definitely good to get it
right.

Also rewrote nall/function.hpp to use C++0x variadic templates. New
version is ~85 lines instead of ~190, 40% smaller, doesn't require
recursively including itself, doesn't require the C preprocessor,
evaluates to ensure the member function pointer is big enough to hold
what you're assigning statically (at compile time) instead of
dynamically (at run time), and supports infinite arguments instead of
zero to eight now.
2010-03-21 07:36:46 +00:00
byuu
02820ef2e9 Update to bsnes v062r07 release.
This is source code only, no binaries. Sorry, worn out after spending
four hours straight writing crazy ass Julian<>Gregorian date
functions. Holy fucking hell that is crazy shit. Tell me, how many
days have passed since 01-01-4731 BC on the Julian calendar?

Okay, this really was just about taking advantage of vectors inside of
vectors. I've updated the XML parser to use vectors of actual objects
instead of pointers. This makes cleanup free, and turns countless ->'s
into .'s -- much nicer to look at. I may take advantage of overloaded
operators for something now, not sure yet.
2010-03-19 12:50:55 +00:00
byuu
0ecce7b93d Update to bsnes v062r06 release.
You'll need snesreader's DLL from my last WIP post to use the above.

This initializes mode, region and ram_size again in Cartridge::load()
to stop the phantom SRAM files from being generated.
This fixes DSP-2 mapping to match Overload's findings (which requires
an unposted snesreader, so Dungeon Master won't run for you guys yet.)
This removes nall/traits.hpp and uses std::tr1::type_traits instead.
It also drops move, forward and identity in favor of those from
std::tr1::utility*.
This fixes linear_vector and pointer_vector to not crash when using
vectors of vectors and copying them.
This fixed linear_vector, pointer_vector and array to initialize all
internal variables for all constructors.
This fixes the file browser to look for patches in your patch
directory, so the "Apply Patch" box should work correctly now.

* I have no objection to using functions from the C++ standard library
when they don't suck.
2010-03-18 15:32:55 +00:00
byuu
f94fcd6f30 Update to bsnes v062r05 release.
To run this, you'll need the DLLs from v062r04's public beta, and the
updated snesreader.dll in the same folder as the WIP. No profiling.

This fixes UPS patching, and it also modifies snesreader to generate
the XML map separately, so that the map can be generated post-
patching.
The new enum classes weren't attaching properly to the config file, so
the input settings, expansion port and region settings are saved
again.
It also converts the S-SMP timers back to unsigned integers instead of
using floating point, no accuracy improvement but much more in line
with hardware.
Lastly, it makes the div register shift left 16 places and pre-shifts
on divide, which is just for aesthetics.

And I'll wait on your tests, FitzRoy. I really hope that Big Run
Jaleco Rally is correct, because I don't have the first idea how to
debug that one. Speedy I can probably handle.
2010-03-17 12:58:18 +00:00
byuu
57f903630a Update to bsnes v062r04 release.
I suppose I should start calling these nightlies, heh. blargg went ahead and verified every last possible edge case with regards to the S-CPU MUL / DIV registers. It uncovered a few errors in my implementation, which have since been corrected. The design used now should be a direct reflection of the hardware implementation: no actual multiplication, no actual division, and no variable-length bit-shifting.
We also spent about eight hours straight hammering away at the S-SMP test register. We have a partial understanding of TEST.d3 and TEST.d0, and a complete understanding of the other six bits. All of this has been implemented as well.
Lastly, snesreader gets a tiny update to fix Test Drive II, which broke due to a slight regression when porting the mapping code to XML.
2010-03-15 23:24:58 +00:00
byuu
9329de0a8d Update to bsnes v062r03 release.
blargg and I sat around for a good 8+ hours today hacking away at the
S-SMP Pandora's Box: the TEST register. What better way to spend Pi
Day, right?

We came up with the following tests:
http://byuusan.kuro-hitsuji.net/blargg_2010-03-14.zip

First, controller_strobebehavior.smc improves emulation of $4016. When
the joypad strobe latch = 1, reading $4016 returns the current value
of the B button. As in, you can keep reading it over and over. It
won't increment the shift register, and it will keep telling you the
actual current state of the button. This is very much like the NES
behavior. One more TODO in the S-CPU code taken care of.

Next, all kinds of S-SMP TEST register improvements. Turns out d7-d6
alone controls the actual S-SMP clock rate. 0 = 100%, 1 = 50%, 2 = 0%
(locks the S-SMP forever), 3 = 10%. Wild stuff, you can actually
permanently slow the S-SMP relative to the S-CPU.

d6-d5 is a timer tick control, but it actually uses d7-d4 overlaid.
The algorithm is fucking nuts, and is really my only contribution to
today's work. The rest was all blargg's research.

We had d2 wrong, it's not MMIO disable, it's RAM disable. As in,
disable read and write. Returns 0x5a on regular SNES, 0xff on mini-
SNES. 0x5a is not the S-SMP MDR. IPLROM is still readable when RAM is
disabled. d1 was correct, just RAM write disable. Can still write to
$f8 and $f9, of course. But it won't go through to RAM.

d3 and d0, we are still a little unsure on. The T0-T2 timers seem to
have a low and high phase, and if you strobe them you can force ticks
of stage 2 to happen, and you can disable them in such a manner than
stage 2 never ticks at all.

blargg is still uncovering all sorts of crazy things in $xB mode, so
emulation of these two bits is not perfect.

But overall we are leaps and bounds further now toward complete
emulation. I'd say we went from 10% to 80% with today's work. But
we'll have to see how deep the rabbit hole goes on d3+d0 first.

Current register map:

    case 0xf0: {  //TEST
    if(regs.p.p) break;  //writes only valid when P flag is clear

    status.clock_speed     = (data >> 6) & 3;  //100%, 50%, 0%, 10%
    status.timer_speed     = (data >> 4) & 3;  //100%, ...
    status.timers_enabled  = data & 0x08;
    status.ram_disabled    = data & 0x04;
    status.ram_writable    = data & 0x02;
    status.timers_disabled = data & 0x01;

    unsigned base = 1 + (1 << status.clock_speed);
    unsigned step = base + (15 >> (3 - status.timer_speed));
    status.timer_step = 1.0 / (3.0 / step);

    t0.sync_stage1();
    t1.sync_stage1();
    t2.sync_stage1();
    } break;


Fairly confident that no emulator prior to this WIP could pass any of
blargg's tests, so this is all brand new information. Fun stuff :)
2010-03-15 15:20:52 +00:00
byuu
989648c21c Update to bsnes v062 release.
Major accuracy improvements have happened over the past few days. They easily warrant a new beta release.
First, it turns out that every emulator to date; not only for the SNES, but for the Apple II GS as well, incorrectly computed ADC (add) and SBC (subtract) flags in BCD (binary-coded decimal) mode. At least fifteen years of emulating the 65816 processor, at least five known investigations into their behavior, and we all still had it wrong.
So I wrote some tests that dumped every possible combination of adc and sbc with every possible input and every possible flag, and recorded both the accumulator result and status flag register. From here, blargg figured out the underlying trick: the CPU was computing overflow before the top-nibble's BCD correction pass. With the routines rewritten, bsnes perfectly matches real hardware now.
Next, some background. The whole reason I got into SNES emulation was because I was tired of writing code that ran perfectly fine on emulators, but failed miserably on real hardware. The number one problem was emulators allowing video RAM to be written while the screen was being rendered. This single bug has broken dozens of fan translations and ROM hacks. Some have been updated to work around this bug, and many others are left in a permanently broken state (such as the translations of Dragon Quest I & II and Sailor Moon: Another Story, to name just two.) After asking emulator authors to fix this since 1997, I finally had enough in 2004 and started on bsnes. For this particular bug, I'm very happy to report that all but one SNES emulator now properly blocks these invalid accesses. Although sadly one still offers a configuration setting for backwards compatibility with these translations. What an ironic shame ... emulating an emulator. And in the process, sapping the motivation to ever go back and fix these 
titles to ever run on real hardware. But I digress ...
The second biggest problem that causes software created under emulation to break on real hardware has, without a doubt, been the hardware delays as the S-CPU computes MUL (multiplication) and DIV (division) results. To date, whenever you used this hardware functionality, emulators have immmediately furnished the correct results. But on real hardware, multiplication requires eight CPU cycles, and division requires sixteen. Each step computes one bit of the source operand and updates the results. Reading the output registers early thus provides the partially computed results.
This is obscure. It isn't well known, and many people writing software for the SNES probably aren't even aware of this limitation. Because of the partial computation results, outright delaying the computation would break many commercial software titles. But by not emulating the delay at all, we were causing a great disservice to anyone wishing to use an emulator for development purposes.
Now, once again, thanks to blargg's algorithm help, he has determined the underlying multiplication and division algorithms. Combined with my expertise of SNES analysis and hardware testing, I was able to determine when and how the ALU (arithmetic logic unit) stepped through each work cycle. Our work combined, bsnes now also perfectly emulates the hardware MUL and DIV delays.
Again, this isn't going to fix commercial software titles. They would have realized that they were reading back invalid MUL and DIV values, and fixed their code. This is for all of the software developed using emulators. This is an extension of my commitment to create a hardware emulator, and not a video game emulator.
We also verified that the S-PPU multiplication interface does indeed return instant results with no delay. So emulation of that interface was already correct.
I'm only labelling this release a beta because it hasn't been tested. But I'm fairly confident that it is stable, and I seriously recommend upgrading from v060 or prior releases. This is easily one of the last major pieces missing from emulation.
The last notable elements are: S-CPU auto joypad poll timing, S-CPUr1 HDMA crash detection, S-CPU<>S-SMP port ORing, S-SMP timer glitching, S-DSP mute pulse, and full cycle-level emulation of the S-PPU. With all of the aforementioned items, I will consider a v1.0 release of bsnes ;)
Lastly, I'll post this screenshot just for fun. When d4s translated Breath of Fire II to German, he added some code that relies on the incorrect emulation of the DIV register to detect emulators. With this emulated properly, you now see the following screen:
./sshots/bs_349.png
Sorry to spoil that, but the secret's already out, as the MESS team reported on it publicly already.
I intend to add pseudo-randomness support shortly, which should eliminate one of the last vectors possible to distinguish bsnes from real hardware :)
A million thanks to blargg for making this release possible.
2010-03-13 23:48:54 +00:00
byuu
0f0dcf9538 Update to bsnes v061r03 release.
This is probably the biggest accuracy fix in several years.

Thanks to the efforts of blargg and myself, bsnes is now the very
first emulator to properly emulate ALU multiplication delays. It's
100% bit-perfect.

Note that we don't yet know the underlying division algorithm. So in
this WIP, I just make it wait eight ticks before storing the results.
It _may_ cause some issues, but I wanted to get rid of the
status.alu_lock and config.alu_mul/div_delay garbage in advance.

I'm absolutely enthralled, I never thought I'd actually see this
emulated properly.
2010-03-13 15:40:21 +00:00
byuu
78e1a5b067 Update to bsnes v061r02 release.
Complete rewrite of adc + sbc opcodes, should fix:
- adc BCD overflow flag
- sbc BCD overflow flag
- sbc BCD invalid input value

Testing is appreciated, I believe Sim Earth is probably the most
likely to observe any difference.
2010-03-13 15:40:21 +00:00
byuu
79404ec523 Update to bsnes v061r01 release.
Found the cause of the issue breaking SuperFX games after loading SA-1 games. Seems the XML mapping tree wasn't being cleared. It's also not a good idea to use bsnes/ as the folder name when the Makefile generates a binary by the same name in the same directory, so back to src/ for the main emulator it is.
With those fixes, this release should be fully stable; but again my intentions are to keep v060 as the stable release for a while.
Nonetheless, you can grab the new beta at Google Code. It should be the last update for at least a few weeks.
2010-03-08 21:04:20 +00:00
byuu
6c59a2f1b4 Update to bsnes v061 release.
Please keep in mind that bsnes v060 remains the current stable release. v061 has been released as a work-in-progress build. As such, it is only available at Google Code.
I am releasing this WIP to allow the public to test out and comment on the new XML mapping system, as well as the integration of mightymo's cheat code database into the cheat editor. I would greatly appreciate feedback on these two on the forums.
There are some important issues with this release. The biggest is the move to C++0x. This requires GCC 4.4.0 or newer to compile, thus it is not currently possible to build this on OS X using Xcode. Nor would it be possible on certain BSDs or older distros. If you have an older compiler, please stick with v060, or use a binary release where available.
Another issue is that TDM/GCC 4.4.1 for Windows crashes with an internal compiler error when attempting to generate a profile for the DSP-1 module. This is a bug in the compiler, and not in the code itself. The workaround is to simply omit profile-guided optimization for this one object.
Lastly, there's also a known bug in the memory mapping. If you load an SA-1 game, SuperFX games will not load properly afterward unless you restart the emulator. I'm looking into the cause now, but it didn't seem serious enough to hold up a WIP release.
So, yes. If you want a good gaming experience that's been fully tested and stable, please stick with v060. If you want to see some bleeding edge features, I'd appreciate feedback on v061. Thanks for reading this.
Changelog:
    - added mightymo's cheat code database, access via "Find Cheat Codes" button on cheat editor window
    - added an option to temporarily disable all cheat codes quickly
    - debugger now properly uses S-SMP IPLROM when needed for disassembling and tracing
    - indexed indirect read opcodes in the S-CPU were testing for IRQs one cycle too early [someone42]
    - fix an off-by-one array iteration in S-PPU OAM rendering [PiCiJi]
    - added some implicit linked libraries to linker flags for Fedora [belegdol]
    - moved from C++98 to C++0x, resulting in substantial code cleanups and simplifications
    - C++0x: implemented foreach() concept for linear container iteration
    - C++0x: implemented concept system using SFINAE and type traits
    - C++0x: utilized auto keyword to increase source readability
    - C++0x: moved to strongly-typed enumerators
    - C++0x: rewrote va_list-based code to use type-safe variadic templates
    - C++0x: replaced noncopyable class with deleted default copy functions
    - C++0x: replaced custom static_assert template class with built-in version
    - C++0x: utilized rvalue references to implement move semantics into string, array, vector and serialization classes
    - C++0x: utilized std::initializer_list for { ... } initialization support to lstring, array and vector classes
2010-03-07 02:17:46 +00:00
byuu
a295c86c05 Update to bsnes v060r12 release.
Added concept support, vastly improved foreach to handle break
properly and only compute the size once (based off concepts), extended
it to work QList, and updated cheateditor.cpp to use foreach
everywhere now.

Added an "Enable Cheat Engine" checkbox to the bottom left of the
cheat editor window with a tooltip to help explain it more. It
essentially simulates the switch on the Game Genie. A way to quickly
toggle all codes on and off, without having to check/uncheck each one
individually. Useful for the codes that lock up games between levels
and such. It's bound to the existing keyboard shortcut that did this,
and they both update the check state and system status properly.
Hopefully the GUI option will make more people aware of this
functionality.

Updated array, linear_vector, pointer_vector and lstring to support
std::initializer_list constructors. This allows:
lstring list = { "apple", "strawberry", 3.4, -27, true,
QString("why?") };
array<int> = { 3, 4, 9, 2 };

std::initializer_list is a pain in the pass, it lacks a subscript
operator, an at() function and a get() function. Forced to use
constant iterators to read out the contents.

[No archive available]
2010-03-06 08:11:35 +00:00
byuu
a539f2f578 Update to bsnes v060r10 release.
Fuck, adding #include <iostream> grows the Windows binary by 300KB
pre-UPX, and 100KB post-UPX. And I'm only using std::cout to avoid the
very last call to printf(). I may just say fuck it and stick with
stdio.h instead.

Nothing really big in this one.

Added "Select All" + "Clear All" buttons to the cheat finder
Added move semantics to dictionary, array, linear_vector and
pointer_vector
Killed class noncopyable and replaced it with proper class(const
class&) = delete; (inheriting noncopyable makes some classes non-POD)
Added type-safe variadic sprint() and print() functions, which are
designed to replace sprintf() and printf(), which I only use for bug-
testing anyway
Couple other small things like that

[No archive available]
2010-03-03 07:00:13 +00:00
byuu
e710259611 Update to bsnes v060r09 release.
This release parses the 1.3MB cheats.xml file about 960x faster than
the last release, no exaggeration at all there. The tiny 5-10ms lag to
search now is probably more due to Qt than anything else. It also
won't eat up an extra 40MB of RAM, instead only using about 100KB now.

So yeah, please give it a try and let me know what you think of the
new cheat lookup system.

Aside from that, I fixed a tiny S-CPU typo bug where the IRQs were
being tested one cycle too early in op dp,x and op dp,y opcodes.

I also redid a bit of nall in C++0x. Most importantly, I've added move
semantics to nall::string, which should cut out ~20% of the memory
allocations bsnes needed before. I really wanted to write a variadic
template string::printf replacement, but I couldn't come up with a
syntax I liked, and I didn't want to write a sprintf clone because
that takes forever and is ugly. So I just said fuck it, removed
string::printf (and with it the very last vestige of va_list in all of
my code, good riddance), and updated the str* functions to take
template arguments to specify padding length and character. Both
optional, another fun C++0x only thing - default function template
arguments.

Before: string foo = string::printf("%.4x", variable);  -- went
through raw sprintf(), va_list, and had a limited 4k buffer
After: string foo = strhex<4>(variable); -- manually built by hand, no
buffer issues

nall/utility.hpp got my own copies of std::move and std::forward. I
have no problem using the std:: ones, but the <move> header seems to
be missing, and I already have my own traits library, so that was easy
enough for now. Added a move-semantic swap as well. Using nall::sort
on an array of nall::string objects should be almost as fast as
sorting integers now.

The cheat code editor .. whenever you import into a new slot, or clear
that slot, it will uncheck the box now as well.

[No archive available]
2010-03-02 07:47:07 +00:00
byuu
f1d1ab7ed1 Update to bsnes v060r08 release.
This version embeds mightymo's cheats.xml inside the bsnes executable.
It's about 1.3MB, but thankfully Qt compresses it heavily first, so
the binary only grows by 100kb. BZip2 doesn't fare as well,
surprisingly, and grows the source archive by 200kb. I think it's
worth it.

The cheat code editor window gets a new button, "Find Cheat Codes ..."
If you click it, it will match the SHA256 of the currently loaded game
to an entry in the database. No matches? It apologizes for letting you
down. But if it finds some, and there's a good chance it will with
~1500 entries, it gives you a list of them. Check the codes you want
and they are imported into the available slots. The way it works is
the first checked code goes to the first empty slot, the second
checked code to the second empty slot, and if there aren't any slots
left available (very unlikely), it won't import them.

It's incredible, actual innovation in the SNES scene.
- no more web searching for codes
- no more applying codes for the wrong revision, or the wrong country,
or whatever
- no more flat out broken codes
- no more having to name the codes yourself
- cheat grouping avoids the need to add and toggle multiple slots to
get a single effect

Anyone who likes this, please send a thank you PM to mightymo77 and
tukuyomi. They deserve all the credit for the amazing database that
makes this possible.

Now then: **major caveat, for the love of god read this first!** My
XML parser is ... brutal on this file. It has to allocate memory for
each attribute and each element. And ... it rapes the ever loving SHIT
out of malloc(). Oh my god. On my E8400, it takes a good 30 seconds to
parse the 1.3MB database on Linux. And on Windows, holy god, it has a
horrendous version of malloc. It takes at least 3-5 minutes.
Seriously, go make yourself a cup of coffee if you are running
Windows.

I only have to parse the file one time per program run, and I only
parse it when you click the find cheat codes button for the first
time. But yes, it is painful. Very, very painful.

[No archive available]
2010-03-01 05:59:52 +00:00
byuu
1934197fb7 Update to bsnes v060r07 release.
Feeling amazing tonight. The low of fighting a bad cold for the past
week, blocked nose, bloody lips and wrist pain combined can't hold me
down.

Two years of searching and I finally found the Midnight Panic EP, and
it's amazing. And from this WIP forward, bsnes now uses C++0x instead
of C++03. I feel like I've been given this new amazing language, and
there's all these wonderful new possibilities for cleaning up and
simplifying code.

foreach is the most amazing concept. The only reason I've made it this
long without it is because I never got to use it. You will pry this
one from my cold, dead hands. Already applied it to the cartridge and
memory classes. It's insane.

Before:
    for(unsigned i = 0; i < memory::wram.size(); i++) memory::wram[i]
    = config.cpu.wram_init_value;
    for(unsigned i = 0; i < cartridge.mapping.size(); i++) {
    Cartridge::Mapping &m = cartridge.mapping[i];


After:
    foreach(n, memory::wram) n = config.cpu.wram_init_value;
    foreach(m, cartridge.mapping) {


Before:
    for(unsigned i = 0; i < 32; i++) {
    char value[4];
    sprintf(value, "%.2x", shahash[i]);
    strcat(hash, value);
    }


After:
    foreach(n, shahash) hash << string::printf("%.2x", n);


And that's just the first thing! So many things I can do now. Can't
wait to come up with uses for all the new features to simplify code
even more.
- auto type inheritance
- variadic templates to nuke the last vestiges of va_list and its
associated horrors
- strongly typed enums (no more enum Mode { ModeOfRedundancyMode }
shit. enum class Mode : unsigned { Normal, BSX };
- _real_ static assertions with actual error messages instead of 40
pages of template errors
- default templates parameters to template functions (but still no
function partial template specialization, grrr)
- property class can be implemented natively without having to trick
GCC into using template friend classes
- rvalue references will allow my string class and such to implement
move semantics, no more useless copying
- uniform list initializers, lstring foo = { "a", "b", "c", ... };

And that's just what's there now, it's only half-way done. The
completed support will be even more awesome:
- lambda functions
- nullptr
- class variable initialization in the header instead of needing
constructors
- native functors to replace nall::function with
- string literals in UTF-8
- native multi-threading support
- and so much more

[No archive available]
2010-02-28 08:37:56 +00:00
byuu
e1c8757a10 Update to bsnes v060r06 release.
Completely rewrote the syntax for all XML parsing, took over five
hours of nonstop work, holy fuck.

Sadly the expanded syntax greatly increases the parser complexity, the
SNES::Cartridge class is twice as big now, XML parsing for all special
chips takes up 20KB of space.

Example:
    void Cartridge::xml_parse_sdd1(xml_element *root) {
    has_sdd1 = true;

    foreach_element(node, root) {
    if(node->name == "mcu") {
    foreach_element(leaf, node) {
    if(leaf->name == "map") {
    Mapping m((Memory&)sdd1);
    foreach_attribute(attr, leaf) {
    if(attr->name == "address") xml_parse_address(m, attr->content);
    }
    mapping.add(m);
    }
    }
    } else if(node->name == "mmio") {
    foreach_element(leaf, node) {
    if(leaf->name == "map") {
    Mapping m((MMIO&)sdd1);
    foreach_attribute(attr, leaf) {
    if(attr->name == "address") xml_parse_address(m, attr->content);
    }
    mapping.add(m);
    }
    }
    }
    }
    }


Of course, C++ doesn't have foreach(), that'd be too goddamned
convenient, right? So behold the spawn of satan himself:

    #define concat_(x, y) x ## y
    #define concat(x, y) concat_(x, y)

    #define foreach_element(iter, object) \
    unsigned concat(counter, __LINE__) = 0; \
    xml_element* iter; \
    while(concat(counter, __LINE__) < object->element.size() \
    && (iter = object->element[concat(counter, __LINE__)++]) != 0)

    #define foreach_attribute(iter, object) \
    unsigned concat(counter, __LINE__) = 0; \
    xml_attribute* iter; \
    while(concat(counter, __LINE__) < object->attribute.size() \
    && (iter = object->attribute[concat(counter, __LINE__)++]) != 0)

[No archive available]
2010-02-27 10:04:33 +00:00
byuu
768e9b589d Update to bsnes v060r05 release.
Forgot the -lXext thing, saw it when posting. It'll be in r06.

Updated the XML parser, will reject a lot more invalid stuff, and
it'll parse comments, <? and CDATA stuff. I haven't seen PCDATA
mentioned anywhere in the spec, so fuck that for now.

Went back to using offset= for SPC7110 data ROM. Thinking about it
more, using offset= allows you to put the data ROM anywhere in the
file, even before the program ROM. size= forces it to go at the end no
matter what. Now, ideally, you want to define both, but offset= should
be more important.

[No archive available]
2010-02-25 05:00:34 +00:00
byuu
582f17b330 Update to bsnes v060r04 release.
I wrote a dedicated XML parser for nall::string, and updated
SNES::cartridge to use that instead of the ad-hoc implementation. It's
still not W3C-quality with 100% standards-adherence, but it's at least
an order of magnitude better now.

The parser supports infinitely nested elements and attributes via
pointers to child nodes, supports both single-tag <eg /> and tag-with
content <eg>content</eg>, and properly handles and validates the
<?xml?> header.

It doesn't fully ignore comments yet, but you should be okay anyway.
Whitespace culling, especially inside tags, still needs a bit of work.
It will properly reject the entire document if there are unopened /
unclosed tags now.

All in all though, it's very small. Only 3KB for the whole parser.
Usage example:

    void Cartridge::parse_xml_cartridge(const char *data) {
    xml_element *document = xml_parse(data);
    if(document == 0) return;

    for(unsigned i = 0; i < document->element.size(); i++) {
    xml_element *head = document->element[i];
    if(head->name == "cartridge") {
    for(unsigned n = 0; n < head->attribute.size(); n++) {
    xml_attribute *attr = head->attribute[n];
    if(attr->name == "region") {
    if(attr->content == "NTSC") region = NTSC;
    else if(attr->content == "PAL") region = PAL;
    } else if(attr->name == "ram") {
    ram_size = strhex(attr->content);
    }
    }

    for(unsigned n = 0; n < head->element.size(); n++) {
    xml_element *node = head->element[n];
    if(node->name == "map") {
    parse_xml_map_tag(node);
    }
    }

    break;
    }
    }

    delete document;
    }


Also updated DSP-3 and DSP-4 to separate ::DR and ::SR, SPC7110 uses
size= for program ROM size calculation now (makes more sense than
using offset=), added PCB info to BS-X, Sufami Turbo and Game Boy
cartridges to give additional meta-data (SGB emulation will properly
size RAM / RTC files again), and updated snesreader with these
changes.

And for better or worse, I made the vector classes copyable. Not
actually used by anything at the moment. I wanted to do:
struct xml_element {
vector<xml_element> element;
};

But obviously that causes an infinite recursion when the vector's copy
constructor is called, hence why I had to use pointers.

[No archive available]
2010-02-23 08:21:20 +00:00
byuu
23866a348d Update to bsnes v060r03 release.
Okay, this should get 100% compatibility back up again. All special
chips map via XML, and I also support BS-X, ST and SGB games again.
Only regression is that SGB currently forces on SRAM size to 128KB for
each loaded game. I need to move that into snesreader, and hook it
into the cartridge interface. Too much work to do it tonight, but in
time ...

Given the extensiveness of this, heavy testing appreciated. Let me
know if you spot any broken titles please.

[No archive available]
2010-02-22 09:33:13 +00:00
byuu
d0de306546 Update to bsnes v060r02 release.
This one is not for the faint of heart.

All header detection code has been removed from the official bsnes
binary. It can now only load games with a valid XML memory mapping
file. If you have /path/to/zelda.sfc, then you also need
/path/to/zelda.xml that describes how to load the cartridge.

The 'ext' archive above contains a new version of snesreader, as well
as its DLL. snesreader now contains header detection, as well as XML
mapping generation. If you have snesreader, and no XML file,
snesreader will create one for you. It won't store it on your hard
disk, it'll only be in memory. An XML on the hard disk always
overrides the snesreader's auto-generated XML file.

So far, only normal ROMs, S-RTC, S-DD1 and SPC7110 games are up and
running. Everything else is broken, I'll have to fix them one by one
by extending the id= attributes in the XML parser.

Here's some example XML files:

    <?xml version="1.0" encoding="UTF-8"?>
    <cartridge ram="2000">
    <title>The Legend of Zelda - A Link to the Past</title>
    <pcb>SHVC-1A3M-30</pcb>
    <map mode="Linear" address="00-7f:8000-ffff" id="ROM"/>
    <map mode="Linear" address="70-7f:0000-7fff" id="RAM"/>
    <map mode="Linear" address="80-ff:8000-ffff" id="ROM"/>
    <map mode="Linear" address="f0-ff:0000-7fff" id="RAM"/>
    </cartridge>


    <?xml version="1.0" encoding="UTF-8"?>
    <cartridge region="NTSC" ram="2000">
    <map mode="Direct" address="00-3f:4800-483f" id="SPC7110::MMIO"/>
    <map mode="Direct" address="80-bf:4800-483f" id="SPC7110::MMIO"/>

    <map mode="Direct" address="00-3f:4840-4842" id="SPC7110::RTC"/>
    <map mode="Direct" address="80-bf:4840-4842" id="SPC7110::RTC"/>

    <map mode="Linear" address="00:6000-7fff" id="SPC7110::RAM"/>
    <map mode="Linear" address="30:6000-7fff" id="SPC7110::RAM"/>

    <map mode="Shadow" address="00-0f:8000-ffff" id="ROM"/>
    <map mode="Shadow" address="80-8f:8000-ffff" id="ROM"/>

    <map mode="Direct" address="50:0000-ffff" id="SPC7110::DCU"/>
    <map mode="Linear" address="c0-cf:0000-ffff" id="ROM"/>
    <map mode="Direct" address="d0-ff:0000-ffff" id="SPC7110::MCU"/>
    </cartridge>

[No archive available]
2010-02-21 00:27:46 +00:00
byuu
2af60d0a13 Update to bsnes v060r01 release.
This WIP fixes the S-PPU overflow issue mentioned by PiCiJi. It won't
cause any difference in terms of accuracy, for reasons I explained
earlier the effect was transparent, but it's good to do things the
right way.

It also adds a new ExSPC7110 memory mapping mode that allows for a 2MB
program ROM. This is an absolute necessity for the Far East of Eden
Zero translation.

[No archive available]
2010-02-15 02:05:28 +00:00
byuu
a8263afc24 Update to bsnes v060 release.
This is a long-term stable release. A full changelog will be available at the forum link below later in the day. Also, please note that I have merged all of the various distributions into two packages. The Windows binary package now contains both the profile-optimized (fast) build, and the debugger build. The source code package now contains sources for bsnes, snesreader, snesfilter and supergameboy.
Changelog:
    - added Direct3D HLSL pixel shader support [mudlord]
    - fixed a signal issue that caused loading games to take 1-2 seconds longer in v059
    - 21fx API revised to its final form, S-MSU (public documentation pending)
    - worked around QTBUG-7188 to fix multi-file 7-zip file listbox to update when scrolling
    - added scale max - normal, wide, and wide zoom modes to fullscreen mode
    - added overscan cropping tool (needed for wide zoom mode; useful for developers simulating games on a real TV)
    - added "go up one folder" button to file load dialog
    - added group (un)assignment to the input settings window
    - now honors input.allowInvalidInput setting; defaults to false [Jonas Quinn]
    - cheat code editor grays out empty slots
    - cheat code editor adds "clear selected" button to quickly erase multiple cheat codes
    - to load folders as game images, folders must end in .sfc, .bs, .st, .gb now
    - debugger: added S-CPU (H)DMA registers; S-SMP registers; S-DSP registers to properties list
    - snesfilter: HQ2x filter is now multi-threaded (scales infinitely: the more cores you have, the less overhead required)
    - pixelshaders: added screen curvature shader to simulate curved CRT tubes
    - source: lots of code cleanup, as always
2010-02-09 00:58:03 +00:00
byuu
a9943ab4f4 Update to bsnes v059r07 release.
Fun WIP, lots of work put into this one.

First, I added .st, .bs, .gb, .sgb, .gbc folder-based loading. Works
the same as .sfc folders. So far, only .st shows additional preview
info (just the ROM size for now), but the base code is in place to
specialize .bs / .st / .(s)gb(c) cartridges next.

Next, I added overscan configuration settings to the video settings
window. The reason for this is twofold:
1. testing your translation / hack without a real TV, you can set
overscan to 6% in all directions to ensure all the text is onscreen
2. for the smart video scale mode, noted below
Now, when in fullscreen mode, you get three additional scale settings:
Scale Max - Normal (keeps aspect ratio, maxes out height)
Scale Max - Fill (fills as much as the screen as possible, no
cropping)
Scale Max - Smart (splits the crop and aspect ratio distortion, 50/50
on each; try it, it looks fairly decent in most titles)
No scale max - zoom, because that's just too much cropping; almost
nothing plays well with it

Note that cropping doesn't work so great right now for games that mix
lores and hires (Secret of Mana 2 textboxes, for instance.) I'm
working on it, but it's going to be very tough. All filters take solid
screen sizes quite well, which surprised me.

Also, scale max - smart is for widescreen monitors. It makes zero
sense to use it in portrait mode. I'll add some sort of special case,
just in case anyone crazy tries it, in a future build.

Lastly, I killed the separation of video.cpp and pixelshader.cpp, it's
all inside video.cpp now; and I cleaned up the object names in
video.cpp.

Scale Max - Smart + Curvature pixel shader + NTSC filter - R/F +
Scanlines - 70% is an incredible sight to behold. So much processing,
yet still easy to get 60fps with perfectly synchronized video and
audio. Add that with the Xbox 360 gamepad, throw in a nice S-MSU CD-
quality soundtrack, and it's nirvana.

Please try out the Scale Max - Smart mode if you are using a
widescreen monitor and let me know what you think.

[No archive available]
2010-01-27 09:25:22 +00:00
byuu
46a1eb8cce Update to bsnes v059r06 release.
This is an experimental release, as such it is posted only to Google Code.
Changelog:
    - 21fx API moved to pre-finalized form as S-MSU1; more about this on the forum
    - OpenGL driver now uses GL_CLAMP_TO_BORDER instead of GL_CLAMP_TO_EDGE to support screen curvature shader
    - rewrote file open dialog; code is greatly simplified, interface is improved
    - all cheat code columns are now enquoted, and empty codes at the bottom of the file are omitted (format is compatible with previous releases still)
    - debugger: added missing DMA variables to S-CPU properties viewer
    - snesfilter: added OpenMP (multi-threading) support to HQ2x filter
    - lots of other miscellaneous code cleanup work
2010-01-24 23:21:38 +00:00
byuu
4517c0249f Update to bsnes v059r05 release.
Funny, much more effective changes but in a lot less time. The file
dialog is just a major pain in the ass, I guess. Had to sit and think
for at least two hours just to handle the differences between activate
(double-click an item) and accept (click accept button.) Eg if it's a
folder, double-clicking needs to go into the folder, but the accept
button needs to use that folder. But files act differently, load has
the open-folder thing that overrides the default entering of folders,
and saving doesn't have any such concept at all. Fun fun fun, but done
now.

libqb (QbWindow, QbCheckAction, QbRadioAction) is dead; DiskBrowser is
dead; HexEditor is dead. They've all been merged into nall/qt now.
nall/Makefile-qt goes to the more logical nall/qt/Makefile. The last
thing to do is export style sheet defaults into nall/qt to get the
spacing of the new file dialog under control.

Improved the save dialog, instead of putting the entire path in the
box, it only puts the non-directory part, and pulls the directory from
the file system mode's root path. I decided not to allow .. and /
commands inside the save text box. I just strip all that out. Go to
the damn folder you want to save in, sheesh. And before anyone
complains about that, note that bsnes doesn't even use the save dialog
mode :P

Still have to hook up the new folder button to an actual dialog,
haven't bothered yet. Since there's plenty of room with the extended
width, I'm just going to leave them both visible.

nall/qt/hex-editor is pretty much a direct port, no changes. But I
intend to make the height programmable, and fork that into a stand-
alone, super light-weight hex editor to replace bless (so that I can
remove Mono.) Same for check-action and radio-action, direct ports.

nall/qt/window is a bit different, binds the geometry outside the
constructor. This fixes some issues where certain windows weren't
saving their geometry properly, like the debugger properties window.
And I think there's some other advantage to it not needing a
complicated constructor, but I don't recall what at the moment.

Modified GL_CLAMP_TO_EDGE to GL_CLAMP_TO_BORDER, so everyone can try
out the curvature pixel shader now. Added it to my pixelshaders pack,
but I haven't uploaded a new pack yet, so get it from the other thread
for now.

I mainly need testing on the new file dialog stuff. Please let me know
if something strange is broken, other than the new folder button.
2010-01-18 16:25:02 +00:00
byuu
b538c13aad Update to bsnes v059r04 release.
Eight hours of non-stop work, for the sole purpose of trying to
separate the file browser underlying mechanics from the bsnes-specific
stuff.

So far, it's going quite well. 95% of the functionality is there with
only 25% of the code size. Forked the underlying stuff to
nall/qt/file-dialog.moc.hpp, which is now designed to support
open+save+folder selection natively. Save mode adds a text box to
enter your own file name, and folder mode hides the filter drop-down
and all files automatically. The top bar now spans 100% of the width.
I like it more this way. I also killed the tree view in favor of a
list view, for the sole reason that I really can't stand how when you
go up a folder and the deeper tree is still open. Since the
QFileSystemModel is asynchronous, I can't close the tree nodes when
navigating up.

The simplifications were needed because it was getting damned-near
impossible to edit that mess of a file (diskbrowser.cpp.) Compare to
filebrowser.cpp, much cleaner. Now I should be able to add open-folder
concept for BS-X, ST and SGB games much easier. And of course, I
should be able to offer the base QFileDialog as an option, too.

After that, I'll probably export the hex editor to a generic class,
and then export the Qb stuff (window geometry save/restore, stock
check / radio menu buttons.)

Also, I just wiped out Windows XP and put Windows 7 back, just to fix
the video tearing issue relating to DWM and ... it works perfectly
fine. Zero tearing, zero skipping, zero audio popping. All I did was
start bsnes v059.04, set audio sync to the usual 31960, and it was
just fine. What the hell are people complaining about, exactly?
2010-01-18 00:55:50 +00:00
byuu
d3d98f9f54 Update to bsnes v059r03 release.
For the emulator, I added some missing S-CPU variables to the
properties viewer: all eight DMA channel registers, and $420b/DMA
enable + $420c/HDMA enable. Should probably add the S-SMP timers in
the future.

Updated nall/Makefile-qt to take $(qtlibs) as input, eg qtlibs =
"QtCore QtGui QtOpenGL" and it does the rest to generate $(qtlib) and
$(qtinc) for you. Killed nall/Makefile::ifhas, as it was rather
stupid.

I tried to bind the CPU/SMP/PPU/DSP modules inside of SNES::System,
but it turned out to be a major pain in the ass. I'll have to plan
that a lot more before trying to do that. The ultimate goal would be
having the entire emulator inside class SNES, so that you can
instantiate multiple copies or whatever.

I also updated snesfilter with a nice treat. Inspired by DOLLS'
phosphor code, I added OpenMP support to the HQ2x filter. I have a
dual core E8400 @ 3GHz. With no filtering, I get 177fps. With HQ2x, I
get 123fps. With HQ2x+OpenMP, I get 143fps. Pegs both CPUs to 100%,
heh. And other open applications will interfere with speed, eg
Audacious drops it to 138fps.

Not bad overall though. It should scale even higher on quad cores. And
before anyone asks, no I can't add it to the NTSC filter. I'd have to
talk to blargg about that, and it's already faster than HQ2x anyway.
This is really more a test for things like
HQ3x/HQ4x/Phosphor3x/Phosphor5x in the future. Also, it only works on
Linux at the moment. Need libgomp and libpthread, which I don't have
on Windows.

ZSNES took the approach of putting the filter in another thread while
the next frame is emulated; whereas bsnes forks off new threads when
rendering is hit. I believe the latter is a better approach: it avoids
a 16-20ms latency penalty, it's much simpler, and it can scale up to
240 cores (instead of being limited to two.)

So yeah, I easily have the fastest, smallest, most definitive version
of HQ2x possible right now; so long as you have a quad core :)

[No archive available]
2010-01-12 06:13:14 +00:00
byuu
1d5e09ef07 Update to bsnes v059r02 release.
Changelog:
    - added folder-up button to the file loading window
    - hid new-folder button except on path selection window
    - removed "Assign Modifiers as Keys" button; replaced with input.modifierEnable in the configuration file
    - fixed a Qt signal issue that was causing ROM loading to take an extra second or two longer than necessary
    - scale 5x setting will now maintain an exact multiple in both width and height for both NTSC and PAL modes
    - re-added group assignment and unassignment to the input settings window
    - re-wrote mouse capture code to be more intuitive, now uses buttons to set assignment
    - re-added input.allowInvalidInput check to stop up+down and left+right key combinations by default [Jonas Quinn]
    - split "Tools Dialog" menu option into separate items for each tool (Cheat Editor, Cheat Finder, State Manager)
    - added S-SMP and S-DSP property information readouts to the debugger
2010-01-11 02:13:12 +00:00
byuu
97a3a28d86 Update to bsnes v059 release.
**Known issues:**
- button menus do not show up with Windows Vista/7 theme
- snesreader's multi-file archive dialog box doesn't redraw itself on
Windows when you choose different games

Windows Qt is buggy as always. Nothing we can do but keep waiting. I'm
also going to hold off on including pixel shaders until Direct3D PS
support is in. It's just going to annoy the 98% of users who can't use
them if I include them now. Yes, Windows OpenGL support is that bad.

Anyway, from v058 wip10, the following changes were made:
- cheat code editor grays out the slot#s when they are empty. I can't
put "Empty" in the text boxes for various reasons.
- added "Clear Selected" button and multi-selection support to cheat
editor. This is meant to quickly erase all slots.
- settings and tools windows start at 600x360 when bsnes.cfg is not
found / empty
- fixed the emulationSpeed section to start with input. instead of
config.
- open-folder concept requires the folders to end in .sfc to work now,
once again doesn't care what the ROM inside is named
(this is meant to mimic OS X .app folders)
- 21fx API extended to map to $2200, $2201 for now; mostly as a test
for A-bus access (21fx->VRAM DMA, etc)
(old $21fx registers remain for now)

I intend to release this on Saturday as-is even if a few small bugs
are reported. But if there's something major we can make another RC
build.
2010-01-07 13:07:56 +00:00
byuu
6ec765f2c4 Update to bsnes v058 release.
We've tested the latest release on at least a dozen computers now, all seems to be in order for a release.
Changelog:
    - added 21fx support (more on this later)
    - added movie recording and playback support
    - added rewind support (enable under Settings->Configuration->Advanced, use backspace key to rewind)
    - added speedup (fast forward) and slowdown key bindings
    - audio no longer stutters on Windows when moving or resizing the main window
    - co-processors can now specify their own clock rates instead of sharing the S-CPU clock rate
    - Super Game Boy 2 now runs at the correct hardware speed, and not 2.4% faster like the Super Game Boy 1 does
    - added Vsync support to the Windows OpenGL driver (Intel graphics drivers do not support this option, because their engineers are lazy)
    - OpenGL driver no longer re-initializes when changing video synchronization, helps pixel shaders
    - refactored user interface compilation; now split into several object files, auto-generated MOC files placed under src/obj/
    - worked around a bug in the PulseAudio sound server that was causing the ALSA output driver to lock up [BearOso]
    - rewrote and simplified the save state manager, it is no longer a part of the core
    - S-DD1 and SPC7110 can now access up to 256MB via their MMCs
    - re-added background and OAM layer toggling under the tools dialog
    - added config file options to adjust emulation speed levels (config.system.speed*)
    - added snesreader, snesfilter and supergameboy support to the OS X port
    - added a really neat pixel shader that can perform point scaling to non-even multiples, eg it looks great even with aspect correction [Fes]
    - upgraded to Qt 4.6.0 official
Debugger changelog:
    - added memory export and import to the memory editor
    - added bus usage analyzer: logs opcodes, memory reads, memory writes and M/X states to usage.bin file
    - added disassembler that can trace both forward and backward from the current execution address
    - extended read/write breakpoints to the S-SMP
    - re-added trace masking option
Errata: there is one known bug in Qt 4.6.0 that affects the Windows port: menus attached to buttons show up as invisible on Windows Vista and above. I only use this on the file load dialog options button, and only to toggle the information pane on and off. Given that this is less severe than the bugs in the beta versions, I've upgraded anyway. I'll submit a bug report to the Qt team for this shortly. Also, my sincerest thanks to Bradley Hughes from the Qt development team for quickly fixing this show-stopper bug that greatly affected performance in bsnes v056.
2009-12-09 13:34:03 +00:00
byuu
54c7b4692d Update to bsnes v057 release.
I'm really sorry about this, but a major issue snuck into v056. It was caused by a bug in the newly released Qt 4.6.0 RC1. Whenever one moved the mouse cursor over the main window in the Windows port, the frame rate was immediately cut in half, which effectively ruined Mouse, Super Scope and Justifier support. As for how this could happen, well ... I'm ... really at a loss for words about this.
This release does not change the source code at all except to increment the version number, and it is built against Qt 4.6.0 beta 1 instead of 4.6.0 release candidate 1 as v055 was.
I will file an official bug complaint and post a link to it here during next week. Again, my apologies for any inconvenience. I incorrectly assumed it would be safe to update to RC1, and didn't spot the bug in time.
2009-11-23 13:24:03 +00:00
byuu
66067f0015 Update to bsnes v056 release.
This release adds a lot of new user interface features, and polishes Super Game Boy support.
Note that many pixel shaders need to be coded specifically for bsnes, eg ones designed for Pete's OpenGL2 plugin will not work. I will maintain a pixelshaders archive on the bsnes download page with a collection of working shaders. Right now, there are three: HDR TV, Scale2x and HQ2x; written by guest(r) and Pete, and ported by myself.
Changelog:
    - lowered Game Boy audio volume so that it matches SNES audio volume
    - fixed Super Game Boy multi-player support
    - fixed Super Game Boy swapped player bug
    - compressed Game Boy cartridges can now be loaded
    - added save state support for Super Game Boy games
    - blocked illegal Super Game Boy packets, fixes Zelda DX, Akumajou Dracula, etc palette issues
    - main window once again shrinks on size changes
    - joypads can now control the file loading window (support is very rudimentary)
    - cleaned up video and audio sliders, increased audio input frequency range for 59hz monitors
    - rewrote all of the input capture system from scratch
    - added dozens of additional GUI hotkey bindings to resize the main window, control synchronization, control speed, etc
    - it is now possible to map keyboard modifiers (shift, control, alt, super) to any input or hotkey; eg alt+enter = fullscreen
    - merged all input capture windows into the main settings panel
    - added turbo button support; hold down turbo buttons to send a 30hz input pulse
    - added asciiPad controller emulation; contains off/turbo/auto fire toggles and slow-motion mode
    - asciiPad support allows for quick switching between keyboard and gamepad input
    - merged scanline filter into the user interface (under Video Settings) to allow it to work on all filters; including the NTSC filter
    - killed off an evil QString <> string intermediary class called utf8; string class can convert to and from QString directly now
    - added fast BS-X, Sufami Turbo and Game Boy cartridge loading: use the filter list under "Load Cartridge" to bypass the BIOS selection screen
    - added pixel shader support to the OpenGL driver on Windows and Linux; note that it only really works well on Linux at the moment
    - added proper Vsync support to the OpenGL driver on Windows and Linux using GL extensions; again this really only works well on Linux
    - added unique path memory for shaders, folders, cartridges, BS-X, Sufami Turbo and Game Boy images
    - upgraded to Qt 4.6.0 release candidate 1; fixes an issue with the first checkbox in lists not updating when clicked
2009-11-22 14:48:58 +00:00
byuu
4c66de6f27 Update to bsnes v055 release.
Happy Halloween, this release adds full Super Game Boy support ... but is it a trick, or a treat? ;) ::cough::, lameness aside ...
The Game Boy emulation core is courtesy of gambatte, and excellent, accuracy-focused, open source, and lightning fast Game Boy Color emulator. Now I know what you're thinking, using a Game Boy Color emulator with the Super Game Boy? The truth is, gambatte was just such an amazingly perfect fit that nothing else compared. I fully believe that even as a CGB emulator, gambatte will do a better job than any pure DMG emulator could.
The emulation of the ICD2 chip (aka the Super Game Boy) was fully reverse engineered by myself. Eventually I'll get an updated document put up explaining how it works.
The next question might be, "why emulate the Super Game Boy when existing Game Boy emulators do?"; well, they can only simulate part of the SGB. Features such as custom SNES sound effects, hand-drawn borders, multi-tap support and custom SNES code execution can only be accomplished by a true SNES emulator. Space Invaders is perhaps the most impressive demonstration, as it contains an entire SNES game embedded inside the Game Boy cartridge.
bsnes' SGB emulation supports virtually every command, full sound mixing from both the SNES and Game Boy sides, both BIOS revisions, etc. The only thing that is not fully functional yet is the multi-player support, but it should be in due time. Save state support is also planned for a later date.
Changelog:
    - added Super Game Boy emulation (thanks to gambatte for the Game Boy core)
    - extended hybrid scanline/cycle PPU renderer to support Mode7 register caching; fixes scanline flickering on NHL '94 title screen
    - all windows (other than the main window) can be closed with the escape key now
    - file dialog path selection now accepts typed paths; can be used to access hidden directories and network shares
    - file dialog's game information panel can now be disabled
    - fixed a crashing issue when the file dialog was given an invalid path
    - fixed screenshot capture save location
    - added screenshot capture option to tools menu
    - state manager now auto-closes when loading a state; it can be reopened quickly with F3
    - fixed GZip archive loading
    - fixed NTSC off-by-one filter bug on hires screens
    - extended Scale2x, LQ2x and HQ2x to properly filter hires screens
    - added Pixellate2x filter
2009-11-01 14:30:51 +00:00
byuu
6a17b5ed4f Update to bsnes v054 release.
After a half-dozen hours of installing and compiling various combinations of MinGW and Qt, I've finally found a combination that once again allows for profile-guided optimizations: MinGW GCC 4.3.3 and Qt 4.6.0-beta 1. Though Qt 4.4 still has broken PGO, the latest Qt beta no longer has the process freeze issue upon termination.
This release is essentially the same as v053, but it's now at least as fast as v052 was, and ~10% faster than v053, which lacked profiling.
I did add in two quick changes, however: first, when starting in fullscreen mode, the video output size was being incorrectly set to the windowed size; second, by requiring save states to match the CRC32 of games, it made debugging with them impossible, so I've turned off the CRC32 matching.
2009-10-19 16:58:29 +00:00
byuu
8135dfdac9 Update to bsnes v053 release.
This release greatly polishes the user interface, adds a new cheat code search utility, adds the snesfilter library, and adds Qt-based GUI support to both snesfilter and snesreader. snesfilter gains 2xSaI, Super 2xSaI and Super Eagle support, plus full configuration for both the NTSC and scanline filters; and snesreader gains support support for multi-file ROM archives (eg GoodMerge sets.)
Statically linking Qt to bsnes, snesfilter and snesreader would be too prohibitive size-wise (~10MB or so.) I have to link dynamically so that all three can share the same Qt runtime, which gets all of bsnes and its modules to ~1MB (including the debugger build); and Qt itself to about ~2.5MB.
However, there is some bad news. There's a serious bug in MinGW 4.4+, where it is not generating profile-guided input files (*.gcno files.) There is also a serious bug in Qt 4.5.2/Windows when using dynamic linking: the library is hanging indefinitely, forcing me to manually terminate the process upon exit. This prevents the creation of profile-guided output files (*.gcda files.) It would be tough enough to work around one, but facing both of these issues at once is too much.
I'm afraid I have no choice but to disable profile-guided optimizations until these issues can be addressed. I did not know about these bugs until trying to build the official v053 release, so it's too late to revert to an all-in-one binary now. And I'm simply not willing to stop releasing new builds because of bugs in third-party software. As soon as I can work around this, I'll post a new optimized binary. In the mean time, despite the fact that this release is actually more optimized, please understand that the Windows binary will run approximately ~10% slower than previous releases. I recommend keeping v052 for now if you need the performance. Linux and OS X users are unaffected.
Changelog:
    - save RAM is initialized to 0xff again to work around Ken Griffey Jr Baseball issue
    - libco adds assembly-optimized targets for Win64 and PPC-ELF [the latter courtesy of Kernigh]
    - libco/x86 and libco/amd64 use pre-assembled blocks now, obviates need for custom compilation flags
    - added a new cheat code search utility to the tools menu
    - separated filters from main bsnes binary to libsnesfilter / snesfilter.dll
    - added 2xSaI, Super 2xSaI and Super Eagle filters [kode54]
    - added full configuration settings for NTSC and scanline filters (12+ new options)
    - further optimized HQ2x filter [blargg]
    - added Vsync support to the Mac OS X OpenGL driver
    - added folder creation button to custom file load dialog
    - fixed a few oddities with loading of "game folders" (see older news for an explanation on what this is)
    - updated to blargg's file_extractor v1.0.0
    - added full support for multi-file archives (eg GoodMerge sets)
    - split multi-cart loading again (BS-X, Sufami Turbo, etc) as required for multi-file support
    - cleaned up handling of file placement detection for save files (.srm, .cht, etc)
    - file load dialog now remembers your previous folder path across runs even without a custom games folder assigned
    - windows now save their exact positioning and size across runs, they no longer forcibly center
    - menus now have radio button and check box icons where appropriate
    - debugger's hex editor now has a working scrollbar widget
    - added resize splitter to settings and tools windows
    - worked around Qt style sheet bug where subclassed widgets were not properly applying style properties
2009-10-18 17:33:04 +00:00
byuu
a0000c7846 Update to bsnes v052 release.
This is a maintenance release, which fixes a few important bugs. It also adds some graphical icons to soften the user interface. Note that if you have set any custom paths with v051, you'll need to set them again for the fix to work. As always, my apologies for releasing two versions so close together. I felt the bugs were important enough to warrant it.
Changelog:
    - fixed loading of files and folders containing non-ANSI characters (Chinese, Japanese, etc)
    - fixed a slight lag on startup due to the new file browser
    - fixed path selection setting, screenshots will now be saved to the correct directory
    - hid memory editor scrollbar since it does not work yet
    - disabled window positioning on Linux due to bugs in the Compiz compositor
    - added icons from the Tango icon library to the menus and panels
2009-09-29 12:25:41 +00:00
byuu
b6a85353bf Update to bsnes v051 release.
Starting with this release, I wish to take bsnes in a new direction. It has always excelled in accuracy, as the only SNES emulator to offer a full 100% compatibility rate with all known commercial software. But over the years, it has also gained an impressive array of features and enhancements not found anywhere else. It is also the only actively developed SNES emulator with rapid, periodic releases. Its only achilles heel is the steep system requirements, which is quickly being overcome by aggressive new optimizations and steadily-increasing hardware speeds.
In an effort to make bsnes even more accessible to everyone, starting with this release, bsnes is now fully open source software, licensed under the terms of the GNU General Public License. I would like to work toward positioning bsnes as a truly general use emulator, and would welcome any help with this.
Specifically, I am looking for an interested Debian maintainer to package bsnes for Linux users; as well as for anyone interested in helping to optimize and improve bsnes as a whole. It also seems that many still do not know about bsnes, I'd appreciate advice and help on spreading the word. Please leave a message on my forum if you are interested.
I would also welcome and support any forks that target specific areas: a speed-oriented version, a tool-assisted speedrun version, netplay bindings, and so on. As part of this targeting, I've also released a custom debugger-enabled version, which trades a bit of speed in turn for best-in-class debugging capabilities.
Please check back here over the following few days, I'll be writing up documentation explaining all of the various unique features of bsnes, as well as detailed compilation instructions for programmers.
Changelog:
    - corrected a small bug in HDMA processing; fixes College Football '97 flickering
    - corrected ROMBR and PBR SuperFX register masking; fixes Voxel demo [MooglyGuy]
    - DSP-4 driver AI bug fixed [Jonas Quinn]
    - added save state support to the S-DD1, S-RTC, DSP-1, DSP-2 and ST-0010 co-processors
    - fixed a freeze issue when the S-SMP encounters STOP and SLEEP opcodes
    - Cx4 save states no longer need floating-point values, and are thus fully portable now
    - added new custom file loading dialog; allows non-modal usage, screenshot previews and ROM info summary, among many other benefits
    - added support for IPS soft-patching
    - added blargg's File_Extractor library
    - added support for archives compressed using 7-zip, RAR and BZip2; which is in addition to existing support for Gzip, ZIP and JMA
    - state manager now properly updates the timestamp column on saves [FitzRoy]
    - added OpenGL renderer to OS X port
    - fixed system beep issue with keyboard input on OS X port
    - fixed menubar visibility issue on OS X port
    - fixed a Display handle leak on Linux port [snzzbk]
    - X-video driver now releases SHM memory properly upon exit [emon]
    - fixed Direct3D rendering issue that was blurring video on some cards [Fes]
    - enhanced window positioning code for all platforms
    - debugger is now GUI-driven instead of via command-line
    - memory hex editor is now fully usable
    - added PPU video RAM viewer to debugger
    - added S-CPU and S-SMP tracing capabilities to debugger
    - Qt version upgraded to 4.5.2, and compiled with optimizations enabled; runs faster but makes the binary slightly larger
    - too many code cleanups to list
2009-09-27 11:40:16 +00:00
byuu
c2453cb634 Update to bsnes v050 release.
I always regret having to post new releases so quickly, but a semi-major bug crept into v049. I'd rather fix it now, before I start making major changes that will need testing again. The problem was that the S-PPU was not being synchronized as often as it should have been, resulting in titles such as F-Zero and Super Mario Kart showing flickering lines here and there. This release fixes that.
This release also adds savestate support for Mega Man X2 and Mega Man X3, which utilize the Cx4 coprocessor; and it fixes a bug where input was still accepted even when the main window was minimized.
2009-08-25 16:00:26 +00:00
byuu
59b86cd3a8 Update to bsnes v049 release.
This is a maintenance release, but it offers a lot of bug-fixes and speed-ups, so it should be well worth the update. The debugger is not finished yet, so use it at your own risk. It is disabled in the binary release because breakpoint testing impacts performance. Once it is ready, I will release a separate binary with the debugger enabled.
Changelog:
    - Optimized S-PPU emulation, provides a ~10-15% speedup in normal games
    - Cleaned up cheat editor user interface
    - Added save state and export data path selections
    - Added workaround for a strange issue that caused PAL games to run at 60 fps sometimes
    - Fixed sprite caching issue; fixes SD F-1 Grand Prix
    - Fixed PPUcounter reset issue; fixes Bishoujo Janshi Suchie-Pai [Jonas Quinn]
    - Fixed scaling on scanline, Scale2x, LQ2x and HQ2x filters on hires and interlace screens
    - Fixed sizeof(bool) serialization issue for PowerPC architecture [Richard Bannister]
    - Fixed cheat code sort ordering
    - Fixed a bug with centering in fullscreen mode
    - Fixed an audio pitch bug when changing frequency
    - Fixed a volume adjust bug when frequency was exactly 32000hz
    - Fixed X-video RGB rendering bugs [thanks to tukuyomi for testing]
    - Fixed a file open dialog issue on Linux when using QGtkStyle [jensbw]
    - Fixed a memory corruption issue involving QApplication::main() [giovannibajo]
    - Added a preliminary debugger (disabled in binary releases due to associated speed hit)
    - Added S-CPU and S-SMP stepping and tracing support
    - Added read/write/execute breakpoint support
    - Added memory editor (currently it can only view memory)
    - Added screenshot capture support [kode54]
    - Save state archives are now ~60% smaller than before
    - Various code cleanup work, as usual (note: the debugger code is messy, as it is in-progress)
2009-08-22 12:09:19 +00:00
byuu
c26f9d912a Update to bsnes v048 release.
The biggest feature of this new release is the addition of save state support. Note that this is only currently supported for normal games, and the SPC7110 and OBC-1 co-processors. Other special chips, such as the SuperFX and SA-1, cannot currently save and load state files. I will be adding support for other co-processors little by little in future releases.
Changelog:
    - Added save state support
    - Added SPC7110 and OBC1 save state support
    - Added new tools group, with new cheat code and save state managers
    - Lots of new UI shortcuts: quick save state, quick load state, show state manager, etc
    - Escape key will now close both the settings and tools group windows
    - Added major speed-ups to both SuperFX and SA-1 emulation; both now run ~15-25% faster than v047
    - Added new video filter, LQ2x; it's as fast as Scale2x while being almost as smooth as HQ2x
    - Re-wrote HQ2x algorithm; code size was reduced to less than 10% of its original size with virtually no speed loss
    - Corrected SuperFX2 cache access timing; fixes Stunt Race FX menus and slowdown in other titles
    - Relaxed palette write limitations for PGA Tour Golf [Jonas Quinn]
    - Fixed a slight timing issue that was breaking 'An Americal Tail - Feivel Goes West'
    - Turned off auto-save of SRAM as it was causing slowdowns when writing to flash memory; can be re-enabled via bsnes.cfg -> system.autoSaveMemory = true
    - Added bsnes.cfg -> system.autoHideMenus, defaults to false; when true, menu and status bars will be hidden upon entering fullscreen mode
    - Added skeletons for ST011 and ST018 support. Both Quick-move titles get in-game now
    - Re-wrote S-CPU and S-SMP processor cores to use templates, removed custom pre-processor
    - Split PPUcounter into a base class inherited by both PPU and CPU; allows both cores to run out-of-order
    - Split inline header functions to separate files, allows headers to be included in any order now
2009-07-12 09:45:57 +00:00
byuu
7b0e484c18 Update to bsnes v047 release.
The most notable feature for this release is the addition of SuperFX support. This enables an additional eight commercial games, and two unreleased betas, to run with full support. Most notably of these would be Super Mario World 2: Yoshi's Island and Starfox. Though timing is not quite perfect just yet, there should be no known issues with any titles at the time of this release. That means there should only be two official, commercially-released titles that are not compatible with bsnes at this time: Quick-move Shogi Match with Nidan Rank-holder Morita 1 and 2 (using the ST011 and ST018 co-processors, respectively.)
SuperFX support was the work of many people. GIGO was a great help by providing the source code to his SuperFX emulator (for reference; the implementation in bsnes is my own design), _Demo_ was very helpful in getting Starfox to work properly, and Jonas Quinn provided roughly a half-dozen very important bug fixes that affected nearly every SuperFX game. Without them, this release would not be possible. So please do thank them if you appreciate SuperFX support in bsnes.
Please note that SuperFX emulation is very demanding. I hate to have to repeat this, but once again: bsnes is a reference emulator. It exists to better understand the SNES hardware. It is written in such a manner as to be friendly to other developers (both emulator authors and game programmers), and the findings are meant to help improve other emulators. As far as I know, bsnes is the first emulator to fully support all SuperFX caching mechanisms (instruction cache, both pixel caches, ROM and RAM buffering caches, ...); as well as many other obscure features, such as full support for ROM / RAM access toggling between the SNES and SuperFX CPUs, and multiplier overhead timing. By emulating these, I was able to discover what additional components are needed to emulate Dirt Racer and Power Slide, two titles that no emulator has yet been able to run (they aren't very good games, you weren't missing much.) It should be possible to backport these fixes to faster emulators now.
That said, with a Core 2 Duo E8400 @ 3GHz, on average I get ~100fps in Super Mario World 2, ~95fps in Starfox and ~85fps in Doom. Compare this to ~165fps in Zelda 3, a game that does not use the SuperFX chip. My binary releases also target 32-bit x86 architecture. For those capable of building 64-bit binaries, especially Linux users, that should provide an additional ~10% speedup. Be sure to profile the application if you build it yourself.
Lastly on the SuperFX front, note that Starfox 2 is fully playable, but that most images floating around have corrupted headers. I do not attempt to repair bad headers, so these images will not work. Please either use NSRT on the Japanese version, or use Gideon Zhi's English fan translation patch, if you are having trouble running this title.
With that out the way, a few other improvements have been made to this release: xinput1_3.dll is no longer required for the Windows port (though you will need it if you want to use an Xbox 360 controller), the video drivers in ruby now allocate the smallest texture size possible for blitting video, and the code has been updated with preliminary compilation support for Mac OS X. Note that I will not be releasing binaries for this: it is primarily meant for developers and for porting my other libraries to the platform. Richard Bannister maintains a much better OS X port with full EE support and a native Apple GUI that follows their interface guidelines much better than a Qt port ever could. He has also synced the Mac port with this release. You can find a link to that in the bsnes download section.
2009-06-07 11:57:05 +00:00
byuu
f8e425ff49 Update to bsnes v046a release.
[No changelog available]
2009-05-12 02:33:49 +00:00
byuu
2a6a66f478 Update to bsnes v046 release.
Unfortunately, I was not able to include any actual Super Game Boy support in this release. I was however able to back-port all other changes since v045, as well as add a lot of new stuff. Though there are few visible changes from the last release, internally much has changed. I'm releasing this mostly as a point release whilst everything should be stable.
I've decided to support the Super Game Boy via external DLL (or SO for Linux users.) There are many reasons for this. Most notably is that the largest special chip in bsnes right now weighs in at ~30kb of code. Emulating an entire Game Boy, not including the SGB enhancements, would require an additional ~800kb of code, or nearly half the size of the entire SNES emulation core. Add to that potential issues with licensing, conflicts with the build process / namespace, a significant increase to build time, and a lack of flexibility over which Game Boy emulator to use, and it's pretty clear that this is something best left external. At least until we have a fully trimmed, fully working SGB emulator available.
The way this will work is bsnes will look for SuperGameBoy.(dll,so), and if present, it will call out to pre-defined functions. Users will need the SGB BIOS loaded, at which point they can select a Game Boy cartridge, and bsnes will use the DLL for actual emulation. Sadly I don't have a working DLL ready for this release, and even if I did, there's no sound bridge yet for the Game Boy audio.
Other than that, much of the core has been updated in an attempt to make the core more library-like. It still has a few major limitations: it requires libco (which is not portable) and nall (which is quite large), and only one instance can be instantiated as all of the base objects are pre-defined and inter-linked. Not that I can imagine any practical use for multiple simultaneous SNES emulators anyway ...
Changelog:
    - Save RAM is now automatically saved once per minute
    - Added delay to Super Scope / Justifier latching to fix X-Zone
    - Fixed an edge case in CPU<>PPU counter history
    - S-CPU can now run up to one full scanline ahead of S-PPU before syncing
    - Added interface for Super Game Boy support (no emulation yet)
    - Fixed a bug with path selection not adding trailing slash
    - All S-SMP opcodes re-written to use new pre-processor
    - Entire core encapsulated into SNES namespace
    - Core accepts files via memory only; zlib and libjma moved outside of core
    - Major Makefile restructuring: it's now possible to build with just "make" alone
    - Linux: libxtst / inputproto is no longer required for compilation
    - Lots of additional code cleanup
2009-05-10 11:01:02 +00:00
byuu
3c42e6caa0 Update to bsnes v045r09 release.
[No changelog available]
2009-04-30 20:58:39 +00:00
byuu
5f96547beb Update to bsnes v045 release.
This is a maintenance release to fix a crashing bug in S-DD1 games (Star Ocean, Street Fighter Alpha 2), and a video issue in games using the WAI instruction.
As always, my apologies for any inconvenience. SA-1 support required modification of a large amount of delicate code in the emulation core, and our limited testing team was not able to catch these in time before release.
2009-04-20 02:55:33 +00:00
byuu
44b5f1bf27 Update to bsnes v044 release.
This release adds full SA-1 support, with no known issues. All 26 games have been tested by myself and others, and a few have been beaten from start to finish. The latter include Super Mario RPG, Kirby's Dreamland 3, Kirby Super Star and Jikkyou Oshaberi Parodius.
Please understand that the SA-1 is essentially four times faster than the SNES' main CPU, so system requirements will be very high for these games. For example, on an E8400 @ 3.0GHz, I average ~160fps in ordinary games. But for SA-1 emulation, this drops to ~90fps, with the worst case being ~80fps.
The following features are emulated:
    - 5a22 CPU core (bus-cycle accurate)
    - Memory access timing
    - SA-1 -> S-CPU interrupts (IRQ + CHDMA IRQ)
    - S-CPU -> SA-1 interrupts (IRQ + Timer IRQ + DMA IRQ + NMI)
    - SIV / SNV interrupt vector selection
    - Timer unit (linear and H/V)
    - Super MMC unit (ROM + BW-RAM)
    - BS-X flash cart slot mapping
    - Normal DMA
    - Character-conversion 1 DMA (2bpp + 4bpp + 8bpp)
    - Character-conversion 2 DMA (2bpp + 4bpp + 8bpp)
    - BW-RAM virtual bitmap mode (2bpp + 4bpp)
    - Arithmetic unit (multiplication + division + cumulative sum)
    - Variable-length bit processing (fixed and auto increment)
While the following features are not currently emulated, mostly due to lack of information:
    - SA-1 bus conflict delays
    - Write protection (BW-RAM + I-RAM)
    - SA-1 CPU priority for DMA transfers
    - DMA access timing
2009-04-19 21:34:23 +00:00
byuu
b0a8de0208 Update to bsnes v043 release.
[No changelog available]
2009-04-18 17:13:29 +00:00
byuu
11e0a2ac18 Update to bsnes v042r05? release.
New WIP. Wasted two and a half hours trying to figure out why re-
implementing IRQs at home was failing in Parodius. Finally just
reverted to wip05 and started again, changing one line at a time.
Turns out I inverted the reset release flag by mistake for the SA-1
CPU. Fun.

Adds S-CPU -> SA-1 IRQs, DMA IRQs and NMIs + SA-1 -> S-CPU IRQs +
CH1DMA IRQs. Also slightly improves variable bit-length reading and
removes DPRIO mode for now until I can test it properly.

Parodius, SRW: Gaiden and Kirby: SS should all be fully playable now.

Mario RPG is damn close, but it freezes immediately after you exit the
level up bonus screen. I don't have any idea what it wants. The
graphics on the bonus screen don't show up either, as I don't support
char conversion modes 1 or 2 yet (it uses mode 1.)

How annoying ... first the graphics on the logo are bad. Add the ALU,
good. Now the title screen background is black. Fix the ALU MA
register reset, good. Now it freezes after the first intro scene. Add
SA-1 -> S-CPU IRQs. Now it freezes half-way through the intro. Fix
S-CPU /IRQ line holding from the SA-1. Now it freezes at the start of
the level up bonus screen. Add CHDMA IRQs. Now it freezes immediately
after the level up bonus screen.

I have no idea what the hell SIV / SNV are for. I'm guessing the SA-1
controller detects which processor activates SA-1 IRQs and uses that
vector address ...? It obviously can't over-ride the S-CPU's vector
addresses.

Documentation is shit. It doesn't specify what vectors DMA / CHDMA
use, or what to do without specific general DMA / CHDMA IRQ enable
flags in the control registers, and on and on.

[No archive available]
2009-04-10 13:52:00 +00:00
byuu
3a6eb56cef Update to bsnes v042r04? release.
New WIP. Copy-paste:
> Working on SA-1, still a long way to go. Fixed a bug where I was
> clearing MA after multiplication / cumulative sum when I wasn't
> supposed to. Fixes Kirby 3 Pop Star scene.

> Added normal DMA, along with full support for DPRIO (allowing DMA to
> run alongside the SA-1 CPU) and blocking of invalid transfer types /
> modes. This fixes sprites in Marvelous.

> Also added BW-RAM bitmap mirroring to $[60-6f]:[0000-ffff], proper
> mapping for the bitmap mode to the $[00-3f|80-bf]:[6000-7fff]
> regions, variable-length bit read data port, and I now at least
> cache the register settings for IRQs (though I still do nothing with
> them.)

> I added support for BW-RAM and I-RAM write protection, but when it's
> enabled, most games will no longer load. So I'm forced to leave that
> off for now. Maybe the protection didn't actually work on the real
> hardware? Hmm ...

> No idea what the bitmap registers $2240-$224f are for, and I don't
> see how it's supposed to be possible to trigger IRQs as needed by
> Super Mario RPG and Parodius. But at least three of five games
> should now be fully playable with no issues. Speed remains the same
> as yesterday. No hit for the SA-1 CPU+DMA simultaneous transfer mode
> support.


Image Image

> I want pictures of SRW Gaiden!


Can always try it and see what happens ... after I get some sleep :D

[No archive available]
2009-04-08 12:22:00 +00:00
byuu
4c92d11d80 Update to bsnes v042r03? release.
I mentioned I wouldn't be posting a new WIP for a while so that I
could work on something in secret. That way in case it didn't work
out, nobody would be bummed out. Imagine my surprise when it only took
me two days to get this far ...

Image Image
Image Image
Image Image
(I removed the title-bar text for the sake of the screenshot
aesthetic. Check the WIP yourself if you don't believe it.)

Kirby's Dream Land 3 and Dragon Ball Z: Hyper Dimension are fully
playable. Note that most games aren't playable, and most of the chip's
added features are missing.

Speed took a ~3-5% hit for non-SA1 games due to all the new co-
processor thread synchronization primitives that you can't really hide
from inlined, super-intensive sections of the scheduler code.

As of now, and this will change, SA-1 games run about ~60% slower than
normal games. Meaning you'll really want at least an E4500, but
preferrably an E8400; and no filters.

The most impressive part is that I emulate this at the bus/clock
level. Meaning if both the S-CPU and SA-1 access RAM at the same time,
they'll see the changes and stay perfectly in sync. I even emulated
the bus conflict resolution of the SA-1 memory controller. So in terms
of accuracy, this is akin to the cycle-level S-PPU. It's the
"theoretical worst case" for the most processor-intensive, lowest-
possible emulation achievable.

I believe it was _Demo_ who speculated that it'd take at least a 10GHz
processor to achieve this. Then again, it's been so long I could be
attributing the quote to the wrong person. Don't even remember the
exact words anymore. Anyone recall?

This gives us insight into the kind of performance we can expect from
the cycle-PPU (also runs at 10.74MHz) and SuperFX. For SA-1+cycle
S-PPU, it would appear that there is no processor on the market that
can maintain full speed with that combo yet, heh. By the time I get
around to S-PPU, there most likely will be though.

Lastly, don't bug me about SuperFX support because of this. This SA-1
support is a simple subclass of the core S-CPU that already existed in
cycle-perfect, bug-free form; plus a memory mapper and ALU. Lots more
to go, and even then, this is easily multiple times less work than the
SuperFX is going to be.

[No archive available]
2009-04-07 13:14:00 +00:00
byuu
f3d1d10d3e Update to bsnes v042r02? release.
New WIP. The entire S-CPU opcode core has been re-written to use my
new pre-processor.

The downside is that it's actually slightly slower, by less than 1%.
Guessing that having almost twice the opcode implementations ends up
eating more valuable L1 cache, making it more painful than the two
conditionals per function I had before. But damn if it isn't more
readable now.

Before:
    ror_addrx(0x7e, ror) {
    1:aa.l = op_readpc();
    2:aa.h = op_readpc();
    3:op_io();
    4:rd.l = op_readdbr(aa.w + regs.x.w);
    5:if(!regs.p.m) rd.h = op_readdbr(aa.w + regs.x.w + 1);
    6:op_io();
      if(regs.p.m) { op_$1_b(); }
      else { op_$1_w();
    7:op_writedbr(aa.w + regs.x.w + 1, rd.h); }
    8:last_cycle();
      op_writedbr(aa.w + regs.x.w,     rd.l);
    }


After:
    @macro op_adjust_addrx(name)
      void {class}::op_{name}_addrx_b() {
        aa.l = op_readpc();
        aa.h = op_readpc();
        op_io();
        rd.l = op_readdbr(aa.w + regs.x.w);
        op_io();
        op_{name}_b();
    {lc}op_writedbr(aa.w + regs.x.w, rd.l);
      }

      void {class}::op_{name}_addrx_w() {
        aa.l = op_readpc();
        aa.h = op_readpc();
        op_io();
        rd.l = op_readdbr(aa.w + regs.x.w + 0);
        rd.h = op_readdbr(aa.w + regs.x.w + 1);
        op_io();
        op_{name}_w();
        op_writedbr(aa.w + regs.x.w + 1, rd.h);
    {lc}op_writedbr(aa.w + regs.x.w + 0, rd.l);
      }
    @endmacro

( note: {lc} is short-hand to 'hide' last_cycle(); )

Really worn out now, so don't expect a new WIP for quite a long time
I'm afraid. I'll worry about the S-SMP's core much later. Would
appreciate thorough testing. Given I rewrote all 256 opcodes by hand,
it's possible I made a mistake somewhere.

> Once Alt has been pressed to access the menubar (even just one
> time), the menu accelerator keys become functional even without
> pressing them together with Alt.


Wow ... that is quite alarming. Not sure why Qt is doing that. But
since I don't have a way of fixing it yet ... for now:

> Stop pressing alt.


:/

[No archive available]
2009-04-06 04:13:00 +00:00
byuu
90aa780d57 Update to bsnes v042r01? release.
New WIP.

Updated centering code, it now just has per-platform centering code.
So it should look great with no flickering / movement on Windows or
Linux.

Fixed the patching status thing so it won't say it patched when it
fails. But seems there's not enough safeties in nall::ups. A patch of
nothing but "UPS1" has a 50% chance of crashing the emulator.

Most importantly, I finally got around to writing my pre-processor,
which is intended to add macro support to both C++ and xkas. Calling
it bpp, for **b**yuu's **p**re-**p**rocessor.

I started rewriting the S-CPU opcodes to use the new pre-processor. 40
of 256 opcodes finished. I'm also separating the 8-bit and 16-bit
versions this time. Twice the code, but it's easier on the eyes.

Old:
    ldy_addrx(0xbc, ldy, regs.p.x),
    ora_addrx(0x1d, ora, regs.p.m),
    sbc_addrx(0xfd, sbc, regs.p.m) {
    1:aa.l = op_readpc();
    2:aa.h = op_readpc();
    3:op_io_cond4(aa.w, aa.w + regs.x.w);
    4:if($2) last_cycle();
      rd.l = op_readdbr(aa.w + regs.x.w);
      if($2) { op_$1_b(); end; }
    5:last_cycle();
      rd.h = op_readdbr(aa.w + regs.x.w + 1);
      op_$1_w();
    }


New:
    @macro op_read_addrx(name)
      void {class}::op_{name}_addrx_b() {
        aa.l = op_readpc();
        aa.h = op_readpc();
        op_io_cond4(aa.w, aa.w + regs.x.w);
        last_cycle();
        rd.l = op_readdbr(aa.w + regs.x.w);
        op_{name}_b();
      }

      void {class}::op_{name}_addrx_w() {
        aa.l = op_readpc();
        aa.h = op_readpc();
        op_io_cond4(aa.w, aa.w + regs.x.w);
        rd.l = op_readdbr(aa.w + regs.x.w + 0);
        last_cycle();
        rd.h = op_readdbr(aa.w + regs.x.w + 1);
        op_{name}_w();
      }
    @endmacro


    @global class sCPU
    @include "opcode_read.bpp"

    @op_read_addry(ldx)
    @op_read_addry(ora)
    @op_read_addry(sbc)


Yes, I know the above can be done with the C pre-processor. Two major
reasons I avoided it:
1) I refuse to put \ after every line.
2) parameters are limited, eg MACRO(&=~, x += 2) would not work.

The important thing was making a more generic / flexible format. Will
allow me to kill off src/tool, though I'll still include the new
parser's source under src/lib/bpp.

May extend bpp in the future, who knows. @if/@else/@endif would be
nice, as would nested macros and static programming functions.

[No archive available]
2009-04-03 11:15:00 +00:00
byuu
b5b21a4ec2 Update to bsnes v042 release.
A new release quite a bit faster than I was expecting, but a lot has changed. Most importantly is a new Windows input driver, "RawInput". The downside is that this makes bsnes require at least Windows XP, as Windows 2000 and earlier lack RawInput support. The upside is that input from multiple keyboards and mice can be distinguished from each other — very useful for dual-Justifier support in Lethal Enforcers. Users of previous versions of bsnes will need to manually select the new driver via Settings->Configuration->Advanced->Input driver, and will need to re-map all assigned input keys, including the default user interface hotkeys. Or alternatively, delete the configuration file under %APPDATA%\.bsnes or ~/.bsnes.
Also new is an XInput driver, which avoids the DirectInput driver limitation of being unable to distinguish the two shoulder trigger buttons. This makes bsnes require DirectX 9.0c or later for the necessary drivers. Note that Windows Vista SP0 does not ship with these, so if you haven't installed it yet, you'll need to do so. This driver is part of the "RawInput" driver mentioned above.
This part is important: if you receive an error regarding xinput1_3.dll, you need to download and install the DirectX 9.0c run-time.
For those on Windows 2000, or without DirectX 9.0c, it is still possible to compile and run bsnes with the older DirectInput driver only; but I won't be providing a binary myself for this — at least not at this time.
More bad news for some: hiro, my Win32 / GTK+ API wrapper, has been discontinued and removed from the source tree for this release. Qt 4.5.0+ is now required for the user interface. Very sorry to the Linux distros that do not have packages for QT 4.5 yet. You'll need to continue with v041 for now.
2009-03-30 18:21:47 +00:00
byuu
2b587de04b Update to bsnes v041r08? release.
Okay then, if everyone possible could test this _quickly_, I can post
a new release tonight. Especially the input mapping, and especially
there for gamepads / controllers.

    http://byuu.org/files/bsnes_test.zip


No source, Windows only binary.

If you get an error about xinput1_3.dll, install the DirectX 9.0c
redistributable.

Changes from last WIP:

- I was able to reproduce FitzRoy's issue, and fix it. Really, really
crappy gamepads that send large phantom movements when the user isn't
even touching the axes may trigger the calibration window early; not
much I can do about that. None of my controllers do this at least.

- I updated the mouse button capture window. It now uses a framed
label (kind of like a groupbox but with text in the center), and you
have to release a mouse button inside the box for it to map.

- Screensaver / monitor power saving disabled on both Windows and
Linux.

- More improvements to window centering.

> Btw, are you on SP1 like me?


No, I'm using Windows 7 beta 1.

[No archive available]
2009-03-29 22:04:00 +00:00
byuu
1e133eeb5e Update to bsnes v041r07? release.
New WIP.

Rewrote a large portion of the RawInput driver, cleaning it up
substantially. Each API is now its own separate class, and pInputRaw
(the ruby private implementation class) pulls data from each separate
driver.

For keyboards, I've added the fixes for print screen and
pause/num_lock.

For joypads, I added XInput controller detection through RawInput's
RIDI_DEVICENAME, instead of that crazy ass COM + wbem shit from MSDN.
I also added a proper XInput driver, so now the left and right axes
can be mapped independently, and you can use both at the same time.
All in all, quite expensive and a lot of work, but it's the little
bits of polish that really make an application shine.

Do note that MinGW still doesn't ship with libxinput.a -- it's only
been out for four years now, after all. You'll need to take XInput.lib
from the DX9 SDK x86\lib folder, copy it to MinGW\lib, and rename it
to libxinput.a. I'm surprised that works, but it does. I tried to use
LoadLibrary("xinput1_3.dll") + GetProcAddress("XInputGetState"), but
the app kept crashing in bsnes when optimizations were enabled. gdb
showed it to crash in msvcrt!memcpy() from inside dinput8.dll. No idea
what the hell was going on there.

Non-XInput controllers will fall back on using DirectInput, of course.

Fixed the joypad indexing, so multiple joypads should work again. Got
the window centering hopefully right on WinXP so that windows opening
for the first time won't 'flicker' anymore. Added the mklib(gdi32)
entry, so you can compile with -mconsole again.

Re-did the mouse capture stuff. 'Assign Mouse Button' + 'Assign Mouse
Axis' are now buttons instead of menu buttons.

For button assignment, you are given a window with a large disabled
button named '(capture box)'. The instructions say to put whatever
mouse you want over this button and click the mouse button that you
want to assign. It'll assign upon release. Right now, assignment won't
work for 1-2 seconds to prevent instant assignment when you click.
I'll make a button mask in the future to avoid that delay. Also, it
only verifies you clicked a mouse button while the capture window was
active. I'll need to look into Qt's methods for mapping cursor clicks
to control regions onscreen. Good news is it's now much easier to
assign extended buttons like up+down ... you don't have to know what
button #s they are anymore.

For axis assignment, mapping based on mouse motion is too dangerous.
So you get a window with two buttons: 'X-axis' and 'Y-axis'. I can add
Z-axis if anyone wants (for the scroll wheel), but it seems kind of
useless. The instructions say to click the axis button you want, with
the mouse you want the axis assigned to.

Now I know the instructions will probably just confuse people with
only one mouse (~99% of users), so if everyone really thinks it'd be
better to leave multi-mouse users in the dark about how the capture
system works, I can take out the verbose notes.

Hoping your controller will work now, FitzRoy. Otherwise I have no
idea what's wrong. Be sure you manually set the driver to RawInput,
too. Will most likely require a config file with "version = 42",
otherwise reset to defaults, for the next release.

[No archive available]
2009-03-29 07:48:00 +00:00
byuu
9de4b1dea2 Update to bsnes v041r06? release.
New WIP. This version adds RawInput support.

I strongly recommend just deleting the old config file, because all
the old bindings won't work. You may also need to select the driver
manually from the advanced tab (it should be the default if no config
file is found.)

I now allow up to sixteen keyboards, sixteen mice and sixteen joypads
to be uniquely identified and independently mappable. So if anyone
wants to setup a 6-man-per tag-team game of N-warp Daisakusen, now you
can. And $50 for the first person to take a picture of said event for
me ;)

While ZSNES beat me to mouse support with ManyMouse, I win with
"ManyKeyboard" :P

And if anyone wants to get me one of those SNES barcode battler games
+ hardware, I'll try and emulate a generic USB HID barcode scanner.

Let's see ... currently the mouse assignment from the UI won't work.
You'll need to edit bsnes.cfg. The format is:

mouseNN.x, mouseNN.y, mouseNN.z, mouseNN.buttonXX
NN = 0 - 16, XX = 0 - 4

Need to plan how I want to design a mouse capture window, so that will
be a while still.

Also didn't get around to the screensaver disable code just yet. Took
me seven hours straight and I just barely finished the RawInput driver
in time.

Testing would be greatly appreciated.

[No archive available]
2009-03-26 14:57:00 +00:00
byuu
2b84d1ef37 Update to bsnes v041r05? release.
Meh, window is appearing on XP when placed at -1,-1. Changed that to
2560,1600 to stop that initial flicker before the windows appear
centered. Also from the WIP I made it use showNormal() so it'll show
windows even if they were previously minimized.

> Some people prefer baby seal meat.


I'm still not following your point. I've already added it. It took me
a few days but it's done. Everything that worked before is exactly the
same, but you now have the _option_ of doing more. Binary size is the
same, source code grew by ~2k (mostly due to extreme commenting.)

Not necessary, no; but I wanted it. Now we have it, and it's one more
bit of polish (along with infinite cheat codes, infinite length
descriptions in UTF-8, cheat code grouping and sorting, UPS support,
single or multi user modes, resizable config windows, flexible theming
and backdrop images, ...) that no other SNES emulator has yet :D

And tons of stuff I'm missing: savestates, rewind, SuperFX, SA-1,
speed, macros / key combos, movies, netplay, ...

-----

This works well enough for Windows:

    class Application : public QApplication {
    public:
      #ifdef _WIN32
      bool winEventFilter(MSG *msg, long *result) {
        if(msg->message == WM_SYSCOMMAND) {
          if(msg->wParam == SC_SCREENSAVE || msg->wParam ==
    SC_MONITORPOWER) {
            printf("blocked sleep\n");
            *result = 0;
            return true;
          }
        }

        return false;
      }
      #endif

      Application(int argc, char **argv) : QApplication(argc, argv) {}
    };


Add XTestFakeKeyEvent sans XSync (to avoid X-Video stuttering issues
per BearOso) and screensaver disable should be taken care of -- at
least until someone works on the OS X port.

[No archive available]
2009-03-24 19:15:00 +00:00
byuu
e2a44195cd Update to bsnes v041r04? release.
Okay, new WIP. That's the best I can possibly do.

For all six axes, I now ignore input until the state changes for the
first time. If it goes from 0 to > 24576 in a single poll, it
considers the axis to be a button. Otherwise it treats it as a stick.

Positive on a stick means down or right, so it's less likely users
will hit this first (up, left are more common for assignment as
they're first in the control lists.)

To minimize the damage of a bad map, I now map each axis to their own
value without regard for axis vs analog button indexing. Eg you will
have { axis00, axis01, analogbutton02, analogbutton03, axis04, axis05
} instead of { axis00, axis01, analogbutton00, analogbutton01, axis02,
axis03 }. That way if you do screw up the mapping and restart, the
indexes won't change on you. I don't do that on Linux to allow as many
axes + analog buttons as possible, and because it's not needed.

I had to choose what to bias, so I went with axes as they seem more
important overall. Eg -32768 to +24575 = stick; +24576 to +32767 =
button. That means it's easier to map a button as an axis than vice
versa.

It's unfortunately still quite easy to map these incorrectly, eg if
you slam down on a button or smack a stick as hard as you can down or
to the right.

But it was basically ... have a chance of mapping inputs wrong, or
don't let them be mappable at all. The former seems better in that
case.

If _anyone_ has a proper solution for this problem, I'd greatly
appreciate it. In fact, let's put a bounty on it. I'll pitch in $20
for the solution (a way to get the true state of axes without
requiring the user to press a button first.)

I also used EnumObjects over all absolute axes to map them to -32768
to +32767. That should help with the Xbox 360 controller that defaults
to half that range or whatever (fuck you, XInput.)

Testing would be appreciated. Both for the Windows and Linux ports,
though I can't foresee there being any problems with the Linux one.

---

SDL on Win32 does the same thing ... not surprising since it just uses
DirectInput anyway.

    #include <SDL/SDL.h>
    SDL_Joystick *gamepad;

    int __stdcall WinMain(HINSTANCE, HINSTANCE, LPSTR, int) {
      SDL_InitSubSystem(SDL_INIT_JOYSTICK);
      SDL_JoystickEventState(SDL_IGNORE);

      gamepad = SDL_JoystickOpen(0);
      while(true) {
        SDL_JoystickUpdate();
        unsigned axes = SDL_JoystickNumAxes(gamepad);
        for(unsigned n = 0; n < axes; n++) {
          printf("%d = %6d; ", n, SDL_JoystickGetAxis(gamepad, n));
        }
        printf("\n");
      }

      return 0;
    }

[No archive available]
2009-03-22 02:09:00 +00:00
byuu
9ac912d100 Update to bsnes v041r03? release.
New WIP.

This adds support for hats and analog buttons, and fixes the centering
code so that it never ends up minimized on Linux at startup. Just went
back to putting the window offscreen before centering, as thanks to
the delay in propagating window messages in Xorg, you don't even
notice the flicker on Linux.

You can now have up to 8 hats, 16 axes, 16 analog buttons and 96
digital buttons. Just to future proof things. If your controller has
more than that ... then I demand you send it to me before I'll support
it.

SDL input for Linux should work fully: hats allow four unique inputs,
axes two and analog buttons one. It calibrates to tell the difference
when you start the emulator.

DirectInput doesn't work so well. The DIJOYSTATE2 struct has a ton of
analog inputs, but only lX/lY map to the first stick, and lRx/lRy to
the analog buttons. But I can't even detect those properly because for
some bastardized reason, polling them at startup returns 0, 0. It
isn't until the user presses at least one button that the controller
'snaps out of it' and returns the proper +32767,+32767 for the two
buttons.

On the bright side, DI treats POV hats like POV hats. It allows up to
four, so that's what you get. You'll have to deal with that or the
first analog stick for Windows.

Unless there's a DirectInput expert here, not sure I can fix this. The
other inputs are not in DIJOYSTATE2 at all. Yet somehow the control
panel applet can sense them.

Mapping is fully inclusive, for joypad buttons and UI shortcuts, you
can use keyboard buttons, mouse buttons, joypad buttons, joypad axes,
joypad hats, joypad analog buttons. For mouse / super scope axes, you
can use mouse axes and joypad axes. Buttons aren't bi-directional and
lack the precision to support the mouse / SS / Justifier to any usable
degree, and analog buttons are uni-directional.

> Have you thought about rendering plugins for sound, input, video?


Would rather not. Cross-platform dynamic library support is terrible.

> Hmm must be "spin the black circle" as far as I can tell.


Yeah, here. I posted about it here a while back. Probably should've
mentioned the name.

> Yeah. That cheating nonsense discourages me from really playing any
> online games with top scores like that. It sucks all the fun out of
> it.


It's usually okay when it's painfully obvious. I cleared every level
at least a dozen times, and took advantage of every collision quirk
there was to get time there. For there to be a > 30 second leap
between #4 and #5 (and #1-4 all from the same person), it's pretty
obvious that he was cheating in some way.

I consider the best time to be 03:58, and 04:06 (edit: 4:01:97 now) is
close enough to make me happy :D

[No archive available]
2009-03-18 16:12:00 +00:00
byuu
d15092dada Update to bsnes v041r02? release.
New WIP.

I've added the centering code. Had to hide and show the window to
prevent the Windows 'restore-from-taskbar' animation. That's causing
Xorg events to not propagate quickly enough so sometimes the windows
start minimized. I'll keep working on it.

I've also killed joypad<>::up, down, left, right; and added
joypad<>::hat<0-3>.

So far, I've adapted the Qt UI to map analog axes. You'll see now when
you map one that you get ::lo or ::hi to indicate the state direction
at the time of assignment. I have not done this for hats, so only the
'up' direction will map currently.

I only know how to read the first two axes (first stick) on Windows,
so it won't see any others yet.

For the mapping, I made it both range-sensitive (requires at least 75%
force to map, 50% force to trigger) and distance-sensitive (prevents
auto-assignment for those annoying analog sticks that flicker within a
few points in any direction; also protects against those sixaxis
buttons that are idle at +32767) -- the distance is at 512, and slow
movement causes ~1,000+ movement based on ~20ms sampling, should be
enough.

To prevent rapid assignment of the same analog axis when using the
"Assign All ..." button, and because it makes no sense to allow it,
I've added a check to make sure that each key assignment is unique to
all previous ones. This doesn't apply to individual assignment in case
you really do want one key to map to two inputs. It was that or add a
~200ms delay between each assignment.

The only thing my emulator doesn't handle completely are those six-
axis buttons. Mostly because I have no way of telling what they are. I
can't tell if a user is holding a stick south-east, or if it's a
button not pressed. You can map them anyway, but it won't work as you
expect a button to.

Lastly, I'm not sure how to support mouse pass-through just yet. Right
now I block mouse input when the mouse isn't exclusively acquired. If
I don't, then clicking to acquire the mouse will send a 'fire' command
to the emulator. But if I do, then you can't use a mouse as a joypad.

[No archive available]
2009-03-17 15:16:00 +00:00
byuu
91270e504a Update to bsnes v041r01? release.
New WIP.

I _may_ have found the SDL POV hat issue. I was masking a result, but
the array wasn't boolean. It may work better now.

I've also dropped the analog -> D-pad mapping in both drivers. It just
doesn't work ... some controls treat the D-pad as a mirror of the main
analog axis, some treat it as a POV-hat, some treat it as its own
'analog' axis (that only returns -32767, 0 or 32767).

What this means is that for now, no mapping of analog sticks will work
correctly. I'm going to have to adapt the mapping system to
accommodate these.

I also added an 'Assign All ...' button to the input capture window.
Note that it is grayed out on 'User interface' items. Although I
could, it makes no sense to quickly assign all of those (as most you
won't want mapped to anything at all.)

I'm thinking about re-ordering the list from:
Up, Down, Left, Right, A, B, X, Y, L, R, Select, Start
to:
Up, Down, Left, Right, Y, X, B, A, L, R, Select, Start

Reason being that it's more natural with the layout of the real
controller. Agree or disagree?

Oh, and I fixed the NTSC merge settings thing. Takes effect
immediately too.

[No archive available]
2009-03-16 14:35:00 +00:00
byuu
f976998222 Update to bsnes v041 release.
I apologize for posting a new version so quickly. This is mostly a maintenance release: joypad analog axes can once again be mapped to the mouse / super scope axis controls, the input capture window has been rewritten to be much more compact, and I've omitted all unneeded features of Qt 4.5 to reduce the final binary size as much as possible (from ~3.33MB to ~2.3MB.) The source archive is also ~20% smaller.
Barring any unforseen problems, this will likely be the last official release for a while.
Also, I finally have dedicated hosting for byuu.org. I ask that you please update any bookmarks to point here, rather than to byuu.cinnamonpirate.com from this point on, as we'd like to free up the cinnamonpirate sub-domain slot.
2009-03-15 03:42:52 +00:00
byuu
def86470f4 Update to bsnes v040 release.
Too much to really name. The biggest news is that the entire user interface has been re-written from scratch. It is now far more polished and professional. To name one example; the cheat code editor now has checkboxes in the list to quickly toggle codes on an off, there is now a global hotkey to toggle all cheat codes, and each cheat code can contain multiple individual Game Genie or Pro Action Replay codes, allowing easy grouping of multi-part codes.
You'll also notice new artwork: a logo created by Derrick Sobodash (note that the logo contest from below is still active — if someone can design a better logo, it can appear in v041), and a new photo-realistic SNES controller graphic by FirebrandX.
I was finally able to utilize MinGW's profile-guided optimizations, which means this release is approximately ~12% faster than v039.
And emulation itself was even improved(!), such as with Jonas Quinn's fix for a sprite overflow bug.
There were many other changes as well: Linux users will be happy to see RGB overlay support for the X-Video driver, many will benefit from greatly enhanced warning messages and tooltips throughout the GUI, Windows users will now be able to access the menu without freezing emulation, etc etc.
2009-03-09 15:17:32 +00:00
byuu
3e7578761a Update to bsnes v039r22? release.
New WIP.

Softened the panel titles a lot, they take less space but still stand
out well enough.

Should I add a checkbox+global hotkey to toggle the cheat code system
itself on and off? Ala the flip switch that's on the real Game Genie.
Not sure if it's as important anymore now that it's easy to group
multiple cheat codes together and toggle them with just one checkbox.
If so, I need a caption for the checkbox widget, eg "Enable cheat code
system", but something more descriptive.

Rewrote a couple chunks of the nall::string library. I had a lot of
problems with casting due to things like this:
    int strdec(const char*);
    string strdec(int);
    string::operator int();
    string::operator const char*();
    string::operator=(int);
    string::operator=(const char*);
    string::operator<<(int);
    string::operator<<(const char*);
    string::string(int);
    string::string(const char*);


It couldn't implicitly determine if string() << 0 should refer 0 as
const char* or int. So I started by dropping the string->integer
implicit conversions, no need for those, use the strTransform(string)
functions instead. More verbose of the format you want anyway (eg
signed or unsigned integer).

Next, rather than try and implement signed+unsigned+signed
short+unsigned short+signed char etc etc for string::operator= +
string::operator<<, I instead wrote them to use templates. Worked
around the limitation that classes can't use explicit template
specialization by using global thunk functions. operator<<, operator=
and lstring::operator<< all share one set of template specialization
functions to perform conversion of any supported type to a string for
assignment or appending. Pass an unsupported type and it will throw a
"template function undefined" error and fail to compile. No run-time
surprises.

I was careful to implement the copy constructor and copy operator= to
stop the compiler from generating its own functions that copy around
the raw pointer (which would lead to memory leaks + double memory
frees.) So it should be 100% leak proof.

I also split strdec(int) into strsigned(signed) and
strunsigned(unsigned); and updated all the other stuff that used the
lib for that (eg nall::config et al), so you can now perform
unsigned->string conversions on UINT_MAX without getting back -1.

Only thing I'm debating now is if I want to trade C compatibility for
speed and store the string lengths inside the string class for O(1)
length + append functions, compared to their O(n) now. Multiple
chained appends raise that to O(n^2), but with ~20 appends at most per
string, it's hardly a bottleneck right now.

I'm hesitant to do this, because if I do, I'll have to remove char*
operator()() to give a raw handle to the string pointer. I use that
for quick libc const char*->string& wrapper functions, and it's also
nice for other functions to use. And char& operator[](size_t) would
take a hell of a speed hit for having to check for '\0' writes to
adjust the length internally.

_Not_ going to allow storing '\0' directly ala std::string, and make
string::c_str() require memory allocation. Fuck that. Use an
appropriate binary container if you want '\0' inside a block of
memory. The whole idea of nall::string is to maintain 100%
compatibility with C89 strings and their functions.

[No archive available]
2009-03-05 11:48:00 +00:00
byuu
45feae8f75 Update to bsnes v039r21? release.
New WIP.

I added FirebrandX's controller image (let me know if you don't have
the WIP link and want to check it out, FB.)

I also added Derrick's SVG logo for now. The contest thing isn't over
yet, and I like DMM's the best so far (sans the aliasing issues.) But
the auto-resizing to exactly what I want is too nice to pass up. I
think I'm going to require SVG for the final submission at this point.
Side note: Qt supports SVG for auto-scaling, but I use a PNG anyway as
not all Qt libs are going to have SVG support built-in. I still want
SVG for website / print purposes.

For belegdol, I added SDL hat support. It only works with the first
hat, as I figured those four-controller-as-one-device cheapass drivers
might not work well if every single players' hat manipulates the same
controller. You'll have to let me know how it works, since SDL doesn't
detect my joypad's hats.

I'd also like it if someone could test the X-Video RGB support. Anyone
with an RGB overlay surface can do so just by selecting the Xv driver.

[No archive available]
2009-03-01 11:09:00 +00:00
byuu
4d10c36870 Update to bsnes v039r20? release.
New WIP. This one's available here:
http://byuu.cinnamonpirate.com/temp/bsn ... ip.tar.bz2
http://byuu.cinnamonpirate.com/temp/qtdlls.zip

Please don't distribute to other news sites.

You will need to extract the Qt run-time DLLs into the same folder as
the bsnes executable. And you'll likely need WinRAR or 7-zip to
extract the WIP archive.

Please report any issues you can find that weren't present in v039.
I'd like for v040's release to be as bug-free as possible.

Changes from wip19:

The new 'current directory' caching mechanism was caching _after_ save
RAM load, so it wasn't loading save files correctly on first run.
Fixed.

I wasn't setting the internal renderer to match the requested video
mode, so PAL mode wasn't showing the extra scanlines. Fixed.

Had to add a 50ms (very conservative) delay when toggling fullscreen
mode to give Xorg enough time to complete the request. Before it was
trying to query the window size too soon and not fully expanding
fullscreen video to fit the screen. Because of this added delay, I
made it clear the video output when toggling modes. Can't help the
slight line redrawing issue in Qt. Not a bug in my code there.

After reading FitzRoy's comments and thinking more about it myself,
I've decided against the 'intelligent' fullscreen auto-menu hide.
Sorry. It'll still remember whether you were in fullscreen mode on the
last run, but the menubar is always visible by default now. It doesn't
change your menu visibility when you toggle fullscreen anymore.

I also added back the aspect adjust settings to the config file. This
time I combined them to floating point values. So instead of the old:
video.ntsc_aspect_x = 54
video.ntsc_aspect_y = 47
You now have:
video.ntscAspectRatio = 1.14893617

It's an advanced feature not in the GUI, so I expect you to know how
to compensate for the 256x224 vs your native monitor's resolution if
you screw with that setting. Maybe someone can make a web script to
calculate it ala those Xorg modeline generators or something.

Lastly, I removed the group boxes. Took advantage of every row having
three options but one, and added a spacer to get everything aligned.
Advanced panel looks a lot better now.

[No archive available]
2009-02-25 12:32:00 +00:00
byuu
cca8164005 Update to bsnes v039r19? release.
New WIP.

- added hardware settings group to advanced panel. Lets you control
hardware region and base unit.
- added descriptive tooltips to video and audio settings.
- revised documentation to list filetypes, mention BS-X issues and
generalize unsupported special chip notes
- improved handling of paths: core now keeps track of cartridge path
rather than relying on the current working directory; export data path
now works the same as SRAM / cheats / etc when not selected
- fixed XvRGB15/16 blue color channel glitch; testing would be much
appreciated
- I now set the drivers to "None" when they fail to initialize and
give a warning. Before the app would just crash on cart load if this
failed
- added more options to the config file: allow invalid input, analog
axis resistance, and for the first time ever -- CPU, PPU1 and PPU2
version configuration

Really not happy with the overall look and feel of the advanced panel.
I don't think the group boxes are working there. Also, the filetype
descriptions are very terse, but I like them that way. Don't really
care if someone doesn't know what 'non-volatile' means, that's why god
made Google. Complain and I'll make the complex terms hyperlinks to
Wikipedia :P

I'll look into the fullscreen menubar thing again in a few days or
something.

> The Cpu and DMA approach is the same like in bsnes. The exception
> are the stp and wai opcodes.


Heheh, I bet someone looking at STP without being aware of how the
cothreads work would gasp in horror :D

> You are right it's really hard to jump back from doing a nested hdma
> transfer within a dma. But with my approach such an action is not
> needed.


Yeah, I know it's possible with enslavement to only make the simpler
processor a state machine. In our case, the S-SMP. That's how SNEeSe
does it. I just really hate the idea of enslavement.

I can certainly see why others get so upset with me on this, but
having each module cleanly separated is, to me, more important than
savestates. That it's somewhat faster here is just an added bonus. I'm
sure you can appreciate my S-SMP op_*.b files over those state
machines for maintenance, too ;)

As for your work on rewriting all the S-SMP opcodes, I wish you
would've mentioned this to me earlier ... the cycle labels in those .b
files are used to create the exact same switch(cycle) {} code you
wrote automatically, you just have to use a different generator. Given
I dropped that generator back at ~v017, it should be easy to update /
rewrite. The downside is that they don't directly support the bus hold
delays.

Still overall, really really impressive stuff. Kudos on making
something so cool :D

[No archive available]
2009-02-23 13:45:00 +00:00
byuu
0f83e39d5c Update to bsnes v039r18? release.
New WIP.

Added fix for OAM Yflip overflow bug pointed out by Jonas Quinn.

Re-added QGroupBox controls as per discussion with jensbw, the frame
issue should be fixed with Qt 4.5.

Config file now omits " #" marker when there is no item description.

Main window resizes itself a bit better before showing itself on Linux
for the first time. Not a problem at all on Windows.

Using _wgetcwd instead of getcwd for Windows UTF-8 support.

Finished Cartridge class revisions: load_foo returns boolean success,
unload() doesn't need one so that was removed, dropped redundant
bsx_cart_loaded() as you can tell via mode() == ModeBsx. Still need
bsx_flash_loaded() for register mapping purposes.

Fixed hiro port to compile again.

I also rewrote much of the Xv driver. It now properly finds modes via
XvListImageFormats(), and I added support for more modes. It used to
be YUY2 only, now it supports RGB32, RGB24, RGB16, RGB15, YUY2 and
UYVY (chooses the driver mode in that order.)

Unfortunately I was only able to test YUY2 and UYVY with my driver, so
no idea if the RGB modes even work or not. I know RGB16/RGB15 will
have problems, forgot to mask the blue channel before uploading: for
line 344 and 359, (p >> 3) needs to be ((p >> 3) & 0x1f).

To test each mode, the optimal ones would have to be manually disabled
since there's no external way to select the preferred driver. And the
RGB32 copy is sub-optimal, I'll probably allow direct rendering to its
surface in a future revision.

[No archive available]
2009-02-22 11:22:00 +00:00
byuu
ebbcc998d0 Update to bsnes v039r17? release.
New WIP. Posted only for the sake of testing for regressions.

The only real change was adding nall::property as discussed earlier,
and completely revamping the Cartridge class with it. Results:
http://byuu.cinnamonpirate.com/temp/cartridge.hpp

Compared to the old version, it's night and day. All stuff that can be
hidden has been, end-user can't screw with important internal-settings
while emulation is active, as many functions as possible were made
const, ditched char* stuff to replace with string, removed a few
useless structs, simplified the public interface, replaced a memory
duplication in the cart loader that removes the header with a
memmove() instead, blah blah blah.

If I screwed any of this up, it may break the following:
- special chip detection
- RAM / PSRAM / RTC data saving
- UPS patching
- cheat code loading
- relative path stuff
- etc

[No archive available]
2009-02-21 10:39:00 +00:00
byuu
78da6946c6 Update to bsnes v039r16? release.
New WIP. Sorry about the delay in adding your .desktop file, belegdol.
I appreciate you sending it to me.

- worked around a cursor bug in Qt/Xlib: if you started the app and
your mouse cursor was on top of where the window appeared, it gave you
the "resize window" grip cursor, and it would stay like that. The
resize function now ensures you always get the normal cursor.
- worked around a bug in Qt/QGtkStyle: if you pass a default path of
"", it throws all kinds of errors at you on the terminal window, I
implemented a current working directory system for both folder path
selection and file selection (when no default game path is selected.)
It starts in your program startup directory (via getcwd()), and will
update whenever you choose a valid file or folder without canceling
the window.
- icon is now stored in $(prefix)/share/pixmaps instead of
$(prefix)/share/icons
- added belegdol's bsnes.desktop. If I can figure out how to get the
one from Derrick, his has stuff that makes it auto-suggest bsnes for
.SFC files and such. I'll probably add his extensions to it later.
This file installs to $(prefix)/share/applications, and bsnes shows up
under 'games' now.
- updated src/cart a bit, merged some 5x ~800 byte files to a general
cart_loader.cpp file, renamed the functions to be clearer:
cartridge.load_cart_bsc() -> cartridge.load_bsx_slotted();
cartridge.unload_cart_st() -> cartridge.unload_sufami_turbo();

- resized HTML viewer, was too small before, but I think it's too wide
now, meh.
- readme was renamed to documentation. I don't care that it's not
verbose enough to warrant the name right now. I intend to expand upon
it in the future and have it be the general sort of "help"
functionality, hence the name change.
- both the documentation and license are now stored inside src/data as
HTML files. These are embedded with Qt's resource compiler into the
final binary. Easier to edit, and the HTML files can stand on their
own.
- I've partially revamped the documentation. It's somewhat of a
compromise between my ideas and FitzRoy's. I may expand on it a bit,
but I like how it is now, so don't expect many more changes there
please.
- Revamped the license stuff a good deal, removed a lot of cruft.
Grant of Rights section remains the same, so no legal changes.

> bsnes could detect the computer's time zone, and switch to purple if
> necessary.


The US SNES is an eyesore. Both the console and especially the
controller. Fuck it, if they want to see that they can look it up on
Google Images :P

[No archive available]
2009-02-17 12:56:00 +00:00
byuu
4d31452bca Update to bsnes v039r15? release.
Okay, new WIP. To my knowledge, the Qt port now matches or exceeds the
feature-set / quality of the hiro port in every regard, sans things
I've intentionally removed.

- added back all the UI shortcut keys
- started using Qt's resource compiler, rcc, to embed files into the
binary on all platforms; not as efficient as my base56+LZSS method,
but much more standardized and avoids string length limits in Visual
C++
- Linux port now sets the program icon from bsnes.png @ 48x48 (any
larger and the filtering makes it look bad)
- Windows port uses embedded 16x16, 32x32, 48x48 or 256x256 icon as
before
- all windows now rise to the top when they are shown
- replaced about screen -- it's just a placeholder for now so that
it's not modal. Want to put the logo on there, with the rest of the
info and a webpage link below
- removed 'Ok' button from document viewer window
- killed icon48.h and controller.h, ~100kb worth of source. Right now,
hiro port shows black boxes in their place. I'll do something nice
with it later; but I don't want to grow the source that big for the
non-standard target
- added .zip, .gz and .jma to filter, based on compilation flags

Thinking about killing src/data, putting the necessary stuff in each
platform folder. Just a slight issue with windres taking a relative
path to the working directory, so it won't allow easy renaming of the
ui folder names if I do that. Can work around it with 'cd' command in
the Makefile, I suppose.

Would be nice to take advantage of rcc a bit more: it's very easy to
use 16x16 / 32x32 icons inside the UI for eg menu and config panel
list icons. Just going to be tough to make nice icons for them.

Stuff removed from hiro:
- controller graphic:
I love this graphic and want to have it in the official binary, but it
looks really odd when it's only there for one controller type ...
should we keep it anyway? If so, I'll embed it with rcc.
- trace logging hotkeys:
Want to replace these with a real debugger that will have buttons for
them. That will be a long-term goal, of course. May add shortcut keys
for the debugger functions too at that time.
- frameskipping:
Probably the biggest one, I didn't want to re-add this as the new PPU
will make it pointless anyway. If we do add this back for the fast
PPU, I'll probably keep the option hidden from the UI side.

> SFT was the acronym used for the catalog codes. For example, Poi Poi
> Ninja World had SFT-0103 on the cartridge. So there is some historic
> precedent for it at least. BSX, not so sure, but I figured
> everything else was three letters.


Sounds good, but I'd like to check with Nach first. He seems to be on
extended leave at the moment.

> Exhaust Heat 2 still bug out


Wasn't aware ST-0010 had any problems. Not sure if it's bit-perfect or
not anymore, but it definitely has no DSP timing.

[No archive available]
2009-02-15 08:23:00 +00:00
byuu
eb1eca4a6d Update to bsnes v039r14? release.
Okay, another new WIP.

Drag-and-drop is in, and it works in Windows and Linux. Tested with
Thunar under Xfce, but it should be fine with any freedesktop.org-
compatible app/WM.

Worked around the Qt bug ... either
qtreewidget->currentItem()->isSelected() returns the true current item
and the Xlib port has a bug, or it returns the previous and the
Windows port has a bug. I'm using
qtreewidget->selectedItems().count()==1 in its place. Works on Windows
and Linux, so the cheat editor should be fine now.

Forgot to add assign / unassign key disable in the last WIP, so I took
care of that this time.

Added back the readme and license viewers. Used QTextBrowser, which
lets me use HTML formatting plus anchor hyperlinks. Not terribly
useful with such small documents, but meh. We can grow "readme" into
"documentation" in the future. Maybe even add a section listbox on the
left ala CHM files. Throw in a custom CSS stylesheet to make it
prettier. Whatever, not worried about it right now, but we'll get it
ironed out before v040 official.

Got too tired (Red Bull having no effect either), forgot to add the
.zip,.gz,.jma file extensions; and didn't check if cheat codes are
saving on Linux. Also need to work on getting window show commands to
put the windows in the foreground. If they're already visible, they
aren't raising to the top / gaining focus.

Still need to add a bunch of GUI hotkey bindings back, and I think
that'll do it for the rewrite. From there it's all adding stuff the
hiro port lacked.

[No archive available]
2009-02-14 10:05:00 +00:00
byuu
07c9df31a6 Update to bsnes v039r11? release.
Finally, a new WIP.

I redid the spacing / margins on all windows, it should match the old
bsnes/hiro port better now.

Removed all instances of QGroupBox, to work around the problem with
QGtkStyle ignoring the frame entirely, as well as getting around the
ridiculously large margin-top in it that you can't remove. Using
horizontal spacers in its place. Quite a bit more annoying to code
for, but it looks better than even the working frame, at least in my
opinion.

Modified the config panel listbox trigger to use currentRowChanged()
instead of itemSelectionChanged(). This fixes an annoying glitch where
if you clicked down on an item and dragged the mouse, it'd be off-by-
one in the list.

The code editor and cheat code panel both disable buttons when actions
aren't allowed, ala bsnes/hiro. There seems to be a bug in
QTreeWidget::itemSelectionChanged() on Linux, the returned
QTreeWidgetItem::isSelected() value is inverted. Too tired to work
around that tonight.

Improved automatic window resize for the input config and ROM add-on
cart loader windows. They should fully shrink as much as possible now,
rather than leaving blank space.

Dropped the Segoe Print font for titles, as it only looks good on
Vista+.

Removed the sort stuff from the cheat core class and hiro UI, since
the Qt UI can sort by header clicks.

Scale Nx items are checked again according to config file setting.

Stuff left to do:
- work around Qt/Linux bug on edit/delete enable on cheat code panel
- cheat codes don't seem to be saving to disk
- need to re-add screensaver disable code

FitzRoy, it's hard to show you the Qt rendering issues on GNOME, if
you're not familiar with how it should look ...

http://byuu.cinnamonpirate.com/temp/clearlooks.png
http://byuu.cinnamonpirate.com/temp/qgtkstyle.png

Clearlooks is the KDE default style. Looks good, but doesn't match
GTK+ apps.

QGtkStyle is the Qt wrapper that tries to use your GTK+ theme. Biggest
annoyance would be the buttons. There's this red box in the middle
that shows up when a button has focus. With the real GTK+, the entire
button turns red (no border) when you click it, but with just focus
alone it shouldn't have any color. The fonts are also much uglier,
like it has really poor anti-aliasing and slightly wrong sizes.

[No archive available]
2009-02-13 08:20:00 +00:00
byuu
c64232a479 Update to bsnes v039r10? release.
New WIP adds a ton of refinement.

I feel it's exceeded the old UI in quality already, so I added the
platform-functions (realpath, userpath, ...), so now it'll look for
the multi-user config file, falling back on single-user. If you use an
old config, most settings from v039 will be lost, but some will be
pulled in. It now looks for bsnes.cfg and style.qss (for theming.)
Slight issue with relative paths and realpath() on Linux. New
initargs() function adds back support for non-ANSI paths.

Path window shows <startup path (/path/used)> rather than just
<startup path>.

All buttons trigger on release (mouse up / off) rather than press
(mouse down).

Revamped the centering code. All windows respect the reserved screen
areas (taskbar, dock, etc) and center perfectly. They only center on
the first show, after that they will remember where you placed them.

Completely rewrote the windowed / fullscreen handling code. It works
properly even on Linux now. Scale max is great, perfect fit to the
edges of your screen sans reserved areas. If menu+status toggle are
bound to the same key, it'll only refresh the window once to reflect
the new state now.

Going back to the forced size thing. I need to re-add the menu checks.
You can't shrink the window smaller than your current settings, and if
you make it bigger, you get black borders (since I can't disable the
resize reliably on all platforms.) Makes more sense this way anyway,
the menu options should reflect what you see, not what the startup
state is.

It remembers the fullscreen setting automatically now. I took it a bit
further, though. If you have no ROM loaded, it will show the
menu+status in fullscreen to alert you there's no cart and give you a
chance to select one. I also re-added command-line loading, and if you
successfully load a game there, it will turn off the menu+status for
you. There was a slight delay there. You see, loading a game calls
snes.init() which needs the interface (video, etc drivers) setup.
Those drivers rely on the UI being created. So we have to make the UI,
setting the menubar visibility, before we can verify that we're going
to load a game.

_Yes, I can work around this!_ Add a first-run boolean and validate
the command-line path is valid, or separate cart load from SNES init
so I can load, setup GUI then start, etc etc. It's just annoying, not
sure if it's worth the effort to hide the menubar 2ms sooner.

ROM slot loader and cheat path windows now both disable buttons when
no cart is loaded. Major work in progress, lots of stuff left to do
here. When you pick a file with the ROM loader, it doesn't steal focus
to the main window anymore. When you pick a path, it clears the audio
buffer to prevent audio looping. Not sure if I want to hook move /
resize events, since Linux doesn't block as much as Windows. Maybe
I'll #ifdef it.

Qt 4.4 has a bug with GTK+ file open, if you give it a blank path it
spits out lots of errors. It needs a fully-qualified path. Going to
make my old-style "remember last selected path" thing that I used in
hiro/gtk to fix it later.

[No archive available]
2009-02-05 11:23:00 +00:00
byuu
85b08fd24b Update to bsnes v039r09? release.
New WIP re-adds the multi-part ROM loader. For some reason that took
way too long, all I got finished.

A bit different this time, one window for all three modes (bs-x
slotted, bs-x and sufami turbo.) It auto adjusts based on what you
want. Much more compact now that I can put the labels on the same line
as the controls.

It otherwise works the same. In the future, I'll be adding a Date/Time
control when loading pure BS-X carts. Makes no sense adding it to the
UI before the core supports it.

> [X] Pause emulation when main window does not have focus
> [X] Ignore input when main window does not have focus


For the hundredth time, that creates four states instead of three.
What's the difference between pause on + ignore on and pause on +
ignore off?

I'll most likely use a QScrollArea to put a scrollbar on the right if
we end up with too many advanced options for one page.

[No archive available]
2009-02-03 09:05:00 +00:00
byuu
3b3214d1be Update to bsnes v039r08? release.
New WIP.

I guess we've tested the container resize enough, at least for
Windows. Set fullscreen container color to pure black.

To avoid the accidental mouse assignments from v039 and earlier, I
went with UI buttons to assign mouse axes / buttons. Keyboard and
joypads assign the same as before. The extra 1-3 buttons are for six-
button mice like my MX518.

Also re-added mouse capture: load a game, and have a mouse/scope set
as an input device, click in the window and it captures. Press escape
to release. I blocked mouse buttons without capture now, too. That was
allowing a fire shot to go through in previous versions without it
when you first gained focus.

Fixed up hiro/GTK+ to compile again. Should give GNOME/Xfce/Qt4.4
distro packagers some reprieve for a while. Not going to be improving
it anymore, though.

Qt/Linux now uses pkg-config, rather than hard-coded paths. No such
luck for Windows users. There's a Win port of pkg-config, but not many
will have it so the path to Qt will remain hard-coded.

Ditched a few more global nall::string functions (count, find,
(q)replace, (q)split) and moved them inside classes. Fixed the
resultant compile errors in bsnes, hiro and xkas.

The rest of the nall::string functions are also useful on char*
arrays, eg strtr, strlcpy, trim, etc; so it doesn't make a lot of
sense to put them inside the string class.

Not entirely impressed with how the code looks mixing class functions
and global functions, but meh. At least it will reduce mistakes in
trying to pass char*s to string-only functions like replace.

[No archive available]
2009-02-02 08:56:00 +00:00
byuu
b5a38d2a07 Update to bsnes v039r07? release.
New WIP. Adds menubar/statusbar toggle, defaults fullscreen to max
scale with no menu/status (you can change the scale and it will
remember your settings in the future), and I re-added all the audio
panel options.

That leaves a few more GUI shortcut key assignments, mouse support +
binding, BS-X / ST ROM loaders, readme/license windows, and a few new
controls to replace the old Firefox-style advanced screen with
something more user-friendly. After that, the rewrite should be
complete.

Trying to move my string lib to a more OO-approach: removed overloaded
strcpy,strcat in favor of =,<< or .assign,.append. Will be trying to
remove more global functions (replace(foo -> foo.replace(, etc) in the
future. Taking it slow so I don't break xkas too badly.

I also want to shave as much excess functionality as I can from it.
Its main purpose is to be a streamable, implicit-castable alternative
to std::string with a few built-in special functions unique to my
needs (eg qsplit,qreplace.)

[No archive available]
2009-02-01 08:35:00 +00:00
byuu
94004f86ec Update to bsnes v039r06? release.
New WIP, looking for feedback on these changes.

First, I switched from a standard QWidget to a more semantically-
correct QMainWindow. Not much difference, except it adds an automatic
menubar and statusbar, no need to make my own. One advantage was free
status hint support without having to catch the event. So I took that
and redesigned the status system.

First, the game name on the status bar ate up too much space for
nothing. I moved it to the titlebar: bsnes v0.nnn - Game Title (U)

Second, I merged the FPS counter with the system state and put it on
the right-hand side of the status bar. It shows "No cartridge loaded",
"Power off", "Paused" and the framerate. This is persistent and always
visible. FPS doesn't show ideal FPS next to it anymore. That just
wastes space.

Third, the new left-hand stuff. It uses the native QStatusBar support
for timed messages. I use that to pump power state changes ("System
was reset.", "Loaded Star Ocean (J), and applied UPS patch.", etc.)
They go away after ~3 seconds. Unsupported special chip warnings now
pop up a modal dialog box instead of showing in the status bar.

Fourth, we can now set special menu group / item descriptions that
appear when the items are hovered. For instance, mouse over
settings->video mode->ntsc and it explains that the setting affects
the perceived video output size, rather than the core emulator mode.
The descriptions there now suck, but it shows off the concept. We'll
leave them off for all the obvious items.

With all of that, I was able to kill off the "Status" class, ~4kb of
nasty code that polled the time constantly and maintained an internal
string queue for statusbar messages.

Also new to this WIP ... it's apparently not trivial to set a fixed
window size with Qt on Xlib. My MinimizeWindowHint that worked on
Windows was making the window top-most on Xfce, and breaking
fullscreen mode.

So, I tried again to write code that could properly switch between
windowed and fullscreen mode. For some reason, this always causes tons
of problems. Window managers like to take their sweet ass time
updating internal states, so rapid geometry changes often fail,
leaving the window in odd positions and sizes.

It took quite a while, but I have it working, hopefully, 100% on
Windows. I even account for the desk area (ignoring the taskbar and
such) and the window decorations. Centering should be truly perfect,
and scale max should be a pixel-perfect fit to all available screen
size, while maintaining the ratio.

Linux support is still kind of flaky, though. Long shot, but any
knowledgeable help here would be appreciated.

    void Utility::updateFullscreenState() {
      if(config.video.isFullscreen == false) {
        config.video.context = &config.video.windowed;
        winMain->window->showNormal();
        application.processEvents();
      } else {
        config.video.context = &config.video.fullscreen;
        winMain->window->showFullScreen();
        application.processEvents();
      }

      //refresh options that are unique to each video context
      for(unsigned i = 0; i < 2; i++) resizeMainWindow();  //call
    twice as Xlib drops window messages sometimes
      updateHardwareFilter();
      updateSoftwareFilter();
    }

    //if max exceeds x: x is set to max, and y is scaled down to keep
    proportion to x
    void Utility::constrainSize(unsigned &x, unsigned &y, unsigned
    max) {
      if(x > max) {
        double scalar = (double)max / (double)x;
        y = (unsigned)((double)y * (double)scalar);
        x = max;
      }
    }

    //0 = use config file value, 1+ = override with new multiplier
    void Utility::resizeMainWindow(unsigned multiplier /* = 0 */) {
      if(multiplier != 0) config.video.context->multiplier =
    multiplier;
      else multiplier = config.video.context->multiplier;

      unsigned width  = 256 * config.video.context->multiplier;
      unsigned height = (config.video.context->region == 0 ? 224 :
    239) * config.video.context->multiplier;

      if(config.video.context->correctAspectRatio) {
        if(config.video.context->region == 0) {
          width = (double)width * 54.0 / 47.0 + 0.5;  //NTSC adjust
        } else {
          width = (double)width * 32.0 / 23.0 + 0.5;  //PAL adjust
        }
      }

      QDesktopWidget *desktop = QApplication::desktop();

      if(config.video.isFullscreen == false) {
        //get effective desktop work area region (ignore Windows
    taskbar, OS X doc, etc.)
        QRect deskRect = desktop->availableGeometry();
        unsigned deskWidth  = (deskRect.right() - deskRect.left() +
    1);
        unsigned deskHeight = (deskRect.bottom() - deskRect.top() +
    1);

        //place window offscreen so resize events do not cause
    flickering
        winMain->window->move(desktop->width(), desktop->height());
        application.processEvents();

        //shrink window as much as possible to compute frame + menubar
    + statusbar size
        winMain->canvas->setFixedSize(0, 0);
        winMain->canvasContainer->resize(0, 0);
        application.processEvents();
        winMain->window->resize(0, 0);
        application.processEvents();
        QRect frameRect = winMain->window->frameGeometry();

        //constrain window so that it will fit inside desktop work
    area
        constrainSize(height, width, deskHeight - (frameRect.bottom()
    - frameRect.top() + 1));
        constrainSize(width, height, deskWidth  - (frameRect.right() -
    frameRect.left() + 1));

        //resize canvas to desired size
        winMain->canvas->setFixedSize(width, height);
        application.processEvents();

        //shrink window so that it contains all of canvas, but is no
    larger
        winMain->window->resize(width, height);

        //allow canvas to be resized along with window by user
        winMain->canvas->setMinimumSize(256,
    config.video.context->region == 0 ? 224 : 239);
        winMain->canvas->setMaximumSize(desktop->width(),
    desktop->height());
        winMain->canvas->setSizePolicy(QSizePolicy::Expanding,
    QSizePolicy::Expanding);
        application.processEvents();

        //force window size change to take effect
        winMain->window->resize(width, height);
        application.processEvents();

        //center window onscreen:
        //take desktop work area and window frame decorations into
    account
        QRect windowRect = winMain->window->frameGeometry();
        unsigned windowWidth  = (windowRect.right() -
    windowRect.left() + 1);
        unsigned windowHeight = (windowRect.bottom() -
    windowRect.top() + 1);

        winMain->window->move(
          deskRect.left() + (deskWidth  - windowWidth ) / 2,
          deskRect.top () + (deskHeight - windowHeight) / 2
        );
      } else {
        constrainSize(height, width,
    winMain->canvasContainer->size().height());
        constrainSize(width, height,
    winMain->canvasContainer->size().width());
        winMain->canvas->setFixedSize(width, height);
      }
    }


If anyone wanted to get stupid, a style for QWidget.backdrop {
background: url(border.png); } when designed for a specific resolution
+ scaling mode would allow Super Gameboy-style borders :P

Let's see ... properly subclassed the generic input binding pools for
clarity, and added user interface key binding support again. So far
only for exit emu + toggle fullscreen, but the rest should be easy
now.

I can't reduce the space for the QFrameWidgets. Only setMargin works,
but it reduces margins on all sides where only the top is bad. I may
have to revert it back to a section label + horizontal separator
between each area. Probably a good idea, QGtkStyle doesn't support
QFrameWidget's decoration anyway. Looks terrible on GNOME.

Finally, fixed ui_hiro for Windows. Still need to fix up the Linux
target. They share the same Makefile, so additional targets should be
easy, eg a pure SDL port or whatever.

> Darn. Oh well, guess I could keep whatever I concoct to myself.


Or tell me what you want to do, as I probably won't mind :P

[No archive available]
2009-01-27 07:24:00 +00:00
byuu
148bbddb1a Update to bsnes v039r05? release.
Man, I don't have time to read all that ... >_>;

New WIP. Lots of UI refinements.
- re-added power on / power off / reset to main menu (expansion port /
region won't be coming back here)
- re-added status message system
- figured out a way to hide the child indicators in list boxes, as
well as enable sorting while starting with default ordering (so
headers are now clickable to sort, you can even rearrange them)
- merged driver settings and input focus policy into advanced panel
- old advanced panel list is dead, driver panel is dead
- replaced scale 5x with scale max; minor help to 1920x1200+
resolutions
- re-added smart scaling + window size clamping
- Linux port should build out-of-the-box, but there's definitely some
issues in regards to window sizing (even Qt has trouble with this)
- new $(ui)/Makefile system -- as if I weren't abusing GNU make enough
before, new automoc rules are madness -- fear:
    # automatically generate .moc files from .hpp files whenever:
    # - they don't exist
    # - .hpp file was modified after .moc file
    %.moc: $<; $(moc) $(patsubst %.moc,%.hpp,$@) -o $@
    $(foreach object,$(moc_objects),$(eval $(object): $(patsubst
    %.moc,%.hpp,$(object))))
    ui_build: $(moc_objects);
    ui_clean:; -$(foreach object,$(moc_objects),@$(call
    delete,$(object)))

- lots of other crap

http://byuu.cinnamonpirate.com/images/b ... 090126.png

Now to update the locales for v039 finally ...

[No archive available]
2009-01-26 09:59:00 +00:00
byuu
e5b2e87ff8 Update to bsnes v039r04? release.
Well that wore me out ... the UI went from 45kb to 109kb in one night,
with no copy/pasting.

New WIP:
- re-added the InputManager + InputDevicePool classes. The latter is
very complicated, but impressive
- re-added Input Configuration Editor
- re-added Cheat Code Editor
- re-designed individual cheat code editor
- re-added Path Editor
- stopped subclassing QWidget w/Q_OBJECT to work around Qt stylesheet
bug
- re-added controller port selections

Sorting by column header clicking is screwy. It has to be manually
enabled, and the second you do that it re-orders everything. This is
really bad when you want the default order, eg "up, down, left ..." or
your default cheat ordering; so I had to leave it off. Would be too
tacky to add a numeral ID column to work around that.

Seems Qt also has a ridiculously complex tree view (MVC-based), but
thankfully they added a simplified version that works well enough,
QTreeWidget. Only problem is I can't seem to make it hide the child
expander space at the very left-most side. This creates an annoying
little gap. Anyone know how to hide those with Qt?

Even got checkboxes inside the list to toggle cheat codes.
Documentation could've been clearer there.

Speaking of which, I was able to use child nodes on the cheat code
list to show each individual cheat code, but it just didn't look right
to me. There was a ton of blank space on the sides. I can actually
fill in multi-line descriptions as well here, but it still looks
really tacky in my opinion.

Thought about using add code + append code + delete code and putting
the textboxes back, but that just seems tacky and error prone, too.
I'm not adding individual descriptions for each code sub-part.

Only way I can think to make it work that way would be to replace the
multi-code method with a grouping affinity (eg group codes 1+3 into a
set), but then we're getting really complex, with a minimum of 5-6
buttons on the window and 3 text boxes. I think the learning curve
would be too high to be worth it.

So, I used the old method, but instead of a textbox to paste in codes,
I went with a slightly less error prone method of a textbox for the
description and a listbox for each code part. Threw in add / delete /
delete all for the code list. Takes a bit longer if you're trying to
copy/paste codes off the web, but the increased intuitiveness and
consistency is worth it in my opinion.

New cheat code editor (description typo due to extreme fatigue)

There's a lot of rough edges and few safety checks, so if you try to
break things you probably can.

Overall, really having fun with the Qt API. It can be awkward at
times, but it's definitely the most straight-forward API I've seen so
far.

[No archive available]
2009-01-25 08:16:00 +00:00
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
byuu
9133129209 Update to bsnes v033 release.
This release adds SPC7110 emulation, without the need for graphics packs!!, and a rewritten S-RTC (real-time clock) emulator.
SPC7110 support means that Far East of Eden Zero, FEoEZ: Shounen Jump Edition, Momotarou Dentetsu Happy and Super Power League 4 are now all fully playable. I will warn you, the emulation is very slow in this version -- while most areas of each game will run at the same speed as other games, there are a few peak moments where speed will drop by up to ~50%. The reason for the slow-down is that I am currently uncertain how to determine the amount of data to decompress in advance, so I default to the maximum amount possible. The reason I am releasing now anyway, is because I beleive in the "release early, release often" paradigm. It will likely take me a few weeks to finish researching this chip, and I didn't want to keep the work I had private during that time. But rest assured, bsnes v034 should feature much faster SPC7110 emulation.
neviksti, Andreas Naive and jolly_codger worked non-stop on the SPC7110 decompression algorithm for the past two weeks. caitsith2 provided valuable data to the effort. I only wish that I could've been of some use, but alas, I had no role in this. In the end, it was neviksti who managed to crack all three(!!) compression modes of this chip, which turned out to be a customized 8-bit QM-coder with a prediction model. You can read more about this here. I would also like to thank Dark Force and John Weidman (aka The Dumper) for their research notes on the SPC7110 register interface.
For those who don't understand the hoopla about figuring out this compression algorithm when we already had graphics pack simulation, I should note that we have since found a few errors in these packs. Not to mention, you no longer need ~4-16MB packs for each game you wish to run. They work like any other game now. Better still, the chip can now be used to compress new graphics, eg for any future translation efforts on these titles.
The real-time clocks in both Far East of Eden Zero and Dai Kaijuu Monogatari 2 will now save a ".rtc" file in your save folder, which contains the clock as set by the video game, as well as a timestamp from your computer when the time was last updated. It uses the difference between the saved timestamp and current time to update the time. This allows you to specify any time you like, whereas previously bsnes would just use your computer's current time, ignoring the time you set in-game. It also allows the "round clock by 30 seconds" option in both games to work. I avoided this before because this method makes supporting daylight savings time and such impractical, although I should note that the original hardware did not support DST, either. This method was required to pass the SPC7110 tests, and is overall much more faithful to how the original chips worked.
Once again, I'd really like to personally thank neviksti for his tireless efforts. Eliminating graphics packs from SNES emulation was one of my primary reasons for getting involved in the SNES emulation scene. That neviksti managed to crack this algorithm means a lot to me. Thank you so much, neviksti. This release is dedicated to you, now go get some sleep Wink
2008-07-20 00:06:28 +00:00
byuu
7d83cde40a Update to bsnes v032r01? release.
This worked great, thank you. libao is now tolerable on ALSA. Now I
just need to add support for disabling "Audio::Synchronize" (by
disabling sound output, since libao is a blocking API.)

---

EDIT: posted a new WIP, with RedDwarf's ALSA and libao fixes. Both
work very well for me, your mileage may vary.

No Windows binary, as it would be exactly the same as v032a, anyway.
This one's mainly for Linux users who can compile from source.

[No archive available]
2008-06-02 02:00:00 +00:00
byuu
bbc77a6cf2 Update to bsnes v032a release.
- Windows: file open filters are now working once again
    - All ports: emulation speed setting is now properly restored at startup
2008-05-26 08:46:05 +00:00
byuu
ebb9367c68 Update to bsnes v032 release.
- Core: simplified CPU / SMP flag calculations
    - Added ALSA audio output driver to Linux port [Nach]
    - Improved font handling for Windows and Linux ports
    - Greatly cleaned up the user interface
    - Windows port now uses Unicode instead of ANSI
    - Added localization support
    - Config and locale files can now be placed inside bsnes executable directory for single-user mode, if desired
    - Fixed crashing bug with HQ2x on Linux/amd64 port [RedDwarf, Nach]
    - Hid "Power Cycle" option by default, as it is too similar to "Reset"
    - Slighty tweaked program icon [FitzRoy]
    - Minor code cleanups -- replaced union bitfields with templates, improved memory allocation, etc
2008-05-25 18:45:59 +00:00
byuu
96fe8f760d Update to bsnes v031r08? release.
Thank you everyone for the translations! I've also posted a new WIP,
with an improved Japanese locale. No changes to the strings that
anyone has to worry about with theirs.

To strike a compromise, I've removed power cycle from the menu by
default, and added a new config file option, "advanced.enable". Set to
false initially, but if you set it to true and restart, power cycle
will re-appear. I intend to use this option to hide the debugger
functionality if and when that gets re-added, as well. Plus we can
remove other questionably useful / confusing stuff this way. The key
binding for it still shows up (removing it there would be tricky), but
it's not bound to anything by default, either. Sound fair?

Also, something I've been meaning to do for a while now ...
unload/reset/power cycle are now disabled when a cartridge is not
loaded.

[No archive available]
2008-05-22 09:18:00 +00:00
byuu
8abd1b2dfe Update to bsnes v031r07? release.
Okay, new WIP. Couple of changes.

One, I was displaying the warning message about unsupported chips no
matter what. Oops, fixed.

Two, removed the "Select Folder" text. The dialog looks a bit empty
now, but oh well.

Three, added "Ok" to the warning message box strings.

Four, added "Enabled" to the cheat editor strings. You'll notice that
"Disabled" is not there -- it's shared by the speed regulation
setting. I know, sharing strings sucks, but that's pretty much how the
localization system works, sorry. You can use something simple like
"On" / "Off" in place of "Enabled" / "Disabled", if necessary.

Also updated the locale.cfg file for everyone:
http://byuu.cinnamonpirate.com/temp/locale.cfg

[No archive available]
2008-05-20 07:02:00 +00:00
byuu
f6efcbe6fd Update to bsnes v031r06? release.
Okay, I've posted a new WIP, which has a completed locale.cfg file.
Well, it's completed for v032, at least. All translations are going to
have to be updated for every release, sadly.

For those interested in translating it, I'm looking to only have
native speakers perform translations. I don't care if things aren't a
perfect literal translation, so long as the general idea gets across.
But I don't want anyone using machine translation tools, either.
They're very unprofessional, better to wait until someone fluent comes
along. Yes, I know that's ironic given my translation to Japanese:
hoping someone will re-do that one.

The reference locale file is here:
http://byuu.cinnamonpirate.com/temp/locale.cfg

Format is obviously UTF-8. Yours will need to be in this format as
well. Any local encodings will fail miserably.

You can see most of the options in bsnes v031 to see where they come
into play. I have them mostly sorted per window. Some windows share
the same string. I doubt that's going to be a problem, but we'll see.

If you have access to the WIPs, be sure to get the latest one to test
with. If not, and you're willing to translate the UI, feel free to PM
me and I'll happily send you a link to it.

I've added a "Localization by:" field to the about screen. Please feel
free to add your name there.

Next up, I'm trying something a bit different for the config files,
and I've updated readme.txt to reflect this:

bsnes will now check in the same folder as the executable for
bsnes.cfg and locale.cfg. If they're found, bsnes will use these
files. If they are not found, it will use your user profile folder for
storage.

So, if you want bsnes to run in single-user mode, just make sure
bsnes.cfg and/or locale.cfg exist. If not, you can create a blank file
and bsnes will use that next time you run it. If you want multi-user
mode, delete the files. If you want multiple profiles, use single-user
mode and multiple copies of the executable.

I'll be distributing future Windows binaries with blank bsnes.cfg and
locale.cfg files, so that single-user mode is the default. Just delete
them to switch to the old method if you prefer. Hopefully this pleases
everyone.

[No archive available]
2008-05-19 08:48:00 +00:00
byuu
36859ea52c Update to bsnes v031r05? release.
Well, that was certainly a pain in the ass ...

Image

Had to port hiro to full-on Unicode / UTF-16. But the GUI API still
takes UTF-8, it's all converted internally now, bidirectionally.

Oh, and don't make fun of my Japanese :P

---

As for the new WIP, I've included my example locale.cfg. No other
lines will translate, so don't try yet. You need to put it in the
.bsnes folder next to bsnes.cfg. And don't try it unless you have
Japanese fonts, obviously.

[No archive available]
2008-05-15 07:51:00 +00:00
byuu
64589148d4 Update to bsnes v031r04? release.
New WIP.

This one adds DPI-independent font sizing for both Windows and Linux.
With that, I've reduced the font size back down to "Tahoma 8" on
Windows, and "Sans 8" on Linux.

Because of that, I was able to reduce textbox and button height from
30 to 25, and label, checkbox and radiobox height from 20 to 18. In
other words, the UI looks like it did back with v019.

There's only one tiny flaw with the Linux port, I'm unable to change
the font face for the listbox column header. It's not actually a
widget, so it ignores my gtk_container_foreach ->
gtk_widget_modify_font() calls. Any help would be greatly appreciated.

I've also added FitzRoy's new icon. It seems to only have 32-bit
icons, and no 256-color icons ... I guess we'll see how that looks on
Win2k soon enough.

Lastly, statusbar toggle was broken in the last WIP, that's fixed now.

[No archive available]
2008-05-12 05:26:00 +00:00
byuu
89ae1101ee Update to bsnes v031r03? release.
Another WIP. This one changes the GUI toolkit to not invoke callbacks
when the API is used to set the state of widgets. With that it was
really easy to get the speedreg / frameskip checks to update when
using the keyboard controls.

What I really need for this WIP is testing to see if any UI elements
are now broken as a result of the change. For example, try and get a
checkbox to not represent the actual state of something. Eg a
frameskip of 2 but the checkbox is on 0. Also check startup states and
that sort of thing.

The UI code really needs to be cleaned up at this point ...

[No archive available]
2008-05-07 06:30:00 +00:00
byuu
340d86845a Update to bsnes v031r02? release.
New WIP. Please be sure to test a few games with this one to look for
regressions.

I got tired of using bit packing for CPU / SMP register flags, because
they do not mask the upper bits properly.

In other words, (assume big endian) if you have struct { uint8_t n:1,
v:1, m:1, x:1, d:1, i:1, z:1, c:1; } p; and you set p.m = 7; it will
set p.v and p.n as well. It doesn't cast the type to bool.

So I rewrote the old template struct trick, but bound it with a
reference rather than relying upon union alignment. Looks something
like this:

    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;
    ...
      CPURegFlags() : data(0), n(data), v(data), m(data), x(data),
    d(data), i(data), z(data), c(data) {}

    };


Surprisingly, benchmarks show this method is ~2x faster, but flags
were never a bottleneck so it won't affect bsnes' speed.

Anyway, with this, I decided to get rid of the confusing and stupid
!!() stuff all throughout the CMP and SMP opfn.cpp files. It's no
longer needed since the template assignment takes only a boolean
argument. Anything not zero becomes one with that.

So code such as this:

    uint8 sSMP::op_adc(uint8 x, uint8 y) {
    int16 r = x + y + regs.p.c;
      regs.p.n = !!(r & 0x80);
      regs.p.v = !!(~(x ^ y) & (y ^ (uint8)r) & 0x80);
      regs.p.h = !!((x ^ y ^ (uint8)r) & 0x10);
      regs.p.z = ((uint8)r == 0);
      regs.p.c = (r > 0xff);
      return r;
    }


Now looks like this:

    uint8 sSMP::op_adc(uint8 x, uint8 y) {
      int r = x + y + regs.p.c;
      regs.p.n = r & 0x80;
      regs.p.v = ~(x ^ y) & (x ^ r) & 0x80;
      regs.p.h = (x ^ y ^ r) & 0x10;
      regs.p.z = (uint8)r == 0;
      regs.p.c = r > 0xff;
      return r;
    }


I also took the time to figure out how the hell the overflow stuff
worked. Pretty neat stuff.

Essentially, overflow is set when you add/subtract two positive or two
negative numbers, and the result ends up with a different sign. Hence,
the sign overflowed, so your negative number is now positive, or vice
versa.

A simple way to simulate it is:
int result = (int8_t)x + (int8_t)y;
bool overflow = (result < -128 || result > 127);

But there's no reason to perform signed math, since the result can't
be used for anything else, not even any other flags, as the opcode
math is always unsigned.

So to implement it with this:
int result = (uint8_t)x + (uint8_t)y;

We just verify that both signs in x and y are the same, and that their
sign is different from the result to set overflow, eg:
bool overflow = (x & 0x80) == (y & 0x80) && (x & 0x80) != (result &
0x80);

But that's kind of slow. We can test a single bit for equality and
merge the &0x80's by using a XOR table:
0^0=0, 0^1=1, 1^0=1, 1^1=0
The trick here is that if the two bits are equal, we get 0, if they
are not equal, we get one.

So if we want to see if x&0x80 == y&0x80, we can do:
!((x ^ y) & 0x80);

... or we can simply invert the XOR result so that 1 = equal, 0 =
different, eg ~(x ^ y) & 0x80;

The latter is nice because it keeps the bit positions in-tact. Whereas
the former reduces to 1 or 0, the latter remains 0x80 or 0x00. This is
good for chaining, as I'll demonstrate below.

Do the same for the second test and we get:
bool overflow = ~(x ^ y) & 0x80 && (x ^ result) & 0x80;

We complement the former because we want to verify they are the same,
we don't for the latter because we want to verify that they have
changed.

Now we can basically use one more trick to combine the two bit masks
here. We want to return 1 when overflow is set, so we can look for a
pattern that will only return one when both the first and second tests
pass.

An AND table works great here. 0&0=0, 0&1=0, 1&0=0, 1&1=1. Only if
both are true do we end up with 1.

So this means we can AND the two results, and then mask the only bit
we care about once to get the result, eg:
bool overflow = ~(x ^ y) & (x ^ result) & 0x80;

And there we go, that's where that bizarre math trick comes from. I
realized while doing this something that bugged me in the past.

I used to think that for some reason, the S-SMP add overflow test
required x^y & y^r, whereas S-CPU add overflow used x^y & x^r.
Probably because I read the algorithm from Snes9x's sources or
something.

But that was flawed -- since addition is commutative, it doesn't
matter whether the latter is x^result or y^result. Only in subtraction
does the order matter, where you must always use x^result to test the
initial value every time.

Subtraction switches up things a little. It sets overflow only when
the signs of x and y are _different_, and when x and the result are
also different, eg:
bool overflow = (x ^ y) & (x ^ result) & 0x80;

Fun stuff, huh?

So I was wanting this tested thoroughly, just in case there was a typo
or something when updating the opfn.cpp files.

---

That said, I also polished up the UI a bit. Moved disabled to the
bottom of the speed regulation list, and added key / joypad bindings
for "exit emulator", "speed regulation increase / decrease" and
"frameskip increase / decrease".

I know these key bindings do not update the menubar radiobox positions
yet. I'll get that taken care of shortly.

[No archive available]
2008-04-19 12:03:00 +00:00
byuu
b895f29bed Update to bsnes v031r01? release.
New WIP posted.

Not much to this one.

- added FitzRoy's updated program icon
- removed safe_free / safe_delete / safe_release template functions
- replaced nearly all malloc / free calls with new / delete[]

And lastly ... long ago, I used "File / Edit / Help" to conform to
standard UI design. I quickly replaced Edit with Settings, and later
Help with Misc. Lately, the last one has been bugging me ... "File"?
File what? Why is there a reset system option under file?

So, it may be somewhat controversial, but I renamed File to System,
and dropped the now superfluous " System" from Reset / Power Cycle.

I'd honestly like to remove "Exit" from that menu as well, but I know
I'd be pushing it then.

What I want to do next is move "Disabled" in speed regulation to the
bottom of the list, and add key bindings to increase / decrease speed
regulation. I'd like the step after fastest to be disabled. It makes
sense, as fastest can never be faster than disabled, but disabled can
be faster than fastest.

Other nice ideas would be: a cartridge info option under the system
menu somewhere, frameskip +/- key bindings, an exit emulator key
binding, a new GUI panel with options to warn on reset / unload /
exit, and cleaning up of the event namespace for the UI. Specifically,
start working on a more advanced status panel that can display five-
second alerts that override the normal output.

[No archive available]
2008-04-16 12:59:00 +00:00
byuu
1ef279cb83 Update to bsnes v031 release.
New release posted. Perhaps the most important change was fixing a bug in the Windows port when the keyboard was used for input. For some reason, the IsDialogMessage() function I use for tab key support was causing the main window to emit the Windows error beep every time a key was pressed after a few minutes of use. I do not know why this is, so I have simply disabled the tab key support to prevent this from happening.
Other than that, lots of polishing went into this release. UPS soft-patching will work with the recently released Der Langrisser v1.02 translation, for those curious. You can also store the UPS patches in GZ/ZIP/JMA support, and bsnes will detect this and decompress the patches first. Use the same ".ups" file extension for this, as it detects via file header.
If you wish to try out the newly added OpenGL support: start bsnes, go to Settings->Configuration->Advanced and set system.video to "wgl" (or "glx" for Linux users), and then restart the emulator. Please bear in mind that ATI's OpenGL drivers are an industry-wide joke, so I'd only recommend trying this on an nVidia or Intel video card.
Changelog:
    - Fixed bug and re-enabled HDMA bus sync delays
    - Emulated newly discovered IRQ timing edge case
    - Optimized offset-per-tile rendering
    - Added state-machine implementation of S-DSP core, ~5% speedup
    - Added SPC7110 detection, will now warn that this chip is unsupported
    - Fixed very annoying Windows port OS beeping noise when using keyboard for input
    - Linux port will now save most recent folder when no default ROM path is selected
    - Added OpenGL rendering support to Windows port [krom]
    - Fixed Direct3D pixel mode scaling bug [krom, sinamas, VG]
    - Improved SNES controller graphic [FitzRoy]
    - Added UPS (not IPS) soft-patching support; UPS patch must be made against unheadered ROM
    - As always, cleaned up source code a bit
2008-04-13 23:40:08 +00:00
byuu
0241dd78b7 Update to bsnes v030r08? release.
New WIP posted, which adds the immediate-mode opcode IRQ delay
findings from this past week. Doesn't have any visible effects on
anything. I also went back to a switch table for the CPU / SMP opcodes
instead of the jump table. Shaves ~100kb off the object files and
compiles faster with no speed loss. I used the jump table before to
simplify PGO, but since that's been broken for at least a year now
anyway ...

Fes, thanks for the temporary workaround. I'll try and get a new
release out this weekend if possible. I'd like to have UPS soft-
patching in before the next release, though, hence the delay.

[No archive available]
2008-04-10 11:05:00 +00:00
byuu
a13c3aece6 Update to bsnes v030r07? release.
New WIP.

Direct3D driver: removed diffuse color vertex information, and made
driver re-initialize whenever window size changes. Should fix ATI
resize in pixel scale mode bug once and for all. Confirmation would be
appreciated. Speed will still be bad on some cards that can't handle
large textures, and I don't really want to implement StretchRect()
profiling, so that's still an issue.

Windows/hiro: disabled IsDialogMessage(). This will prevent the tab
key from working in the configuration panel, but will also stop the
main window from beeping every time you push a key -- the lesser of
two evils. Blame Microsoft for this bullshit. IsDialogMessage() should
empty the key buffer, but it doesn't when there are no tabbed controls
on a window. I'll rig something up in the future for this.

Linux/hiro: GTK+ file open / file save / folder select dialogs will
now save the path if you selected a valid file, so that next time you
will start in that folder. This didn't matter if you set hard-coded
paths in bsnes, but it makes a positive difference if you did not.

[No archive available]
2008-04-07 03:34:00 +00:00
byuu
20977817ae Update to bsnes v030r06? release.
New WIP up.

This one fixes HDMA bus sync timing. I verified this was correct per
hardware with the HDMA test sync ROM. It was definitely wrong before.

Secret of Mana, Street Racer and Jumbo Ozaki no Hole in One all work.
Yes, they worked in the official v030 release, but that release had
HDMA sync disabled and rounded.

Mecarobot is improved greatly, but still flickers when the golf course
is moving. If you're as desperate as I am to play this amazing
masterpiece _right now_, you can always hex edit the ROM and change
offset 0x1c6f from 0x40 to 0x80 :)

I'm still investigating that issue more before I start running
hardware tests. I want to rule out things that can't be the cause of
the bug first.

I've also added (hopefully) proper SPC7110 detection. If anyone wants
to test all of them to make sure it works, great. It should give you a
popup now saying that it's unsupported. Down to just needing ST-011
detection now.

[No archive available]
2008-04-03 11:50:00 +00:00
byuu
ba25c82939 Update to bsnes v030r05? release.
New WIP posted, which adds:
- krom's Direct3D fix; point mode at multiples of 3x and higher
without aspect ratio correction is no longer blurry
- FitzRoy's updated SNES controller graphic
- glX improvement for Linux, window will clear to black on startup for
ATI cards now too, but it still doesn't redraw when the window is
damaged because I can't trap the exposure events
- tiny clarification to S-DSP emulator source (use echo_hist_pos enum
instead of just "8")
- started to add SPC7110 _detection_ for the sole purpose of advising
that the chip isn't supported. Not finished yet. Also need to fix
ST-011 detection while I'm at it (it's detected as ST-010 now; they
share ROM type and mapper IDs), and all special chip games should be
covered.
- re-added the slightly incorrect HDMA sync timing. It helps (but
doesn't fix) Mecarobot, it breaks the SoM intro again; but Street
Racer and Jumbo Ozaki are still working right -- looks like other
timing improvements since then were enough for those titles

For those asking for WIP access, I'm really sorry but I have way too
many testers now. It's extremely hard for me to even keep track
anymore. I just don't have the bandwidth.

If you absolutely need a specific WIP, I'll stick it on a file sharing
site or something for you. Otherwise, my apologies for not sending you
the link. I absolutely do appreciate the offers to help beta test,
though.

[No archive available]
2008-04-02 05:41:00 +00:00
byuu
3babe932fd Update to bsnes v030r04? release.
One thing we can always do is add some platform-specific profiling
code. Have bsnes try and determine what the fastest driver is upon
first run. As if I don't have enough to do already, heh.

New WIP, which converts the S-DSP ring buffers to an internal class
object. Surprisingly, it actually does make the code a bit nicer to
look at, although it's kind of unfortunate I can't hijack operator[]=,
heh. I'd be forced to use modulus for that.

Even more surprising, it's about ~2% faster than before. Even though
it's technically even more complex now with three writes instead of
two. Makes no sense at all, but I won't complain. Getting 122fps now
on Zelda 3 load screen.

---

ATI Radeon X300LS:
Direct3D = 64fps
OpenGL = 24(!!)fps

... as if we needed _another_ reason not to buy ATI products. What the
hell was AMD thinking, buying them?
Better yet, why do people buy ATI products? Laptops, I can understand.
But for desktops?? Seriously. That performance is so terrible, you
couldn't even play OpenGL games with that. We really need more OGL
titles to rape ATI on benchmark tests, so that they'll get their heads
out of their asses.

[No archive available]
2008-03-26 08:58:00 +00:00
byuu
6bdeaef0f4 Update to bsnes v030r03 release.
v030 wip3 posted.

This one add's krom's ruby changes, meaning Windows OpenGL support.

For consistency, I changed the Windows system.video setting to "wgl",
and Linux OpenGL to "glx". Linux users should be sure to update that
to avoid SDL video output.

I get ~119fps with OpenGL, and ~120fps with Direct3D. I'd appreciate
if everyone else would test OpenGL support. If it works everywhere
that D3D works, and avoids that texture size slowdown issue, then we
should make it the default driver.

The only issue I see with the driver now is that vsync is enabled no
matter what. You can turn it off in eg the nVidia control panel by
overriding the setting. I also recommend enabling triple buffering.
With that, video is perfectly smooth and audio is ~99.5% perfect. So,
so close. A slight cpu.freq change and you can probably get it
perfect.

God, it's so nice having perfect video and audio. I really wish that
worked across the board. It's absolute euphoria playing games like
that.

[No archive available]
2008-03-26 07:10:00 +00:00
byuu
9e3827e2a2 Update to bsnes v030 release.
I didn't want to release a new version so soon, however there is a rather serious bug in bsnes v029 where the path information for the save RAM files is discarded when one has not selected a default save RAM / cheat path from the path settings tab in the configuration settings window. Because of this, it gets stored to the base directory. For Windows users, this is c:\, and for Linux users, this is /
This bug forced my hand, so I'm releasing v030 to correct this issue. I also cleaned up the S-DSP emulation code to be more consistent with my programming style -- it gets bit-perfect matches to v029's wave output, so I don't foresee there being any problems.
2008-03-24 12:43:32 +00:00
byuu
e499670ad9 Update to bsnes dsp release.
Okay, it's just blargg's. I hope he doesn't mind ...

I rewrote his S-DSP emulator in pure C++. Only took me seven hours,
not bad. anomie's took a few days.

Now, given, it's extremely similar of course. First, the algorithms
are going to be mostly the same regardless of who writes the code.
Second, I really didn't see a reason to waste too much time on this
reverse engineering a bunch of stuff myself, so I pretty much just
took the code and "rewrote" (read: copied) it in my unique style, and
changed a few things here and there. Code flow, variable names,
tables, exact algorithms, etc were blatant, direct copies.

Things I did change:
- counter rate 0 is now hardcoded to not ever hit zero
- counter read is now boolean instead of unsigned short
- a lot of multiplication was converted to shifts
- broke up the program into ~9 source files
- no more global functions anywhere, all in one class
- removed the hooks for things like external channel muting -- will
re-add if I ever add an option like that to bsnes
- modified VREG to not need the voice regs handle passed to it
- all voice functions take a reference instead of pointer to the voice
structs now
- packed 32-line timing table expanded to multi-line
- left everything in their own small chunk functions ... kind of torn
on whether I want to merge that with the main timing function. I like
the encapsulation, but it would remove the need to keep so many
struct-based state variables
- added a few more comments on parts that confused me at first
- removed assignment inside conditional stuff; even though I do that
myself on occasion in other code I write, heh
- yadda yadda, more minor stuff like that

Going to keep working at it -- wanted to get it working now, so that
finding regressions will be easier. I want to remove the double writes
for the ring buffer, make a decision on whether I want to rely on sign
extension, or use sclip<> for that, implement a compile-time option to
bypass libco (will save 2.048 million co_switch calls a second) since
the S-DSP's entire operation fits into a single switch table quite
easily, convert a lot of the mul / div stuff to shifts, convert those
clever split up branches in the envelope and BRR decoding routines to
switch / case tables, remove the shift tables from the BRR decoding,
and try and figure out what's going on with some of the code so that I
can try and document it :)

I'll see if I can contribute something back, too. Perhaps I can look
into what happens when you enable mute or something.

New WIP up which has the new core enabled by default. For those
without WIP access, I've posted the new source for reference. Comments
welcome.

    byuu.org/files/bsnes_dsp.zip


... man, feels weird posting a new topic.

[No archive available]
2008-03-22 15:37:00 +00:00
byuu
805398e5a8 Update to bsnes v029 release.
A new version of bsnes has been released. It contains a few minor emulation fixes, as well as user interface improvements. Behind the scenes, the source has been cleaned up more in preparation for running the CPU and PPU (video processor) separately from each other (eg with no enslavement.) This is required for implementing a clock cycle based PPU renderer.
    - Greatly improved invalid DMA transfer behavior, should be nearly perfect now
    - Major code cleanup -- most importantly, almost all PPU timing-related settings moved back to PPU, from CPU
    - Added option to auto-detect file type by inspecting file headers rather than file extensions
    - Rewrote video filter system to move it out of the emulation core -- HQ2x and Scale2x will work even in hires and interlace modes now, 50% scanline filter added
    - Re-added bsnes window icon
    - Added new controller graphic when assigning joypad keys [FitzRoy]
    - Redundant "Advanced" panel settings which can be configured via the GUI are no longer displayed
    - Improved speed regulation settings
    - XP and Vista themes will now apply to bsnes controls
    - Added "Path Settings" window to allow easy selection of default file directories
    - Tab key now mostly works throughout most of the GUI (needs improvement)
    - Main window will no longer disappear when setting a video multipler which results in a window size larger than the current desktop resolution
    - Added two new advanced options: one to control GUI window opacity, and one to adjust the statusbar text
2008-03-18 06:19:43 +00:00
byuu
7e6e3e3a69 Update to bsnes v028r16? release.
Lots of talking.

 As I've said many times before, I typically don't like working on fan
translations. The programmers are almost always far less skilled than
professional developers, and they almost always test on emulators
rather than hardware.

 I may look into this when I'm feeling particularly bored, though I
don't know how you could have possibly picked a worse game for me to
be caught debugging at work. Well, maybe those "Adult Manga" PD ROMs
...

 EDIT: New WIP. This one adds IsDialogMessage() support. It isn't
perfect, the test apps get the highlighted dots around the active
controls, but bsnes isn't for some reason. Don't know why that is yet.
And it seems once tab enters into a child window, you can't get back
to the outer window. But otherwise, it's better than nothing. I even
got the z-order thing down so tab works in the right direction.

[No archive available]
2008-03-16 05:36:00 +00:00
byuu
16ba1d1191 Update to bsnes v028r15? release.
Thanks, FitzRoy. The controller graphic looks really amazing. I have
two very minor changes to request if you don't mind.

 First, I had to increase the size to 372x178 (Windows BMP format adds
alignment if width is not a multiple of 4 -- this makes it a real
bitch to convert the image to my UI wrapper pixel format), and shift
the actual image one pixel left to center the gradient fade.

 Second, and more importantly, could you store the controller graphic
in 32-bit format with alpha? Rather than using a white or gray
background, if I could get the full alpha channel information, then I
can adjust the background color to anything I like in the future.
Depending on how it looks, maybe I can just let the controller blend
against the window background itself.

 And thank you, King of Chaos, as well. It was extremely difficult to
choose one over the other. I wish I could use just both so as not to
offend anyone. But I kind of like FItzRoy's more. I was kind of going
for that pristine, "cleaner than real life" look. Still, I really
appreciate your help in making a controller graphic.

             ---

             New WIP.

 I've added FitzRoy's controller graphic to the input capture window.
It will only display when configuring joypad buttons, not when
configuring UI buttons.

 I've also added the new UI settings panel. This lets you control
window translucency for all but the main bsnes window. I capped
opacity to 50% minimum, because I don't want to hear bug reports when
people slide it to 0% and can't find the config window anymore :P
 Works on Windows and Linux. If you lack a compositor on Linux, it'll
just stay a solid color. If you have Compiz / Beryl and the blur
filter, use it with gaussian alpha blur. Then you can set opacity all
the way down to 50% and it will still look amazing. I want to post a
screenshot of it, but the image is ~3MB. Maybe later I'll post it to
one of those file hosting sites.

 There's also a setting here to control what gets written to the
statusbar. I went back to just displaying the raw ROM title. So you
can use %t for that, %n for the filename, and %f for the frame rate.
Still working on this feature. Plan to keep the game name visible when
pausing, add some additional info that can be output here, etc. It may
be better to keep this setting in the advanced panel, as it's not the
most user friendly thing in the world. Up to you guys, I guess.

             Need more settings here, though. Need to fill out that
window more.

[No archive available]
2008-03-09 06:01:00 +00:00
byuu
29c871ef62 Update to bsnes v028r14? release.
New WIP. Adds Win2k alpha adjust (against black background), some
minor code cleanups, LZSS compression / decompression for storing
graphics, and puts the program icon onto the about screen, which has
been shrunk down a bit again.

             So, too late mudlord, the answer was LZSS :P
 I wanted to just go with RLE for simplicity, but the compression
ratio sucked. LZSS is the same number of lines of code, yet is three
times more efficient with the icon. And something like a controller
with much more repetition will probably make an even bigger
difference. Meh, the code's easy enough. I wrote it for clarity over
speed, and decompression is always lightning fast with LZ anyway.

             Good job decoding the base64 portion, though. Very useful
routine for a library.

 As for the controller graphics, wow ... I'm really torn. I really
love how clean FitzRoy's version looks, yet at the same time King of
Chaos' version is so lifelike it's scary. I dislike the "flaws",
though. The scratches on the X, the dot on the bottom right, and the
off-center buttons ... since it's digital anyway, I'd prefer it to
appear perfect, if at all possible.

             But it's a tough call. I'll have to hold a vote or
something :)
             Thanks a million for helping with the controller graphic,
both of you!

[No archive available]
2008-03-03 09:24:00 +00:00
byuu
42f1d08c02 Update to bsnes v028r13? release.
New WIP.

 Adds a base64 encoder, which zaps the ~21kb icon down to ~5kb. With
the extra space, I used the 48x48 icon instead. It should look a tiny
bit better, but it still obviously can't beat a non-resampled icon.
Also added Linux icon support. That turned out to be a royal pain, as
the gdk-pixbuf library documentation was separate from the GDK
documentation. Tried finding visuals, to make colormaps, to get GCs,
to create pixmaps to blit onto as drawables, to create pixbufs with,
to attach to the window. Turns out, gdk-pixbuf has a function to turn
raw data into a pixbuf.







> Could we have an option to disable this effect in advanced settings
> so that the mode can appear "crisp" as it does in other emulators?




               This blurring is required for pseudo-hires to operate
properly, eg in Jurassic Park.

 Nonetheless, if you guys really want the option to disable the
blurring, I can add it. Just keep in mind that we're opening up a can
of worms. People will then want an option to disable the sprite
drawing limit, to add hi-res mode7, etc etc. Harder to draw a line in
the sand when you aren't all or nothing.







> This is a problem? If it's a question of storing them all in an ico,
> why not simply say "Here's a nicer ico set seperately, DL if you
> want'.




 I'm not going to put resources external to the executable, unless I
absolutely have to. Thus, I have to put all of these icons inside the
source code, and I have to modify the GUI API wrapper to handle this.







> I was thinking, you know, one of you could report it to them.




               "Hi, uh, Microsoft? Yeah, your compiler is erroring out
when I compile my emulator with it and PGO enabled."
               "Sure, as that's a $12,000 Team Suite Edition feature,
if I could just get your serial number, that'd be great."
               "Oh, uh ... I think I left that at home. I'll call you
right back with it, okay?"
               "Oh, no problem. If I can just get your full name, I'll
pull you up in our system ... ... hello? Sir?"
               ::dial tone::

               And for the _official_ legal record, I only used the
free trial and express editions :)







> Yeah, one issue they can fix is maybe implement blargg's spc core;
> then again, I thought Snes9x was dead.




 Not dead, but on severe life support. Same for SNEeSe and Super
Sleuth. anomie, TRAC and Overload have minimal presence anymore. A
damn shame. The SNES scene is in worse shape than most people realize
at the moment. NES emulators have had dot-based PPU renderers for
years now.

[No archive available]
2008-02-28 18:39:00 +00:00
byuu
521f4f6952 Update to bsnes v028r12? release.
New WIP.

 vcounter / hclock / hcounter renamed to vcounter / hcounter / hdot. I
think it's more clear this way. Fixed up the v/hc stuff to v/h in
bppu_mmio.cpp to match.

 Instead of building each driver for ruby independently, I grouped
them all together into one object file. I know everyone else hates
that, but too bad -- that's the way I program. No sense building ~10
object files when one will do just as well. I was able to cut out ~20
lines from the Makefile as a result of this.

 I added CB_SETITEMHEIGHT magic to actually set combo box to requested
height. Neat. Of course, bsnes doesn't currently use any combo boxes
in the UI, but it'll be nice when it does, at least.

             Lastly, I added something new to the Windows port (that
used to be there a long time ago), just for FitzRoy :P
             I'll go over that in more detail tomorrow. For now,
consider it a surprise.

[No archive available]
2008-02-27 05:55:00 +00:00
byuu
92cfb1268a Update to bsnes v028r11? release.
New WIP up.

             I was a little too busy to work on bsnes this weekend,
but I got some work done tonight.

             First, I moved the field / interlace / overscan status
functions over to the PPU, where they belong.

 This led me to kill a lot of extra CPU timing variables, such as
vblstart and vnmi_trigger_pos. The latter I had to kill because I can
no longer call sCPU::update_interrupts() when the PPU changes the
overscan setting. You may be wondering about interlace toggle -- well,
it can only take effect at the start of a new frame anyway, and the
timing for scanline 0 is the same regardless of interlace setting, so
it doesn't really need to call update_interrupts() anyway.

 With this moved back to the PPU, I was able to clean up the PPU
functions a bit, too. Before, I had PPU::scanline_is_hires() and
CPU::interlace(), and then a function called PPU::get_scanline_info()
that would read the previous two functions and copy them into a
struct. What an odd construct, I'm sure it was more complex in the
past. Cruft, basically. I just killed that, renamed scanline_is_hires
to just hires, and now SNES::Video just queries ppu.hires() and
ppu.interlace() directly. Much nicer.

 I didn't lose any speed here, either. I made up the difference by
force inlining the PPU states in the bPPU header file.

 I ran all my IRQ and NMI tests again, I didn't see any regressions.
Testing of games that use interlace and overscan, as well as of IRQ-
sensitive games, would be appreciated.

 While cleaning up the PPU, I had some code that would flush the PPU
buffer when disabling interlace. I removed that as it looked rather
ugly. Don't really have a clean way of handling that. Not like any
game out there toggles interlace every frame anyway.

 I went through and killed a bunch of config file options that don't
actually do anything anymore, such as audio.frequency and
video.use_vram.

 Lastly, I rewrote the advanced panel code finally. All options that
can be controlled through the UI have been removed. The list is ~80%
smaller now. I also improved a lot of the descriptions. I think it
looks a lot better now, at least. I went with a blacklist, rather than
whitelist. I figure, better to have extra options if I forget to
filter them out; than to have missing options if I forget to add them.

 Before the next release, I'd like to add back default_height() stuff
to get the textboxes and buttons smaller on the Windows port. Maybe
revert that back to Tahoma 8. I should also add descriptions to the
last few advanced panel options missing them. Other than that -- just
regression testing, I suppose. I can't break up the PPU enslavement
any more without adversely affecting performance at this point.

 Hmm, would also be nice to rename vcounter / hclock / hcounter to
vcounter / hcounter / hdot. Afraid of missing a reference somewhere
and screwing up the timing, heh.

 I tried to get the icon working again on the Windows port. But using
LoadImage or CreateIconIndirect doesn't handle the alpha level of
bsnes' icon properly. It ends up as a 1-bit transparency that looks
terrible in the titlebar, as well as the taskbar. The only way I can
get it to look good is with LoadIcon and grabbing the icon from the
resource file. The reason I don't want to do this is because it's not
at all portable to GTK+. Sigh. Tested this on Win2k, by the way. Win2k
isn't supposed to support the alpha channel in icons at all, but it
sure the hell does on the taskbar.

 I even tried GetIconInfo() on the icon returned from LoadIcon(), and
then CreateIconIndirect on that, and it crushes the translucency
again. So it isn't a problem with the format of hbmMask and hbmColor
in my ICONINFO struct.

[No archive available]
2008-02-26 04:07:00 +00:00
byuu
4d922ba17c Update to bsnes v028r10? release.
New WIP.

 This one nukes the region, region_scanlines, prev_line_clocks and
prev_field_lines variables, and removes timeshift.cpp; replaced with
the new history ring buffer. It doesn't appear to affect speed at all,
which is fine by me. Next up, I want to move interlace and overscan
settings back to the PPU.

 All of my NMI and IRQ test ROMs, even the absolutely insane clock-
perfect ones, still pass. So there shouldn't be any regressions. But
if you feel like testing any IRQ sensitive games, that's cool.

 More visibly, I've bound the .cht path to the selection in the path
settings window. So all three paths actually work now. I tested it by
sorting all of my images by ROM, SRAM and Cheat ... have to say, the
folder looks a whole hell of a lot nicer now. I can see why this
feature is so popular.







> Mainly, there needs to be mechanisms to capture the current frames,
> like through render targets.




               Well, I guess if you don't mind writing up a small
example I could work on porting the current code over.

[No archive available]
2008-02-22 15:05:00 +00:00
byuu
3b2918791c Update to bsnes v028r09? release.
New WIP with XP / Vista theming and cheat path selection. Note that
cheat selection is just a placeholder. It still saves in the same
folder as the ROM for now.

I also spent about four hours trying to get the dual counter into a
fork of bsnes ... and had my ass handed to me. Rigging something up
really quickly that will break every last timing test I have is easy.
But it looks like doing this properly is going to be an extreme
undertaking that will take at least a few weeks. The code is just too
old and too hardcoded.

 I've started cleaning up that code to match my modern programming
style. It seems the only way to really tackle this is going to be very
slowly moving variable by variable to a separate class/struct
somewhere (and running my regression test ROMs each time), and then
once the entire thing is moved out of the CPU, try and clone it and
fork off the PPU to its own thread.

 By my estimates, it appears that simply splitting the CPU and PPU,
and giving the PPU its own cothread, is eating ~8% of performance. The
good news though is that if and when I succeed, it's quite possible I
can emulate the OAM cache behavior, which would fix the black
scanlines in Dr Franken and Winter Olympics.

 Some other good news ... I decided there was really no sane reason to
have different clock frequencies for the CPU<>PPU and SMP<>DSP, since
the real SNES only has two crystal clocks anyway. A novelty, sure, but
that would complicate the fuck out of dual counters. With that gone, I
can avoid a 64-bit multiplication during each SMP/DSP addclocks call.
That gives a modest ~2% speedup -- possibly placebo.

 Looks like a ring buffer for timeshifting backwards isn't going to
help much. I only notice a ~1-2fps difference even when disabling
timeshifting completely. Not surprising, timeshifting really doesn't
have that much overhead to it.

 Oh yeah, it seems I disabled the code that set the hclock to 186 upon
reset a while back, which was causing some of my oldest tests to fail.
I can't remember why I disabled that (maybe something to do with
cothreads), and enabling it didn't seem to cause any problems, so ...
I left it enabled. Let me know if anything screwy happens.

[No archive available]
2008-02-21 05:34:00 +00:00
byuu
b7d34a8aa3 Update to bsnes v028r08? release.
New WIP.

 Fixed the frameskipping bug, fixed the DirectDraw renderer. I also
added a new folder_select function to both ports of hiro (Windows and
GTK+), and with that, I added a new path settings panel to the
configuration window.

               You can see how it looks here:






    http://byuu.cinnamonpirate.com/images/bsnes_20080219.png




 Also, I compiled the Windows binary with Direct3D support omitted.
tetsuo55, please grab this version, as I intend to compile with
Direct3D support for subsequent WIPs.

[No archive available]
2008-02-19 14:28:00 +00:00
byuu
8fd90cc123 Update to bsnes v028r07? release.
New WIP adds an option to enable or disable filetype
detection by reading the format header. I received no feedback, so I'm
defaulting to this behavior being off. In other words, I'm defaulting
to requiring the file extension to be correct to properly handle the
file. This is because there's no reason a real SNES would behave
different just because $8000 = 'P' and $8001 = 'K', and with the
option enabled by default, you wouldn't be able to get such a game to
run. But the option is there for those who want it.

I've also added bumpers to everything but the core (cpu, smp, ppu,
dsp) and some of the library stuff and platform-specific stuff (hiro,
libfilter, libco, ui) -- really can't add them to libco as I want each
individual file to compile on its own if the user wants. But overall,
it should make things a lot easier for those trying to build bsnes
without using my Makefile.

               Not in the WIP, I just fixed a frameskipping bug. It
was broken in the last few WIPs, including the most recent.







> You'd be best off reading 7 bytes, and then memcmp()'ing them.




 Can't memcmp() the low five bits of the GZ flags byte. I'm not
concerned about rigid speed here anyway. It's just file type
detection. I changed it to fread() the bytes, that's good enough.

               Thanks for the information, I've extended JMA to a
40-bit check.







> Anyway, the -mdynamic-no-pic option does work and is likely the
> better solution, since it apparently continues to allow linking to
> dynamic libraries, whereas -static apparently does not.




 Well, we use -static only when building libco.c. I like -static more,
because it exists in all versions of GCC. I will mention -mdynamic-no-
pic in the libco documentation for v0.13 official.







> Well, turns out the CGRAM content is the same... Surprised
>                    bsnes, ZSNES and vSNES show 8/16/24, so it's
> something to do with SNES9x.




               Thank you for testing! If only all beta testers had
your technical prowess :D

               Glad to see it's not a bug on my side. Not really in
the mood to track down bugs at the moment, heh.







> You obviously haven't been around here very long. Razz
>                    Believe me, someone has or will try it.




 I've actually been very fortunate in that regard. At least 95%, if
not all, of bsnes users have been very intelligent and well spoken :)







> Another small issue could be adding a list of recently loaded ROMs
> to the menu.




               Not a chance. I can't _stand_ recently opened document
lists.







> now I'll leave you all to this medical hijacking of the thread,
> while waiting for richard bannister to successfully compile and
> release a new bsnes




               He has. Get it here. Be sure to send him thanks, please
:)







> byuu's been planning to write documentation for ages, he's just
> never gotten around to it. Perhaps all the experience he's gained
> restructuring bsnes will help him plan out the documentation when he
> does, though




 I won't start on docs until I have a functional CPU<>PPU cycle-level
emulation model. I'll try documenting the PPU as I work on cycle
timing, and I can expand upon the documentation from there.

[No archive available]
2008-02-18 17:02:00 +00:00
byuu
e651beb72e Update to bsnes v028r06? release.
New WIP.

 Richard Bannister asked me a year ago to add support to detect the
file compression type by reading the header, as apparently Mac users
can't be bothered to use proper file extensions.

               In an act of extreme expediency, I've added his request
in record time :P

               Here's the detection code I wrote:







    Reader::Type Reader::detect(const char *fn) {
                       FILE *fp = fopen(fn, "rb");
                       if(!fp) return Unknown;

                       fseek(fp, 0, SEEK_END);
                       unsigned size = ftell(fp);
                       rewind(fp);

                       uint8_t a = size >= 1 ? fgetc(fp) : 0;
                       uint8_t b = size >= 2 ? fgetc(fp) : 0;
                       uint8_t c = size >= 3 ? fgetc(fp) : 0;
                       uint8_t d = size >= 4 ? fgetc(fp) : 0;
                       fclose(fp);

                       if(a == 0x1f && b == 0x8b && c == 0x08 && d <=
    0x1f) return GZIP;
                       if(a == 0x50 && b == 0x4b && c == 0x03 && d ==
    0x04) return ZIP;
                       if(a == 0x4a && b == 0x4d && c == 0x41 && d ==
    0x00) return JMA;
                       return Normal;
                       }




 If anyone sees any problems, please let me know. And unless your name
is Nach, I expect you to read and cite official documentation to point
out any problems.

 Note: I need more than 16-bit accuracy to avoid false positives, so I
read the compression type and flags for GZIP. Compression type should
always be 0x08 according to my understanding of GZ. Flag top 3 bits
are always 0 per spec. I guessed with JMA's fourth byte. I hope it's
always zero, but I don't know that for certain.

 The new WIP has GZ/ZIP/JMA support built-in, so testing would be
appreciated, though I doubt you'll hit any false positives.

               Now, a more important question. Should I enable this
detection by default in bsnes, or go by filename? It's _possible_ an
SNES ROM could have these headers, despite not being compressed at
all. One could even add these signatures intentionally if they really
wanted. A real SNES game could have these bytes at the top of the
file, quite obviously.

So, is it better to cater to people who misname extensions, or to the
possibility that a game might have these bytes in the signature (a one
in four billion chance of happening accidentally. One in 500 million
for GZ false detection.)

               ---

 Also, I added some changes by KarLKoX to allow OpenAL to build on
Windows. Namely, I removed the unused ALut dependency, and added
support to the makefile to include openal32. I don't intend to build
OpenAL into the default Windows binaries (because I don't want extra
DLL dependencies that most people do not have; and because OpenAL
support sucks on Windows for non-Creative cards), but perhaps in the
future I'll offer more than one version for download.







> The "almost black" color below the door is 8/16/24 in bsnes
> (standard preset) and 0/16/16 in SNES9x. It's best to see on a black
> background.

>                    EDIT: This might be due to the RGB565 format.




 Wow, that's quite a difference. If you have bsnes v013-v019, you can
dump the palette through the memory viewer. Perhaps see what SNES9x
has from its savestate, and if it's different -- one of us has an
emulation bug.

               Not an RGB565 problem, or the colors would match when
ignoring the low three bits (two for green.)

               bsnes:
               00001000
               00010000
               00011000

               SNES9x:
               00000000
               00010000
               00010000

[No archive available]
2008-02-17 16:49:00 +00:00
byuu
4cbba77fc7 Update to bsnes v028r05? release.
New WIP up. This one re-adds HQ2x and NTSC, so all
filters from v028 are back, plus there's the new scanline filter.

 So all of that code is now out of the core. It was pretty silly that
eg the S-SMP core was dependent upon the SNES class, which depended on
the VideoFilter class, which depended upon the HQ2x class, which
depended upon the ~50kb HQ2x blending tables. Well, no longer.

 While I didn't make V-only HQ2x and Scale2x filters (yet?), I did add
some code to make it fallback on the direct renderer if hires or
interlace is being used. This means the issues with hires games (eg
DKC intro) should be gone. Let me know if you find any problems.

 I also re-added DMPSDisable to the GTK+ screensaver disable code,
since that was triggering after ~30 minutes or so still. It probably
won't even work, but whatever.







> Why default to a crippled renderer to save those people a few
> clicks?




               First impressions and all that, mostly.







> I have an Intel Mac with OS X 10.4 (no Leopard, sorry, but it
> shouldn't be that different yet) I can test whatever on




               Thank you! :D

               Okay, first thing would be to make sure libco itself
works. Please download this:







    http://byuu.cinnamonpirate.com/files/libco_v13_rc2.zip




               You can compile the test program like this:







    g++ -O3 -fomit-frame-pointer -c test_timing.cpp
                       gcc -O3 -fomit-frame-pointer -o libco.o -c
    ../libco.c
                       g++ -O3 -fomit-frame-pointer test_timing.o
    libco.o -o test_timing




               Then just run test_timing that is produced, and let me
know what the output is, or if it segfaults.







> Really, you want a first-gen Core 2 Duo or newer.




               Yeah, it's pretty slow. Especially since v018. It used
to be easy to get 80-100fps with a 3500+.

[No archive available]
2008-02-14 13:54:00 +00:00
byuu
1194d3f9dc Update to bsnes v028r04? release.
New WIP. Windows binary included. I've added back
Scale2x support, and I also added a scanline filter for Snark. No, I
don't plan on combining them so you can do things like Scale2x +
scanlines. It's a 50% scanline filter. I may add 75% and 100% in the
future.

               Ah, and a while back I mentioned a certain software
filter I saw. Here is that picture:







    http://byuu.cinnamonpirate.com/temp/PhosphorSimTest1.jpg




 Unfortunately, I don't even remember where I found the image anymore,
let alone who made it. Does anyone here know how to recreate the
filtered image from the source image?

 I'd prefer to avoid baseless speculation, if you know how it is done
-- and better yet, if you can duplicate it -- please let me know. I
really, really like the filter and would love to add it to bsnes.

[No archive available]
2008-02-13 14:09:00 +00:00
byuu
89a1b3d65f Update to bsnes v028r03? release.
Posted a new WIP, which cleans up src/snes. I've completely killed all
the video filtering stuff, and cleaned up the rest. Only the audio WAV
logger remains. Didn't feel like moving that to the UI tonight.

 So far, I have the colortable and a direct filter moved to libfilter.
I'll probably just add Scale2X and a simple scanline filter for the
time being, but HQ2x and NTSC will have to be re-added before another
official release can happen.

[No archive available]
2008-02-12 13:45:00 +00:00
byuu
5a82cdf978 Update to bsnes v028r02? release.
Okay, I've posted a new WIP. Windows binary included.

             Changes:
             - Video output uses RGB888, rather than RGB565
 - Removed RGB modes from Xv. They're a major hassle, I can't test
them, and they didn't even work right. Maybe I'll try again in the
future
             - $(DESTDIR) added to Makefile
             - Increased Linux usleep idle delay from 20 to 20,000, so
bsnes appears to consume 0% CPU time when idle
             - Started moving src/snes/video to src/lib/libfilter. So
far, only the colortable has been moved over

 I held off on actually using libfilter's colortable. I'm intending to
break things completely here very shortly by eliminating
src/snes/video stuff, but I wanted to get a WIP out before doing so,
so that people could mess around with RGB888.

 Speed is going to be a little slower for Linux users who use the GLX
or Xv video driver. Very sorry about this. If you need to, stick with
v0.028 official for the time being.

             ---

 By the way, RGB888 is the bottom row. Thanks for playing. RGB888
doesn't make bright colors darker or vice versa, it avoids rounding
errors. It has the biggest effect on near-black colors, as before they
were getting crushed badly by the exponential curve gamma adjust. But
don't be fooled: really dark colors will still be much harder to see
than with the gamma curve turned off.

             Anyway, if you liked the top row more, then just adjust
the settings slightly on the raster settings tab :)

             EDIT: Neat, fglrx driver goes from 57.5fps to 59.5fps
with GLX. YMMV.

[No archive available]
2008-02-11 10:14:00 +00:00
byuu
52be510d2b Update to bsnes v028r01? release.
New WIP posted, Linux only. Need all the testers I can
get on this one, please.

 First and foremost, I spent about four hours figuring out how to
disable the screensaver on Linux. I tried XSetScreensaver,
XResetScreenSaver, XScreenSaverSuspend, DPMSDisable, synthetic
XSendEvent, and all of them failed miserably. I ended up getting it to
work with only one thing: XTestFakeKeyEvent. I send a fake keypress
every ~20 seconds. The key send is keycode (not keysym) 255. I don't
know of many 256-key keyboards, so I think that should be fine.

 Anyway, testing would be greatly appreciated. Please make sure the
synthetic key events do not interfere with your applications in any
way. Technically, the fake key send goes to whatever the active app
is. It shouldn't matter as the keycode used is undefined. I haven't
seen any GTK+ or Qt apps do anything with it, they just ignore it. If
any issues come up, then the best I can do is enable the screensaver
whenever bsnes doesn't have focus, and disable when it does have
focus. I think it should be fine, though. Totem uses the same trick
and nobody seems to mind. mplayer tries all of my above methods plus
bizarre fake messages and dbus commands to try and stop the
screensaver, and it still fails for a lot of people.

 Next up, I've extended the Xv renderer. It can handle RGB15, 16, 24,
32 and YUY2 formats now. It defaults to RGB ones if you have them. I'd
like if all of them could be tested. RGB15 and 16 should be perfect,
24 and 32 will likely have bad pointer arithmetic, but will hopefully
work.

 Need to set driver to "xv", and check what you have with "xvinfo". It
defaults to RGB16, then RGB15, then RGB32, then RGB24, then YUY2, then
it gives up and fails. In the future we can see about letting the
encoding be user-selectable.







> if your repository-maintaining friend doesn't have an amd64 install
> with which to build packages




               That's exactly it, sorry. Plus I don't want to burden
him more than I do already.

[No archive available]
2008-02-08 10:33:00 +00:00
byuu
8b7219bdef Update to bsnes v028 01 release.
[No changelog available]
2008-02-06 22:58:42 +00:00
byuu
926ffd9695 Update to bsnes v028 release.
Changelog:
    - OpenGL (with hardware filter mode support) and SDL video drivers added to Linux port
    - OpenAL (with speed regulation disable support) and OSS audio drivers added to Linux port [Nach]
    - SDL input driver (with joypad support) added to Linux port
    - Emulator pause option added
    - Added option to select behavior of bsnes when idle: allow input, ignore input or pause emulator
    - Added support to remap common GUI actions to key/joypad presses on the "Input Configuration" screen
    - bsnes will now clamp the video output size when it is larger than the screen resolution
    - GUI library has been enhanced, and renamed to hiro
    - Fullscreen mode now always centers video, rather than approximates
    - Fullscreen mode now works correctly on Linux/Openbox
    - Extra layer of abstraction in src/ui has been removed, as GUI lib unifies all ports anyway
    - Video, audio and input drivers unified into standard library, named ruby
    - All custom headers have been merged into a new template library, named nall
    - Makefile rewritten, vastly improved. Allows quick toggling of compiled-in drivers
    - Makefile: all object files now placed in /src/obj, binary placed in /
    - libco greatly enhanced, no longer requires an assembler to build [byuu, blargg, Nach]
    - libco SJLJ driver added; bsnes should now build on any Unix-derivative now (Solaris, OS X, PS3, etc) [Nach]
    - Fixed register $213e.d4 PPU1 open bus behavior [zones]
    - Windows port will not activate screensaver while bsnes is running [Nightcrawler]
    - Visual C++ target no longer requires stdint.h
    - And lots more -- mostly code refactoring related
2008-02-04 16:16:34 +00:00
byuu
a1389a2ba3 Update to bsnes v027r14? release.
> Anything is better than re-using an already well-established name
> (even a short acronym like "vai"), but that's just me.




               I was asking about eliminating the extra layer of
abstraction in the UI.

 But since you brought it up ... I'm sure vai has been taken before.
Quark certainly has been. Hell, BSNES was taken by some people trying
to port ZSNES to BeOS (they gave up). Given, none of those have
anywhere near the popularity of the programming language. But eh, I
_really_ don't care. I like the name, and nobody else in the world is
ever going to use any of my software libraries anyway, so I'll use it.

               Speaking of which, I hate the name miu for the GUI
library, it sounds stupid. So in the spirit of selecting **totally
random names** that are _certainly not associated with any licensed /
trademarked / copyrighted proper nouns_, **especially** not from any
_video games_ or somesuch; I've renamed miu to the **completely
arbitrary** name of hiro. Boy, I'm so creative and original with
naming.

               ---

               That said, new WIP up, with Windows binary.

 Windows users, be sure to set system.video to "direct3d",
system.audio to "directsound", system.input to "directinput".

               Linux users, "opengl", "openal" and "sdl" are
preferred. "xv", "ao" and "x" are safer fallbacks.

               Changes:

               - Finally found a problem with dots in folder names, it
screws with GNU make. So foo.bar has been renamed foo_bar.
 - Decided to drop the pointless duplications of folder names into
file names, such as miu.gtk/miu.gtk.button.cpp -> hiro_gtk/button.cpp.
Same for libco.
 - ruby is completed, all 13 drivers are in the ruby namespace, and
bound to the base ruby.cpp file. The UI just calls
ruby::video.driver("name"); to select a driver. Before v028's release,
omitting the name will select the default best-case driver. ruby is no
longer dependent on anything besides nall (the template library, for
those losing track in the sea of _arbitrary_ names.)
 - miu became hiro, as mentioned above. Like ruby, I wanted to remove
the need for platform-specific tests inside the UI for it. There's now
a base hiro.cpp file that will auto-select the best implementation and
compile it. Just build hiro.cpp on whatever platform you want and it
does the rest.
 - UI platform abstraction removed. src/ui/miu was moved to src/ui.
The two main.cpp files were merged into one. With the GUI wrapper and
hardware drivers moved out of this folder, it's quite orderly there
now.
 - More improvements to the Makefile system. New folder obj/
accumulates all of the object files now. Added streq(al) and
strn(ot)e(qual) to Makefile.string library. Improved the delete
command to support deleting from either obj/*.$(obj) with rm, or
obj\*.$(obj) with del. bsnes executable is moved up one folder above
src/ for both Windows and Linux now. The batch file doesn't perform
this copy anymore.
               - Killed the doc/ folder. Just a pointless, out of date
.dia file there anyway.

               Future plans:
 - I want to make ruby take advantage of nall/config.hpp, and output
to ~/.bsnes/ruby.cfg. This file will contain driver-specific
configuration settings. I may or may not add editing support for them
to the advanced window. Or maybe I'll be lazy and just throw
everything into bsnes.cfg.
               - Really need to add automatic driver selection to
ruby. Can't release it with "" defaulting to no driver.
 - I'd like to replace the god-awful GTK+ video driver (that spawns a
new window) with SDL video. Yeah, I know. At least with SDL_WINDOWID
environment variable hack, it will go into the main window. I'll
probably make this the default driver on Linux, since ATI can't even
seem to get X-Video right with their drivers.

[No archive available]
2008-02-03 10:12:00 +00:00
byuu
5263ffb7aa Update to bsnes v027r13? release.
Yeah, I'll probably worry about the axis stuff later. I didn't intend
to spend a ton of time on adding SDL input support like this, to be
honest. Though I guess I should have known better with SDL and Linux.

 Okay, new WIP with no Windows binary. There's really no reason to get
the WIP. The only change is renaming vai to ruby. That's right matz,
ruby. Deal.

 Moved the folder to lib/ruby from ui/vai. The main point is trying to
make it easier to use for other applications. Instead of having each
app include all sorts of platform-specific header files and manually
create the objects at runtime, it's all done for you now. Just
#include <ruby/ruby.h>, call ruby::input.init(const char *driver = "")
and use it. So far, only the input driver has been ported in this way.

 Note: if you use this WIP, you'll want to make sure system.input is
set to either "sdl"/Linux or "directinput"/Windows. It defaults to no
driver with "", for the time being.

 Once I finish the video and audio drivers in the same manner, I'm
strongly considering eliminating the "multiple UI" bindings, as my
Win32/GTK+ wrapper is pretty much meant to wrap all possible
interfaces into one. This means it would be harder to create a
standalone, GUI-less SDL or VESA2/DOS only port in the future, for
example. But I really don't have any plans to do that anyway. So it's
just needless separation of components, really.

 That extra separation layer was being blurred a lot recently anyway.
The config.cpp file was adding miu-specific GUI commands, where they
had to be to bind to interface.cpp, which binds to the core. Meh.

             So basically, I'm wanting to change the structure from:
             core <> abstracted UI <> miu, SDL, VESA2
             to:
             core <> miu

 Even with this, porting to pure SDL would still be doable in the
future, you'd just have more code to write to do it.

             Any objections?

[No archive available]
2008-02-02 11:58:00 +00:00
byuu
1744bcb99c Update to bsnes v027r12? release.
New WIP.

 I removed property.hpp, as I really didn't like it. Reverted Audio
wrappers to use cap/get/set method that Video and Input wrappers use.
Yay, consistency.

 Capped input.sdl to only poll up to six axes. I suppose if someone
really only has 2 or 4, and has phantom 5,6 axes, they'll run into
Glenn's problem. Meh. We'll wait for a way to configure vai settings
on a per-driver basis to work on that problem more. I was thinking of
just giving it the handle to either unique configuration class
objects, or to the bsnes.cfg one. Just dump all settings for all
(compiled-in) drivers in there, in case the user wants to keep
swapping between drivers.

 Added Nightcrawler's screensaver and monitorpower disable code. Happy
now? Note, I don't use screensavers, nor do I feel like playing for
ten minutes to verify. If anyone else could verify whether or not it's
working, I'd appreciate it. Note again, this won't work on X11, only
Windows.

 Improved the makefile a bit more for Visual C++. Disabled the warning
about passing "this" in a constructor. It's valid and safe C++, and
the only way to implement a bidirectional private implementation by
reference. The last warning is comparison between unsigned long long
and bool, which I can't see a problem with (it gives no warnings about
unsigned long and bool, either). Should I just disable that warning,
as well?







> It ended up being axis 6, but yes, that pinpointed it exactly.




 Oops, sorry. When there are two of something, I always have a really
hard time telling them apart (x/y, hidori/migi, edge/level
(sensitive), etc etc). Not sure why that is. Three or more choices and
it's never a problem.







> Would need porting for BSD gamepads however.




 If it doesn't support BSD, then I'm not really interested. I kind of
have to special case Windows (~95+% userbase), but I don't personally
want to waste my time writing Linux only code.

[No archive available]
2008-02-01 11:46:00 +00:00
byuu
6362044c05 Update to bsnes v027r11? release.
Alright, new WIP posted, Windows binary included.

 I've added the auto-pause setting. I removed the formerly useless
joypad selection comboboxes, as I want to stick those in the main menu
when they are ready anyway. It defaults to auto-pause, so that
discussion is moot now.

 Don't complain that three combo boxes are not natural compared to two
checkboxes -- I don't care. There are only three possible states, and
I like it the way it is. Thanks in advance.

 Nach, you have my humble thanks for your input today. This was
definitely a lot easier than I thought it would be with your help.

               For those curious, here's how things look at the
moment:

               [image]

 I also fixed up the CPU usage when paused. I tried to stress test as
many things as possible (manual pause <> auto pause conflicts,
statusbar update failures, toggling settings in real time, etc etc),
but I may have overlooked something. Rigorous testing would be
appreciated :)

               ---

 In other news, I completely rewrote the Makefile. It is now far more
advanced, and will allow you to easily remove vai modules. Once
removed, the dependencies on those modules will automatically be
removed. The source still needs to be updated to auto-detect non-
existent modules, but this is a step in the right direction.

               Take a look at some of my GNU make-fu:







    ifneq ($(findstring gcc,$(compiler)),) # GCC family
                       flags = -O3 -fomit-frame-pointer -Ilib
                       c = $(compiler) $(flags)
                       cpp = $(subst cc,++,$(compiler)) $(flags)










    ifeq ($(platform),x) # X11
                       miu = miu.gtk
                       vai = video.glx video.xv video.gtk audio.openal
    audio.oss audio.ao input.sdl input.x










    link += $(if $(findstring audio.directsound,$(vai)),$(call
    mklib,dsound))
                       link += $(if $(findstring
    audio.openal,$(vai)),$(call mklib,openal) $(call mklib,alut))
                       link += $(if $(findstring
    input.directinput,$(vai)),$(call mklib,dinput8) $(call
    mklib,dxguid))
                       link += $(if $(findstring
    input.sdl,$(vai)),`sdl-config --libs`)










    arch := $(patsubst %,$(call mkdef,%),$(arch))
                       objects := $(patsubst %,%.$(obj),$(objects))










    compile = $(strip \
                       $(if $(filter %.c,$<), \
                       $(c) $(1) $(rule), \
                       $(if $(filter %.cpp,$<), \
                       $(cpp) $(1) $(rule) \
                       ) \
                       ) \
                       )

                       %.$(obj): $<; $(call compile)










    video.glx.$(obj) : ui/vai/video/video.glx.cpp ui/vai/video/*
                       video.gtk.$(obj) : ui/vai/video/video.gtk.cpp
    ui/vai/video/*
                       $(call compile,`pkg-config --cflags gtk+-2.0`)




               Hahahahahah :)

[No archive available]
2008-01-29 07:42:00 +00:00
byuu
319b244af4 Update to bsnes v027r10? release.
New WIP posted.

 I downloaded a 64-bit Linux OS to verify that libco.x86-64.c worked
this time. Turns out the problem was that I declared "register stack =
*(long long*)to;" -- forgot the size qualifier, so it was being
truncated to 32-bits. Anyway, it works now.

 I also added two more GUI keys, one to pop open the load ROM window,
and one to pause emulation. Yes, took me eight versions, but I finally
re-added pause mode. It probably still consumes CPU time, not sure. I
don't really care, I'll fix it before release. The whole thing is
silly anyway, task scheduler is so easy to cheat. Add sleep(1) inside
the main loop and it states bsnes uses ~1-2% CPU time. As if.

               Windows binary updated, too.







> Unfortunately, it will be 64-bit and using Vista 64 Ultimate, so I'm
> not sure what all will be compatible in terms of software and
> emulators.




 32-bit software runs fine for the most part on Vista. bsnes works
there for sure. But if you want it 64-bit native, you'll have to
compile it yourself, as I have no idea how to make a 64-bit Windows
binary. Nor do I really feel like maintaining another build :/

[No archive available]
2008-01-28 06:27:00 +00:00
byuu
a3f1802845 Update to bsnes v027r09? release.
New WIP. No Windows binary. This one fixes the GTK+
fullscreen issue on Openbox completely. How do I know? Because I'm
running Openbox now to verify :P
               It's pretty spiffy, whole thing is only consuming ~5mb
of memory. Total mem usage sans the 'fox is ~40mb.

 The cool part with these changes is that video no longer flickers for
one frame when you toggle the menubar in fullscreen mode anymore. Not
even on XFCE.

 Just in case, verification always helps. Hopefully it'll work on all
the esoteric window managers out there, so long as they honor the
undecorate window request. You may have some small issues if not.

 I didn't need keepabove to get on top of my XFCE panel, even when I
run the panel in Openbox. I'd like to keep it off if possible.







    void pWindow::fullscreen() {
                       if(state.is_fullscreen == true) return;
                       state.is_fullscreen = true;

                       gtk_window_fullscreen(GTK_WINDOW(window));
                       gtk_window_set_decorated(GTK_WINDOW(window),
    false);
                       gtk_widget_set_size_request(window,
    gdk_screen_width(), gdk_screen_height());
                       }

                       void pWindow::unfullscreen() {
                       if(state.is_fullscreen == false) return;
                       state.is_fullscreen = false;

                       gtk_widget_set_size_request(formcontainer,
    state.width, state.height);
                       gtk_widget_set_size_request(window, -1, -1);
                       gtk_window_set_decorated(GTK_WINDOW(window),
    true);
                       gtk_window_unfullscreen(GTK_WINDOW(window));
                       }




 I also fixed the "esc" -> "escape" keysym for menu toggle, and
updated the x86-64 target with OpenGL + SDL input stuff. Thanks
everyone for the awesome feedback!







> EDIT3: How come you haven't added the icon to the window? Need to
> write another class for handling it (for MIU)? Adding the following
> to the end of pWindow::create() in
> 'src/lib/miu.gtk/miu.gtk.window.cpp':




 Yes, I need a way to do the same in Windows. Ideally, I need a way to
embed the icon inside the EXE, and have an API that allows me to set
the icon both on Windows and Linux from it. I'd prefer to not require
another external file for bsnes binary releases.

               Thanks for the GTK+ code, though. It's a step in the
right direction.







> I tested the linux version of bsnes with my Radeon Mobility x1400,
> and I don't get any video inside the bsnes window. I'm running
> Ubuntu, and I've set up all the ATI driver stuff, AFAIK (Compiz, at
> least, works).




 Aw ... well, thanks for trying. I kind of figured it wouldn't work.
Perhaps ATI doesn't support GLX ... I honestly have no idea. I'll look
into it.







> What other package(s) do I need to install to correct these
> warnings/errors?




               libsdl1.2-dev







> My first problem when running this WIP is that my statusbar is
> black. All black. No one else has complained, so this must just be
> happening over here... any ideas why? Also, fullscreen won't work
> for me... gameplay freezes for a moment when I toggle it and then
> continues windowed, as normal.




 Sigh. I fixed this a while back. Certain GTK+ themes weren't painting
the background of statusbars, so I embedded the statusbar inside an
event box. I don't know why it still isn't working for you. It seems
to work for everyone else now ...







> Secondly, when attempting to map my gamepad, every single key logged
> correctly... except my right directional. What? Weird.




 Good question. The SDL docs say axis 0 = x, axis 1 = y. but the two
thumbs are axes 2, 3 left and 4,5 right. The left thumb uses 2 for X
and 3 for Y, but the right uses 4 for Y and 5 for X. Since the API has
no way to tell you what direction an axis is in, I decided to play it
safe and do axis&1 over all axes. I guess I'll just hardcode for D-pad
+ two thumbs in the next version by swapping 4 and 5 ... no idea how
other apps do it.







> Finally, turning on Scale2x with or without opengl as video does
> this to the Donkey Kong Country intro (note the statusbar)...




 Longstanding issue. Never modified the hq2x and scale2x filters to
support hires modes. Only direct and NTSC do. Hoping to bypass the
issue with pixel shaders in the future. That, or wait until I cleanup
the video filter code and get it out of the core.







> Does GtkSocket not do what you're looking for?
>                    http://www.gtk.org/api/2.6/gtk/GtkSocket.html




 Nah, that's for other processes. I just need to convert an X11 handle
back to a gtk_drawing_area GtkWidget. Sounds weird, but miu only has
one handle() function for cross-platform reasons. So I make that
export an X11 handle (that Xv and OGL take) rather than a GtkWidget
handle (which requires gdkx.h header to extract the X11 handle from in
a safe manner.)

[No archive available]
2008-01-22 07:37:00 +00:00
byuu
4370acae2e Update to bsnes v027r08? release.
Okay, new WIP. This time there's a Windows binary.

 I improved input.hpp a lot, and now InputManager will scan the
joypads as well. DirectInput is fixed, so the Windows port works
again. Now that the InputCaptureWindow stuff is cleaned up, I made it
only capture joypad assignment keypresses when that window has focus.

 I'm also planning to make a "fast assign all keys" button or
something, like I used to have. Not sure how I want to do that just
yet.

               I also tested triggering UI events through the joypad,
it works great :)
 Now I just need to add entries to Input Configuration window for each
UI action. Hmm, should I list the UI entries above or below the SNES
joypad entries? (eg ui.fullscreen, joypad1.up, ... or ...
joypad2.start, ui.fullscreen?)

 The rest of my time tonight I spent working on my cross assembler,
xkas. Added sublabels to it, and some more parsing improvements. It's
getting messy already, though. Trying to write complex grammar parsers
in C++ usually does. But it has to be pure C++. No yacc, flex, etc.
So, I'll have to go back through and find redundant code to factor
out. Why would you care about xkas? Well, the sooner I get that done,
the sooner I can help out the Mother 3 translation project a bit more.
GBA cross assemblers suck for ROM hacking.







> You have a big disclaimer about how it's perfectly legal to use "_0"
> as an identifier inside a namespace... and then never actually do
> it.




 I was using it for joypad button IDs, but I just decided to go with
button_0n. I removed the comment in the latest WIP. Also added a way
to index joypad IDs at runtime, and packed the enums into a linear
list.







> Apps that process input according to 'the characters printed on the
> key' are my pet hate because I the Dvorak layout, so Z and X or WASD
> are not nearly as convenient as you might otherwise expect.




 Would require supporting every keyboard in existence, and needing
some sort of lower-level stuff to translate keycodes to raw keyboard
IDs. The only issue you'll have to reassign your keys one time on
first startup :(

 I envy you though for managing to switch to dvorak. I tried for a
really long time, I could never get above ~40wpm, whereas I get
~110wpm with qwerty now. I think programming is the worst part, all of
my brackets moved? Well, that or the fact that all apps use
Ctrl+C/X/V/Z. That hack to make Ctrl+ use qwerty on dvorak doesn't
solve the underlying issue, either.







> If there is any other areas in the bsnes ppu rendering code that you
> want me to verify in a similar fashion, please tell me, so that I
> can try and code something to prove if it is right.




               Hahah, there sure are :)

 I think the biggest one is that I've yet to test setting BG3 tilesize
to 16x16 when using Mode2/4/6's offset-per-tile mode. Does it affect
indexing? I don't think that it does. May want to also toggle BG1/2
tilesize, just for fun, but I'm almost certain I have that right
already.

 Don't worry about it if you're busy. It's obviously not a big deal
since no game in the world uses the effect (that, or I already emulate
it correctly), and I'll no doubt get around to it if I ever rewrite
the PPU emulation.

               Either way, many thanks for helping me with this :D

[No archive available]
2008-01-17 06:48:00 +00:00
byuu
5a804eac58 Update to bsnes v027r07? release.
Okay, new WIP.
 But before you download it ... there's no Windows binary, because I
haven't finished porting some changes over to DirectInput yet. So it
won't compile just yet.

             But, here's the changes anyway:
             - fixed up the recursive descent math parser, it should
reject 100% of invalid math now
 - added a new header, new.hpp, by Nach. This allows for uint8_t
*buffer = new(zeromemory) uint8_t[65536]; //zeromemory ==
memset(buffer, 0, 65536);
             - updated input.hpp more, and removed keymap.hpp
completely -- this is why DirectInput is broken right now
 - rewrote all of inputmgr.cpp, and InputCaptureWindow. The really
ugly, hackish code is now gone. InputCaptureWindow no longer needs to
hijack the main UI event loop to catch keycodes. Instead, a ~20ms
polling occurs that will alert event::key(up|down) of key changes. The
really, really good news about this, is that it also catches the UI
keypresses now, too. That means that I can now map GUI events to the
joypad, or alternate keys!! Expect that within the next release or
two.
 - ran krom's mode7 test -- holy hell, he has good eyes o.O -- took me
about 20 minutes to definitively tell which output looked correct on
my SNES. He was right of course, and I trusted him, but double
verification is always nice, right? Removed TRAC's theorem from the
mode7 code, and spruced up the formatting in that file a bit.
             - **a real emulation change!!** zones recently pointed
out that anomie figured out that $213e.d4 was PPU1 open bus. I'm
pretty sure I was really thorough when I initially added PPU1+PPU2
open bus (even verified CGRAM.d15 open bus (-much- harder than it
sounds)), but I guess I missed a bit ... odd. anomie also said that
$213e.d5 is basically tied to GND, so that should mean it always
returns 0. I read previously that it was some weird "no PPU activity
for ~40 frames" bit or something, but I don't even remember where I
saw that. I trust anomie anyway, so that means all PPU register status
bits should be accounted for. Thanks for the heads up, zones! :) Now,
of course, it's _extremely_ minor and it won't fix any games (there
aren't any known bugs anyway), but it's still nice to actually fix
something in the core for a change.

[No archive available]
2008-01-16 07:59:00 +00:00
byuu
3b65b50aea Update to bsnes v027r06? release.
Double post! Better to separate this, I think.

             Okay, new WIP lacks Windows binary, and only changes one
header.

 I figured it might be fun to show you guys what I've been doing as
far as code cleanup goes, something a little different, you know?

             Okay, here was the config.hpp file from the last WIP:
             http://byuu.cinnamonpirate.com/temp/config_old.txt

             And here is the new one:
             http://byuu.cinnamonpirate.com/temp/config_new.txt

             Or for those who do not know C++ ... :)
 Like a standard library should be, I've reverted UpperCase to
lower_case, I've converted everything to const-correctness, I've
hidden everything that should not be public, improved the code
formatting, added proper casting, removed the needless template
overloads all over the place, converted the variable names from
incomprehensible gibberish (idef, ifmt?) to clean, understandable
alternatives (default_value, type), removed needless copying of const
char* data, which means no more destructors needed, and added proper
int -> unsigned types when indexing arrays.

 The only thing left is to add better-named integer->string conversion
routines to string.hpp, to get rid of the ugly sprintf code.

[No archive available]
2008-01-09 06:53:00 +00:00
byuu
a85ff8c437 Update to bsnes v027r05? release.
Another WIP, this one's really just for myself to look
over at work tomorrow.

 Changed any.hpp again to not auto upcast fundamental types, as it
causes problems such as downcasting references to long doubles and
such. Sucks how limited the any type is by forced casting 100% of the
time, but whatever ... no endian issues possible now, at least.

 I added property.hpp and bound that to the Audio class (not to Video
or Input yet). It's a lot more complicated than the old integral
identifier cap/get/set functions, but I need the char*-named list
functionality to allow changing driver-specific settings from the GUI
one day. Not too much done there yet. Need to work on it more, I'd
like to make bconfig use property.hpp rather than the IntegerSetting +
StringSetting classes. Tried to make property.hpp read in a config
file without bstring, talk about pain ... ugh.

 Tried to move bstring into nall, failed miserably. When strcpy(char*,
const char*) is in the global namespace and strcpy(string&, const
char*) is not, the compiler gets angry. Not going to work. Really
should go object-oriented entirely and ditch libc functions, but ...
that's a _lot_ of code rewriting on my part. Need to think about it
more first.

 Removed bbase.h dependency from bstring, miu and xkas. Now I just
need to do something about bkeymap.h, and things will be looking a lot
better for code sanity.

               Nach wrote the _seventh(!!)_ libco driver tonight, an
implementation using setjmp / longjmp. Pretty neat, overhead is ~20x,
which puts it only slightly worse off than Windows Fibers on my
machine. Using it in bsnes slows the emulator down by <1%, but it
should be portable across all Unix-derivative systems now. This means
eg a PS3, Alpha, SPARC, etc port should be completely doable now, just
need someone to compile it.

               Planning to position libco as a competitor to GNU Pth,
so that leaves me with:

               SDL -> vai
               wxWidgets -> miu
               GNU Pth and pthreads -> libco
               boost and Loki -> nall
               std::string -> bstring

               Good times. Now I just need to register
inventedhere.org for all of these libraries.







> but it's pointless since the sound quality of the S-DSP isn't good
> enough to make a difference.




 The only thing we could possibly bypass would be the driver / API
resampling our audio (eg 32khz -> 44khz native). Running each SNES
channel through its own hardware channel is just silly. Either use an
API that bypasses the mixer, or don't.

 And yes, there's lots of ways to "enhance" the audio. Replacing
gaussian with a higher end interpolation, bypassing the clipping, etc.
But then you end up with "better" (in most cases), but less accurate
sound.







> is anyone currently working on an enhancement snes emu?




 ZSNES adds cubic spline audio interpolation, SNES9x adds "hi-res"
mode7, ZSNES/XBOX adds rumble pad support to most games.

               Other than smaller things like that, not really.

 I've talked about adding things like rumble, a new MMC to map more
than 64mbits, CD-audio and video playback capabilities. Nobody seemed
all that interested. Eh, maybe if someone finds and sends me one of
those SNES CD player addons used by that one English teaching game,
I'll add support for that to bsnes and then rig something like Der
Langrisser to use it :P

[No archive available]
2008-01-02 07:31:00 +00:00
byuu
a15d15047c Update to bsnes v027r04? release.
Okay, I posted a new WIP. This one's source only again,
since the Windows port is still unchanged.

 I went through and used std::min + std::max, rather than my own
#define, for the sole benefit of getting Nach's JMA code to compile
again (JMA includes a C++ standard header that doesn't like you
#defining min/max, apparently). I was kind of cheap with it though,
max(0, min(10, value)) -> max(0U, min(10U, value)), etc.
 Geez, std::min/max can't even cast between uint16 and uint32. What a
joke, I'll have to write my own that takes advantage of type traits.

 I also started killing off the "bheader.h" files. Since 90% of them
are just template classes, I figure I may as well stick them all in a
namespace and make something akin to boost / Loki. I'm calling this
one nall (I love making up all these names, lately). I also use gcc -I
to point to it, so you get #include <nall/array.hpp> instead of
#include "../../../lib/barray.h", much nicer.

 Taking advantage of the new template library, I added any.hpp
(generic object container), traits.hpp (type traits) and static.hpp
(static assert, if), and with that, I made stdint.hpp, which is a C++
implementation of stdint.h. Since stdint.h is part of C99, it isn't
included with all compilers (eg Visual C++). By using sizeof() and
static_if, I was able to make my own compiler-independent version of
this file. Thus, the dependency on stdint.h was removed.

               I'd be very interested in feedback on anything in nall/
(it's located in src/lib).

 Specifically, could someone with a big-endian machine test any.hpp?
I'm worried that downcasting will reverse the order of data read back.

               Example test app:






    #include <stdio.h>
                       #include <nall/any.hpp>
                       int main() {
                       nall::any t = 0x01020304;
                       printf("0x%x\n",nall::any_cast<short>(t));
    //should print 0x0304
                       return 0;
                       }










> Please byuu, can you extend the API, would you be so kind?




 Of course, I want vai to be used for more than just SNES emulation.
Though I've yet to get anyone using any of my libraries before, so it
may be a fairly pointless endeavor.

               It'll take me some time, though. I'm working on a lot
of other stuff first.







> Anyways, byuu, here's what I wrote of the OpenGL renderer so far, to
> prove its very much being worked on.




 Really cool! My only concern is the use of Win32-specific code
(header, GetForegroundWindow(), HDC stuff, setting up the pixel format
stuff) ... no idea how this is going to compile on Linux :(
               I don't know the Linux equivalents to all of the
Win32-specific stuff being done.

 Nonetheless, please take your time. I'll check it out when you have
the Win version finished. Thanks a million for making this :D







> What about guys like me who just stick to Intel HDA.




               Hah, I do the same. I'm not going to spend more on my
sound card than on my mainboard that comes _with_ onboard sound. HDA
sounds just fine to me :/

[No archive available]
2008-01-01 19:24:00 +00:00
byuu
f77aca7172 Update to bsnes v027r03? release.
I have a new WIP up. Again, this one has only source, as nothing has
changed on Windows since wip01.

 This time, I've just cleaned up the OSS and OpenAL drivers. Nach will
probably want to kill me, since by cleaned up, I mean "removed lots of
not-so-helpful comments and safety checks", but I intend to add them
back. Before v028, I'd like to have vai init() functions return a
boolean success value, and have bsnes continue to fall back on lesser
drivers until there are none left, in which case it won't use one. But
it will keep the program from crashing.

 Also, I tried some black magic on the OSS4 support. Because
soundcard.h is included in a different location than the OSS3 one, I
tried manually defining the new SNDCTL options and invoking ioctl
regardless of OSS version. This is supposed to be safe -- the ioctls
should just fail silently and it will behave just like OSS3. Let me
know if you have problems compiling or using the driver with OSS3,
especially on non-Linux boxen.

             > Will you update the readme with recommendations for
which sound driver to use on which system?

 I suppose I can do that. I was planning on writing up an article
about OSS4 and such, perhaps I can just link to that in the readme.

 > I changed it to set_background_color(0, 255, 0) and sure enough I
had a green statusbar. The main window background color was still
black though. Assuming that set_background_color() is meant to be used
for the main UI this is very odd.

 Okay, here's how this works. Inside the main window, there is a view
control, which is a gtk_drawing_area(). I draw the video to this. When
bsnes is in windowed mode, obviously this control fills the entire
window. And the view control draws a black background by default. But
when you go fullscreen, the view area centers itself on your screen
(or tries to, some issues in GTK+ size requests render it non-
perfect.) Now there's the problem that the window itself is exposed on
the sides. Therefore, I have to set the window background to black
here, otherwise it will show up gray, which is _very_ distracting in
fullscreen mode, to say the least.

 Now, I only tell GTK+ to set the window to black. The reason I do
this is because just setting the formcontainer to black has no effect,
since containers do not draw a background. As for why that is causing
your statusbar to render black ... good lord, I have no idea at all
o.O

 I don't know what to do to fix this, unfortunately ... but at least
we now know where the problem is so we can research it. Thank you very
much for tracking that down [vEX], I realize my request to have an
end-user look into that was unreasonable, but it's very much
appreciated.

 > EDIT2: After some testing it doesn't appear that bsnes was guilty.
I can't reproduce the memory consumption, but it could be all the
recompiling bsnes that somehow ate all my memory.

 bsnes does appear to have a tiny memory leak at the moment. It loses
about ~100k a minute on me. I'm not sure if it's specific to the Linux
port or not. This will certainly be a hard one to track down in such a
big program.

             > I believe OpenAL is pretty smart in frequency handling.

 Definitely. I don't really like complex APIs, but the buffering
system in OpenAL will actually come in handy. I failed with
DirectSound, but maybe with OpenAL I can manage to resample audio --
maybe even let OpenAL do the resampling for me by calculating the
frequency as a measure of "how many samples should have been created"
versus "how many actually were."

 That would be awesome. Combine that with OpenGL triple buffering, and
SDL/libjsw joypad support, and wow ... I'll have something really,
really usable :)

[No archive available]
2007-12-26 13:03:00 +00:00
byuu
c32195cbd6 Update to bsnes v027r02? release.
Okay, here's the deal with sound.

 wertigon's initial OpenAL driver was incomplete and produced no
audio, and _willow_'s had some Windows-specific bindings.

 So, Nach took those, some OpenAL sample code, and some other
application's OpenAL code and produced a working driver for it. Then
Nach and I refined the driver -- I got rid of the crashing on exit and
frequency changing, and both of us wrote new sample() functions.
Nach's is vastly superior on CPU resources, so we'll probably go with
that one.

               That code can be found here:
http://byuu.cinnamonpirate.com/temp/audio.openal.cpp

               This code wouldn't be possible without the help from
wertigon, _willow_ _and_ Nach, so many thanks to everyone, and I'm
sorry I wasn't able to go directly with anyone's specific OpenAL
driver. Linux compatibility was a big concern here. You'll all be
getting full credit in the source and documentation for bsnes v0.028.

               ---

 Now, as for the driver itself. It should work on Windows now with the
sample() and init() corrections, but maybe not. I don't have the means
at the moment to build a Windows binary with it, but maybe I can in
the future.

 But anyway, I don't intend to compile in OpenAL/Win support by
default with bsnes, but rather leave it as an option for those who
compile it themselves. Why? Because Windows does not come with
alut.dll and OpenAL32.dll. I don't want to require another download to
use bsnes, and I don't want to package an extra 300kb of DLLs with it
either. Plus, it doesn't seem to be working too well for most people
anyway thus far.

 Windows does come with DX9, and basically nobody has problems with
DirectSound. It's great, it has very low latency, and it seems to work
on everyone's sound cards, unlike the OpenAL stuff. So it's really not
needed for Windows.

               ---

 However, on Linux, OpenAL has a lot of good points. Unlike with
Linux/OSS3, OpenAL backends to ALSA which supports software mixing.
Meaning audacious and bsnes can run at the same time. And OpenAL has
much lower latency than libao, as well as the ability to disable speed
throttling when necessary.

               But! The OSS4 driver, with SND_DSP_COOKEDMODE,
absolutely _destroys_ even the OpenAL driver. In fact, it's even twice
as good as the DirectSound driver on Windows! No joke!

               From http://wiki.freebsd.org/RyanBeasley/ioctlref :






> ... this ioctl is meant to give processes direct access to the
> hardware buffer, giving the application the most control possible
> (ex: minimizing latency by avoiding in-kernel processing).




 With this, I get roughly ~15-20ms latency, at the very most, with
bsnes. It skips kernel processing entirely! It's hard to even describe
such a low latency. I've never heard Link's sword sound effect start
so quickly. It's really quite impressive. Remember when kode54 was
talking about ASIO or kmixer or whatever? That super low latency
kernel-level audio setup that bypasses the kernel and goes directly to
the sound card? This is it, but for Linux. It's that good.

 But the problem, of course, is Linux' obsession with ALSA, even
though OSS4 is GPLv2 now (and not to mention portable). ALSA is, of
course, total garbage. Anyone who's programmed for it knows that.

 It's very easy to install OSS4, download a DEB package, double click
it, hit install and reboot. But the problem is, many Linux distros try
their best to kill OSS now. Lots of apps are compiled by Linux distro
vendors to only support ALSA, so it does cause some problems, and you
have to reconfigure many apps to use OSS afterwards, so it's not a
very good solution to make bsnes default to the OSS driver.

 Further, because ALSA is so terrible, it causes the OpenAL driver
(which is really just a wrapper to ALSA here) to suck, and it causes
lots of static in the sound. And ALSA's OSS emulation causes severe
video lag -- bizarre, but it has something to do with the blocking
mechanism in ALSA. Only installing OSS4 fixes this. For both drivers,
in fact.

 So, because of ALSA's pathetically poor emulation of both OSS and
OpenAL, I can't default bsnes to either of these drivers. Therefore, I
have to leave the libao driver as the default, but I really recommend
the installation of OSS4 (if you haven't gotten that hint already) if
you really want the best audio possible, and don't mind losing a
couple of your favorite ALSA-only apps. If installing OSS4 is too much
of a plunge, then I still recommend experimenting with the OpenAL and
OSS (in that order) drivers under ALSA. If they work good, great. If
not, sorry, it isn't a problem with the bsnes drivers. You'll have to
stick with libao and it's terrible latency and forced blocking. Unless
someone else wants to write an ALSA driver. I have no intentions of
programming for yet another single-platform API, myself.

               ---

 With all of that said, I have a new WIP up. I'll send the link to any
Linux users who want to test it, as well. Feel free to ask.

               This WIP is source code _only_ (nothing changed on
Windows), and has both the new OpenAL and OSS drivers. Testing would
be greatly appreciated.

[No archive available]
2007-12-25 17:54:00 +00:00
byuu
161366df9b Update to bsnes v027r01? release.
I posted a new private WIP that adds the new statusbar. But much more
importantly, thanks to Nach, the Linux port now has an OSS driver.

             It's current set as the default. You can get ao again by
setting system.audio to, yep, you guessed it, "ao".

 Would some Linux users mind giving it a spin? For me, it appears to
be blocking and causing serious video lag (xv [XV_SYNC_TO_VBLANK=0] or
GTK+ video, 60hz monitor, speed regulation = normal). Not happening
for Nach ... it's quite possible the problem is just on my system.

 The complete and utter lack of perceived latency lag though, makes
this sound a million times better than the ao driver.

[No archive available]
2007-12-23 15:25:00 +00:00
byuu
4c43e85141 Update to bsnes v027 release.
This version replaces libui with miu -- a new GUI wrapper library, and cleans up large portions of the source code.
Unfortunately, the GUI rewrite took far, far longer than I ever imagined. As a result, no work has gone into the core emulation for this version. But with the GUI rewrite out of the way, that should change in the near future. And thanks to the new UI library, I can now begin work on adding a cross-platform debugger to bsnes, at long last.
Changelog:
    - Major source code cleanup (lib/, ui/miu/, ui/vai/)
    - Cheat code editor was broken in v0.026, this is now fixed
    - Cheat code file format simplified for human readability
    - Makefile install target improvements [belegdol]
    - libui replaced with miu GUI library
    - Custom video / audio / input drivers replaced with vai HW library
    - ppc and ppc64 libco targets added [Vas Crabb]
    - x86 and x86-64 libco targets now work on OS X [Lucas Newman]
2007-12-22 18:26:54 +00:00
byuu
9da42c18c3 Update to bsnes v026r04? release.
Another WIP. Consider this one v0.027 RC1.

             Bugs fixed:
 - cheat code editor works once again -- cart/ was not loading or
saving the files, and memory/ was not reading from it. Yeah, it was
completely broken in v0.026
 - miu/Win supports window.set_background_color(). The trick was to
capture WM_ERASEBKGND and use FillRect to draw the background myself.
 - miu/Win menubar toggle in fullscreen mode works as expected now for
me. Testing would be appreciated. A total shot in the dark, I tried
using SWP_FRAMECHANGED when resizing the windows, and it worked. It
seems to be an issue due to having two windows that are both set to
use the same menu (I have a hidden window I use for resize-purposes
only, because AdjustWindowRect doesn't work right on multi-line menus,
but the resize window is never visible.) I'm not sure exactly why
SWP_FRAMECHANGED fixed the problem, or why it wasn't needed in libui,
but it works, so I'll take it.
 - make install target uses "install" rather than cp+chmod, but
belegdol unfortunately removed his makefile patch, and I don't recall
where $(DESTDIR) and $(PREFIX) are supposed to go, so those aren't in
there yet ... belegdol, could you please repost that? You're of course
free to change my makefile with your packages as always in case it
gets missed before v027.

             Bugs remaining:
 - D3D renderer is still acting weird. If you start at 256x224 window
size, then the point video filter never works. If you resize to a
larger window and back to 256x224, the video image is linear filtered
no matter what. I tried to fix this tonight, but I had no luck. I'm
really not sure what's wrong, I don't think it's ever really worked
right. Should I fallback on the DDraw renderer for the next release?
It lacks the point filter mode (DDraw lacks an API to control mag
filtering), but that's it. Also, mudlord, PM me if I haven't given you
my WIP URL and you wanted to look at the latest stuff. I can never
remember who I gave the link to or not.
 - system.video / audio / input are not checked, so you get the
compiled defaults only. All vai drivers have now been ported, however.

             I changed the cheat code format. It is now:
             code = status, "description" \r\n

             Or for an example:
             7e1234:56 = enabled, "Infinite Lives"
             7e1235:67 = disabled, "Infinite Health"

 A little easier to read. But maybe still not perfect. I'd really like
to unify the .cht file format with other SNES emu devs ... I don't
want to use a binary file format like ZSNES and SNES9x does.

 I tried testing log audio data -- it seems to be working for me both
on Windows and Linux. FitzRoy, maybe the file isn't going to the
folder you are expecting? Or maybe I fixed it and didn't realize it?
Hmm ...

             Anything else I'm forgetting before a new release? Anyone
see any new / show stopping bugs?

[No archive available]
2007-12-20 10:43:00 +00:00
byuu
d115c7f6aa Update to bsnes v026r03? release.
Another WIP. This one builds on Windows and Linux, and the binary has
the terminal window disabled.

             Bugs fixed:
             - Added WM_ENTERMENULOOP message. Fixes audio looping for
the 37th time since I started on bsnes.
             - Esc toggles menu properly
 - F11 fullscreen centers, but only to the screen, not to the window
(meaning when the menubar is visible, it isn't really centered) --
this is because GTK+ does not return the correct widget size after
calling gtk_window_fullscreen() for up to ~200ms after processing all
messages via gtk_main_iteration_do(), and thus I can't make a
window.get_size() function. I really hope
GetSystemMetrics(SM_CXSCREEN) and gdk_screen_width() only return the
width of the active monitor, and not both for multi-monitor setups
 - Background of main window is black on Linux only. Only one
background brush per class for Windows. It may end up staying gray on
Windows for the next release ...
 - miu/Win enable/disable works. Even for menu items now, so I can
disable features that aren't supported by certain drivers now.

             Bugs remaining:
             - bsnes/Win background in fullscreen mode is gray --
quite ugly
             - D3D still blurring images even with perfect multiplier
             - cheat code editor still doesn't load .cht files on ROM
load

             New bugs:
             - bsnes/Win menubar is ultrafucked in fullscreen mode if
you toggle it on and off with esc. I have _no_ idea what the hell is
up with that. Code to show and hide the menu is identical to
libui/bsnes v026. Not sure I can fix this one. Basically, when the
menu gets toggled back on, clicking it does nothing, and if you press
alt, it will pop up the menu, but it will be _below_ the visible
menubar, so you end up seeing two of them. And you can only access the
new menubar via keyboard. Weird stuff ... could use some help here.
Anyone ever seen or heard of anything like this before?
             - I still need to work on that makefile cp+chmod ->
install thing for belegdol, I think ...

[No archive available]
2007-12-19 14:39:00 +00:00
byuu
2efce0fd83 Update to bsnes v026r02? release.
New WIP. Much, much closer to release quality. Linux port (probably)
won't compile at the moment due to minor changes to miu and vai. I
left the console enabled for this WIP.

             Bugs fixed:
             - Windows always appear at 0,0 instead of centered
 - Input capture window doesn't actually read anything. I actually can
get this working now, I just don't like the hacky way I did it before.
             - miu doesn't send Key events, so no F11 / esc shortcut
keys.
 - miu/Win is still missing some event messages, so some controls may
appear unresponsive. miu/Linux should be complete.
             - miu/Win may still send duplicate messages in some
cases, like that old log audio option bug was doing
             - miu lacks an on_show event, so the config window can't
set focus to the listbox on show just yet
 - bsnes will no longer crash when you try and load a GZ / ZIP / JMA
file with the support not built in (it obviously won't play the games
either) [Richard Bannister]

             Bugs remaining:
             - D3D still blurring image, haven't looked at it yet
 - Cheat code list never populates when loading ROM, probably doesn't
save either (I probably removed that code when rewriting cart/ and
memory/ a while back)
 - miu doesn't emit WM_ENTERMENULOOP, meaning audio cycles when going
into the menu. I wish there were a way to make it pre-emptive like
GTK+ without needing multiple threads ...

             New bugs:
             - Esc doesn't toggle menu yet
 - F11 fullscreen doesn't center, and window background is gray. This
will be tricky, as I only have one RegisterClass() in miu, but you can
only have one HBRUSH per class. Hopefully there's a window message I
can hijack to add back window.set_background_color().
             - miu/Win enable() / disable() doesn't work -- input
config dropdowns active, despite them not working yet

 Other than that, any new bug reports would be appreciated. I hope to
have v027 out by Sunday, but I may not make it in time.

[No archive available]
2007-12-18 12:29:00 +00:00
byuu
f6732133e7 Update to bsnes v026r01? release.
Alright, it's been a full month now since the last private WIP.

 I have Direct3D, DirectSound and DirectInput all working on the
Windows port now; and Xv, GTK+ Video, libao and XInput working on the
Linux port, so now's a good time for a beta.

             Note that countless things are broken, still.
             - D3D still blurring image, haven't looked at it yet
 - Cheat code list never populates when loading ROM, probably doesn't
save either (I probably removed that code when rewriting cart/ and
memory/ a while back)
             - Windows always appear at 0,0 instead of centered
 - miu doesn't emit WM_ENTERMENULOOP, meaning audio cycles when going
into the menu. I wish there were a way to make it pre-emptive like
GTK+ without needing multiple threads ...
 - Input capture window doesn't actually read anything. I actually can
get this working now, I just don't like the hacky way I did it before.
             - miu doesn't send Key events, so no F11 / esc shortcut
keys.
 - miu/Win is still missing some event messages, so some controls may
appear unresponsive. miu/Linux should be complete.
             - miu/Win may still send duplicate messages in some
cases, like that old log audio option bug was doing
             - miu lacks an on_show event, so the config window can't
set focus to the listbox on show just yet

             Any bugs outside of this that seem serious, please tell
me about. Otherwise, I'm working on the rest still :/

[No archive available]
2007-12-16 10:08:00 +00:00
byuu
95547f4ff8 Update to bsnes v026 release.
- Major source code cleanup
    - Completely rewrote memory mapper to support runtime MMCs
    - Updated S-DD1 MMC to use new memory mapping interface
    - Improved S-DD1 emulation, thanks to information from orwannon
    - Added support for SameGame -- load via "Load Special -> Load BS-X Slotted Cart" menu option
    - Completely rewrote cartridge loader to support BS-X, BS-X slotted carts and ST carts
    - Created custom dialog windows for multicart loading
    - Improved generic memory mapper, which eliminates the need for cart.db [Nach]
    - Added BS-X slotted cart detection to generic memory mapper [Nach]
    - Linux port will now ignore keypresses when window is inactive
    - Linux port will use much less CPU power when idle
    - Added detailed compilation instructions to Makefile for Linux port
    - Added "make install" target and PNG program icon for Linux port
    - Switched Windows compiler to MinGW/GCC4
    - Windows executable is now packed with UPX to decrease filesize
    - Removed .ufo, .gd7 and .078 ROM extensions; added .bs extension
    - Added preliminary support for the BS-X base unit, BS-X base cartridge + MMC, and BS-X flash I/O
2007-11-18 21:49:20 +00:00
byuu
4f5bdfe347 Update to bsnes v025r12? release.
New WIP is up.

 I fixed PSRAM size, it's now 512kbytes. SRAM was correct before at
32kbytes. I also now save these files to "bsxbios.psr" (PSRAM) and
"bsxbios.srm" (SRAM). I honestly don't know if the PSRAM is supposed
to be battery backed or not. If it's not, it'll be easy enough to
remove. I imagine it is, because that's where you'd store your games
on if you lacked a flash cart. Would be pretty lousy to have it wiped
every time you power cycle.

 I also save the PSRAM+SRAM data only once, just as a real BS-X cart
would work, and it also makes the Ancient Tablets series work with no
file renaming needed. I may add an option later to save these files
separately per-game.

 BS-X support overall is still pitiful. bs-x.txt doc says $03 has to
be set to mirror PSRAM, SNES9x thinks it needs to be clear. Neither
know whether it affects just $60-6f or also $70-77. bs-x.txt doesn't
say to mirror hi/lo on PSRAM based on $02 setting, but SNES9x seems to
try it. LoROM doesn't map well into 64k granularity banks. Still don't
emulate $0c/$0d flash i/o register enable. Base unit is still
completely unsupported, and it's apparently needed for some games. And
I have no intentions of including an internal database of times to
manually hack the clock (even while the system is running!) ala
SNESGT. I'm just going to map the BS-X base unit RTC to the PC clock.
Some stuff like Dragon Slayer Eiyuu Densetsu work fine under regular
mapping, yet don't work with BS-X mapping. No idea why. Still don't
hack-enable headers during load, so that has to be done manually still
(do this if the game doesn't show up in cart menu. Make a backup if
you care.)

 Added SameGame support. Load it with "Load BS-X Slotted Cartridge"
(that's what it is, after all.) Unfortunately, I don't know what the
memory map is supposed to be, so the add-on cart doesn't appear to be
working. Or maybe I just can't figure out how to tell.
 Nach or anyone else, would you mind sharing that info with me? The
code in SNES9x looks identical to what I have, but loading the FEoEZ
512kbyte cart doesn't seem to do anything. Well, at least the game
itself works under this menu option now.

 Fixed config::path.save, and added realpath() for the Linux port, so
./ paths work too. Of course it won't be useful at all if you
"install" bsnes to /usr/bin, but if you keep it in its own folder,
it's helpful.

 Fixed the SRAM mapping bug affecting Fire Emblem 776. Also optimized
the file loading stuff a little more, removing a couple redundant ROM
memcpy's. Still far from perfect.

             If possible, please test this WIP a lot. I'd like to post
a new public release this weekend.

[No archive available]
2007-11-17 10:09:00 +00:00
byuu
49b0bed1a6 Update to bsnes v025r11? release.
New WIP up. Has a Windows binary this time.

 I completed the BSX cart MMIO registers. It definitely doesn't work
too well. For one, I don't override the header bit in the emulator, so
anyone testing will have to modify the bit as discussed first. It also
doesn't work on my only other BS game, BS Dragon Quest. I don't know
why, it throws a St. GIGA error (09). Maybe it needs base unit
emulation ... who knows. There's probably bugs in the cart and flash
reg support, too.







> My notes on the subject tell me it's the year of download or'd with
> other data. I haven't entirely figured out everything it's or'd with
> though.




 Well, Lancer said the BIOS makes sure d15 of $ffd5,$ffd4 is not set.
If it is, the game does not appear in the list of games you can start.
I'm guessing certain (all?) games expired after a certain date. If
that's true, then we're quite fortunate that only a header bit was
set, rather than the entire cart erased. So then, most likely all of
these games with $80 in $ffd5 appeared "blank", but were dumped and
the games retrieved.

 Sigh, such a sad fate. Really makes you wonder why Nintendo hates
their fanbase so much to go out of their way to destroy these games.

[No archive available]
2007-11-15 10:43:00 +00:00
byuu
1554170312 Update to bsnes v025r10? release.
Yeah, even if we still don't have the S-DD1 100% understood, we can at
least get all known software working properly. And now we at least
have all the registers understood, just the edge cases that need to be
tested. I'm honestly glad I was incorrect in that the original patch
worked on hardware. Given it will never be updated again, this means I
won't have to get bug reports from now unto infinity about it.

 I posted a new binary WIP. If anyone wants to play through a few
levels of SFA2 or dungeons in SO and look for corrupted graphics, it'd
be appreciated. I'm sure it'll be fine, though. Oh, and the speedhit I
reported a few days ago was wrong. The old builds ran at the same
speed. Seems I have a ~6-8fps variance in that game per reboot.

 New WIP also starts the BS-X mapping. You can map in a cart now, but
it immediately freezes because the flash I/O registers do not respond.

             ---

             Also, I'd like to get serious about emulating the
SPC7110. But to do that, I need custom-made hardware.

 I asked someone about this already, but I may as well throw it out
there publicly in case anyone else would like to help.

             Here is the PCB for one of the SPC7110 games:
             http://nsrt.edgeemu.com/INFO/chip-pix/SPC7110.JPG

 What I would need is for the top two ICs to be desoldered, and socket
IC connectors to be placed on them instead. I would also obviously
need lots of compatible EEPROMs to connect to it (just two would
suffice, more would be better as it's quite possible I'd wear out the
write cycles with lots of intense testing, or bend up the pins like I
usually do when removing socket ICs).

             I would also need software+hardware to actually flash the
EEPROMs, as I don't have anything like this presently.

 More complex solutions, such as a ROM emulator with a parallel/USB
interface to the PC would be acceptable as well. So long as it's
something I can reprogram at my relatively low skill level.

 One cart would suffice, but again, the more carts the better in case
of failure. And I'd also like to see about sending one to another
person who's been interested in the SPC7110 for a while. So, three or
four preferred.

             I can supply the cartridges and money for time +
shipping. I'd prefer someone who _knows_ they can do this well try, so
that we don't ruin any unnecessary cartridges and so that the test
cartridges are as durable as possible. Especially since they most
likely won't be encased anymore.

             So, any takers?

[No archive available]
2007-11-13 16:08:00 +00:00
byuu
ec137d6fb9 Update to bsnes v025r09? release.
I posted a new WIP last night. No binary this time,
sorry.
 It redoes the memory mapping of the cartridge and moves it into the
cartridge class -- forking each slotted cart away from the base cart
memory.
 This allows me to determine the proper sizes for each individual cart
again, so I can now map RPG Tsukuru II again correctly.

               EDIT:

               Ahahahahahah!! Finally! I figured out how the S-DD1
$4800 and $4801 registers work! :D

               Original game transfer (should transfer
compressed->decompressed):







    CC2418 LDA #$4000 A:00DA X:F458 Y:1C00 S:01FA DB:00 D:0000 P:01 e
                       CC241B PEA $00DB [0000DB] A:4000 X:F458 Y:1C00
    S:01FA DB:00 D:0000 P:01 e
                       CC241E LDX #$E8ED A:4000 X:F458 Y:1C00 S:01F8
    DB:00 D:0000 P:01 e
                       CC2421 LDY #$0800 A:4000 X:E8ED Y:1C00 S:01F8
    DB:00 D:0000 P:81 e
                       CC2424 JSR $2470 [CC2470] A:4000 X:E8ED Y:0800
    S:01F8 DB:00 D:0000 P:01 e
                       CC2470 STA $2116 [002116] A:4000 X:E8ED Y:0800
    S:01F6 DB:00 D:0000 P:01 e
                       CC2473 SEP #$20 A:4000 X:E8ED Y:0800 S:01F6
    DB:00 D:0000 P:01 e
                       ;* enable $4800 *
                       CC2475 LDA #$01 A:4000 X:E8ED Y:0800 S:01F6
    DB:00 D:0000 P:21 e
                       CC2477 STA $4800 [004800] A:4001 X:E8ED Y:0800
    S:01F6 DB:00 D:0000 P:21 e
                       CC247A LDA #$09 A:4001 X:E8ED Y:0800 S:01F6
    DB:00 D:0000 P:21 e
                       CC247C STA $4300 [004300] A:4009 X:E8ED Y:0800
    S:01F6 DB:00 D:0000 P:21 e
                       CC247F LDA #$18 A:4009 X:E8ED Y:0800 S:01F6
    DB:00 D:0000 P:21 e
                       CC2481 STA $4301 [004301] A:4018 X:E8ED Y:0800
    S:01F6 DB:00 D:0000 P:21 e
                       CC2484 STX $4302 [004302] A:4018 X:E8ED Y:0800
    S:01F6 DB:00 D:0000 P:21 e
                       CC2487 LDA $03,S [0001F9] A:4018 X:E8ED Y:0800
    S:01F6 DB:00 D:0000 P:21 e
                       CC2489 STA $4304 [004304] A:40DB X:E8ED Y:0800
    S:01F6 DB:00 D:0000 P:A1 e
                       CC248C STY $4305 [004305] A:40DB X:E8ED Y:0800
    S:01F6 DB:00 D:0000 P:A1 e
                       CC248F LDA #$01 A:40DB X:E8ED Y:0800 S:01F6
    DB:00 D:0000 P:A1 e
                       CC2491 STA $4801 [004801] A:4001 X:E8ED Y:0800
    S:01F6 DB:00 D:0000 P:21 e
                       CC2494 PHA A:4001 X:E8ED Y:0800 S:01F6 DB:00
    D:0000 P:21 e
                       CC2495 PLA A:4001 X:E8ED Y:0800 S:01F5 DB:00
    D:0000 P:21 e
                       CC2496 STA $420B [00420B] A:4001 X:E8ED Y:0800
    S:01F6 DB:00 D:0000 P:21 e
                       CC2499 STZ $4800 [004800] A:4001 X:E8ED Y:0800
    S:01F6 DB:00 D:0000 P:21 e
                       CC249C REP #$20 A:4001 X:E8ED Y:0800 S:01F6
    DB:00 D:0000 P:21 e
                       CC249E RTS A:4001 X:E8ED Y:0800 S:01F6 DB:00
    D:0000 P:01 e




               Custom transfer (should transfer
decompressed->decompressed):







    CC2428 LDA #$5008 A:00DB X:E8ED Y:0800 S:01FA DB:00 D:0000 P:01 e
                       CC242B PEA $00E9 [0000E9] A:5008 X:E8ED Y:0800
    S:01FA DB:00 D:0000 P:01 e
                       CC242E LDX #$0400 A:5008 X:E8ED Y:0800 S:01F8
    DB:00 D:0000 P:01 e
                       CC2431 LDY #$04E0 A:5008 X:0400 Y:0800 S:01F8
    DB:00 D:0000 P:01 e
                       CC2434 JSR $244C [CC244C] A:5008 X:0400 Y:04E0
    S:01F8 DB:00 D:0000 P:01 e
                       CC244C STA $2116 [002116] A:5008 X:0400 Y:04E0
    S:01F6 DB:00 D:0000 P:01 e
                       CC244F SEP #$20 A:5008 X:0400 Y:04E0 S:01F6
    DB:00 D:0000 P:01 e
                       ;* disable $4800 *
                       CC2451 STZ $4800 [004800] A:5008 X:0400 Y:04E0
    S:01F6 DB:00 D:0000 P:21 e
                       ;* $43x0.d3 (fixed transfer flag) is irrelevent
    to S-DD1 *
                       ;* can be #$01 or #$09 here *
                       CC2454 LDA #$09 A:5008 X:0400 Y:04E0 S:01F6
    DB:00 D:0000 P:21 e
                       CC2456 BRA $247C [CC247C] A:5009 X:0400 Y:04E0
    S:01F6 DB:00 D:0000 P:21 e
                       CC247C STA $4300 [004300] A:5009 X:0400 Y:04E0
    S:01F6 DB:00 D:0000 P:21 e
                       CC247F LDA #$18 A:5009 X:0400 Y:04E0 S:01F6
    DB:00 D:0000 P:21 e
                       CC2481 STA $4301 [004301] A:5018 X:0400 Y:04E0
    S:01F6 DB:00 D:0000 P:21 e
                       CC2484 STX $4302 [004302] A:5018 X:0400 Y:04E0
    S:01F6 DB:00 D:0000 P:21 e
                       CC2487 LDA $03,S [0001F9] A:5018 X:0400 Y:04E0
    S:01F6 DB:00 D:0000 P:21 e
                       CC2489 STA $4304 [004304] A:50E9 X:0400 Y:04E0
    S:01F6 DB:00 D:0000 P:A1 e
                       CC248C STY $4305 [004305] A:50E9 X:0400 Y:04E0
    S:01F6 DB:00 D:0000 P:A1 e
                       CC248F LDA #$01 A:50E9 X:0400 Y:04E0 S:01F6
    DB:00 D:0000 P:A1 e
                       CC2491 STA $4801 [004801] A:5001 X:0400 Y:04E0
    S:01F6 DB:00 D:0000 P:21 e
                       CC2494 PHA A:5001 X:0400 Y:04E0 S:01F6 DB:00
    D:0000 P:21 e
                       CC2495 PLA A:5001 X:0400 Y:04E0 S:01F5 DB:00
    D:0000 P:21 e
                       CC2496 STA $420B [00420B] A:5001 X:0400 Y:04E0
    S:01F6 DB:00 D:0000 P:21 e
                       CC2499 STZ $4800 [004800] A:5001 X:0400 Y:04E0
    S:01F6 DB:00 D:0000 P:21 e
                       CC249C REP #$20 A:5001 X:0400 Y:04E0 S:01F6
    DB:00 D:0000 P:21 e
                       CC249E RTS A:5001 X:0400 Y:04E0 S:01F6 DB:00
    D:0000 P:01 e




               Original transfer right after custom transfer:







    CC2438 LDA #$4000 A:00E9 X:0400 Y:04E0 S:01FA DB:00 D:0000 P:01 e
                       CC243B PEA $00DC [0000DC] A:4000 X:0400 Y:04E0
    S:01FA DB:00 D:0000 P:01 e
                       CC243E LDX #$E0E8 A:4000 X:0400 Y:04E0 S:01F8
    DB:00 D:0000 P:01 e
                       CC2441 LDY #$1080 A:4000 X:E0E8 Y:04E0 S:01F8
    DB:00 D:0000 P:81 e
                       CC2444 JSR $2458 [CC2458] A:4000 X:E0E8 Y:1080
    S:01F8 DB:00 D:0000 P:01 e
                       CC2458 STA $2181 [002181] A:4000 X:E0E8 Y:1080
    S:01F6 DB:00 D:0000 P:01 e
                       CC245B SEP #$20 A:4000 X:E0E8 Y:1080 S:01F6
    DB:00 D:0000 P:01 e
                       CC245D LDA #$7F A:4000 X:E0E8 Y:1080 S:01F6
    DB:00 D:0000 P:21 e
                       CC245F STA $2183 [002183] A:407F X:E0E8 Y:1080
    S:01F6 DB:00 D:0000 P:21 e
                       CC2462 LDA #$01 A:407F X:E0E8 Y:1080 S:01F6
    DB:00 D:0000 P:21 e
                       ;* $4800 enabled again *
                       CC2464 STA $4800 [004800] A:4001 X:E0E8 Y:1080
    S:01F6 DB:00 D:0000 P:21 e
                       CC2467 LDA #$08 A:4001 X:E0E8 Y:1080 S:01F6
    DB:00 D:0000 P:21 e
                       CC2469 STA $4300 [004300] A:4008 X:E0E8 Y:1080
    S:01F6 DB:00 D:0000 P:21 e
                       CC246C LDA #$80 A:4008 X:E0E8 Y:1080 S:01F6
    DB:00 D:0000 P:21 e
                       CC246E BRA $2481 [CC2481] A:4080 X:E0E8 Y:1080
    S:01F6 DB:00 D:0000 P:A1 e
                       CC2481 STA $4301 [004301] A:4080 X:E0E8 Y:1080
    S:01F6 DB:00 D:0000 P:A1 e
                       CC2484 STX $4302 [004302] A:4080 X:E0E8 Y:1080
    S:01F6 DB:00 D:0000 P:A1 e
                       CC2487 LDA $03,S [0001F9] A:4080 X:E0E8 Y:1080
    S:01F6 DB:00 D:0000 P:A1 e
                       CC2489 STA $4304 [004304] A:40DC X:E0E8 Y:1080
    S:01F6 DB:00 D:0000 P:A1 e
                       CC248C STY $4305 [004305] A:40DC X:E0E8 Y:1080
    S:01F6 DB:00 D:0000 P:A1 e
                       CC248F LDA #$01 A:40DC X:E0E8 Y:1080 S:01F6
    DB:00 D:0000 P:A1 e
                       CC2491 STA $4801 [004801] A:4001 X:E0E8 Y:1080
    S:01F6 DB:00 D:0000 P:21 e
                       CC2494 PHA A:4001 X:E0E8 Y:1080 S:01F6 DB:00
    D:0000 P:21 e
                       CC2495 PLA A:4001 X:E0E8 Y:1080 S:01F5 DB:00
    D:0000 P:21 e
                       CC2496 STA $420B [00420B] A:4001 X:E0E8 Y:1080
    S:01F6 DB:00 D:0000 P:21 e
                       CC2499 STZ $4800 [004800] A:4001 X:E0E8 Y:1080
    S:01F6 DB:00 D:0000 P:21 e
                       CC249C REP #$20 A:4001 X:E0E8 Y:1080 S:01F6
    DB:00 D:0000 P:21 e
                       CC249E RTS A:4001 X:E0E8 Y:1080 S:01F6 DB:00
    D:0000 P:01 e




 I was completely wrong, and was thrown off by ZSNES' memory remapping
magic that worked due to an oversight with $43x0.d3, or the fixed
transfer flag. I never added a check for the fixed transfer flag
because it quite honestly made no sense. Why would the S-DD1 care
about that?

               Turns out, it doesn't. What really matters is $4800.
The register everyone currently ignores completely.

               I figured out what purpose it serves: it's a sticky
toggle, whereas $4801 is a loose toggle.

 It works like this: in order for the S-DD1 to decompress a DMA
transfer, both $4800 and $4801 have to be set. Upon completion of the
transfer, $4801 is cleared. But $4800 is not.

 If you look at the above logs, it becomes clear. And it's all
contained inside the S-DD1 code. It has nothing to do with $43x0.

 Now, how can I verify this? orwannon made a flash cart for Star Ocean
and ran my old title screen patch on it. Sure enough, it did not try
and decompress the graphics data, despite the fixed transfer flag
being set. That tells us that the fixed transfer flag has nothing to
do with this.

 What's interesting is that every single S-DD1 supporting emulator
works just fine with my title screen patch. Meaning that they've all
implemented these two registers wrong.

 What was also interesting is that it's supposedly been confirmed that
the patched SO works on real hardware. That means the bug was in bsnes
after all. No excuses, I was flat out wrong. My sincere apologies.

 I've added the above changes, and bsnes now works with the original
patch, and fails with my custom patch. This mimics the behavior of
real hardware.

 Huge thanks to orwannon for the screenshot of my patch running on
real hardware. This fix wouldn't have been possible without that.

[No archive available]
2007-11-12 21:52:00 +00:00
byuu
aee683a475 Update to bsnes v025r08? release.
New WIP up.

 I spent four hours completely rewriting everything but the generic
header parsing code in src/cart. I'm now happy with the code both in
src/memory and src/cart. Hoorah.

 With the new load_cart() functionality, I made the "Load Special"
menu entries functional. For those of you stuck on Windows or without
WIP access, you can see how nice the load menus look on Linux below :)

             http://byuu.cinnamonpirate.com/bsnes/images/ui_bsx.png
             http://byuu.cinnamonpirate.com/bsnes/images/ui_st.png

 There is one bug: because of the way I map the slotted carts into one
contigious chunk of ROM (and hence update the size accordingly), it
throws off the memory mirroring on some of the BS-X slotted cart games
(like RPG Tsukuru II). I need to work on that a bit. For now, you can
play it through the normal load cartridge menu option.

 And of course, there's still that annoying Windows issue where the
main window steals focus after loading a ROM. Haven't looked into that
yet.

 And I still need to rework the file extension stuff per previous
discussions. It'd be nice to have the BS-X / ST windows only show .bs
/ .st ROMs by default.

[No archive available]
2007-11-05 07:22:00 +00:00
byuu
cdbf07b642 Update to bsnes v025r07? release.
Ok, posted the new WIP with the LoROM map corrections. This one also
modified the load special menu. They now bring up a new window that
lets you select the base cart + slot cart(s). However, the menus do
not work yet. There's also some odd issue that it loses focus when you
select a ROM from the browse button, but only on Windows. Hitting load
just hides the window. I also need to add code to automatically load /
save the BIOS filenames where applicable.

Also, forgot to mention last time, but I added a new config file
option, cpu.wram_initial_value or something like that. It's purpose
should be pretty obvious.

[No archive available]
2007-11-04 11:36:00 +00:00
byuu
8a857dada3 Update to bsnes v025r06? release.
Ok, new WIP up. Pretty much all of the credit goes to others, this
time.

             Changelog:
             - I forgot to set the region, so PAL games were running
as NTSC; this is fixed
             - Added Nach's BS-X slotted flashcart detection (added
his Ys'3 SRAM detection earlier)
 - Used BSC-1A7M-10 PCB mapper from Overload's documentation for the
generic BS-X slotted cart games; Derby Stallion '96, Sound Novel
Tsukuru and RPG Tsukuru II are all playable once again; hopefully the
rest of the slotted games work, too (sans the SA-1 game(s)). Please
test if you can
 - Added krom's (and I suppose Nach's earlier submitted) MinGW32 icon
support; so FitzRoy's wonderful icon is there now on the EXE -- still
need to add it to the window titlebar (easy on Windows), and to Linux
in general, ugh
 - Removed win-mingw4-lui target, simplifying Makefile. Use win-mingw-
lui now. Thanks again to krom's suggestion to just copy the MinGW4
-sjlj files, that worked great
             - Some more cleanup work to src/cart. Still a lot to go
here.

 Everything that was playable in the last release should now be
playable, excepting Yoshi's Island music. Please let me know if
anything is broken that wasn't before now.

 As always, I'm really thankful to everyone for their contributions.
My program would be useless if not for all the help I've gotten from
everyone else.

             ---

 Now then, I aim to support those BS-X slotted cart games as well. But
one thing I did not know until today was that you could actually
exchange those carts between games. That ruins the model I planned to
use for them (eg make romname.smc -> romname.bsf files).

 Thinking about it -- I really need to completely redesign file
loading. BS-X and Sufami Turbo stuff really throws off the "Load ROM"
paradigm that is so popular amongst emulators.

 I'm thinking ... remove the "Load Special" menu completely. Modify
the main ROM loading routine to parse what exactly is being loaded.

 If it's a BS-X slotted cart, pop up a menu that lets one optionally
select to load an additional flash cart, or cancel the menu to load
nothing in the slot. This won't be hot-swappable in-game.

 If it's a Sufami Turbo cart, assume Slot A for the cart. If this game
supports dual slotting*, pop up an additional menu to select the Slot
B game, which can also be left empty. (* perhaps popup the menu no
matter what, to more closely simulate that with real hardware, you
could stick incompatible games in both slots anyway?)

             Same deal for Same Game, G-Next, and all that other crap,
if or whenever I end up supporting those.

 I think it's best to keep the BIOS stuff in the config file, rather
than giving an optional popup menu to modify which BIOS to load. The
reason being that it will allow direct loading of BS-X games with no
need to ever show a popup menu.

 Lastly, I will have to add a new Misc menu option to generate empty
BS-X flashcart files. Though it's really easy to make one, I imagine
end users might have trouble doing that.

             Ideas or suggestions welcome.

[No archive available]
2007-11-02 09:30:00 +00:00
byuu
ab1975a6cb Update to bsnes v025r05? release.
I mentioned that it wasn't there. Exact reason was because I reloaded
Ubuntu and Windows, and I really hate installing Visual C++. It takes
forever. I posted a new WIP, and built it with MinGW4. Need to figure
out how to get the icon into the binary with MinGW.

             Anyway, new stuff in the WIP:

 - Much, much faster mirror() function; thanks to lots of help from
Nach (doesn't speed anything up, but might help with BS-X MMIO
registers)
             - Removed cart.db and all database-related code, now that
Ys3 works
             - Lots of code cleanups everywhere
             - New help information for trying to run ./configure or
make by itself
             - Cheap temporary MinGW fix for non-C99 vsnprintf

 The BS-X slot games (Derby Stallion et al) won't work on this
release. Nach gave me the code to detect those, and I'll get that
mapper in eventually before the next release. Also, Yoshi's Island
won't play audio anymore most likely.

 If anything else is broken, it's due to mapping. Please let me know
so I can fix it. If there are more than three broken games, that's
good -- please don't overwhelm me with a list of 500+ broken games in
the morning :)

             EDIT: fixed the Windows issues I was having. The Realtek
HD Audio driver software is fucking stupid. You _have_ to unplug your
speakers, reconnect them, and then select line out (rather than the
option for speakers) to get audio. This is the _only_ way to get
audio. And apparently both regular Winamp (without visualization) and
Mozilla Firefox now need DEP turned off not to crash the fuck all over
themselves constantly. Wonderful.

 EDIT2: forgot to set the region, so PAL games will run as though they
are NTSC. Most will probably give you an error splash screen. I'll fix
that.

[No archive available]
2007-10-31 10:18:00 +00:00
byuu
476a1c819a Update to bsnes v025r04? release.
New WIP up. This one's a bit better than last, but I
don't want bug reports yet. This one only maps generic LoROM and HiROM
games.

 Took about four or five hours, but I reworked most of the new memory
mapper yet again. SRAM should be working now, and I managed to gain
back the speed lost by dropping the address masking and forcing Visual
C++ to inline (__forceinline). The masking was no good anyway, because
the ROM file loaded in is definitely not always a power of two, which
means I'd have to use modulus and holy fuck no I'm not adding a
division for every memory access.

 The old memory mapper didn't have this either, as it stored a bunch
of pointers into memory chunks. The new one just stores one pointer
plus integer offsets into that pointer (a bit slower but cleaner and
necessary for abstraction), so it's really mostly the same thing.

 Man, I was looking at my old generic LoROM / HiROM mapper, and the
difference from that and what I have now is astounding ... it would
seem I've certainly gotten better at programming since then.







    /* new */
                       void sBus::map_generic() {
                       switch(cartridge.info.mapper) {
                       case Cartridge::LOROM: {
                       map(MapLinear, 0x00, 0x3f, 0x8000, 0xffff,
    memory::rom);
                       map(MapLinear, 0x80, 0xbf, 0x8000, 0xffff,
    memory::rom);
                       map(MapLinear, 0x40, 0x7f, 0x0000, 0xffff,
    memory::rom);
                       map(MapLinear, 0xc0, 0xff, 0x0000, 0xffff,
    memory::rom);
                       } break;
                       case Cartridge::HIROM: {
                       map(MapShadow, 0x00, 0x3f, 0x8000, 0xffff,
    memory::rom);
                       map(MapShadow, 0x80, 0xbf, 0x8000, 0xffff,
    memory::rom);
                       map(MapLinear, 0x40, 0x7f, 0x0000, 0xffff,
    memory::rom);
                       map(MapLinear, 0xc0, 0xff, 0x0000, 0xffff,
    memory::rom);
                       } break;
                       }

                       if(memory::sram.size() == 0) { return; }
                       map(MapLinear, 0x20, 0x3f, 0x6000, 0x7fff,
    memory::sram);
                       map(MapLinear, 0xa0, 0xbf, 0x6000, 0x7fff,
    memory::sram);
                       map(MapLinear, 0x70, 0x7f, 0x0000, 0x7fff,
    memory::sram);

                       if(cartridge.info.mapper != Cartridge::LOROM) {
    return; }
                       map(MapLinear, 0xf0, 0xff, 0x0000, 0x7fff,
    memory::sram);
                       }

                       /* old */
                       void bMemBus::cart_map_generic(uint type) {
                       uint rom_size = cartridge.info.rom_size;
                       uint ram_size = cartridge.info.ram_size;

                       for(uint page = 0x0000; page <= 0xffff; page++)
    {
                       if(memory_type(page << 8) !=
    TYPE_CART)continue;

                       uint addr = page << 8;
                       uint bank = page >> 8;

                       //RAM mapping is incorrect in several games,
    this is the most compatible
                       //layout I can create using only ROM header
    information. Additional accuracy
                       //requires PCB identification.

                       //Unmapped region
                       //$[00-1f|80-9f]:[6000-7fff]
     if((bank & 0x7f) >= 0x00 && (bank & 0x7f) <= 0x1f && (addr &
    0xe000) == 0x6000) {
                       continue;
                       }

                       //HiROM RAM region
                       //$[20-3f|a0-bf]:[6000-7fff]
     if((bank & 0x7f) >= 0x20 && (bank & 0x7f) <= 0x3f && (addr &
    0xe000) == 0x6000) {
                       if(ram_size == 0)continue;

                       addr = ((bank & 0x7f) - 0x20) * 0x2000 + ((addr
    & 0xffff) - 0x6000);
                       addr %= ram_size;
                       page_handle[page] = cartridge.ram + addr;
                       page_read [page] = &bMemBus::read_ram;
                       page_write [page] = &bMemBus::write_ram;
                       continue;
                       }

                       //LoROM RAM region
                       //$[70-7f|f0-ff]:[0000-7fff]
                       //Note: WRAM is remapped over
    $[7e-7f]:[0000-ffff]
     if((bank & 0x7f) >= 0x70 && (bank & 0x7f) <= 0x7f && (addr &
    0x8000) == 0x0000) {
                       if(!(bank & 0x80) || type == Cartridge::LOROM)
    {
                       //HiROM maps $[f0-ff]:[0000-7fff] to ROM
                       if(ram_size == 0)continue;

                       addr = ((bank & 0x7f) - 0x70) * 0x8000 + (addr
    & 0x7fff);
                       addr %= ram_size;
                       page_handle[page] = cartridge.ram + addr;
                       page_read [page] = &bMemBus::read_ram;
                       page_write [page] = &bMemBus::write_ram;
                       continue;
                       }
                       }

                       //ROM region
                       switch(type) {

                       case Cartridge::LOROM: {
                       addr = (bank & 0x7f) * 0x8000 + (addr &
    0x7fff);
                       addr = mirror(rom_size, addr);
                       } break;

                       case Cartridge::HIROM: {
                       addr = mirror(rom_size, addr);
                       } break;

                       }

                       page_handle[page] = cartridge.rom + addr;
                       page_read [page] = &bMemBus::read_rom;
                       page_write [page] = &bMemBus::write_rom;
                       }
                       }




 Note that those two certainly aren't identical in function, and I'll
no doubt have some memory mapping bugs again (probably with Final
Fight, SFII and such), but it should only require minor changes to fix
that.







> byuu: is it possible there's supposed to be steam appearing there to
> create the illusion, but isn't?




               That's a lot more likely, honestly. Hopefully someone
can make it to level 5, heh. I know I sure as hell can't.

[No archive available]
2007-10-18 09:40:00 +00:00
byuu
42d3f2a37f Update to bsnes v025r03? release.
New WIP up, and this one is _not_ for playing games on.

 I replaced the memory mapper entirely with a new system that should
be infinitely easier to remap dynamically. This is a necessary step
for BS-X MMIO register emulation. It should also speed up S-DD1
emulation by eliminating the need for a special address conversion
routine to simulate its memory mapper.

 However, the new bus memory mapper is anything but complete. Right
now, it only loads really, really basic LoROM games. Stick to Super
Mario World and Zelda 3.

 Some good news is that it's ~1-2% faster with MinGW4, but the bad
news is that it's ~10% slower with Visual C++, and MS' compiler is
stupidly storing my 128kb array directly into the EXE, making the file
size bigger. And yet the ZIP of the whole thing is smaller! >_<

 Bah. I think I can fine tune most of the performance lost back out of
Visual C++ with some forced inlining, and I'll make that WRAM array
allocate at runtime.

 Surprised I was able to get any games playable in less than three
hours, replacing the entire memory mapping system like that. Lucky me.







> -O8 -mtune=prescott -ffloat-store -fforce-addr -finline-functions
> -fexpensive-optimizations -funroll-all-loops -ffast-math -fomit-
> frame-pointer




 I didn't realize you could go above -O3 ... interesting. If you want,
try building with profile guided optimizations for another ~15% speed
boost. It's pretty unstable like that, though. Maybe you'll have
better luck than me.

               The warning message is in src/cart/cart_file.cpp at the
top.

[No archive available]
2007-10-17 04:51:00 +00:00
byuu
c58e3af1b5 Update to bsnes v025r02? release.
Alright, posted a new WIP with the BS-X skeleton. The
BIOS needs to be named bsxbios.bin, and it can't have a header.

 There's also "Load Special -> Load BS-X Cartridge ...", but it
doesn't work yet. It maps the flash cart into $[c0-ff]:[0000-ffff],
but that doesn't do much good. The BIOS then detects the flash cart
and starts probing the memory mapping registers and eventually
deadlocks.

               To emulate the MMIO registers, I will have to
_completely_ rework my memory mapping code to support dynamic
remapping. Not necessarily a bad thing, I was planning to rewrite all
of that anyway (per my diagram yesterday). Might as well kill two
birds with one stone.

 Gonna take at least a few days of planning before I go at that. I
want to get it right this time, so I don't have to do this again.

               In the meantime, have fun walking around the dead St.
GIGA ghost town ;)







> Byuu, that's some sweet ass shiz. You are a man on a mission this
> week. Let me know when you feel you've supported it enough to remove
> it from the list.




 Yeah, not sure what's up. I rarely have motivation to do anything
anymore, but it always comes in bursts. So I'll take advantage of it
now, and hope it doesn't burn out soon.

 I've a long way to go with BS-X before we can remove it, sadly. I
think we can remove when I get >50-75% of games loading. I doubt we
can reach 100%. There's missing info, corrupted / hacked BS ROMs
galore, and I don't even have BS-X hardware to test with.







> byuu, you always show something cool in a new version RIGHT after
> your official releases




 Sorry about that, it's not intentional. The thing is that no BS-X
games are even playable yet. I suppose when it's stable, I'll post
another public version, assuming the core is still stable with all the
plans I have for it.







> I really enjoy following your development of bsnes. I can't wait for
> the day I have a computer that is actually fast enough to play games
> with it (I'm currently using an Athlon 1.1 GHz).




               Sorry about that :(

               ---

 Side note: I also posted v0.025a, which removes the warning message
when SRM files don't exist. Nothing else is different, though.

[No archive available]
2007-10-16 05:50:00 +00:00
byuu
8226e243b8 Update to bsnes v025a release.
My apologies, I added code to display an alert when the Sufami Turbo BIOS was not present at the last minute before the recent release. What I failed to realize was that I added the alert to the same routine that loads save RAM files. Meaning that whenever one loads a game that has not yet created a .srm file, one will get a warning that the save RAM file does not exist. Oops.
You'll never see the warning more than once, and it's harmless, but for those it annoys, and for people who haven't upgraded yet, I've posted bsnes v0.025a. This version changes absolutely nothing other than disabling the warning box in question. I'll be sure to get a proper, tested fix into the next release. Again, I apologize for any inconveniece this may have caused.

[No archive available]
2007-10-16 00:00:00 +00:00
byuu
9ab3fa6227 Update to bsnes v025r01? release.
I'll bet this will surprise you all, I already have a
private WIP for the v0.025 series up :P
 Absolutely no emulation changes, just lots of major code changes I
held off on as I didn't want to break anything last minute.

 - Polymorphism through pointers using compile-time flag is dead. It
took a ~10% speed hit, so it was never feasible to use anyway. This is
also a required step to encapsulating the entire emulator inside a
single class which can support multiple instances. r_cpu-> becomes
cpu. , r_smp-> becomes smp. , etc.
 - Greatly cleaned up interface.h as much as possible for now. Right
now, bsnes takes a lot longer than it should to compile because every
single object includes every last header for all objects. In the
future, I want to move headers so that only objects that need others
include those headers. Will increase compile speed a good bit.
               - Created chip/chip.h to start on the above.
               - Finally renamed chip/c4 to chip/cx4. Class name also
changed from C4 to Cx4.
               - Removed libsort, as it's not used (yet?). Was
needlessly slowing down compile time.
 - Created src/doc. This will be a folder that contains source code
documentation, diagrams, maps, to-do lists, etc. Started things off by
creating a _very_ basic overview of bsnes as a whole.

 Much more radical stuff to come. I don't anticipate making another
public release for quite a long time, so I should be able to go wild
here with restructuring things.







> I just checked out the new bsnes version 0.025, but I could not find
> any option in the config file to change the memory / mem via PRNG
> initialization byte, that we were talking about earlier to help get
> some old pd stuff working...




 Oh, I'm sorry about that. Didn't get a chance to add it this time. I
need to work a PRNG with a consistent seed value into the core first.
Not sure how I want to do that.

 For what it's worth, initializing RAM to 0x00 unfortunately did not
fix Sidmania's graphical issues as I had hoped. Given FitzRoy reports
the glitches occur on real hardware as well, I'm afraid there's not a
whole lot I can do about it. I will pay attention to it when working
on my cycle-based PPU in the future, though.







> On another note your emulator has inspired me to do my first
> translation for the snes "Albert Odyssey", and has been very useful
> for this purpose.




 Neat! Be sure to check out bsnes v0.013 on RHDN for its debugger.
It's the only SNES emulator with VRAM breakpoints, as far as I know.
Also be sure to try out xkas for your cross assembler :D </shameless
self-promotion>







> Oct. 14 also happens to be the 10th anniversary of the first public
> release of ZSNES, interestingly enough.




               o.O
 Holy crap, why didn't I ever hear about this before? That's really,
really interesting ... of course, the difference is that bsnes was
started on 10-14, ZSNES was first released then but obviously started
much sooner. Still cool, though.

 I wonder if anyone knows the exact date zsKnight started on ZSNES, or
Jeremy Koot on SNES9x. It would be really cool to have a history of
the SNES emulation scene. So many emulators most have never even heard
of ... RSRSNES, GrimSNES, TrepSNES, Moonlit Coalition's emulator (that
played one game, heh), Simkin's simulator thing ... heh, I wonder if
anyone here knows the name of the SNES emulator I tried (and failed)
making way before bsnes, back in 2001. Google doesn't even know of it
:)

[No archive available]
2007-10-15 05:21:00 +00:00
byuu
85fa3cc968 Update to bsnes v025 release.
bsnes is exactly three years old today. I've posted a new version which adds DSP-3 and DSP-4 special chip support. The DSP-3 is used by SD Gundam GX, and the DSP-4 is used by Top Gear 3000. Please note that the DSP-3 is not fully emulated, thusly SD Gundam GX is not fully playable. Also, due to lack of timing emulation with the DSP-4, the Top Gear 3000 track sometimes flickers in split screen mode. However, it is believed that Top Gear 3000 is fully playable.
I should also note that I have started on SuperFX emulation, as some will inevitably see said code in my source releases. What I have now is nothing more than a skeleton implementation, and absolutely nothing using it is playable yet. I am making absolutely no promises that I will ever be able to emulate this chip. It will take at least several months of work, and even then, the speed will probably be too slow to reach 60fps on any system, but ... I'm working on it. While I have no way to run tests on the actual SuperFX hardware, I will do the best I can to emulate the chip accurately. I will be emulating the caching and cycle delays as best I can, but the information I have on this chip is extremely limited, so don't expect miracles.
Lastly, as promised, I have released the special chips I have personally emulated to the public domain. See license.txt for more information if interested. I cannot release the special chips whose code I did not write to the public domain, but all of that is already available under the GPLv2 (from ZSNES) or the SNES9x license.
Changelog:
    - Added DSP-3 support, thanks to John Weidman, Kris Bleakley, Lancer, z80 gaiden
    - Added DSP-4 support, thanks to Dreamer Nom, John Weidman, Kris Bleakley, Nach, z80 gaiden
    - Started on support for SuperFX, no games playable as chip emulation is less than 1% complete
    - Unsupported special chips will now display an alert
    - Missing stbios.bin file when loading Sufami Turbo cartridges will now display an alert
    - Video settings now saved separately for windowed and fullscreen mode
    - Advanced option video<.mode>.synchronize can be enabled for vsync, but will cause sound crackling
    - Added menu option to toggle FPS counter
    - Minor source code cleanup
2007-10-15 10:03:36 +00:00
byuu
d1fcddee9c Update to bsnes v024r01? release.
New WIP up.

 This one merges the most recent DSP-3 / DSP-4 work. Not sure if it
fixes any bugs or not, but good to be up to date, right? Testing would
be appreciated.

             I also cleaned up the cart stuff a bit. Nicer enums,
removed some unused variables and such.

 Then I turned all of the special chip class object pointers into
actual objects. It was kind of stupid to dynamically create them all,
and was just wasting performance.

 I also finished adding all of the SuperFX registers, and mapped them
all to the GSU interface range ($3000-$32ff). Fixed an oversight with
the mapping, and added a new PCB database entry to get the memory map
for Yoshi's Island perfect. If you want to hear something nice, try
loading the USA version in this WIP with sound + speed regulation
enabled.

 Then I added a 'Show FPS' option to the misc menu. I also didn't
realize I was still embedding the SNES controller bitmap even though
it wasn't displayed anywhere, so for now that's been removed. Makes
the EXE and archive a bit smaller.

 Lastly, I redid the bsnes section of my site to look a little more
polished. Getting ready for 10/14. I've always hated the way SNES
emulator authors always cherry picked most of their screenshots to
show off their special chip support (jealousy because I didn't have
any for a long time), so I decided I'd do the exact same thing myself
this time :P
 Ripped off Overload yet again, this time I stole his screenshot
layout style. Sorry, Overload ... but imitation is the sincerest form
of flattery, right? :)

 Also, note that all of the ?page=bsnes_* URIs have changed to
?page=bsnes/* ... so if you get redirected to the main page from a
bookmark or something, that's why.

             Whew, busy day today ...

[No archive available]
2007-10-12 06:55:00 +00:00
byuu
9fd379613a Update to bsnes v024 release.
This is an interim release between some major changes to the video mode support, which may take a long time to complete. It also fixes a bug with CGRAM access timing, re-adds the Sufami Turbo load menu, and adds support for the ST-010 coprocessor, used by F1 Race of Champions.
To load Sufami Turbo cartridges, stbios.bin must be placed inside a folder named bios in the bsnes folder. There is not currently a warning if this file is missing.
2007-10-01 09:03:44 +00:00
byuu
aabf52d678 Update to bsnes v023r01? release.
Alright, I've posted the new WIP.

             Changelog:
             - CGRAM fix for WWF Super Wrestlemania
             - Updated to blargg's snes_ntsc library to version 0.2.2
             - Added ST and ST dual cart loading menu options (*)
             - Redesigned the video mode configuration panel a bit --
let me know what you think (**)

 (*) - You have to set path.bios to an -absolute- path, ./ is
currently broken and I need to fix that. So, set it to eg
"c:/path/to/bsnes/bios" where stbios.bin is inside that folder.
             (**) - The video menu obviously doesn't do anything, it's
just there for design advice / suggestions for now.

 You'll notice the icon is gone. This is because I built this version
with MinGW 4, and I'm not sure how to add the icon to MinGW apps.
You'll also notice it's ~6% faster on Core 2 processors as a result.

 The 16% speedup was only when PGO was enabled. But I can't enable
that, because it causes bsnes to crash randomly. GCC gets too risky
with its optimizations and ends up generating bad code (the GCC manual
states as much, I'm not just trying to blame problems in my app on GCC
here.)

 So, 6% is the best speedup we can do for now. Compare to v0.023
official if you like. You probably won't see the speedup on older
processors like the Pentium IV.

 EDIT: it seems like that MinGW vsnprintf problem is based on DLL
files on the local computer. Probably the MS VisualC runtime files.
The WIP works fine on my home PC (WinXP Pro), but not on my work PC
(Win2k). I'm going to have to stick with Visual C++ builds until I am
able to completely remove all sprintf-style calls from the emulator.

 If you get an error about memory at 0xffffffff which cannot be read,
you know why. Try building with Visual C++ if you have it, or maybe
there's some way to upgrade libc DLLs that the app is binding to.
Whatever DLL has vsnprintf is the one that needs to be updated, if at
all possible.

             Here's what the video config screen looks like at the
moment.

             [image]

 I tried putting the text at the top, that way there won't be any odd
gaps between the text and combo box dropdown, due to different sized
fonts on different platforms.

[No archive available]
2007-09-25 14:20:00 +00:00
byuu
c9ca01fe20 Update to bsnes v023 release.
I've recently fixed a bug in bsnes that I feel is serious enough to warrant a new release, even though little else has changed.
I attempted to build this release with MinGW, but ran into problems with profiling and JMA support, so this release was built with Visual C++ once again.
Changelog:
    - Fixed serious bug in S-SMP incw and decw instructions -- fixes sound bug in Emerald Dragon
    - Added Nach's MinGW fixes -- can now be compiled with MinGW/GCC3 or MinGW/GCC4
    - Fixed const char* cast warnings in GCC 4.2, thanks to [vEX] for the feedback
    - Updated source to use latest libraries for libco, libui, etc.
    - Added new advanced options to adjust aspect ratio correction
    - Cleaned up source code a bit
2007-09-16 19:30:35 +00:00
byuu
becf122aaa Update to bsnes v022r04? release.
Ok, I've posted a new WIP with the Emerald Dragon bug
fix. This time, I'm not posting the WIP publically. My last request
not to link directly to the file elsewhere was ignored, and ended up
on at least two emulation news sites (I won't mention names.) I'm not
trying to be a jerk about it, I really can't spare that kind of
bandwidth.

 If anyone has contributed any code or bug fixes, reported any
confirmed bugs, or is an emulator author I've spoken to in the past,
feel free to request a link to the WIP page from me in PM if desired.

               Sorry to everyone else. I'll have the new version out
as soon as possible.







> As for the AR advanced option, I think option 2 looks perfect.




 Done. I didn't add any sanity checks, so that people can have a
little fun with it. It's not going to be a GUI option, so only
advanced users can play with it anyway. Try setting a crazy aspect
like 3:1 and play a platform game. It's guaranteed to mess with your
mind.

 I also added the ... stuff, but I did not add the pause support back
in yet. Not sure if that'll make the next release, because it requires
some changes to the main loop functions that have been missing for a
while now. I usually like to leave more of a beta testing window
before messing with that stuff.







> byuu, you may know this, but on the front page of your web site, the
> link to your Philosophical Ramblings page is
> "http://localhost/index.php?page=articles/philosophy".




               Hahah, oops. No, I didn't notice that. I must have
copied the link from my browser instead of typing it manually.

 It's a stupid article, anyway. Didn't come out like I planned. I was
also reading some comments by Miguel de Icaza (supporting patent
pacts) and Linus Torvalds (bashing the hell out of C++ programmers),
and came across an interesting comment that got me thinking. Basically
that people who have any kind of notability really shouldn't go around
talking about things outside their specific expertise, because it
makes them look foolish when people take them too seriously (and
people do) as those two comments by de Icaza and Torvalds did. Lucky
for me I really _don't_ have any kind of notability, but it's a good
principle to adhere to anyway. Stick to talking about what I know
best. That goes against my whole personality though, so I probably
won't change at all anyway.

[No archive available]
2007-09-12 10:08:00 +00:00
byuu
1e130d7872 Update to bsnes v022r03 release.
Double post!

 I've uploaded a new WIP, which I'll make public (only to this forum,
please don't post about it anywhere else unless you mirror the file):







    http://byuu.org/files/bsnes_v022_wip03.zip




 This version adds all of Nach's MinGW fixes, updated libco, libui and
libfunctor, cleans up the code that detects if the main window has
focus or not (if not, ignore keyboard input), adds the new makefile
target win-mingw-lui, finally fixes all of the char* conversion
warnings with GCC 4.2.x (thanks [vEX]), and I'm sure there's more, but
I don't remember.

 The ZIP includes a Visual C++ generated binary, but it also works
with MinGW GCC4. It won't work with MinGW GCC3 because that one lacks
a C99-compliant vsnprintf function. You can hack your way around that
by editing src/lib/libstring_sprintf.cpp if you really want to use
MinGW GCC3.

 You may also need to change the CC / CPP variable names. I went with
the generic names mingw32-gcc and mingw32-g++, but the GCC4 binaries
have -sjlj or -dw2 appended to them. You'll also need to set
-I/path/to/directxheaders, or copy them all into
/path/to/mingw/include, since MinGW seems to ignore the include
environment variable.

 And finally, a bit of good news. It appears that MinGW GCC4 builds
binaries that are ~6% faster than Visual C++. That means with PGO
enabled, they should be at least ~16% faster than v0.022 official. If
I can figure out how to hide the ugly terminal window in the
background, I'll start making official releases with MinGW GCC4 from
now on.
2007-09-08 08:41:18 +00:00
byuu
c57c733d7d Update to bsnes v022 release.
Today marks a milestone for bsnes, and possibly for SNES emulation as a whole. With this new release, bsnes' compatibility has now reached 100.0%, with zero game-specific hacks. With every last commercially released game tested by both FitzRoy and tetsuo55 for at least five minutes each, all known bugs have been resolved.
Now, needless to say, I am referring to the emulation of the base SNES unit. As many SNES cartridges contain additional coprocessors on their PCBs, there are still unplayable titles. So how can I claim compatibility of 100%? Because I don't consider special chips inside game cartridges as part of the base SNES hardware. I realize that many people enjoy these games, and I do actively attempt to emulate as many coprocessors as possible (six are supported thus far). However, coprocessors such as the SuperFX and SA-1 continue to pose very significant challenges.
So, after nearly three years of development, I've finally achieved my primary goal. But it wasn't a complete victory ... I've learned a lot over the years. Emulation accuracy is not black and white -- there are heavy costs to pay and forced tradeoffs to achieve it. I no longer believe there is only one absolute path for emulation, as I did in 2004.
So does this mean bsnes is now perfect? Of course not. There are many technical details that are not emulated correctly. This also does mean that there are no bugs, merely that there are no bugs that we are aware of. While absolute verification of 100% compatibility is obvioulsy impossible, even by actually beating every single game from start to finish, this very well should be the first time any SNES emulator could claim zero known bugs with all known games tested. I very much expect this announcement to entice many new users to begin actively searching for bugs, in an effort to discredit my above claim. My response? Go for it! I would very much appreciate any and all discovered bugs to be posted here, so that they can be verified and addressed.
One major thing that needs to be said, is that there consists of one major hack in all SNES emulators, including bsnes: the use of scanline-based PPU renderers. This necessitates global hacks in all emulators to minimize their inaccuracies. I was going to write up a very long post here, going into specifics, but I've decided an article would be a better place for that. I will hopefully be writing up this article in a few days to post here.
In the meantime, one very important issue does need to be addressed. This version fixes a bug in Uniracers 2-player mode, where the game writes to OAM during active display. Like other PPU global hacks, Uniracers required a special consession. But because this hack only affects one game, it can very fairly be seen as cheating. Suffice to say, bsnes does not contain a game-specific hack, and the change made to fix Uniracers affects all games, but I do still very much consider it to be a hack. The fix I have added is quite literally and honestly more accurate than the behavior of bsnes v0.021. Before, writes to OAM and CGRAM during active display went where a programmer would expect, which would cause bugs when ran on real hardware. Uniracers is the only game known to do this, and it is very dangerous to do so. The writes do go through, but not where one would expect. The access address basically changes as the screen is rendered. With a scanline-based PPU, it is not possible to emulate the individual 
steppings of the PPU, as there is not enough precision. Further, the entire SNES emulation community has virtually no information on how active display OAM and CGRAM writes work. Now, as Uniracers is the only game known to do this, I had the choice of either intentionally remapping the writes to an arbitrary location, or change it to the address Uniracers expects. Neither would be more accurate than the other, as both are completely wrong from a haradware standpoint. So the decision was to either fix Uniracers and deal with some calling it a game-specific hack, or to leave it broken with absolutely no gain to accuracy. Rather than decide for myself, I asked those who have supported me over the past three years for their opinions. The decision was unanimous to fix Uniracers. You can read the discussion, along with a more technical explanation of the issue, here. I will be addressing this topic in much greater detail in the article I will be writing up shortly.
Changelog:
    - Fixed buffer overflow that was manifesting as corrupted tiles in Lemmings 2
    - OAM and CGRAM addresses are now invalidated during active display, however the algorithms for how this address invalidation occurs is currently still unknown, so reads/writes are mapped to static addresses for now
    - Re-added cheat code editor.
    - Windows only: keypresses when main emulation window is not active are ignored once again
2007-08-04 19:54:35 +00:00
byuu
e41aa25887 Update to bsnes v021r02? release.
I've posted a new private WIP. This one just adds the
cheat code editor back in again. Feedback on how it works is
appreciated. You'll notice it's a lot simpler than v0.019's cheat
editor ... I was going for simplicity this time. Editing a code means
deleting and re-adding it (or edit the text file directly). Yes, I
realize it's damn annoying entering codes because the emulator detects
your keypresses as controller presses (unless you're using a joypad).
Sorry, I still need to add code to determine if the active window is
the main emulator window or not for GTK+ before I can fix this on both
ports.

 Hopefully I can get that in before v0.022, but no promises. Worst
case, I'll add a dummy Window::active() function that always returns
true for GTK+ if needed.

 The cheat editor works the exact same on Windows and Linux, so this
should be the first release to allow Linux users to use it.

 Looking more at how useful bsnes is in its' current form ... I'm
simply not going to be able to walk away from it. Fuck it, I'll just
have to split the emulator and maintain two separate versions. It may
cost me some time, but whatever. It'll be good practice in trying to
streamline things to share as much code as possible. I'll keep them
together in one version as long as possible, too (using #defines and
such).

 If I do this, any suggestions on how to differentiate the two
versions? Different names? Different acronyms after bsnes (eg bsnes/AE
and bsnes/SE ...)? Different icons?







> One important point imo is the potential for "code longetivity".
> That is, I'd like the original, untouched code to continue to exist
> (while permitting derivative works) many decades from now.




 No matter the license, that won't change. People can close derived
works with PD, but it's their code that they added which becomes
closed, not mine. It won't make my code cease to be.

 It's not like it all matters that much. Regardless of license, anyone
is always free to get PD access to my code by asking. This is just me
trying to get a public consensus on whether or not I should allow
people to use my code without my permission, and to what extent I
should allow it.

 I was hoping the votes would be less 'all over the board' like the
Uniracers fix ... this vote isn't going very well. Sigh.

 It'd be annoying specifying licenses on everything. Maybe I'll just
bundle the core components (cpu, smp, ppu, dsp, memory, chip sans c4
(I don't own the rights to that)) and stick them in a separate
downloadable archive that's PD [or GPL w/permission exception]. That
way, I'm giving away the stuff that's important and can help others
the most, the emulation core. If someone can't be bothered to ask me
for mine, then they can write their own GUI. Call the package
something like 'libbsnes'. Meh.

[No archive available]
2007-08-03 08:23:00 +00:00
byuu
435f7d4371 Update to bsnes v021r01? release.
Alright, I've posted the new WIP.

             This one's really important, so please test it
thoroughly! :D
 I've ran it through my usual list of troublesome games, and
everything looks good, but it's possible I've overlooked something.

             The new config file settings are:
             ppu.hack.oam_address_invalidation
             ppu.hack.cgram_address_invalidation

 Set to true, OAM goes to 0x0218 (for Uniracers), CGRAM to 0x0000
(address is insignificant, we know of zero examples of this behavior,
so the address chosen does not matter for now). Set to false, the
writes are allowed and go where 'expected' (by programmers, not by
hardware).

 There's a slight difference in that OAM access is invalid even during
hblank, whereas CGRAM is obviously not (that's how games draw those
gradient fades and such).

             This WIP also has the Lemmings II fix.

             ---

 Now, I know I said I wouldn't bring this up again, but meh. So,
assuming I decide to go full force at this PPU renderer ... I still
want to let bsnes live on in its' current form, even if that means
losing my userbase to a competitor :(
 I'm planning for the next release to allow derivative works, in hopes
that someone will continue it. Does anyone have any objections to
that? Would it be better to use GPLv2/3 to ensure source availability
(even though I disagree with the notion of 'freedom through
restrictions' -- I liken it to becoming your enemies to defeat them),
or better to use PD to ensure the widest possible use of the code
(even if that means the source can be closed off to the public, and
the binary sold for profit -- which I also detest as immoral)? I
realize the latter means the value of all of my work will be lost, but
I never intended to profit from any of this anyway, so ...

 If you prefer GPL, please specify either v2 only, v2+ or v3. I can
use v3 and grant ZSNES an exception to use it under v2, so their v2
only license won't be a problem.

             Some examples:
             ZSNES is GPLv2, which got them the source to Zsnexbox.
 PocketNES is PD, which got the emulator used in commercial software
by Atlus, Hudson and Jaleco (though the assholes couldn't even be
bothered to send a thank you letter to the PocketNES devs).

 EDIT: I can also stick with the current license, a no-derivative one,
and do my best to maintain bsnes' old PPU renderer, if you like. But I
won't lie ... the pace of development _will_ slow down a lot on the
older version (it shouldn't affect my new PPU development speed much)
if we go with this option.

             Once again, I'll go with community opinion this time. I'm
personally not casting a vote for either.

[No archive available]
2007-08-02 08:46:00 +00:00
byuu
a1980fab09 Update to bsnes v021 release.
This is a maintainence release. I am mostly releasing this for the sake of the recently released Der Langrisser translation.
Changelog:
Windows port can once again map joypads through the Input Configuration panel
Using enter or spacebar to assign a key should no longer instantly map those keys
F11 now toggles fullscreen mode
Esc now toggles menu on and off (use F11+Esc combined to hide UI completely)
Fixed a bug in King of Dragons (J, U, E), KOFF was not cleared during S-DSP power(), thanks to FitzRoy for the report, and blargg for assistance fixing the bug
Fixed serious crashing error with File->Load on Linux/amd64 port
Hopefully fixed min/max undefined error on GCC 4.2.0, but I am unable to test to verify
Fixed many cast const char* to char* warnings for GCC 4.2.0, but some probably remain, as again, I am unable to test as I lack GCC 4.2.0
Set XV_AUTO_COLORKEY to 1 for Video/Xv renderer. Should fix some video drivers where there was no output, especially after running mplayer, etc. Thanks to sinimas for the fix
Added clear_video() to Video/Xv renderer. Green edges at the bottom and right sides of the video output are now gone, and unloading a ROM will clear video
I have finally figured out how to poll the keyboard status in real-time through Xorg: the XQueryKeymap function. I will be rewriting the Linux key capture system to use this, instead of capturing window key up / down messages through GTK+. This will finally allow me to completely abstract the UI from the hardware video, audio and input interfaces: a necessary step toward Linux joypad support.
2007-06-10 19:27:46 +00:00
byuu
ebb234ba5f Update to bsnes v020 01 release.
[No changelog available]
2007-06-05 15:50:59 +00:00
byuu
2cc7fe30b4 Update to bsnes v020 release.
Five months and 43 WIP releases in the making, today I am releasing bsnes v0.020. I'd really like to express my thanks to blargg, for he has written a new S-DSP emulator that is an impressive 32 times more precise than all existing S-DSP emulators. It is now bus-accurate, and should produce bit-perfect sound output to that of a real SNES, excepting very minor, very extreme edge cases. Not only did he do this, he went out of his way to develop a special version exclusively for bsnes to ease licensing concerns and take advantage of bsnes' unique features, notably cothreads. I can't thank him enough. Unfortunately, bsnes has taken a ~10% speed hit over v0.019 by using this new S-DSP emulator, but I must stress the speed hit is entirely due to the way bsnes is implemented. blargg's standalone S-DSP emulator is very, very fast. Anyone is free to take a look at his S-DSP emulator, as he has released it as open source under the LGPL, by visiting his homepage, here.
Unfortunately, the new cross-platform UI is not entirely finished. Some sacrifices had to be made to support libui. Specifically, the following features are missing from v0.019, but will hopefully be added back in future releases:
    - Fullscreen support
    - Input Configuration panel cannot capture joypad input. Joypad support is still present, but it must be mapped manually through the Advanced panel or through editing bsnes.cfg by hand
    - The Cheat Code Editor is missing, but cht files can still be used from bsnes v0.019, and created by hand
    - Sufami Turbo support is not accessible from the UI
    - The UI on Windows is slightly less polished due to compromises to allow the UI to be readable on Linux.
I am sorry for the rough edges listed above, but I wanted to get a new release out, as it has been over five months since the last release, and I really want the world to be able to experience blargg's new S-DSP emulator.
Changelog:
    - Added blargg's new S-DSP emulator, runs at 1.024mhz. Many thanks to blargg for this, as this puts all portions of SNES emulation except for the S-PPU at bus-accuracy
    - blargg's S-DSP core fixes bugs in both Koushien 2 (J) and Toy Story (U)
    - Corrected all S-SMP cycle timings to be hardware accurate. Thanks to blargg for creating an amazing test ROM that tested every possible opcode
    - Corrected S-CPU wai instruction timing, fixes Mortal Kombat II
    - Reverted HDMA sync emulation once more to fix Breath of Fire II (G) and Secret of Mana (U)
    - Completely rewrote user interface to use libui, which is a wrapper that allows the same code to produce the same UI on both Windows (through the Win32 API) and Linux (through the GTK+ API)
    - Corrected $2100.d7 OAM reset behavior, thanks to research from anomie
    - Massively revamped the Linux port, should compile with no warnings or errors now
    - Added 64-bit support to libco, tested on FreeBSD/amd64, should work on Linux as well
    - Revamped makefile with suggestions from Nach
    - Improved Linux Xv renderer to use the far more common YUY2 format, which should work on most Xorg drivers, allowing hardware accelerated video scaling
    - Completely rewrote config file system. bsnes.cfg is now saved to user's profile folder on both Windows and Linux, allowing multi-user support
    - A lot more work has been done behind the scenes, including massive code cleanups and portability improvements
You may download the new version on the main bsnes page.
2007-06-03 00:20:00 +00:00
byuu
5c3c872b78 Update to bsnes v019r41? release.
New WIP up.

 I've replaced the interface::input setup, since Visual C++ was having
problems with it. I wanted something that wasn't so seemingly directly
linked to SNESInterface, anyway. Now I have InputManager, which will
handle not only all of the joypad mappings, but the GUI shortcut keys
as well. Yes -- I finally have all the code in place to support user-
defined shortcut keys. See? Something good did come out of the rewrite
after all. Dynamic keyboard mapping works on Windows now, but there
probably won't be joypad capture support until v0.021.

 Further, I have added SHGetFolderPath to the Windows port. libbase.h
sadly requires shell32.lib now. I haven't tested this on 9x, but I
don't believe bsnes has worked on 9x in a long, long time now. I've
also heard you can copy shfolder.dll or something to use it on 9x
anyway.

 Anyway, the config file now saves in your 'Application Data' folder
on Windows, and in your local directory on Linux. There's no need to
worry about what happens when you update bsnes and don't delete the
file ... as I use a text-based config file, like ZSNES / PSR, no harm
will come of it. Old variables will be flushed out, new variables will
be added with default values upon first load of the new version.
Thanks again to Nach for the code and help with this.

             Lastly, I've added a bsnes license page. So instead of
debating whether to look up four letter English words in Perens',
Stallman's or Webster's dictionary, you can just link to that page
instead :)

Again, the license applies to current and previous versions of bsnes.
If and when it forks, the fork will likely be licensed in a way that
others can take over the old version.

 Opinions on how to fix contradictions / loopholes welcome, blanket
statements that it's totally flawed without describing why or how are
not. Thanks in advance.

[No archive available]
2007-05-30 05:00:00 +00:00
byuu
36bf915244 Update to bsnes v019r40 release.
Ok, here's a public WIP for everyone:







    http://byuu.cinnamonpirate.com/files/bsnes_v019_wip40.zip




               Please ... if you link to this post or file elsewhere,
please mirror it.

               Fixes since wip39:
               - menu enter event captured, audio no longer hangs when
entering the menu.
 - multiple click problems resolved for all menu items plus list box
controls. Behavior should now be the same on both Windows and Linux,
but further polish is definitely needed here.
               - buttons to set values on input config and advanced
panels are now disabled when no item is selected.

               Known problems:
 - Windows/VC++ port is still complaining about that
interface::input.bind() thing. I believe it is a compiler problem. I
am not working around it, as I prefer a real fix. If anyone can help,
please see src/ui/lui/settings/ui_inputconfig.cpp, look for that line.
It is #if !defined(_MSC_VER) blocked at the moment. Until this is
resolved, you must restart before input settings take effect.
 - Joypads cannot be auto polled on input config screen. You can set
the values manually on the advanced tab, they use the same values as
bsnes v019, IIRC.
 - When pressing enter (or spacebar on Linux) on the input config
panel, the dialog pops up and closes right away assigning that key. I
have no easy way to fix this, since I can't poll the realtime status
of those keys on Linux to wait for them to clear before showing the
input capture window. It would really be immensely useful to be able
to do that.
 - Linux with ati driver requires you to move the window one time to
make the image visible ... I have no idea why this is needed. nv and
nvidia drivers work fine. Use the gtk renderer if you don't like the
chroma blending that using YUY2 mode requires.
               - Linux port does not focus properly to panel list when
opening config screen.
 - Config file still saves to startup working directory, rather than
the user folder. Still planning to work on that.
 - UI is still pretty ugly on Windows, but overall it's not too bad.
Looks beautiful on Linux, though ... maybe if I could find a way to
enable theme support for Windows. I tried making a .manifest file and
using mt, and setting WINVER + _WIN32_WINNT to 0x0500, none of those
did anything.
 - Cheat code editor has not been reimplemented yet. Really the last
major thing holding back a new release, but the above are pretty
important, too.

               Let me know if anything else major pops up.







> Plus it prevents a smart user/admin from making their program
> directory read-only.




               Once again, blargg has the most convincing argument :)
               Wouldn't want that config file on a read-only medium,
eg CD-ROM.
               I was wanting to implement this on Windows anyway, but
this makes it something I simply have to do.

[No archive available]
2007-05-29 08:37:00 +00:00
byuu
045a0f7e79 Update to bsnes v019r24? release.
New WIP. This one adds a GDI renderer for windows. If
anyone wants to test it, edit bsnes.cfg and set system.video to "gdi".
It will be very slow, obviously. It's just there for the hell of it,
as another fallback I guess. I'd be interested if it didn't work for
someone.
I had to add the code to libui to support pixel buffer images, so now
I can add things like the controller art into the new lui port, and
it'll work on Windows and Linux. The best part is that I can make
these image buffers anywhere, so things like PPU VRAM / OAM / CGRAM
viewers in the debugger will now not only be possible, but trivial, to
add in the future.

 Refined libui a lot more, but I did not merge that into this bsnes
WIP, because it would break the source pretty bad. Still working on
the API, too, so I'll probably hold off a bit longer. After I get the
new libui merged in, I can start working on that configuration
settings window. That window is the only thing holding up a new
official release.

 I'm trying to figure out how the hell you enable WinXP themes now. I
tried making a manifest file, even attaching the manifest to the EXE
directly with the mt tool, but it's still drawing the controls using
the old win32 compatibility mode.







> I can see that he hesitates to add "MAXI" codes and has no multiple
> codes for any game, despite how prevalent I've found them to be.




 You have cartridges where it's the exact same game (eg bit-for-bit
identical ROM dumps), with the only difference being the PCB codes?
Care to cite an example? The last two digits may change for revisions
of the same game, obviously.

 That complicates things, but there's no harm in just picking one in
that case. If the game didn't work with that PCB, it wouldn't have
been released with it, so ...

[No archive available]
2007-04-11 12:51:00 +00:00
byuu
a209e6ffbe Update to bsnes v019r23 release.
Ok, this is a very important WIP release. Note that
this file is rather large, please mirror it if you must link to it
elsewhere.







    http://byuu.cinnamonpirate.com/files/bsnes_v019_wip23.zip




               Included are two executables:
               bsnes_adsp.exe - This version uses anomie's S-DSP
emulator, clocked at 32khz
               bsnes_bdsp.exe - This version uses blargg's S-DSP
emulator, clocked at 1.024mhz

 Please note that blargg's code is experimental and in-progress. That
said, I have been unable to find any errors with it so far. I hope I
haven't missed anything blargg wanted me to do before release.
Everyone, please give your thanks to blargg for creating this emulator
and allowing me to use his code :)

 This day marks an important milestone, at least in bsnes, possibly in
the SNES emulation scene: the addition of a subsample-accurate S-DSP
emulator brings us one major step closer to the most faithful SNES
emulation that will ever be possible. Excepting bugs, this now gives
us bus-accurate S-CPU, S-SMP and S-DSP cores. It is not possible (nor
desirable) in software to get more precise than bus-level accesses.
The only core component remaining using an older, less faithful
approach is the S-PPU[1/2], and is not so coincidentally the source of
the only remaining bugs in bsnes. This will very likely be the biggest
leap forward in accuracy that will ever be seen for S-DSP emulation
from this date on.

 The old win32 interface is now completely broken, so I am forced to
distribute using lui. As such, I've fixed the NTSC/PAL mode switches,
and added software video filter selection to the UI. Any configuration
changes that are not in the menu will have to be done via the config
file for the time being. I have also added the log audio data option
back to the misc menu. If you are not able to get 60fps in bsnes, or
would like to analyze the audio output between adsp and bdsp in
another program, you can use this option. Also, I'm aware of the lui-
specific issues, such as audio repeating when entering menus. lui is
still a work in progress.

 Please test all of the games you can, and look for subtle audio
differences and the like. Bugs, improvements, whatever, would be very
useful to know. Please keep in mind that every commercial game ever
released was tested by both FitzRoy and tetsuo55, and there are
currently zero known problems with anomie's S-DSP emulator. Also note
that blargg's emulator will be slower, by nature of being more low-
level. I'll leave the decision on which core to enable by default to
you guys. Eventually, I'll have polymorphism fully functional, and
this will be a runtime-selectable option, and not require two separate
builds. But still, we unfortunately have to pick one to be the default
setting, which I hope does not offend anyone :(

 I'm very appreciative and in debt to both anomie and blargg for their
help with S-DSP emulation. They have both done a very large service to
us all by creating these cores, so I thank both of them again for all
their hard work, and for allowing me to use their work in bsnes.

[No archive available]
2007-03-07 10:27:00 +00:00
byuu
3bf672dd97 Update to bsnes v019r19? release.
Ok, added blargg's changes. Played four levels, seems to be working
fine.

 Posted a new WIP with this change. I also replaced libkeymap with a
new implementation of it, this one is designed to work with window key
messages, meaning we can finally have input configuration for GUI
events and such in the future, and Linux users will finally have input
support shortly.

             Still not now, though. Input on Windows might be a little
sketchy, as well.

             Just need to create an InputWM class for Linux.

[No archive available]
2007-03-06 10:15:00 +00:00
byuu
157ddf3e8f Update to bsnes v019r18? release.
Unfortunately, even an S/PDIF link from a real SNES isn't good enough,
as we can't verify/match its' CPU<>SMP communications. Our best bet
for verification is still the echo buffer.

I uploaded a new private WIP. This build is just demonstrating part of
the new UI. I'm trying to move back to putting everything commonly
used in the menubar, and moving all of the obscure/complex stuff out
into separate windows.

             So far, lots of stuff is still missing, and the speed
setting (not enable) doesn't work.

 How does the video mode configuration feel in this WIP compared to
v0.019's video settings panel? Easier, better, worse? I realize it
loses a bit of flexibility (eg with custom resolutions), but eh. I'd
rather go back to simplicity than feature bloat.

[No archive available]
2007-02-19 03:37:00 +00:00
byuu
ea23bf53ae Update to bsnes v019r17 release.
Ok, as promised, a public WIP build:







    http://byuu.cinnamonpirate.com/files/bsnes_v019_wip17.zip




               As always, please be generous with this one. If you
must link to it elsewhere, please at least mirror it.

 This should finally take care of the Toy Story bug. Yes, the audio
should halt roughly. The developers felt the need to use an evil trick
to force the audio to release faster than it normally should.

[No archive available]
2007-02-18 04:29:00 +00:00
byuu
d4598e1d01 Update to bsnes v019r13a release.
(Repost, since this got bumped by another page, but
updated message.)

 Ok, this build has TRAC's and my idea for an S-DSP EDL fix applied.
EDL writes take effect immediately, and echo index bounds checking
occurs before FIR filtering and echo buffer writes. Please test this
with all of the really really picky/sensitive audio games you're aware
of, and see if you notice a difference between this and v0.019
official. Obviously, the sound differences should only exist in echo
effects, but luckily just about every game out there uses the echo
buffer. Note any differences you find either way, but I'm particularly
interested if things get worse, which will imply this fix is incorrect
(assuming the difference is verified in hardware as being correct in
v0.019 official), and we can try out the fix idea suggested by DMV27.
If no one finds any new audio bugs, we'll assume the fix was correct.

 And no, there's no audio resampling in this. I think log audio data
might still work, if that'll make it easier. It might not, the win32
port is falling apart as I rewrite the cross-platform port.







    http://byuu.cinnamonpirate.com/files/bsnes_v019_wip13.zip




 If anyone insists on posting about this on some other site (I'd
prefer not, as always), please at least mirror the file.

 Update: audio logger works. I binary compared two files. The only
difference is that audio is being output four samples sooner now,
they're otherwise exact matches. Doesn't seem to be a bad thing by any
means.

[No archive available]
2007-02-09 08:50:00 +00:00
byuu
f9a8564af0 Update to bsnes v019r11 release.
Ok, I tried my best to add the audio synchronization
method (drop video frames) yet again, and once again failed
completely.

 The below WIP is completely unusuable as it stands, so please don't
link to it, host it anywhere else, or even download it unless you can
help with the programming. I'm not going to be able to fix this myself
as I've tried countless times over the last two years in vain to fix
it.







    http://byuu.cinnamonpirate.com/files/bsnes_v019_wip11.zip




 The included config file is important: it uses the DirectDraw
renderer instead of the D3D renderer, and has triple buffering
enabled.

               The relevant code is in src/ui/video/ddraw.cpp and
src/ui/audio/dsound.cpp.

               The most important code is below, but obviously any
tests would need the above WIP to build and try out.







    void AudioDS::run(uint32 sample) {
                       uiVideo->tick();
                       data.buffer[data.buffer_pos++] = sample;

                       if(data.buffer_pos < latency)return;

                       uint32 ring_pos, pos, size;
                       do {
                       Sleep(1);
                       uiVideo->tick();
                       dsb_b->GetCurrentPosition(&pos, 0);
                       ring_pos = pos / data.ring_size;
                       } while(config::system.regulate_speed == true
    && ring_pos == data.ring_pos);

                       data.ring_pos = ring_pos;
                       void *output;
                       if(dsb_b->Lock(((data.ring_pos + 2) % 3) *
    data.ring_size,
                       data.ring_size, &output, &size, 0, 0, 0) ==
    DS_OK) {
                       //Audio::resample_hermite((uint32*)output,
    data.buffer, latency, data.buffer_pos);
                       memcpy(output, data.buffer, data.ring_size);
                       dsb_b->Unlock(output, size, 0, 0);
                       }

                       data.buffer_pos = 0;
                       }

                       bool VideoDD::lock(uint16 *&data, uint &pitch)
    {
                       if(video_buffer[video_active]->Lock(0, &ddsd,
    DDLOCK_WAIT, 0) != DD_OK) return false;
                       video_valid[video_active] = false;
                       pitch = ddsd.lPitch;
                       data = (uint16*)ddsd.lpSurface;
                       return data;
                       }

                       void VideoDD::unlock() {
                       video_buffer[video_active]->Unlock(0);
                       }

                       void VideoDD::refresh() {
                       video_valid[video_active] = true;
                       video_active ^= 1;
                       tick();
                       }

                       void VideoDD::tick() {
                       if(video_valid[0] == false && video_valid[1] ==
    false) return; //nothing to render
                       uint idx = video_valid[!video_active] == true ?
    !video_active : video_active;
                       // if(video_valid[!video_active] == false)
    return;
                       //uint idx = !video_active;

                       if(settings.triple_buffering == true) {
                       BOOL in_vblank;
                       lpdd7->GetVerticalBlankStatus(&in_vblank);
                       if(in_vblank == false) return;

                       //DWORD scanline;
                       // lpdd7->GetScanLine(&scanline);
                       // if(scanline < screen_height()) return;

                       //
    lpdd7->WaitForVerticalBlank(DDWAITVB_BLOCKBEGIN, 0);
                       }

                       HRESULT hr;
                       RECT rd, rs;
                       snes.get_video_info(&vi);
                       SetRect(&rs, 0, 0, vi.width, vi.height);

                       POINT p = { 0, 0 };
                       ClientToScreen(hwnd, &p);
                       GetClientRect(hwnd, &rd);
                       OffsetRect(&rd, p.x, p.y);

                       hr = screen->Blt(&rd, video_buffer[idx], &rs,
    DDBLT_WAIT, 0);
                       video_valid[idx] = false;

                       if(hr == DDERR_SURFACELOST) {
                       screen->Restore();
                       video_buffer[0]->Restore();
                       video_buffer[1]->Restore();
                       }
                       }




               What I'm basically doing is:
 Audio keeps a ring buffer, and waits until the temporary buffer fills
up before forcing the emulator to sleep until the audio playback
catches up. Every time an audio sample is generated, and every time
the emulator sleeps for one millisecond, it gives Video a chance to
run.

 Video has two backbuffers (a poor man's triple buffering, since that
doesn't work in windowed mode for DDraw). The PPU renders the entire
screen line by line, but it doesn't go from the PPU to the video card
until Video::video_lock is called. At this time, the current buffer
sets a flag to say it's contents are invalid, then it draws to the
frame, then sets a flag saying the current contents are again valid.
Finally, it calls the Video tick function to finish.

 Every time the Video tick function is called from Audio (well over
32,000 times a second, so it should have good precision for detecting
vblank edges).

 First, it will see if any frames have completely rendered. If not, it
will give up and return. Next, it will see if "triple buffering"
(really a vsync now, but emulates triple buffering at least) is
enabled. If so, it will return and do nothing if not in vblank.
Otherwise, or if triple buffering is disabled, it will continue. Next,
it finds the most recently rendered video frame that was valid and
blits that to the screen, and then sets that frame to invalid, so that
it is not rendered again (though it wouldn't hurt, it wastes CPU time
to blit the same image twice).

 I've tried even adding in a 1ms interrupt timer to try and help with
any emulation code that might be freezing the emulator for over an
entire vblank (nothing in bsnes should be that intensive), and this
did not help either.

 Basically, it's like I'm missing an unbelievable amount of frames,
like five out of six end up never getting drawn at all, so the video
is so choppy it's completely unusable. In reality, only one frame
should be dropped every 11 seconds. And when I enable the resampler,
that should change to only one frame every 66 seconds.

 As a side note, I added a four-tap hermite resampler in. It sounds
good too, but I have no idea if it's better or worse than cubic.

[No archive available]
2007-02-03 13:10:00 +00:00
byuu
6d66b1136d Update to bsnes v019r09 release.
Alright, I'm in a semi-good mood.







    http://byuu.cinnamonpirate.com/files/bsnes_v019_wip9.zip




 This one uses the old win32 interface, and adds a new feature I'd
like people with sound troubles to try out. The config file now
contains "audio.latency". Don't mess with "audio.frequency", it won't
do you any good and gets overridden by the speed regulation settings
for now.

 The audio.latency is a precise measurement of the millisecond delay
between sound being output by a real SNES and hearing that same sound
in bsnes. It takes into account the current playback frequency, as
well as the three-ring buffering system used by bsnes' audio system.
 Formula: sample_latency = CURRENT_playback_frequency / 1000 *
config_file_latency * 3 (so 32khz + 75ms latency means each ring
buffer is 800 samples long). The new formula should make latency sound
better (it's consistent now) on fast / slow emulation speed throttling
settings as well.
 I also cut out the fourth ring, since it was redundant. This should
make bsnes appear ~25% more responsive to sound with the same buffer
latency. As a result, I increased the latency to 75ms (it was at ~45
before).
 I'd like to know what the lowest good value is that works on 95% of
sound cards, so I can use that. I'll let people with cheap sound cards
increase their latency setting manually (eventually it will be an
option in the GUI).

               **NOTE:** this version does nothing for triple
buffering/vsync/whatever. You must _disable_ triple buffering to try
out the latency settings. This version is strictly to test audio
playback support.

 I also added in my audio point resampler. Good god, it sounds
terrible. Regardless of the latency setting (either really high or
really low), the pitch difference between each audio ring is
_extremely_ noticeable. The code is there now in
src/ui/audio/dsound.cpp : AudioDS::run_videosync(), if anyone would
like to take a look. I'll hold my breath ;)

               -----

 Comparisons against ZSNES at this point are rather silly. Aside from
much more flexible timings, it probably has a nice audio resampler,
which I don't. If I faked CPU/SMP clock timings, I could get the SNES
spitting out 60 frames a second and 32khz audio a second. I'm not
going to do that, so I have to figure out how to resample the two. All
of my attempts at resampling video _and_ audio have both failed
miserably to date. I really only need one of those to work to get
smooth video+audio, but both would be nice so the user can decide
what's more important to them.

I don't care to add 2xSaI. I'm planning on redoing the filter stuff
soon to support 32-bit output for Xv, so if someone wants to add 2xSaI
support to bsnes after that, I'll add it in. Otherwise, HQ2x is
superior and Scale2x looks about the same, yet is way faster.

 Regarding the IPS thing, exactly. As I said, IPS is a bad format. You
can't tell if you need to patch against a headered or unheadered ROM
unless you read the documentation that fuckheads like Cowering remove
in their ROM sets ("at least it's already prepatched"), or try
patching twice to see which one works. UPS will eliminate both of
these problems. Readmes will be included inside the patches, and UPS
will work regardless if your ROM has a header or not. It will also be
reversible. It'll be better in every regard over IPS, so I have no
reason to support IPS.

 Lastly, I don't have any intention of working on fixing DeJap's
patch, regardless of where the problem is, as I have no way to run the
game on my copier. Maybe when and if the last two serious bugs
(Uniracers and Koushien 2) get fixed, I'll take a look at it then.
2007-01-31 00:00:24 +00:00
byuu
b01f18c34c Update to bsnes v019r01? release.
First screenshots of libui in bsnes:

             [image] [image]

 Same exact codebase. The current WIP is obviously missing any
semblance of a GUI, other than the menubar and a ROM file loader.

 Lots of issues on both ports, of course. I'm aware of the audio
repeating issue on the Windows port and already know how to fix it
(had the same problem with the old Windows UI). Linux of course simply
has no audio or input.

 I'm planning on moving the framerate counter to display inside the
image, rather than on the titlebar this time. That of course won't
happen anytime soon. I don't expect to be adding fullscreen support
back in anytime soon, either.

 Once this port gets stable enough, I intend to remove the "ui/win"
and "ui/sdl" ports completely. After that, I'm going to have to start
seriously rewriting a lot of internal stuff.

 I'm also planning to go with a simpler user interface this time
around. bsnes v0.019 had too many options and features. I think I may
scale back this time and make things a lot simpler. Move a lot of the
control settings back into the menubar, rather than in the custom
options panel (which will most likely still exist).

[No archive available]
2007-01-15 04:25:00 +00:00
byuu
1ebdb69516 Update to bsnes v019 release.
I´m releasing bsnes v0.019 today. This version contains Bandai Sufami Turbo support, new IRQ emulation code, and some various bugfixes.
Unfortunately, this release is not entirely cause for celebration. Due to fatal errors in Microsoft´s "enterprise class" c++ compiler package, I am no longer able to compile bsnes with profile guided optimizations. I have tested v0.018 with and without these optimizations, and the difference is a 40% speedup when PGO is used, even more significant than I had previously believed. However, bsnes has now become too complex for Visual C++ to handle. Unfortunately, there is nothing I can do about this, except wait for Microsoft to fix their compiler.
(Warning: this paragraph contains personal opinions, skip it if you can´t handle that) As if this wasn´t enough, I´m now doing my best to wean my dependence from Microsoft´s line of operating systems, as I´m particularly concerned about the black box nature of Vista and its´ DRM control mechanisms. This isn´t a road I wish to begin traveling down, and thusly have no interest in upgrading to future versions of Windows. Therefore, as of late, I´ve been writing a UI wrapper that will allow me to code applications that are truly platform independent. The biggest goal for this library is to design a GUI for bsnes that runs virtually identically on both Windows and Linux/BSD. This is mostly complete, however there were many tricks I used in bsnes using the win32 API that I simply cannot do with GTK+ on Linux/BSD, such as the memory editor window subclassing. I will be porting bsnes to use this new UI wrapper, and in turn this will lessen the attractiveness / functionality of the bsnes UI to a certain degree.
Perhaps the most devastating news is that I am still contemplating the idea of designing a dot-based PPU renderer for bsnes. As if the loss of PGO wasn´t bad enough, this will likely eat away an unimaginable level of performance as well. I can only estimate the speed loss being between 100-500%. Yes, it will be that bad. And despite weeks of planning, I cannot think of a way to allow a scanline-based and dot-based renderer to coexist as selectable options, given their massive differences in implementation.
And let´s not even joke about SA-1 or SuperFX support ... those processors are each four to eight times more powerful than the SNES´ main CPU.
All of these speed losses will basically make bsnes mostly irrelevant as an alternative to ZSNES, SNES9x et al. Although I believe I really came close to a viable alternative with v0.018, I know that I cannot both create a mainstream emulator, as well as keep with my original goal to emulate the SNES as accurately as possible.
The past few months have been very tough for me; trying to decide which of the above two goals to pursue. I´ve still not absolutely made up my mind. But for now, I´ve been sitting on a mostly untouched version of bsnes for the last few months, and have decided to release it to the public, profile guided optimizations be damned.
I´m once again asking for help, if anyone can figure out why bsnes won´t compile with PGO support, please let me know. I´d very much like to get one last PGO build of bsnes released before starting on a dot-based PPU renderer. But given the usual response I get from these requests for help, I´d suggest no one getting their hopes up that bsnes will ever be as fast as it once was again.
The new version can be downloaded at the usual place. I´m leaving v0.018 up, as it may very well be the last stable, fast version of bsnes ever released.
2007-01-01 21:04:34 +00:00
byuu
add0f74387 Update to bsnes v018r10? release.
Ok, Sufami Turbo is finished. Now I just need to add back in
cheat/patch loading, and that should do for src/cart modifications for
a while.
             Maybe I'll add split ROM support while I'm at it just for
fun.

             There's now _some_ safety code regarding ST loading, but
it's not all there. Specifically, if a file fails to load, then you
won't get any errors, the game will just not work, obviously. I now
protect against loading oversized ROMs and SRAM files.

The database now lists each Sufami Turbo cart only once, and the cart
loading code handles matching up two ROMs from the database. It is
also now possible to play ST games with invalid checksums, so eg
translations/hacks of these games should now be possible, however
unlikely.

             FF:MQ (E) is fixed now too, so we're back to
FAVOR_ACCURACY in WIP builds again.

 A little more src/cart polishing and I'm going to start documenting
all that's known about IRQs, and try and figure out how they work once
and for all (hahah, yeah right -- I give it 2-3 weeks after fixing it
again before more problems are found).

[No archive available]
2006-11-07 08:55:00 +00:00
byuu
b20f70f333 Update to bsnes v018r09? release.
Ok, the new WIP is extremely fragile with ST stuff, but it should work
if you're careful.

             It took a _lot_ of rewriting to get those damn dual carts
booting. Right now, everything but the SD Gundam games are in the
database. I need to think of a way of combining those. So, the only
other dualable game is SD Ultra Battle - Ultraman Densetsu + Seven
Densetsu. Otherwise, test with just one ST cartridge at a time.

Anyway, it's definitely a work in progress, so be gentle with it. You
need "stbios.bin" in bsnes.cfg::path.bios for it to work. It probably
won't even give you an error if it isn't there.

             Suggestions for how to layout the file menu are welcome.

[No archive available]
2006-11-06 07:51:00 +00:00
byuu
9aebf7bc6b Update to bsnes v018r08? release.
Ok, the new WIP adds ppu.hack.obj_cache = [true/false], and renames
the scanline render pos to ppu.hack.scanline_render_position = [dec].

             OBJ cache defaults to off now, as two bugs are better
than four.

 Made SDP a bit more friendly to view now. I may port that style over
to my main website, too. Specifically the non fixed width part.

[No archive available]
2006-11-03 07:58:00 +00:00
byuu
a7bf219d5d Update to bsnes v018r07? release.
> Overall, I have a small list of possibles. Will wait until after
> R-Type to explore.




               Damn :(
 I don't think the R-Type III fix will correct anything else. But,
cross your fingers I guess. The new WIP fixes the aforementioned game.

 My SNES tests seem to indicate that writing #$20 to $4200 when
VCOUNTER==VIRQ will trigger an IRQ, even after an IRQ has already
fired on said line. My tests today indicate that it will not trigger
an IRQ under the above circumstances when the I flag is set. I don't
know why, it's the only thing other than the final IRQ trigger test
that cares what the I flag is set to. I'm not happy with the fix, but
it's the only explanation I can come up with, and all IRQ sensitive
games are running, as well all IRQ tests are still passing. So for
now, it'll have to do.

 I'm going to attempt to document all of SNES IRQs and see if I can
figure out a more simple method of emulating them, but I'm not
hopeful.

 I also removed the "guessed" entries from my database. I've decided
not to add anything unless we definitively know its' PCB ID, or in the
case of ST games, if it doesn't have one.

 Lastly, rewrote my SDP page on my site. It now uses XHTML 1.0 + pure
CSS2, so it should be a little easier on the eyes and a lot easier to
write documentation pages for.

[No archive available]
2006-11-01 09:05:00 +00:00
byuu
04118be59a Update to bsnes v018r04 release.
Ok, _please_ be courteous to my webhost and only download this WIP if
you're going to test it on a processor that hasn't been tested thus
far.

             byuu.org/files/bsnes_v018_wip4.zip
             byuu.org/files/bsnes_tests.zip

 This has two separate builds. Neither have PGO, SSE, SSE2, ZIP or JMA
support. They are identical except for the FAVOR_ flag define and
title of the program.

             FAVOR_ACCURACY [bsnes_accurate.exe]:
             - Always tests OAM RTO flags even on skipped frames
             - Tests NMI/IRQ trigger every clock cycle

             FAVOR_SPEED [bsnes_fast.exe]:
             - Only tests OAM RTO flags on rendered frames (always
with no frameskipping)
             - Tests NMI/IRQ trigger using ranges

 If you'd like to test, please run demo_mode3.smc on both versions of
bsnes, turn off speed regulation, and report the framerate both with a
frameskip of zero and a frameskip of nine (max), along with your
processor speed.

 The other test ROMs are just to verify that IRQ behavior is still
reliable in both versions. A blue screen indicates passing, they all
pass on both versions. Don't expect test_* ROMs to pass on other
emulators, but demo_* ones should.

             Example (my main PC):
             AMD Athlon 3500+

             Accurate:
             - 121.5 fps w/o frameskipping
             - 171 fps w/max frameskipping

             Fast:
             - 146.5 fps w/o frameskipping
             - 271.5 fps w/max frameskipping

             -----

             As you can see, there are _major_ speed differences on my
A64. Personally, I'm all for accuracy, but I also want people to
actually be able to use this program in the interim. Perhaps in the
future when a low end computer is a current low-end Core 2 Duo, we can
remove all of the "speedhack" code. And in the meantime, the full 100%
precision is there for people who have the CPU power to afford it.

             -----

             If anyone wants to try and help, heh.
 src/cpu/scpu/timing/irqtiming_accurate.cpp and
src/cpu/scpu/timing/irqtiming_fast.cpp are the two versions of the IRQ
testing code. If you see any ways to optimize either (preferrably the
former, obviously), I'd greatly appreciate it. Understand that both
the CPU counters (VCOUNTER, HCLOCK) and the IRQ timing positions
(VIRQPOS, HIRQPOS) can wrap not only the horizontal clock position
(1362->0), but the vertical position as well (261->0). And also that
they are "misaligned" by 10 clocks (which is really more of an
internal CPU IC delay thing, we aren't entirely sure why the
difference is there). You probably shouldn't mess with the code if you
don't understand the implications of this on eg range testing :/
2006-10-20 03:53:34 +00:00
byuu
f24d17859f Update to bsnes v018r01? release.
I've written a new scheduler for bsnes to take 100% full advantage of
cooperative multithreading. Now, bsnes only performs jumps directly
from one thread to another (CPU->SMP instead of CPU->main->SMP), and
even then only when absolutely needed (eg CPU is accessing SMP when
CPU is currently ahead of SMP).
This unfortunately makes bCPU and bSMP no longer compile. However, it
does yield some impressive speed gains. From 109fps to 125fps.
             By comparison, bsnes v0.017 yielded 128fps with my test
ROM.
 The speed gain though is dependant upon how utilized the CPU<>SMP
communication is, the difference in speed between v0.017 and my WIP
can be anywhere between 1% and 10%, with the WIP always being slower.
 The better news is that this is still without IRQs fully optimized. I
don't know how easy it will be to optimize these, if it's even doable
at all... but if I can, that would yield another very important speed
increase, making the next release the fastest ever. Here's to hoping.
 The bad news though is that cothreading's advantages are pretty much
maxed out completely now. Don't expect any future leaps in performance
from this. Still, overall... a 40% total speed increase and double the
processor synchronization precision was definitely worth the effort,
even for the potential loss of savestates.

 The scheduler should also make sPPU much faster when and if that's
ever started upon, but that's still going to take a very significant
speed hit over bPPU.

 One last benefit of the scheduler is that the new synchronization
method isn't limited to only two clocks. I can now easily add another
clock, eg for SFX/SA-1. Not that I'll be emulating either of those
within the next year or two, though. Just saying...

 I might also make two schedulers, one for cothreaded cores and one
for non-cothreaded cores. One thing is for certain though, I won't be
writing schedulers for every combination of cothreaded<>non-cothreaded
cores (there's 4 of them, CPU, SMP, PPU and DSP). And this will also
rule out run-time polymorphism's compile-time option, so expect that
to change to a compile-time only setting, meaning possibly two
versions of bsnes in the future.

 Now then, I also fixed up S-CPU emulation mode opcodes. Direct page
wrapping, stack wrapping with native mode opcodes and processor status
flag fixes. No games use emulation mode, but accuracy is always nice.

[No archive available]
2006-10-18 05:33:00 +00:00
byuu
35fd80bde7 Update to bsnes v018 release.
I began working on bsnes on October 14th, 2004. I am releasing bsnes v0.018 today to celebrate bsnes' two year anniversary. Please note that this release incurs a ~15% speed reduction since v0.017, due to IRQ and S-SMP timing improvements.
Changelog:
    - Fixed many critical errors in IRQ timing, should be *very* close to real hardware now
    - Corrected major CPU timing bug involving CPU I/O condition 4
    - Corrected bug with generic HiROM / LoROM memory maps
    - Corrected bug involving HDMA indirect channel termination [anomie]
    - OAM address reset now occurs when screen display is enabled, per recent research
    - Readded full DMA, HDMA and HDMA init bus sync timing
    - Added preliminary emulation of S-SMP $00f0 TEST register (6 of 8 bits are supported)
    - Readded emulation of known timing differences between CPU revisions 1 and 2
    - Config file can now control scanline-based PPU render position. This will only be needed until a proper dot-based PPU renderer is added
    - Removed core debugging hooks so that debugging console can remain in public releases, it now functions as a tracer and memory editor
    - Config file paths once again work correctly even if missing trailing backslash
    - Video configuration simplified, sorry in advance to those who enjoyed the profile mode used before
    - Added new configuration screen to control some emulation settings
    - Replaced bsnes program icon with a much nicer one [FitzRoy]
    - Optimized memory speed detection algorithm
    - Preliminary UPS soft-patching support (do not use this yet!)
    - Decreased memory usage and optimized generic libraries used by bsnes (/src/lib)
    - Now caching OAM by one line, somewhat similar to a real SNES. Fixes Winter Gold, but causes line rendering error in Mega lo Mania
    - Lots more, as usual
The following games have been fixed since v0.017 by the above bugfixes:
    - Battle Blaze (J, U)
    - Circuit USA (J)
    - F1 Grand Prix (J)
    - Funaki Masakatsu no Hybrid Wrestler - Tougi Denshou (J)
    - Jumbo Ozaki no Hole in One (J)
    - Mahjongg Taikai II (J)
    - RPG Tsukuru - Super Dante (J)
    - Robocop Versus The Terminator (U, E)
    - Sink or Swim (U, E)
    - Street Racer (J)
    - Touge Densetsu Saisoku Battle (J)
    - Winter Olympics (U, E)
2006-10-14 05:34:24 +00:00
byuu
ccf1c00b58 Update to bsnes v017r16? release.
Ok, reverted the SPCRAM initialization pattern, which
should fix Kamen Rider SD.
 Verified DMA timing steps, I had them right. Still need to verify
HDMA/HDMA init, but they're almost definitely the same anyway.
 Also, I noticed the spc700.txt doc by anomie on romhacking.net was
more recent than mine, and had info on $00f0 - TEST o_O
 So, went ahead and added emulation for 5 out of 8 of these bits.
Notably, the CPU speed control bits and the RAM write enable bit. The
other three aren't well understood enough to add support for them just
yet.
 Now, the CPU speed control in the S-SMP means the SMP core is taking
a significant speed hit to support this register. ~5% total speed hit,
though I can probably get that number down a little with some more
optimizations. I know the register is never used by any games, but you
know how I am. I added support for it anyway.
 Note that the WIP doesn't like my inlining combination and is taking
a much more significant speed hit with global optimizations turned on,
so the WIP is ~13% slower than the last one.







> On a side note, kernel streaming method works with event
> notification per audio packet you feed into it, and that
> notification receives full precision time slices even without
> setting the timer resolution manually. At least, when I was using
> kernel streaming in my NES emulator, it didn't need vsync to output
> almost a smooth 60fps, while WaveOut mode outputs in bursts and
> requires vsync to smooth out the frames.




 If you wouldn't mind turning that into a compatible derived Audio
class, I'd love to add this as an option into bsnes :)
 It'll be drop-in and compile, so you don't have to worry about me not
adding the code this time. No problem if you don't have the time /
desire / patience to do this.
 Although, I wouldn't want to do this if it requires 3rd-party
libraries / loading a special .sys driver into the kernel space /
Windows DDK to compile / something else crazy like that.

[No archive available]
2006-10-04 06:27:00 +00:00
byuu
f4520d41ec Update to bsnes v017r06? release.
New WIP should fix: RPG Tsukuru, Circuit USA, Jumbo Ozaki no Hole in
One (not a permanent fix, I'm not entirely happy with the HDMA timing,
but at least the name entry screen works again for now), and Taz-
Mania.

 The two games you said started flickering since v0.017.07 might be
fixed now, but I'm not worried about these horizontal-line issues
regardless of when they started occurring at the moment. The other
ones you said would be fixed by setting HCLOCK=256 should be fixed as
well, as this is the new default value.

 Super Mario Kart's line doesn't appear to flicker now, but I think
it's because I'm technically running the emulation a little too fast
again, due to the Ozaki fix. Another game you shouldn't expect to stay
fixed, and again another game I'm not worried about remaining fixed.

 Koushien 2 and Mahjongg Taikai 2 are very likely still broken.
Uniracers definitely is. These appear to be the only three serious
known bugs remaining.

[No archive available]
2006-09-20 04:06:00 +00:00
byuu
e308cf4275 Update to bsnes v017 release.
- This version adds major accuracy improvements, countless bugfixes and DSP-1 support. At the time of this release, the only remaining known bug in bsnes is with Uniracers 2-player mode, with well over 300+ games tested.
Changelog:
    - DSP-1 support added [Andreas Naive, byuu]
    - Added cooperative multithreading library, written by myself
    - Rewritten CPU core, now bus accurate
    - Rewritten APU core, now bus accurate
    - Added cartridge database
    - Added several PCB mappers, thanks to research from Overload
    - Added several games to database, fixing several mapping-related bugs
    - Improved mirroring [Nach, grinvader, byuu]
    - vscroll bug in hires, interlaced mode fixed. Fixes RPM racing
    - RTO X=256 bug corrected. Fixes Super Conflict title screen [anomie]
    - Fixed bug in NTSC filter with hires games
    - Updated snes_ntsc to version 2.0.1 [blargg]
    - Fixed bugs in HiROM / LoROM memory mapping. Fixes countless games
    - Fixed major bugs in HDMA routine. Fixes ToP, Mortal Kombat and Genjuu Ryodan
    - Added out-of-order execution to CPU, APU synchronization for major speedup with no accuracy loss
    - IRQs are now delayed after H/DMA transfers. Fixes Wild Guns
    - HDMA transfers now kill active DMA channels that are on the same channel. Fixes Bugs Bunny and World Class Rugby. Special thanks to zones for researching this
    - CPU emulation mode accuracy was improved
    - Cleaned up port-specific code to ease porting
    - Created unified Makefile, used by all ports [Nach]
    - Created GTK+ port of bsnes (although input is currently broken)
    - WRAM is now initialized to 0x55, SRAM to 0xff. Fixes Power Drive, Death Brade and RPM Racing
    - Fixed extreme NMI / IRQ edge case. Fixes Chou Aniki
    - Adjusted PAL execution speed. Fixes Earthworm Jim 2 (E) sound effects
    - Fixed auto joypad polling bug. Fixes La Wares
    - Fixed H/DMA bug that was preventing saves from working in Secret of Evermore
    - bsnes low loads d3dx9_*.dll dynamically at runtime, it is no longer required
    - Added support for 239-line PAL mode rendering
    - As usual, there have been much more changes I've forgotten about since the last release
    - Two C4 bugs fixed. Mega Man X2 / X3 have no remaining known bugs [anomie, byuu]
2006-08-27 03:01:06 +00:00
byuu
192e53bb87 Update to bsnes v016r52 release.
bsnes now builds with no warnings on Linux:
               http://byuu.cinnamonpirate.com/images/desktop082106.png
               However, input is not working unless you build the non-
GTK+ port (see below for more info).

 I'm planning on releasing next weekend. This will likely be the last
public WIP, unless something major is found before the weekend:
               byuu.cinnamonpirate.com/files/bsnes_v016_wip52.zip <-
copy/paste link







> If you can actually get it going fast in an all-in-one window like
> that it'd be cool. I normally just punt and have the GUI separate
> from the emulator output (GTK or Qt for the UI, SDL for the output)
> but it'd be nice for my NEStopia port if I could make it "one piece"
> like the Win32 original




 I can. Please take a look at my above sourcecode, and check your
private messages for another note. Specifically, src/ui/video/sdl.cpp
and src/ui/gtk/gtk_mainwindow.cpp. I am able to merge the SDL output
into the GTK+ window by setting the environment variable
"SDL_WINDOWID=%ld", GDK_WINDOW_XWINDOW(mydrawingbox->window).
 One important thing to note is that you must not initialize SDL video
until the render window has been realized. Simply showing the window
is not enough. You need to also clear all pending events in GTK+ after
showing the window before calling SDL video init, or it will die.
               You can do that with this code:






    gtk_widget_show(mainwindow);
                       while(gtk_events_pending() == true) {
                       gtk_main_iteration_do(false);
                       }




 However, one problem I am having is that by calling
gtk_main_iteration_do(), it steals all SDL input, and I'm not able to
poll any keypresses. This happens whether I embed the SDL video output
into the GTK+ window or not. The only way to get SDL input is to
ignore all GTK+ events, effectively freezing the window completely.

               I don't suppose you'd mind sharing how you got SDL
input working with GTK+ with me?
2006-08-21 00:43:46 +00:00
byuu
0ed9edfcdb Update to bsnes v016r46 release.
wip46 up. Adds all kinds of things, please test.

 First, no more d3dx9_27.dll requirement to run the application, but
screenshots still work if you have any d3dx9_nn.dll files.
 I specifically want to know if any of the other versions (24, 30,
etc) cause the emulator to crash when use. I'm pretty sure the
function is backwards-compatible, but we should probably make sure
before I make the next release and start getting bugreports about
screenshots crashing the program.
             Note: there is no error message for failed screen
captures, I'll add that in eventually.

 Next, the video options finally enable/disable controls depending on
certain settings. Should make using the video options a little easier.

 Next, to enable SDL audio on Windows and remove the win32 port's
wMain.hwnd reference, I now pass GetDesktopWindow() to DirectSound's
SetCooperativeLevel function, since no sound comes out if you pass a
null handle. This is because I don't know how to get the window handle
from SDL, and I prefer to keep port-specific code out of there if
possible.
             Note: SDL is not a windows port, but it builds on
windows, and thus needs DirectSound to output audio on windows.
 I'm hoping this doesn't cause audio problems for anyone else, but
honestly I have no idea what DSound uses the window handle with
DSSCL_PRIORITY for anyway.

 The $2100 luminance stuff was improved by adding rounding support to
the double-to-int casts, so fades should appear a little smoother now
in games.

 Possibly fixed a bug where RTO wasn't being calculated when
brightness=0 and the screen is enabled. Didn't see any improvements in
the three known bugged games.

[No archive available]
2006-08-11 06:59:00 +00:00
byuu
764fe1974a Update to bsnes v016r44 release.
[No changelog available]
2006-08-08 02:02:38 +00:00
byuu
a55d640459 Update to bsnes v016r42 release.
Ok, one semi-large change if anyone wants to test.

             byuu.cinnamonpirate.com/files/bsnes_v016_wip42.zip

 This is built for maximum speed. No debugger, PGO enabled, favor
speed, no c++ EH (so no ZIP/JMA), and a new addition: links against
msvcrt instead of libcmt.

 By using msvcrt and some evil linker hacks I was finally able to
build the SDL port again on Windows. So now I just need to focus on
cleaning that up so the next release will build on Linux out of the
box. Anyway, I tried it on the non-SDL port for the hell of it, and
noticed not only a 20% drop in EXE size, but a ~10-11% speedup as
well. Only problem is it requires msvcr80.dll, and I have no idea how
common that file is. So, that's what this wip is for. Does this
version work for you, and if it does, does it run faster? A direct FPS
comparison between v0.016 and v0.016.42 would be helpful if you're not
sure.
2006-08-04 01:27:04 +00:00
byuu
6010bffe5d Update to bsnes v016r38 release.
Ok, this WIP rewrites the input code and modifies the PAL clock speed.
Fairly major changes. Ideally, this will wipe out four bugs without
causing any new ones since wip37.

             Bug fixes :
             Earthworm Jim 2 (E) - adjusted PAL CPU clock speed.
Please test for *new* sound problems in PAL games
             La Wares (J) + Galivan 2 (J) - no longer return 0 when
auto joypad is off for polling $4218-$421f
             Super Conflict (J) - added anomie's new OAM RTO findings
to fix title screen

 The input code was almost completely rewritten to simulate real
hardware more. As such, it's very possible there are new input bugs.

             Ok, so then
byuu.cinnamonpirate.com/files/bsnes_v016_wip38.zip
 Please only download if you intend to test games and report feedback.
This version is slower than normal, lacks ZIP+JMA loading, and has the
debugger enabled (that is only useful to me, it lacks a functional
user interface) which slows down emulation even more. eg you're better
off with v0.016 official if you just want to run games.
             As always, please don't post this link anywhere else, or
I will be forced to remove the file to conserve bandwidth.

 If anyone posts bugs that hasn't tested against wip37, can I please
have someone with wip37 verify/deny the bug presence in wip37 as well
as in 016 official? wip37 isn't on my website because I don't have a
lot of web space to spare.

             Thank you to everyone in advance for helping.
2006-07-27 23:56:42 +00:00
byuu
e492268025 Update to bsnes v016r27a release.
Ok, I tried converting the switch/case table to a jump table for both
CPU+APU cores. Results? EXE is 70kb larger, compile time is 5-10%
slower, and speed is identical. Needless to say I reverted that change
back. I then tried narrowing down the cause of the PGO error. Found
out it was Dai Kaijuu Monogatari. If I don't run that, I can build
with PGO. Unfortunately, this is the ROM I use to stress optimize
color add/sub. So as a result, this game will run a little slowly now
(sort of like how Chrono Trigger's OPT title screen effects were
before). But, better one game than all, right?

             byuu.org/files/bsnes_v016_wip27a.zip

 Once again, please do not submit news about this to an emulation
site. The file will be removed if I notice anyone mentioning it
anywhere.

             That will be 20-25% faster than wip27, but otherwise
everything is identical.

 DSP1: there's either a bug in op02, op06, or in the getSr/getDr/setDr
functions. We have so far been unable to spot the error and correct
it. Help is always welcome, as always. Please consider DSP-1 support
as not being there at all. I doubt any games will work right with it
right now :(

             This is how interlace works :
             I call each frame a "field", meaning even or odd fields
on your television / monitor.
             When interlace is off, I draw to the even fields every
time, so you don't notice anything.
 However, when interlace is on, I alternate between which one I draw
to each field. So depending on your frameskip, this can cause serious
problems for interlace mode. I also only physically draw to "half" the
resolution each field, much like a real TV would. This makes 512x448
mode just as fast as 512x224 mode.
 I can't think of an easy way to cheat the system with frameskipping.
Luckily, very very few games use interlace at all. Most use hires
512x224 and that's it.
2006-07-09 05:32:10 +00:00
byuu
a36c26c997 Update to bsnes v016r27 release.
Here's a WIP to try out, it's 20-40% slower than it
should be, due to PGO crashing the compiler*.

               Please copy and paste link, and _do not_ post this on
emulation news sites or I will remove the file.

               byuu.org/files/bsnes_v016_wip27.zip

 Even though it's slower, could I get some people to try running
through a bunch of games and look for new bugs? Given I rewrote the
entire CPU+APU, it's possible some new bugs crept in.

               * No release this weekend. Please be sure to thank
Microsoft personally for the delay.







    rc /r /fobsnes.res bsnes.rc
                       cl /Febsnes.exe /nologo /O2 /GL /EHsc main.obj
    libco.obj libstring.obj
                       libconfig.obj libbpf.obj reader.obj cart.obj
    cheat.obj memory.obj bmemory.obj
                       cpu.obj scpu.obj bcpu.obj apu.obj sapu.obj
    bapu.obj bdsp.obj ppu.obj bppu.ob
                       j snes.obj srtc.obj sdd1.obj c4.obj dsp1.obj
    dsp2.obj obc1.obj adler32.obj co
                       mpress.obj crc32.obj deflate.obj gzio.obj
    inffast.obj inflate.obj inftrees.obj
                       ioapi.obj trees.obj unzip.obj zip.obj zutil.obj
    jma.obj jcrc32.obj lzmadec.obj
                       7zlzma.obj iiostrm.obj inbyte.obj lzma.obj
    winout.obj bsnes.res kernel32.lib use
                       r32.lib gdi32.lib comdlg32.lib comctl32.lib
    d3d9.lib d3dx9.lib ddraw.lib dsound
                       .lib dinput8.lib dxguid.lib /link
    /PGD:bsnes.pgd /LTCG:PGOPTIMIZE
                       Merging bsnes!1.pgc
                       Generating code
                       \bsnes\src\apu\sapu\core\core.cpp(16) : fatal
    error C1001: An internal er
                       ror has occurred in the compiler.
                       (compiler file
    'f:\rtm\vctools\compiler\utc\src\P2\main.c[0x10CB9ABB:0x00000025]
                       ', line 182)
                       To work around this problem, try simplifying or
    changing the program near the l
                       ocations listed above.
                       Please choose the Technical Support command on
    the Visual C++
                       Help menu, or open the Technical Support help
    file for more information

                       LINK : fatal error LNK1000: Internal error
    during IMAGE::BuildImage




               What is on sapu\core\core.cpp(16) that's too complex
for Visual c++ to handle?







    status.in_opcode = false;




               Please, if anyone can simplify that for me, let me
know.

 Seriously, though, if anyone can take a look at the source and fix
this compiler error I'd really appreciate it, and I'll get a release
out this weekend. I'm using Visual C++ 2005 Professional. Otherwise
I'll have to set it aside because I don't have time.

[No archive available]
2006-07-09 01:38:00 +00:00
byuu
a3945e5772 Update to bsnes v016 release.
- Added Direct3D renderer with options for disabling hardware filtering and scanlines
    - Screenshots can now be captured in BMP, JPEG, or PNG format
    - Added config file option to specify default ROM and SRAM paths
    - Config file is always loaded from path to bsnes executable
    - Added support for analog mode joypad input
    - Up to 32 joypads can be used at once now
    - Fixed bug regarding enabling interlace mid-frame
    - Moved PPU rendering to V=240, from V=0
    - Started on new debugger. So far only debug messages and memory editor added
    - Added joypad axis resistance option for analog input mode
    - Added config file option to set window style attributes
    - Added color adjustment settings for brightness, contrast, gamma, and scanline intensity
    - Added grayscale, sepia, and invert color settings
    - Added NTSC filter by blargg, HQ2x filter by MaxSt, and Scale2x filter
    - PPU now renders scanline 224
    - Revampled about box
    - Added Game Genie / PAR cheat code support + editor, saves codes to .cht files
    - HDMA channels are no longer disabled when starting DMA, fixes Dracula X [DMV27]
    - Fixes to OAM priority mode (not perfect), fixes Final Fantasy: Mystic Quest [DMV27]
    - Fixed ENDX sound bug, fixes voices in Earthworm Jim 2 [DMV27]
    - bsnes should now compile with MinGW [DMV27]
    - Added DSP-2 support
    - Added OBC-1 support
    - Major rewrite of SNES address bus mirroring and MMIO handlers
    - Many address mirroring corrections, fixes Dezaemon, etc
    - Blocked invalid (H)DMA transfers, fixes Kirby's Super Funhouse
    - Wrote Win32 API wrapper and ported all GUI code to use it, should help to create Linux GUI later on
    - Revampled input system, should lead to customizable GUI shortcut keys later on
    - Fixed numerous bugs with input registers. Fixes many games that previous had their intro cut off (Super Conflict, etc), and many that never accepted input (Super Double Dragon, etc)
    - Moved auto joypad strobing from V=225 to V=227
    - Killed OAM table caching and window range caching, as they were actually hindering speed
    - Rewrote input configuration screen to show currently mapped keys
    - Greatly enhanced configuration options for each video profile
    - Modified fullscreen mode to exit to windowed mode when menu is activated, use F11 to toggle fullscreen mode
    - Fixed bugs in txs, wai, brk, cop, and rti opcodes [DMV27]
    - Fixed bug with emulation-mode IRQs [DMV27]
    - Initializing DMA registers to $ff [DMV27]
    - Memory writes now update CPU MDR register (open bus) [DMV27]
    - Improved ROM header detection, fixes Chou Jikuu Yousai Macross [DMV27]
    - Reading OAM no longer updates OAM latch
    - Writing to OAM high table no longer updates OAM latch
    - Writing CGRAM now updates CGRAM latch
    - Improved pseudo-hires rendering [blargg]
    - Much, much more
2006-04-25 15:51:10 +00:00
byuu
6b6233b3af Update to bsnes v015 rc3 release.
[No changelog available]
2006-04-22 01:02:32 +00:00
byuu
9f63cb1b99 Update to bsnes v015 rc2 release.
[No changelog available]
2006-04-20 00:26:54 +00:00
1172 changed files with 182514 additions and 42113 deletions

202
bsnes.cfg
View File

@@ -1,202 +0,0 @@
# Applies contrast adjust filter to video output when enabled
# Works by lowering the brightness of darker colors,
# while leaving brighter colors alone; thus reducing saturation
# (default = true)
snes.video_color_curve = true
# Selects color adjustment filter for video output
# 0 = Normal (no filter, rgb555)
# 1 = Grayscale mode (l5)
# 2 = VGA mode (rgb332)
# 3 = Genesis mode (rgb333)
# (default = 0)
snes.video_color_adjust_mode = 0
# Mutes SNES audio output when enabled
# (default = false)
snes.mute = false
# Regulate speed to 60hz (NTSC) / 50hz (PAL)
# (default = true)
system.regulate_speed = true
# Slowest speed setting (in hz)
# (default = 16000)
system.speed_slowest = 16000
# Slow speed setting
# (default = 24000)
system.speed_slow = 24000
# Normal speed setting
# (default = 32000)
system.speed_normal = 32000
# Fast speed setting
# (default = 48000)
system.speed_fast = 48000
# Fastest speed setting
# (default = 64000)
system.speed_fastest = 64000
# Video mode at startup
# (default = 2)
video.mode = 2
# Video mode 0 (windowed)
# (default = "256x223")
video.mode_0 = "256x223"
# Video mode 1 (windowed)
# (default = "512x446")
video.mode_1 = "512x446"
# Video mode 2 (windowed)
# (default = "640x480")
video.mode_2 = "640x480"
# Video mode 3 (windowed)
# (default = "960x720")
video.mode_3 = "960x720"
# Video mode 4 (windowed)
# (default = "1152x864")
video.mode_4 = "1152x864"
# Video mode 5 (fullscreen)
# (default = "640x480@60:640x480")
video.mode_5 = "640x480@60:640x480"
# Video mode 6 (fullscreen)
# (default = "800x600@60:800x600")
video.mode_6 = "800x600@60:800x600"
# Video mode 7 (fullscreen)
# (default = "1024x768@60:1024x768")
video.mode_7 = "1024x768@60:1024x768"
# Video mode 8 (fullscreen)
# (default = "1280x960@60:1280x960")
video.mode_8 = "1280x960@60:1280x960"
# Video mode 9 (fullscreen)
# (default = "1600x1200@60:1600x1200")
video.mode_9 = "1600x1200@60:1600x1200"
# Use Video RAM instead of System RAM
# (default = true)
video.use_vram = true
# Use triple buffering
# (default = false)
video.triple_buffering = false
# Show framerate in window title
# (default = true)
gui.show_fps = true
# Allow "impossible" key combinations for joypad 1 (not recommended)
# (default = false)
input.joypad1.allow_invalid_input = false
# Joypad1 up
# (default = 0x80c8)
input.joypad1.up = 0x80c8
# Joypad1 down
# (default = 0x81d0)
input.joypad1.down = 0x81d0
# Joypad1 left
# (default = 0x82cb)
input.joypad1.left = 0x82cb
# Joypad1 right
# (default = 0x83cd)
input.joypad1.right = 0x83cd
# Joypad1 A
# (default = 0x42d)
input.joypad1.a = 0x42d
# Joypad1 B
# (default = 0x32c)
input.joypad1.b = 0x32c
# Joypad1 X
# (default = 0x11f)
input.joypad1.x = 0x11f
# Joypad1 Y
# (default = 0x1e)
input.joypad1.y = 0x1e
# Joypad1 L
# (default = 0x620)
input.joypad1.l = 0x620
# Joypad1 R
# (default = 0x72e)
input.joypad1.r = 0x72e
# Joypad1 select
# (default = 0x836)
input.joypad1.select = 0x836
# Joypad1 start
# (default = 0x91c)
input.joypad1.start = 0x91c
# Allow "impossible" key combinations for joypad 2 (not recommended)
# (default = false)
input.joypad2.allow_invalid_input = false
# Joypad2 up
# (default = 0xff14)
input.joypad2.up = 0xff14
# Joypad2 down
# (default = 0xff22)
input.joypad2.down = 0xff22
# Joypad2 left
# (default = 0xff21)
input.joypad2.left = 0xff21
# Joypad2 right
# (default = 0xff23)
input.joypad2.right = 0xff23
# Joypad2 A
# (default = 0xff25)
input.joypad2.a = 0xff25
# Joypad2 B
# (default = 0xff24)
input.joypad2.b = 0xff24
# Joypad2 X
# (default = 0xff17)
input.joypad2.x = 0xff17
# Joypad2 Y
# (default = 0xff16)
input.joypad2.y = 0xff16
# Joypad2 L
# (default = 0xff18)
input.joypad2.l = 0xff18
# Joypad2 R
# (default = 0xff26)
input.joypad2.r = 0xff26
# Joypad2 select
# (default = 0xff1a)
input.joypad2.select = 0xff1a
# Joypad2 start
# (default = 0xff1b)
input.joypad2.start = 0xff1b

BIN
bsnes.exe

Binary file not shown.

View File

@@ -1,26 +0,0 @@
bsnes License:
--------------
You are free to redistribute this software, and its source code; provided
there is no charge for the software, nor any charge for the medium used to
distribute the software. You are also free to use and modify the source code
as you desire for personal use only. No publically-released derivative works
of this source code are permitted without my permission, though I will likely
grant you permission if you ask me. You must also abide by the terms of any
additional source code licenses contained within this program.
Simple DirectMedia Layer License:
---------------------------------
The Simple DirectMedia Layer (SDL for short) is a cross-platform library
designed to make it easy to write multi-media software, such as games and
emulators.
The Simple DirectMedia Layer library source code is available from:
http://www.libsdl.org/
This library is distributed under the terms of the GNU LGPL:
http://www.gnu.org/copyleft/lesser.html
Licensing Exemptions:
---------------------
Richard Bannister has asked for and received my permission to distribute
a binary-only port of bsnes on the Mac OS X platform.

132
snesfilter/2xsai/2xsai.cpp Normal file
View File

@@ -0,0 +1,132 @@
//2xSaI / Super 2xSaI / Super Eagle filter
//authors: kode54 and Kreed
//license: GPL
#include "2xsai.hpp"
#include "implementation.cpp"
//=====
//2xSaI
//=====
void _2xSaIFilter::size(unsigned &outwidth, unsigned &outheight, unsigned width, unsigned height) {
outwidth = width;
outheight = height;
if(width <= 256 && height <= 240) {
outwidth *= 2;
outheight *= 2;
}
}
void _2xSaIFilter::render(
uint32_t *output, unsigned outpitch,
const uint16_t *input, unsigned pitch, unsigned width, unsigned height
) {
if(width > 256 || height > 240) {
filter_direct.render(output, outpitch, input, pitch, width, height);
return;
}
for(unsigned y = 0; y < height; y++) {
const uint16_t *line_in = (const uint16_t *) (((const uint8_t*)input) + pitch * y);
uint32_t *line_out = temp + y * 256;
for(unsigned x = 0; x < width; x++) {
line_out[x] = colortable[line_in[x]];
}
}
_2xSaI32( (unsigned char *) temp, 1024, 0, (unsigned char *) output, outpitch, width, height );
}
_2xSaIFilter::_2xSaIFilter() {
temp = new uint32_t[256*240];
}
_2xSaIFilter::~_2xSaIFilter() {
delete[] temp;
}
//===========
//Super 2xSaI
//===========
void Super2xSaIFilter::size(unsigned &outwidth, unsigned &outheight, unsigned width, unsigned height) {
outwidth = width;
outheight = height;
if(width <= 256 && height <= 240) {
outwidth *= 2;
outheight *= 2;
}
}
void Super2xSaIFilter::render(
uint32_t *output, unsigned outpitch,
const uint16_t *input, unsigned pitch, unsigned width, unsigned height
) {
if(width > 256 || height > 240) {
filter_direct.render(output, outpitch, input, pitch, width, height);
return;
}
for(unsigned y = 0; y < height; y++) {
const uint16_t *line_in = (const uint16_t *) (((const uint8_t*)input) + pitch * y);
uint32_t *line_out = temp + y * 256;
for(unsigned x = 0; x < width; x++) {
line_out[x] = colortable[line_in[x]];
}
}
Super2xSaI32( (unsigned char *) temp, 1024, 0, (unsigned char *) output, outpitch, width, height );
}
Super2xSaIFilter::Super2xSaIFilter() {
temp = new uint32_t[256*240];
}
Super2xSaIFilter::~Super2xSaIFilter() {
delete[] temp;
}
//===========
//Super Eagle
//===========
void SuperEagleFilter::size(unsigned &outwidth, unsigned &outheight, unsigned width, unsigned height) {
outwidth = width;
outheight = height;
if(width <= 256 && height <= 240) {
outwidth *= 2;
outheight *= 2;
}
}
void SuperEagleFilter::render(
uint32_t *output, unsigned outpitch,
const uint16_t *input, unsigned pitch, unsigned width, unsigned height
) {
if(width > 256 || height > 240) {
filter_direct.render(output, outpitch, input, pitch, width, height);
return;
}
for(unsigned y = 0; y < height; y++) {
const uint16_t *line_in = (const uint16_t *) (((const uint8_t*)input) + pitch * y);
uint32_t *line_out = temp + y * 256;
for(unsigned x = 0; x < width; x++) {
line_out[x] = colortable[line_in[x]];
}
}
SuperEagle32( (unsigned char *) temp, 1024, 0, (unsigned char *) output, outpitch, width, height );
}
SuperEagleFilter::SuperEagleFilter() {
temp = new uint32_t[256*240];
}
SuperEagleFilter::~SuperEagleFilter() {
delete[] temp;
}

View File

@@ -0,0 +1,35 @@
class _2xSaIFilter {
public:
void size(unsigned&, unsigned&, unsigned, unsigned);
void render(uint32_t*, unsigned, const uint16_t*, unsigned, unsigned, unsigned);
_2xSaIFilter();
~_2xSaIFilter();
private:
uint32_t *temp;
} filter_2xsai;
class Super2xSaIFilter {
public:
void size(unsigned&, unsigned&, unsigned, unsigned);
void render(uint32_t*, unsigned, const uint16_t*, unsigned, unsigned, unsigned);
Super2xSaIFilter();
~Super2xSaIFilter();
private:
uint32_t *temp;
} filter_super2xsai;
class SuperEagleFilter {
public:
void size(unsigned&, unsigned&, unsigned, unsigned);
void render(uint32_t*, unsigned, const uint16_t*, unsigned, unsigned, unsigned);
SuperEagleFilter();
~SuperEagleFilter();
private:
uint32_t *temp;
} filter_supereagle;

File diff suppressed because it is too large Load Diff

89
snesfilter/Makefile Normal file
View File

@@ -0,0 +1,89 @@
include nall/Makefile
qtlibs := QtCore QtGui
include nall/qt/Makefile
c := $(compiler) -std=gnu99
cpp := $(subst cc,++,$(compiler)) -std=gnu++0x
flags := -O3 -I. -Iobj -fomit-frame-pointer $(qtinc)
link :=
ifeq ($(platform),x)
flags := -fPIC -fopenmp $(flags)
link += -s -fopenmp -lpthread -lgomp
else ifeq ($(platform),osx)
flags := -fPIC -fopenmp $(flags)
link += -fopenmp -lpthread -lgomp
else ifeq ($(platform),win)
flags := -fopenmp $(flags)
link += -fopenmp -lpthread
endif
objects := snesfilter
compile = \
$(strip \
$(if $(filter %.c,$<), \
$(c) $(flags) $1 -c $< -o $@, \
$(if $(filter %.cpp,$<), \
$(cpp) $(flags) $1 -c $< -o $@ \
) \
) \
)
%.o: $<; $(call compile)
all: build;
objects := $(patsubst %,obj/%.o,$(objects))
moc_headers := $(call rwildcard,./,%.moc.hpp)
moc_objects := $(foreach f,$(moc_headers),obj/$(notdir $(patsubst %.moc.hpp,%.moc,$f)))
# automatically run moc on all .moc.hpp (MOC header) files
%.moc: $<; $(moc) -i $< -o $@
# automatically generate %.moc build rules
__list = $(moc_headers)
$(foreach f,$(moc_objects), \
$(eval __file = $(word 1,$(__list))) \
$(eval __list = $(wordlist 2,$(words $(__list)),$(__list))) \
$(eval $f: $(__file)) \
)
##################
### snesfilter ###
##################
obj/snesfilter.o: snesfilter.cpp *
###############
### targets ###
###############
build: $(moc_objects) $(objects)
ifeq ($(platform),x)
ar rcs libsnesfilter.a $(objects)
$(cpp) $(link) -o libsnesfilter.so -shared -Wl,-soname,libsnesfilter.so.1 $(objects) $(qtlib)
else ifeq ($(platform),osx)
ar rcs libsnesfilter.a $(objects)
$(cpp) $(link) -o libsnesfilter.dylib -shared -dynamiclib $(objects) $(qtlib)
else ifeq ($(platform),win)
$(cpp) $(link) -o snesfilter.dll -shared -Wl,--out-implib,libsnesfilter.a $(objects) $(qtlib)
endif
install:
ifeq ($(platform),x)
install -D -m 755 libsnesfilter.a $(DESTDIR)$(prefix)/lib
install -D -m 755 libsnesfilter.so $(DESTDIR)$(prefix)/lib
ldconfig -n $(DESTDIR)$(prefix)/lib
else ifeq ($(platform),osx)
cp libsnesfilter.dylib /usr/local/lib/libsnesfilter.dylib
endif
clean:
-@$(call delete,obj/*.o)
-@$(call delete,obj/*.moc)
-@$(call delete,libsnesfilter.a)
-@$(call delete,libsnesfilter.so)
-@$(call delete,libsnesfilter.dylib)
-@$(call delete,snesfilter.dll)

2
snesfilter/cc.bat Normal file
View File

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

1
snesfilter/clean.bat Normal file
View File

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

View File

@@ -0,0 +1,23 @@
#include "direct.hpp"
void DirectFilter::size(unsigned &outwidth, unsigned &outheight, unsigned width, unsigned height) {
outwidth = width;
outheight = height;
}
void DirectFilter::render(
uint32_t *output, unsigned outpitch, const uint16_t *input, unsigned pitch,
unsigned width, unsigned height
) {
pitch >>= 1;
outpitch >>= 2;
for(unsigned y = 0; y < height; y++) {
for(unsigned x = 0; x < width; x++) {
uint16_t p = *input++;
*output++ = colortable[p];
}
input += pitch - width;
output += outpitch - width;
}
}

View File

@@ -0,0 +1,5 @@
class DirectFilter {
public:
void size(unsigned&, unsigned&, unsigned, unsigned);
void render(uint32_t*, unsigned, const uint16_t*, unsigned, unsigned, unsigned);
} filter_direct;

195
snesfilter/hq2x/hq2x.cpp Normal file
View File

@@ -0,0 +1,195 @@
//HQ2x filter
//authors: byuu and blargg
//license: public domain
//
//note: this is a clean reimplementation of the original HQ2x filter, which was
//written by Maxim Stepin (MaxSt). it is not 100% identical, but very similar.
#include "hq2x.hpp"
void HQ2xFilter::size(unsigned &outwidth, unsigned &outheight, unsigned width, unsigned height) {
if(width > 256 || height > 240) return filter_direct.size(outwidth, outheight, width, height);
outwidth = width * 2;
outheight = height * 2;
}
void HQ2xFilter::render(
uint32_t *output, unsigned outpitch,
const uint16_t *input, unsigned pitch, unsigned width, unsigned height
) {
if(width > 256 || height > 240) {
filter_direct.render(output, outpitch, input, pitch, width, height);
return;
}
pitch >>= 1;
outpitch >>= 2;
#pragma omp parallel for
for(unsigned y = 0; y < height; y++) {
const uint16_t *in = input + y * pitch;
uint32_t *out0 = output + y * outpitch * 2;
uint32_t *out1 = output + y * outpitch * 2 + outpitch;
int prevline = (y == 0 ? 0 : pitch);
int nextline = (y == height - 1 ? 0 : pitch);
in++;
*out0++ = 0; *out0++ = 0;
*out1++ = 0; *out1++ = 0;
for(unsigned x = 1; x < 256 - 1; x++) {
uint16_t A = *(in - prevline - 1);
uint16_t B = *(in - prevline + 0);
uint16_t C = *(in - prevline + 1);
uint16_t D = *(in - 1);
uint16_t E = *(in + 0);
uint16_t F = *(in + 1);
uint16_t G = *(in + nextline - 1);
uint16_t H = *(in + nextline + 0);
uint16_t I = *(in + nextline + 1);
uint32_t e = yuvTable[E] + diff_offset;
uint8_t pattern;
pattern = diff(e, A) << 0;
pattern |= diff(e, B) << 1;
pattern |= diff(e, C) << 2;
pattern |= diff(e, D) << 3;
pattern |= diff(e, F) << 4;
pattern |= diff(e, G) << 5;
pattern |= diff(e, H) << 6;
pattern |= diff(e, I) << 7;
*(out0 + 0) = colortable[blend(hqTable[pattern], E, A, B, D, F, H)]; pattern = rotate[pattern];
*(out0 + 1) = colortable[blend(hqTable[pattern], E, C, F, B, H, D)]; pattern = rotate[pattern];
*(out1 + 1) = colortable[blend(hqTable[pattern], E, I, H, F, D, B)]; pattern = rotate[pattern];
*(out1 + 0) = colortable[blend(hqTable[pattern], E, G, D, H, B, F)];
in++;
out0 += 2;
out1 += 2;
}
in++;
*out0++ = 0; *out0++ = 0;
*out1++ = 0; *out1++ = 0;
}
}
HQ2xFilter::HQ2xFilter() {
yuvTable = new uint32_t[32768];
for(unsigned i = 0; i < 32768; i++) {
uint8_t R = (i >> 0) & 31;
uint8_t G = (i >> 5) & 31;
uint8_t B = (i >> 10) & 31;
//bgr555->bgr888
double r = (R << 3) | (R >> 2);
double g = (G << 3) | (G >> 2);
double b = (B << 3) | (B >> 2);
//bgr888->yuv888
double y = (r + g + b) * (0.25f * (63.5f / 48.0f));
double u = ((r - b) * 0.25f + 128.0f) * (7.5f / 7.0f);
double v = ((g * 2.0f - r - b) * 0.125f + 128.0f) * (7.5f / 6.0f);
yuvTable[i] = ((unsigned)y << 21) + ((unsigned)u << 11) + ((unsigned)v);
}
for(unsigned n = 0; n < 256; n++) {
rotate[n] = ((n >> 2) & 0x11) | ((n << 2) & 0x88)
| ((n & 0x01) << 5) | ((n & 0x08) << 3)
| ((n & 0x10) >> 3) | ((n & 0x80) >> 5);
}
}
HQ2xFilter::~HQ2xFilter() {
delete[] yuvTable;
}
bool HQ2xFilter::same(uint16_t x, uint16_t y) {
return !((yuvTable[x] - yuvTable[y] + diff_offset) & diff_mask);
}
bool HQ2xFilter::diff(uint32_t x, uint16_t y) {
return ((x - yuvTable[y]) & diff_mask);
}
void HQ2xFilter::grow(uint32_t &n) { n |= n << 16; n &= 0x03e07c1f; }
uint16_t HQ2xFilter::pack(uint32_t n) { n &= 0x03e07c1f; return n | (n >> 16); }
uint16_t HQ2xFilter::blend1(uint32_t A, uint32_t B) {
grow(A); grow(B);
A = (A * 3 + B) >> 2;
return pack(A);
}
uint16_t HQ2xFilter::blend2(uint32_t A, uint32_t B, uint32_t C) {
grow(A); grow(B); grow(C);
return pack((A * 2 + B + C) >> 2);
}
uint16_t HQ2xFilter::blend3(uint32_t A, uint32_t B, uint32_t C) {
grow(A); grow(B); grow(C);
return pack((A * 5 + B * 2 + C) >> 3);
}
uint16_t HQ2xFilter::blend4(uint32_t A, uint32_t B, uint32_t C) {
grow(A); grow(B); grow(C);
return pack((A * 6 + B + C) >> 3);
}
uint16_t HQ2xFilter::blend5(uint32_t A, uint32_t B, uint32_t C) {
grow(A); grow(B); grow(C);
return pack((A * 2 + (B + C) * 3) >> 3);
}
uint16_t HQ2xFilter::blend6(uint32_t A, uint32_t B, uint32_t C) {
grow(A); grow(B); grow(C);
return pack((A * 14 + B + C) >> 4);
}
uint16_t HQ2xFilter::blend(unsigned rule, uint16_t E, uint16_t A, uint16_t B, uint16_t D, uint16_t F, uint16_t H) {
switch(rule) { default:
case 0: return E;
case 1: return blend1(E, A);
case 2: return blend1(E, D);
case 3: return blend1(E, B);
case 4: return blend2(E, D, B);
case 5: return blend2(E, A, B);
case 6: return blend2(E, A, D);
case 7: return blend3(E, B, D);
case 8: return blend3(E, D, B);
case 9: return blend4(E, D, B);
case 10: return blend5(E, D, B);
case 11: return blend6(E, D, B);
case 12: return same(B, D) ? blend2(E, D, B) : E;
case 13: return same(B, D) ? blend5(E, D, B) : E;
case 14: return same(B, D) ? blend6(E, D, B) : E;
case 15: return same(B, D) ? blend2(E, D, B) : blend1(E, A);
case 16: return same(B, D) ? blend4(E, D, B) : blend1(E, A);
case 17: return same(B, D) ? blend5(E, D, B) : blend1(E, A);
case 18: return same(B, F) ? blend3(E, B, D) : blend1(E, D);
case 19: return same(D, H) ? blend3(E, D, B) : blend1(E, B);
}
}
const uint8_t HQ2xFilter::hqTable[256] = {
4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 15, 12, 5, 3, 17, 13,
4, 4, 6, 18, 4, 4, 6, 18, 5, 3, 12, 12, 5, 3, 1, 12,
4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 17, 13, 5, 3, 16, 14,
4, 4, 6, 18, 4, 4, 6, 18, 5, 3, 16, 12, 5, 3, 1, 14,
4, 4, 6, 2, 4, 4, 6, 2, 5, 19, 12, 12, 5, 19, 16, 12,
4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 12, 5, 3, 16, 12,
4, 4, 6, 2, 4, 4, 6, 2, 5, 19, 1, 12, 5, 19, 1, 14,
4, 4, 6, 2, 4, 4, 6, 18, 5, 3, 16, 12, 5, 19, 1, 14,
4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 15, 12, 5, 3, 17, 13,
4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 12, 5, 3, 16, 12,
4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 17, 13, 5, 3, 16, 14,
4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 13, 5, 3, 1, 14,
4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 12, 5, 3, 16, 13,
4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 12, 5, 3, 1, 12,
4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 12, 5, 3, 1, 14,
4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 1, 12, 5, 3, 1, 14,
};

30
snesfilter/hq2x/hq2x.hpp Normal file
View File

@@ -0,0 +1,30 @@
class HQ2xFilter {
public:
void size(unsigned&, unsigned&, unsigned, unsigned);
void render(uint32_t*, unsigned, const uint16_t*, unsigned, unsigned, unsigned);
HQ2xFilter();
~HQ2xFilter();
private:
enum {
diff_offset = (0x440 << 21) + (0x207 << 11) + 0x407,
diff_mask = (0x380 << 21) + (0x1f0 << 11) + 0x3f0,
};
static const uint8_t hqTable[256];
uint32_t *yuvTable;
uint8_t rotate[256];
alwaysinline bool same(uint16_t x, uint16_t y);
alwaysinline bool diff(uint32_t x, uint16_t y);
alwaysinline void grow(uint32_t &n);
alwaysinline uint16_t pack(uint32_t n);
alwaysinline uint16_t blend1(uint32_t A, uint32_t B);
alwaysinline uint16_t blend2(uint32_t A, uint32_t B, uint32_t C);
alwaysinline uint16_t blend3(uint32_t A, uint32_t B, uint32_t C);
alwaysinline uint16_t blend4(uint32_t A, uint32_t B, uint32_t C);
alwaysinline uint16_t blend5(uint32_t A, uint32_t B, uint32_t C);
alwaysinline uint16_t blend6(uint32_t A, uint32_t B, uint32_t C);
alwaysinline uint16_t blend(unsigned rule, uint16_t E, uint16_t A, uint16_t B, uint16_t D, uint16_t F, uint16_t H);
} filter_hq2x;

53
snesfilter/lq2x/lq2x.cpp Normal file
View File

@@ -0,0 +1,53 @@
#include "lq2x.hpp"
void LQ2xFilter::size(unsigned &outwidth, unsigned &outheight, unsigned width, unsigned height) {
if(width > 256 || height > 240) return filter_direct.size(outwidth, outheight, width, height);
outwidth = width * 2;
outheight = height * 2;
}
void LQ2xFilter::render(
uint32_t *output, unsigned outpitch,
const uint16_t *input, unsigned pitch, unsigned width, unsigned height
) {
if(width > 256 || height > 240) {
filter_direct.render(output, outpitch, input, pitch, width, height);
return;
}
pitch >>= 1;
outpitch >>= 2;
uint32_t *out0 = output;
uint32_t *out1 = output + outpitch;
for(unsigned y = 0; y < height; y++) {
int prevline = (y == 0 ? 0 : pitch);
int nextline = (y == height - 1 ? 0 : pitch);
for(unsigned x = 0; x < width; x++) {
uint16_t A = *(input - prevline);
uint16_t B = (x > 0) ? *(input - 1) : *input;
uint16_t C = *input;
uint16_t D = (x < 255) ? *(input + 1) : *input;
uint16_t E = *(input++ + nextline);
uint32_t c = colortable[C];
if(A != E && B != D) {
*out0++ = (A == B ? colortable[C + A - ((C ^ A) & 0x0421) >> 1] : c);
*out0++ = (A == D ? colortable[C + A - ((C ^ A) & 0x0421) >> 1] : c);
*out1++ = (E == B ? colortable[C + E - ((C ^ E) & 0x0421) >> 1] : c);
*out1++ = (E == D ? colortable[C + E - ((C ^ E) & 0x0421) >> 1] : c);
} else {
*out0++ = c;
*out0++ = c;
*out1++ = c;
*out1++ = c;
}
}
input += pitch - width;
out0 += outpitch + outpitch - 512;
out1 += outpitch + outpitch - 512;
}
}

5
snesfilter/lq2x/lq2x.hpp Normal file
View File

@@ -0,0 +1,5 @@
class LQ2xFilter {
public:
void size(unsigned&, unsigned&, unsigned, unsigned);
void render(uint32_t*, unsigned, const uint16_t*, unsigned, unsigned, unsigned);
} filter_lq2x;

107
snesfilter/nall/Makefile Normal file
View File

@@ -0,0 +1,107 @@
# Makefile
# author: byuu
# license: public domain
[A-Z] = A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
[a-z] = a b c d e f g h i j k l m n o p q r s t u v w x y z
[0-9] = 0 1 2 3 4 5 6 7 8 9
[markup] = ` ~ ! @ \# $$ % ^ & * ( ) - _ = + [ { ] } \ | ; : ' " , < . > / ?
[all] = $([A-Z]) $([a-z]) $([0-9]) $([markup])
[space] :=
[space] +=
#####
# platform detection
#####
ifeq ($(platform),)
uname := $(shell uname -a)
ifeq ($(uname),)
platform := win
delete = del $(subst /,\,$1)
else ifneq ($(findstring Darwin,$(uname)),)
platform := osx
delete = rm -f $1
else
platform := x
delete = rm -f $1
endif
endif
ifeq ($(compiler),)
ifeq ($(platform),osx)
compiler := gcc-mp-4.4
else
compiler := gcc
endif
endif
ifeq ($(prefix),)
prefix := /usr/local
endif
#####
# function rwildcard(directory, pattern)
#####
rwildcard = \
$(strip \
$(filter $(if $2,$2,%), \
$(foreach f, \
$(wildcard $1*), \
$(eval t = $(call rwildcard,$f/)) \
$(if $t,$t,$f) \
) \
) \
)
#####
# function strtr(source, from, to)
#####
strtr = \
$(eval __temp := $1) \
$(strip \
$(foreach c, \
$(join $(addsuffix :,$2),$3), \
$(eval __temp := \
$(subst $(word 1,$(subst :, ,$c)),$(word 2,$(subst :, ,$c)),$(__temp)) \
) \
) \
$(__temp) \
)
#####
# function strupper(source)
#####
strupper = $(call strtr,$1,$([a-z]),$([A-Z]))
#####
# function strlower(source)
#####
strlower = $(call strtr,$1,$([A-Z]),$([a-z]))
#####
# function strlen(source)
#####
strlen = \
$(eval __temp := $(subst $([space]),_,$1)) \
$(words \
$(strip \
$(foreach c, \
$([all]), \
$(eval __temp := \
$(subst $c,$c ,$(__temp)) \
) \
) \
$(__temp) \
) \
)
#####
# function streq(source)
#####
streq = $(if $(filter-out xx,x$(subst $1,,$2)$(subst $2,,$1)x),,1)
#####
# function strne(source)
#####
strne = $(if $(filter-out xx,x$(subst $1,,$2)$(subst $2,,$1)x),1,)

View File

@@ -0,0 +1,17 @@
#ifndef NALL_ALGORITHM_HPP
#define NALL_ALGORITHM_HPP
#undef min
#undef max
namespace nall {
template<typename T, typename U> T min(const T &t, const U &u) {
return t < u ? t : u;
}
template<typename T, typename U> T max(const T &t, const U &u) {
return t > u ? t : u;
}
}
#endif

74
snesfilter/nall/any.hpp Normal file
View File

@@ -0,0 +1,74 @@
#ifndef NALL_ANY_HPP
#define NALL_ANY_HPP
#include <typeinfo>
#include <type_traits>
#include <nall/static.hpp>
namespace nall {
class any {
public:
bool empty() const { return container; }
const std::type_info& type() const { return container ? container->type() : typeid(void); }
template<typename T> any& operator=(const T& value_) {
typedef typename static_if<
std::is_array<T>::value,
typename std::remove_extent<typename std::add_const<T>::type>::type*,
T
>::type auto_t;
if(type() == typeid(auto_t)) {
static_cast<holder<auto_t>*>(container)->value = (auto_t)value_;
} else {
if(container) delete container;
container = new holder<auto_t>((auto_t)value_);
}
return *this;
}
any() : container(0) {}
template<typename T> any(const T& value_) : container(0) { operator=(value_); }
private:
struct placeholder {
virtual const std::type_info& type() const = 0;
} *container;
template<typename T> struct holder : placeholder {
T value;
const std::type_info& type() const { return typeid(T); }
holder(const T& value_) : value(value_) {}
};
template<typename T> friend T any_cast(any&);
template<typename T> friend T any_cast(const any&);
template<typename T> friend T* any_cast(any*);
template<typename T> friend const T* any_cast(const any*);
};
template<typename T> T any_cast(any &value) {
typedef typename std::remove_reference<T>::type nonref;
if(value.type() != typeid(nonref)) throw;
return static_cast<any::holder<nonref>*>(value.container)->value;
}
template<typename T> T any_cast(const any &value) {
typedef const typename std::remove_reference<T>::type nonref;
if(value.type() != typeid(nonref)) throw;
return static_cast<any::holder<nonref>*>(value.container)->value;
}
template<typename T> T* any_cast(any *value) {
if(!value || value->type() != typeid(T)) return 0;
return &static_cast<any::holder<T>*>(value->container)->value;
}
template<typename T> const T* any_cast(const any *value) {
if(!value || value->type() != typeid(T)) return 0;
return &static_cast<any::holder<T>*>(value->container)->value;
}
}
#endif

141
snesfilter/nall/array.hpp Normal file
View File

@@ -0,0 +1,141 @@
#ifndef NALL_ARRAY_HPP
#define NALL_ARRAY_HPP
#include <stdlib.h>
#include <initializer_list>
#include <type_traits>
#include <utility>
#include <nall/algorithm.hpp>
#include <nall/bit.hpp>
#include <nall/concept.hpp>
#include <nall/foreach.hpp>
#include <nall/utility.hpp>
namespace nall {
//dynamic vector array
//neither constructor nor destructor is ever invoked;
//thus, this should only be used for POD objects.
template<typename T> class array {
protected:
T *pool;
unsigned poolsize, buffersize;
public:
unsigned size() const { return buffersize; }
unsigned capacity() const { return poolsize; }
void reset() {
if(pool) free(pool);
pool = 0;
poolsize = 0;
buffersize = 0;
}
void reserve(unsigned newsize) {
if(newsize == poolsize) return;
pool = (T*)realloc(pool, newsize * sizeof(T));
poolsize = newsize;
buffersize = min(buffersize, newsize);
}
void resize(unsigned newsize) {
if(newsize > poolsize) reserve(bit::round(newsize)); //round reserve size up to power of 2
buffersize = newsize;
}
T* get(unsigned minsize = 0) {
if(minsize > buffersize) resize(minsize);
if(minsize > buffersize) throw "array[] out of bounds";
return pool;
}
void append(const T data) {
operator[](buffersize) = data;
}
template<typename U> void insert(unsigned index, const U list) {
unsigned listsize = container_size(list);
resize(buffersize + listsize);
memmove(pool + index + listsize, pool + index, (buffersize - index) * sizeof(T));
foreach(item, list) pool[index++] = item;
}
void insert(unsigned index, const T item) {
insert(index, array<T>{ item });
}
void remove(unsigned index, unsigned count = 1) {
for(unsigned i = index; count + i < buffersize; i++) {
pool[i] = pool[count + i];
}
if(count + index >= buffersize) resize(index); //every element >= index was removed
else resize(buffersize - count);
}
optional<unsigned> find(const T data) {
for(unsigned i = 0; i < size(); i++) if(pool[i] == data) return { true, i };
return { false, 0 };
}
void clear() {
memset(pool, 0, buffersize * sizeof(T));
}
array() : pool(0), poolsize(0), buffersize(0) {
}
array(std::initializer_list<T> list) : pool(0), poolsize(0), buffersize(0) {
for(const T *p = list.begin(); p != list.end(); ++p) append(*p);
}
~array() {
reset();
}
//copy
array& operator=(const array &source) {
if(pool) free(pool);
buffersize = source.buffersize;
poolsize = source.poolsize;
pool = (T*)malloc(sizeof(T) * poolsize); //allocate entire pool size,
memcpy(pool, source.pool, sizeof(T) * buffersize); //... but only copy used pool objects
return *this;
}
array(const array &source) : pool(0), poolsize(0), buffersize(0) {
operator=(source);
}
//move
array& operator=(array &&source) {
if(pool) free(pool);
pool = source.pool;
poolsize = source.poolsize;
buffersize = source.buffersize;
source.pool = 0;
source.reset();
return *this;
}
array(array &&source) : pool(0), poolsize(0), buffersize(0) {
operator=(std::move(source));
}
//index
inline T& operator[](unsigned index) {
if(index >= buffersize) resize(index + 1);
if(index >= buffersize) throw "array[] out of bounds";
return pool[index];
}
inline const T& operator[](unsigned index) const {
if(index >= buffersize) throw "array[] out of bounds";
return pool[index];
}
};
template<typename T> struct has_size<array<T>> { enum { value = true }; };
}
#endif

View File

@@ -0,0 +1,90 @@
#ifndef NALL_BASE64_HPP
#define NALL_BASE64_HPP
#include <string.h>
#include <nall/stdint.hpp>
namespace nall {
class base64 {
public:
static bool encode(char *&output, const uint8_t* input, unsigned inlength) {
output = new char[inlength * 8 / 6 + 6]();
unsigned i = 0, o = 0;
while(i < inlength) {
switch(i % 3) {
case 0: {
output[o++] = enc(input[i] >> 2);
output[o] = enc((input[i] & 3) << 4);
} break;
case 1: {
uint8_t prev = dec(output[o]);
output[o++] = enc(prev + (input[i] >> 4));
output[o] = enc((input[i] & 15) << 2);
} break;
case 2: {
uint8_t prev = dec(output[o]);
output[o++] = enc(prev + (input[i] >> 6));
output[o++] = enc(input[i] & 63);
} break;
}
i++;
}
return true;
}
static bool decode(uint8_t *&output, unsigned &outlength, const char *input) {
unsigned inlength = strlen(input), infix = 0;
output = new uint8_t[inlength]();
unsigned i = 0, o = 0;
while(i < inlength) {
uint8_t x = dec(input[i]);
switch(i++ & 3) {
case 0: {
output[o] = x << 2;
} break;
case 1: {
output[o++] |= x >> 4;
output[o] = (x & 15) << 4;
} break;
case 2: {
output[o++] |= x >> 2;
output[o] = (x & 3) << 6;
} break;
case 3: {
output[o++] |= x;
} break;
}
}
outlength = o;
return true;
}
private:
static char enc(uint8_t n) {
static char lookup_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
return lookup_table[n & 63];
}
static uint8_t dec(char n) {
if(n >= 'A' && n <= 'Z') return n - 'A';
if(n >= 'a' && n <= 'z') return n - 'a' + 26;
if(n >= '0' && n <= '9') return n - '0' + 52;
if(n == '-') return 62;
if(n == '_') return 63;
return 0;
}
};
}
#endif

51
snesfilter/nall/bit.hpp Normal file
View File

@@ -0,0 +1,51 @@
#ifndef NALL_BIT_HPP
#define NALL_BIT_HPP
namespace nall {
template<int bits> inline unsigned uclamp(const unsigned x) {
enum { y = (1U << bits) - 1 };
return y + ((x - y) & -(x < y)); //min(x, y);
}
template<int bits> inline unsigned uclip(const unsigned x) {
enum { m = (1U << bits) - 1 };
return (x & m);
}
template<int bits> inline signed sclamp(const signed x) {
enum { b = 1U << (bits - 1), m = (1U << (bits - 1)) - 1 };
return (x > m) ? m : (x < -b) ? -b : x;
}
template<int bits> inline signed sclip(const signed x) {
enum { b = 1U << (bits - 1), m = (1U << bits) - 1 };
return ((x & m) ^ b) - b;
}
namespace bit {
//lowest(0b1110) == 0b0010
template<typename T> inline T lowest(const T x) {
return x & -x;
}
//clear_lowest(0b1110) == 0b1100
template<typename T> inline T clear_lowest(const T x) {
return x & (x - 1);
}
//set_lowest(0b0101) == 0b0111
template<typename T> inline T set_lowest(const T x) {
return x | (x + 1);
}
//round up to next highest single bit:
//round(15) == 16, round(16) == 16, round(17) == 32
inline unsigned round(unsigned x) {
if((x & (x - 1)) == 0) return x;
while(x & (x - 1)) x &= x - 1;
return x << 1;
}
}
}
#endif

View File

@@ -0,0 +1,34 @@
#ifndef NALL_CONCEPT_HPP
#define NALL_CONCEPT_HPP
#include <nall/static.hpp>
#include <nall/utility.hpp>
namespace nall {
//unsigned count() const;
template<typename T> struct has_count { enum { value = false }; };
//unsigned length() const;
template<typename T> struct has_length { enum { value = false }; };
//unsigned size() const;
template<typename T> struct has_size { enum { value = false }; };
template<typename T> unsigned container_size(const T& object, typename mp_enable_if<has_count<T>>::type = 0) {
return object.count();
}
template<typename T> unsigned container_size(const T& object, typename mp_enable_if<has_length<T>>::type = 0) {
return object.length();
}
template<typename T> unsigned container_size(const T& object, typename mp_enable_if<has_size<T>>::type = 0) {
return object.size();
}
template<typename T> unsigned container_size(const T& object, typename mp_enable_if<std::is_array<T>>::type = 0) {
return sizeof(T) / sizeof(typename std::remove_extent<T>::type);
}
}
#endif

123
snesfilter/nall/config.hpp Normal file
View File

@@ -0,0 +1,123 @@
#ifndef NALL_CONFIG_HPP
#define NALL_CONFIG_HPP
#include <nall/file.hpp>
#include <nall/string.hpp>
#include <nall/vector.hpp>
namespace nall {
namespace configuration_traits {
template<typename T> struct is_boolean { enum { value = false }; };
template<> struct is_boolean<bool> { enum { value = true }; };
template<typename T> struct is_signed { enum { value = false }; };
template<> struct is_signed<signed> { enum { value = true }; };
template<typename T> struct is_unsigned { enum { value = false }; };
template<> struct is_unsigned<unsigned> { enum { value = true }; };
template<typename T> struct is_double { enum { value = false }; };
template<> struct is_double<double> { enum { value = true }; };
template<typename T> struct is_string { enum { value = false }; };
template<> struct is_string<string> { enum { value = true }; };
}
class configuration {
public:
enum type_t { boolean_t, signed_t, unsigned_t, double_t, string_t, unknown_t };
struct item_t {
uintptr_t data;
string name;
string desc;
type_t type;
string get() const {
switch(type) {
case boolean_t: return string() << *(bool*)data;
case signed_t: return string() << *(signed*)data;
case unsigned_t: return string() << *(unsigned*)data;
case double_t: return string() << *(double*)data;
case string_t: return string() << "\"" << *(string*)data << "\"";
}
return "???";
}
void set(string s) {
switch(type) {
case boolean_t: *(bool*)data = (s == "true"); break;
case signed_t: *(signed*)data = strsigned(s); break;
case unsigned_t: *(unsigned*)data = strunsigned(s); break;
case double_t: *(double*)data = strdouble(s); break;
case string_t: trim(s, "\""); *(string*)data = s; break;
}
}
};
linear_vector<item_t> list;
template<typename T>
void attach(T &data, const char *name, const char *desc = "") {
unsigned n = list.size();
list[n].data = (uintptr_t)&data;
list[n].name = name;
list[n].desc = desc;
if(configuration_traits::is_boolean<T>::value) list[n].type = boolean_t;
else if(configuration_traits::is_signed<T>::value) list[n].type = signed_t;
else if(configuration_traits::is_unsigned<T>::value) list[n].type = unsigned_t;
else if(configuration_traits::is_double<T>::value) list[n].type = double_t;
else if(configuration_traits::is_string<T>::value) list[n].type = string_t;
else list[n].type = unknown_t;
}
virtual bool load(const char *filename) {
string data;
if(data.readfile(filename) == true) {
data.replace("\r", "");
lstring line;
line.split("\n", data);
for(unsigned i = 0; i < line.size(); i++) {
if(auto position = qstrpos(line[i], "#")) line[i][position()] = 0;
if(!qstrpos(line[i], " = ")) continue;
lstring part;
part.qsplit(" = ", line[i]);
trim(part[0]);
trim(part[1]);
for(unsigned n = 0; n < list.size(); n++) {
if(part[0] == list[n].name) {
list[n].set(part[1]);
break;
}
}
}
return true;
} else {
return false;
}
}
virtual bool save(const char *filename) const {
file fp;
if(fp.open(filename, file::mode_write)) {
for(unsigned i = 0; i < list.size(); i++) {
string output;
output << list[i].name << " = " << list[i].get();
if(list[i].desc != "") output << " # " << list[i].desc;
output << "\r\n";
fp.print(output);
}
fp.close();
return true;
} else {
return false;
}
}
};
}
#endif

66
snesfilter/nall/crc32.hpp Normal file
View File

@@ -0,0 +1,66 @@
#ifndef NALL_CRC32_HPP
#define NALL_CRC32_HPP
#include <nall/stdint.hpp>
namespace nall {
const uint32_t crc32_table[256] = {
0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
};
inline uint32_t crc32_adjust(uint32_t crc32, uint8_t input) {
return ((crc32 >> 8) & 0x00ffffff) ^ crc32_table[(crc32 ^ input) & 0xff];
}
inline uint32_t crc32_calculate(const uint8_t *data, unsigned length) {
uint32_t crc32 = ~0;
for(unsigned i = 0; i < length; i++) {
crc32 = crc32_adjust(crc32, data[i]);
}
return ~crc32;
}
}
#endif

View File

@@ -0,0 +1,30 @@
#ifndef NALL_DETECT_HPP
#define NALL_DETECT_HPP
/* Compiler detection */
#if defined(__GNUC__)
#define COMPILER_GCC
#elif defined(_MSC_VER)
#define COMPILER_VISUALC
#endif
/* Platform detection */
#if defined(_WIN32)
#define PLATFORM_WIN
#elif defined(__APPLE__)
#define PLATFORM_OSX
#elif defined(linux) || defined(__sun__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
#define PLATFORM_X
#endif
/* Endian detection */
#if defined(__i386__) || defined(__amd64__) || defined(_M_IX86) || defined(_M_AMD64)
#define ARCH_LSB
#elif defined(__powerpc__) || defined(_M_PPC) || defined(__BIG_ENDIAN__)
#define ARCH_MSB
#endif
#endif

View File

@@ -0,0 +1,75 @@
#ifndef NALL_DICTIONARY_HPP
#define NALL_DICTIONARY_HPP
#include <nall/array.hpp>
#include <nall/string.hpp>
#include <nall/utility.hpp>
namespace nall {
class dictionary {
public:
string operator[](const char *input) {
for(unsigned i = 0; i < index_input.size(); i++) {
if(index_input[i] == input) return index_output[i];
}
//no match, use input; remove input identifier, if one exists
if(strbegin(input, "{{")) {
if(auto pos = strpos(input, "}}")) {
string temp = substr(input, pos() + 2);
return temp;
}
}
return input;
}
bool import(const char *filename) {
string data;
if(data.readfile(filename) == false) return false;
ltrim_once(data, "\xef\xbb\xbf"); //remove UTF-8 marker, if it exists
data.replace("\r", "");
lstring line;
line.split("\n", data);
for(unsigned i = 0; i < line.size(); i++) {
lstring part;
//format: "Input" = "Output"
part.qsplit("=", line[i]);
if(part.size() != 2) continue;
//remove whitespace
trim(part[0]);
trim(part[1]);
//remove quotes
trim_once(part[0], "\"");
trim_once(part[1], "\"");
unsigned n = index_input.size();
index_input[n] = part[0];
index_output[n] = part[1];
}
return true;
}
void reset() {
index_input.reset();
index_output.reset();
}
~dictionary() {
reset();
}
dictionary& operator=(const dictionary&) = delete;
dictionary(const dictionary&) = delete;
protected:
lstring index_input;
lstring index_output;
};
}
#endif

119
snesfilter/nall/dl.hpp Normal file
View File

@@ -0,0 +1,119 @@
#ifndef NALL_DL_HPP
#define NALL_DL_HPP
//dynamic linking support
#include <string.h>
#include <nall/detect.hpp>
#include <nall/stdint.hpp>
#include <nall/utility.hpp>
#if defined(PLATFORM_X) || defined(PLATFORM_OSX)
#include <dlfcn.h>
#elif defined(PLATFORM_WIN)
#include <windows.h>
#include <nall/utf8.hpp>
#endif
namespace nall {
struct library {
bool opened() const { return handle; }
bool open(const char*);
void* sym(const char*);
void close();
library() : handle(0) {}
~library() { close(); }
library& operator=(const library&) = delete;
library(const library&) = delete;
private:
uintptr_t handle;
};
#if defined(PLATFORM_X)
inline bool library::open(const char *name) {
if(handle) close();
char *t = new char[strlen(name) + 256];
strcpy(t, "lib");
strcat(t, name);
strcat(t, ".so");
handle = (uintptr_t)dlopen(t, RTLD_LAZY);
if(!handle) {
strcpy(t, "/usr/local/lib/lib");
strcat(t, name);
strcat(t, ".so");
handle = (uintptr_t)dlopen(t, RTLD_LAZY);
}
delete[] t;
return handle;
}
inline void* library::sym(const char *name) {
if(!handle) return 0;
return dlsym((void*)handle, name);
}
inline void library::close() {
if(!handle) return;
dlclose((void*)handle);
handle = 0;
}
#elif defined(PLATFORM_OSX)
inline bool library::open(const char *name) {
if(handle) close();
char *t = new char[strlen(name) + 256];
strcpy(t, "lib");
strcat(t, name);
strcat(t, ".dylib");
handle = (uintptr_t)dlopen(t, RTLD_LAZY);
if(!handle) {
strcpy(t, "/usr/local/lib/lib");
strcat(t, name);
strcat(t, ".dylib");
handle = (uintptr_t)dlopen(t, RTLD_LAZY);
}
delete[] t;
return handle;
}
inline void* library::sym(const char *name) {
if(!handle) return 0;
return dlsym((void*)handle, name);
}
inline void library::close() {
if(!handle) return;
dlclose((void*)handle);
handle = 0;
}
#elif defined(PLATFORM_WIN)
inline bool library::open(const char *name) {
if(handle) close();
char *t = new char[strlen(name) + 8];
strcpy(t, name);
strcat(t, ".dll");
handle = (uintptr_t)LoadLibraryW(utf16_t(t));
delete[] t;
return handle;
}
inline void* library::sym(const char *name) {
if(!handle) return 0;
return (void*)GetProcAddress((HMODULE)handle, name);
}
inline void library::close() {
if(!handle) return;
FreeLibrary((HMODULE)handle);
handle = 0;
}
#else
inline bool library::open(const char*) { return false; }
inline void* library::sym(const char*) { return 0; }
inline void library::close() {}
#endif
};
#endif

View File

@@ -0,0 +1,38 @@
#ifndef NALL_ENDIAN_HPP
#define NALL_ENDIAN_HPP
#if !defined(ARCH_MSB)
//little-endian: uint8_t[] { 0x01, 0x02, 0x03, 0x04 } == 0x04030201
#define order_lsb2(a,b) a,b
#define order_lsb3(a,b,c) a,b,c
#define order_lsb4(a,b,c,d) a,b,c,d
#define order_lsb5(a,b,c,d,e) a,b,c,d,e
#define order_lsb6(a,b,c,d,e,f) a,b,c,d,e,f
#define order_lsb7(a,b,c,d,e,f,g) a,b,c,d,e,f,g
#define order_lsb8(a,b,c,d,e,f,g,h) a,b,c,d,e,f,g,h
#define order_msb2(a,b) b,a
#define order_msb3(a,b,c) c,b,a
#define order_msb4(a,b,c,d) d,c,b,a
#define order_msb5(a,b,c,d,e) e,d,c,b,a
#define order_msb6(a,b,c,d,e,f) f,e,d,c,b,a
#define order_msb7(a,b,c,d,e,f,g) g,f,e,d,c,b,a
#define order_msb8(a,b,c,d,e,f,g,h) h,g,f,e,d,c,b,a
#else
//big-endian: uint8_t[] { 0x01, 0x02, 0x03, 0x04 } == 0x01020304
#define order_lsb2(a,b) b,a
#define order_lsb3(a,b,c) c,b,a
#define order_lsb4(a,b,c,d) d,c,b,a
#define order_lsb5(a,b,c,d,e) e,d,c,b,a
#define order_lsb6(a,b,c,d,e,f) f,e,d,c,b,a
#define order_lsb7(a,b,c,d,e,f,g) g,f,e,d,c,b,a
#define order_lsb8(a,b,c,d,e,f,g,h) h,g,f,e,d,c,b,a
#define order_msb2(a,b) a,b
#define order_msb3(a,b,c) a,b,c
#define order_msb4(a,b,c,d) a,b,c,d
#define order_msb5(a,b,c,d,e) a,b,c,d,e
#define order_msb6(a,b,c,d,e,f) a,b,c,d,e,f
#define order_msb7(a,b,c,d,e,f,g) a,b,c,d,e,f,g
#define order_msb8(a,b,c,d,e,f,g,h) a,b,c,d,e,f,g,h
#endif
#endif

259
snesfilter/nall/file.hpp Normal file
View File

@@ -0,0 +1,259 @@
#ifndef NALL_FILE_HPP
#define NALL_FILE_HPP
#include <stdio.h>
#include <string.h>
#if !defined(_WIN32)
#include <unistd.h>
#else
#include <io.h>
#endif
#include <nall/stdint.hpp>
#include <nall/utf8.hpp>
#include <nall/utility.hpp>
namespace nall {
inline FILE* fopen_utf8(const char *utf8_filename, const char *mode) {
#if !defined(_WIN32)
return fopen(utf8_filename, mode);
#else
return _wfopen(utf16_t(utf8_filename), utf16_t(mode));
#endif
}
class file {
public:
enum FileMode { mode_read, mode_write, mode_readwrite, mode_writeread };
enum SeekMode { seek_absolute, seek_relative };
uint8_t read() {
if(!fp) return 0xff; //file not open
if(file_mode == mode_write) return 0xff; //reads not permitted
if(file_offset >= file_size) return 0xff; //cannot read past end of file
buffer_sync();
return buffer[(file_offset++) & buffer_mask];
}
uintmax_t readl(unsigned length = 1) {
uintmax_t data = 0;
for(int i = 0; i < length; i++) {
data |= (uintmax_t)read() << (i << 3);
}
return data;
}
uintmax_t readm(unsigned length = 1) {
uintmax_t data = 0;
while(length--) {
data <<= 8;
data |= read();
}
return data;
}
void read(uint8_t *buffer, unsigned length) {
while(length--) *buffer++ = read();
}
void write(uint8_t data) {
if(!fp) return; //file not open
if(file_mode == mode_read) return; //writes not permitted
buffer_sync();
buffer[(file_offset++) & buffer_mask] = data;
buffer_dirty = true;
if(file_offset > file_size) file_size = file_offset;
}
void writel(uintmax_t data, unsigned length = 1) {
while(length--) {
write(data);
data >>= 8;
}
}
void writem(uintmax_t data, unsigned length = 1) {
for(int i = length - 1; i >= 0; i--) {
write(data >> (i << 3));
}
}
void write(const uint8_t *buffer, unsigned length) {
while(length--) write(*buffer++);
}
void print(const char *string) {
if(!string) return;
while(*string) write(*string++);
}
void flush() {
buffer_flush();
fflush(fp);
}
void seek(int offset, SeekMode mode = seek_absolute) {
if(!fp) return; //file not open
buffer_flush();
uintmax_t req_offset = file_offset;
switch(mode) {
case seek_absolute: req_offset = offset; break;
case seek_relative: req_offset += offset; break;
}
if(req_offset < 0) req_offset = 0; //cannot seek before start of file
if(req_offset > file_size) {
if(file_mode == mode_read) { //cannot seek past end of file
req_offset = file_size;
} else { //pad file to requested location
file_offset = file_size;
while(file_size < req_offset) write(0x00);
}
}
file_offset = req_offset;
}
int offset() {
if(!fp) return -1; //file not open
return file_offset;
}
int size() {
if(!fp) return -1; //file not open
return file_size;
}
bool truncate(unsigned size) {
if(!fp) return false; //file not open
#if !defined(_WIN32)
return ftruncate(fileno(fp), size) == 0;
#else
return _chsize(fileno(fp), size) == 0;
#endif
}
bool end() {
if(!fp) return true; //file not open
return file_offset >= file_size;
}
static bool exists(const char *fn) {
#if !defined(_WIN32)
FILE *fp = fopen(fn, "rb");
#else
FILE *fp = _wfopen(utf16_t(fn), L"rb");
#endif
if(fp) {
fclose(fp);
return true;
}
return false;
}
static unsigned size(const char *fn) {
#if !defined(_WIN32)
FILE *fp = fopen(fn, "rb");
#else
FILE *fp = _wfopen(utf16_t(fn), L"rb");
#endif
unsigned filesize = 0;
if(fp) {
fseek(fp, 0, SEEK_END);
filesize = ftell(fp);
fclose(fp);
}
return filesize;
}
bool open() {
return fp;
}
bool open(const char *fn, FileMode mode) {
if(fp) return false;
switch(file_mode = mode) {
#if !defined(_WIN32)
case mode_read: fp = fopen(fn, "rb"); break;
case mode_write: fp = fopen(fn, "wb+"); break; //need read permission for buffering
case mode_readwrite: fp = fopen(fn, "rb+"); break;
case mode_writeread: fp = fopen(fn, "wb+"); break;
#else
case mode_read: fp = _wfopen(utf16_t(fn), L"rb"); break;
case mode_write: fp = _wfopen(utf16_t(fn), L"wb+"); break;
case mode_readwrite: fp = _wfopen(utf16_t(fn), L"rb+"); break;
case mode_writeread: fp = _wfopen(utf16_t(fn), L"wb+"); break;
#endif
}
if(!fp) return false;
buffer_offset = -1; //invalidate buffer
file_offset = 0;
fseek(fp, 0, SEEK_END);
file_size = ftell(fp);
fseek(fp, 0, SEEK_SET);
return true;
}
void close() {
if(!fp) return;
buffer_flush();
fclose(fp);
fp = 0;
}
file() {
memset(buffer, 0, sizeof buffer);
buffer_offset = -1;
buffer_dirty = false;
fp = 0;
file_offset = 0;
file_size = 0;
file_mode = mode_read;
}
~file() {
close();
}
file& operator=(const file&) = delete;
file(const file&) = delete;
private:
enum { buffer_size = 1 << 12, buffer_mask = buffer_size - 1 };
char buffer[buffer_size];
int buffer_offset;
bool buffer_dirty;
FILE *fp;
unsigned file_offset;
unsigned file_size;
FileMode file_mode;
void buffer_sync() {
if(!fp) return; //file not open
if(buffer_offset != (file_offset & ~buffer_mask)) {
buffer_flush();
buffer_offset = file_offset & ~buffer_mask;
fseek(fp, buffer_offset, SEEK_SET);
unsigned length = (buffer_offset + buffer_size) <= file_size ? buffer_size : (file_size & buffer_mask);
if(length) unsigned unused = fread(buffer, 1, length, fp);
}
}
void buffer_flush() {
if(!fp) return; //file not open
if(file_mode == mode_read) return; //buffer cannot be written to
if(buffer_offset < 0) return; //buffer unused
if(buffer_dirty == false) return; //buffer unmodified since read
fseek(fp, buffer_offset, SEEK_SET);
unsigned length = (buffer_offset + buffer_size) <= file_size ? buffer_size : (file_size & buffer_mask);
if(length) unsigned unused = fwrite(buffer, 1, length, fp);
buffer_offset = -1; //invalidate buffer
buffer_dirty = false;
}
};
}
#endif

190
snesfilter/nall/filemap.hpp Normal file
View File

@@ -0,0 +1,190 @@
#ifndef NALL_FILEMAP_HPP
#define NALL_FILEMAP_HPP
#include <nall/stdint.hpp>
#include <nall/utf8.hpp>
#include <stdio.h>
#include <stdlib.h>
#if defined(_WIN32)
#include <windows.h>
#else
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#endif
namespace nall {
class filemap {
public:
enum filemode { mode_read, mode_write, mode_readwrite, mode_writeread };
bool open(const char *filename, filemode mode) { return p_open(filename, mode); }
void close() { return p_close(); }
unsigned size() const { return p_size; }
uint8_t* handle() { return p_handle; }
const uint8_t* handle() const { return p_handle; }
filemap() : p_size(0), p_handle(0) { p_ctor(); }
~filemap() { p_dtor(); }
private:
unsigned p_size;
uint8_t *p_handle;
#if defined(_WIN32)
//=============
//MapViewOfFile
//=============
HANDLE p_filehandle, p_maphandle;
bool p_open(const char *filename, filemode mode) {
int desired_access, creation_disposition, flprotect, map_access;
switch(mode) {
default: return false;
case mode_read:
desired_access = GENERIC_READ;
creation_disposition = OPEN_EXISTING;
flprotect = PAGE_READONLY;
map_access = FILE_MAP_READ;
break;
case mode_write:
//write access requires read access
desired_access = GENERIC_WRITE;
creation_disposition = CREATE_ALWAYS;
flprotect = PAGE_READWRITE;
map_access = FILE_MAP_ALL_ACCESS;
break;
case mode_readwrite:
desired_access = GENERIC_READ | GENERIC_WRITE;
creation_disposition = OPEN_EXISTING;
flprotect = PAGE_READWRITE;
map_access = FILE_MAP_ALL_ACCESS;
break;
case mode_writeread:
desired_access = GENERIC_READ | GENERIC_WRITE;
creation_disposition = CREATE_NEW;
flprotect = PAGE_READWRITE;
map_access = FILE_MAP_ALL_ACCESS;
break;
}
p_filehandle = CreateFileW(utf16_t(filename), desired_access, FILE_SHARE_READ, NULL,
creation_disposition, FILE_ATTRIBUTE_NORMAL, NULL);
if(p_filehandle == INVALID_HANDLE_VALUE) return false;
p_size = GetFileSize(p_filehandle, NULL);
p_maphandle = CreateFileMapping(p_filehandle, NULL, flprotect, 0, p_size, NULL);
if(p_maphandle == INVALID_HANDLE_VALUE) {
CloseHandle(p_filehandle);
p_filehandle = INVALID_HANDLE_VALUE;
return false;
}
p_handle = (uint8_t*)MapViewOfFile(p_maphandle, map_access, 0, 0, p_size);
return p_handle;
}
void p_close() {
if(p_handle) {
UnmapViewOfFile(p_handle);
p_handle = 0;
}
if(p_maphandle != INVALID_HANDLE_VALUE) {
CloseHandle(p_maphandle);
p_maphandle = INVALID_HANDLE_VALUE;
}
if(p_filehandle != INVALID_HANDLE_VALUE) {
CloseHandle(p_filehandle);
p_filehandle = INVALID_HANDLE_VALUE;
}
}
void p_ctor() {
p_filehandle = INVALID_HANDLE_VALUE;
p_maphandle = INVALID_HANDLE_VALUE;
}
void p_dtor() {
close();
}
#else
//====
//mmap
//====
int p_fd;
bool p_open(const char *filename, filemode mode) {
int open_flags, mmap_flags;
switch(mode) {
default: return false;
case mode_read:
open_flags = O_RDONLY;
mmap_flags = PROT_READ;
break;
case mode_write:
open_flags = O_RDWR | O_CREAT; //mmap() requires read access
mmap_flags = PROT_WRITE;
break;
case mode_readwrite:
open_flags = O_RDWR;
mmap_flags = PROT_READ | PROT_WRITE;
break;
case mode_writeread:
open_flags = O_RDWR | O_CREAT;
mmap_flags = PROT_READ | PROT_WRITE;
break;
}
p_fd = ::open(filename, open_flags);
if(p_fd < 0) return false;
struct stat p_stat;
fstat(p_fd, &p_stat);
p_size = p_stat.st_size;
p_handle = (uint8_t*)mmap(0, p_size, mmap_flags, MAP_SHARED, p_fd, 0);
if(p_handle == MAP_FAILED) {
p_handle = 0;
::close(p_fd);
p_fd = -1;
return false;
}
return p_handle;
}
void p_close() {
if(p_handle) {
munmap(p_handle, p_size);
p_handle = 0;
}
if(p_fd >= 0) {
::close(p_fd);
p_fd = -1;
}
}
void p_ctor() {
p_fd = -1;
}
void p_dtor() {
p_close();
}
#endif
};
}
#endif

View File

@@ -0,0 +1,12 @@
#ifndef NALL_FOREACH_HPP
#define NALL_FOREACH_HPP
#include <type_traits>
#include <nall/concept.hpp>
#undef foreach
#define foreach(iter, object) \
for(unsigned foreach_counter = 0, foreach_limit = container_size(object), foreach_once = 0, foreach_broken = 0; foreach_counter < foreach_limit && foreach_broken == 0; foreach_counter++, foreach_once = 0) \
for(auto &iter = object[foreach_counter]; foreach_once == 0 && (foreach_broken = 1); foreach_once++, foreach_broken = 0)
#endif

View File

@@ -0,0 +1,90 @@
#ifndef NALL_FUNCTION_HPP
#define NALL_FUNCTION_HPP
#include <functional>
#include <type_traits>
namespace nall {
template<typename T> class function;
template<typename R, typename... P>
class function<R (P...)> {
private:
struct base1 { virtual void func1(P...) {} };
struct base2 { virtual void func2(P...) {} };
struct derived : base1, virtual base2 {};
struct data_t {
R (*callback)(const data_t&, P...);
union {
R (*callback_global)(P...);
struct {
R (derived::*callback_member)(P...);
void *object;
};
};
} data;
static R callback_global(const data_t &data, P... p) {
return data.callback_global(p...);
}
template<typename C>
static R callback_member(const data_t &data, P... p) {
return (((C*)data.object)->*((R (C::*&)(P...))data.callback_member))(p...);
}
public:
R operator()(P... p) const { return data.callback(data, p...); }
operator bool() const { return data.callback; }
void reset() { data.callback = 0; }
function& operator=(const function &source) { memcpy(&data, &source.data, sizeof(data_t)); return *this; }
function(const function &source) { operator=(source); }
//no pointer
function() {
data.callback = 0;
}
//symbolic link pointer (nall/dl.hpp::sym, etc)
function(void *callback) {
data.callback = callback ? &callback_global : 0;
data.callback_global = (R (*)(P...))callback;
}
//global function pointer
function(R (*callback)(P...)) {
data.callback = &callback_global;
data.callback_global = callback;
}
//member function pointer
template<typename C>
function(R (C::*callback)(P...), C *object) {
static_assert(sizeof data.callback_member >= sizeof callback, "callback_member is too small");
data.callback = &callback_member<C>;
(R (C::*&)(P...))data.callback_member = callback;
data.object = object;
}
//const member function pointer
template<typename C>
function(R (C::*callback)(P...) const, C *object) {
static_assert(sizeof data.callback_member >= sizeof callback, "callback_member is too small");
data.callback = &callback_member<C>;
(R (C::*&)(P...))data.callback_member = (R (C::*&)(P...))callback;
data.object = object;
}
//lambda function pointer
template<typename T>
function(T callback) {
static_assert(std::is_same<R, typename std::result_of<T(P...)>::type>::value, "lambda mismatch");
data.callback = &callback_global;
data.callback_global = (R (*)(P...))callback;
}
};
}
#endif

386
snesfilter/nall/input.hpp Normal file
View File

@@ -0,0 +1,386 @@
#ifndef NALL_INPUT_HPP
#define NALL_INPUT_HPP
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <nall/stdint.hpp>
#include <nall/string.hpp>
namespace nall {
struct Keyboard;
Keyboard& keyboard(unsigned = 0);
static const char KeyboardScancodeName[][64] = {
"Escape", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
"PrintScreen", "ScrollLock", "Pause", "Tilde",
"Num1", "Num2", "Num3", "Num4", "Num5", "Num6", "Num7", "Num8", "Num9", "Num0",
"Dash", "Equal", "Backspace",
"Insert", "Delete", "Home", "End", "PageUp", "PageDown",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
"LeftBracket", "RightBracket", "Backslash", "Semicolon", "Apostrophe", "Comma", "Period", "Slash",
"Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6", "Keypad7", "Keypad8", "Keypad9", "Keypad0",
"Point", "Enter", "Add", "Subtract", "Multiply", "Divide",
"NumLock", "CapsLock",
"Up", "Down", "Left", "Right",
"Tab", "Return", "Spacebar", "Menu",
"Shift", "Control", "Alt", "Super",
};
struct Keyboard {
const unsigned ID;
enum { Base = 1 };
enum { Count = 8, Size = 128 };
enum Scancode {
Escape, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12,
PrintScreen, ScrollLock, Pause, Tilde,
Num1, Num2, Num3, Num4, Num5, Num6, Num7, Num8, Num9, Num0,
Dash, Equal, Backspace,
Insert, Delete, Home, End, PageUp, PageDown,
A, B, C, D, E, F, G, H, I, J, K, L, M,
N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
LeftBracket, RightBracket, Backslash, Semicolon, Apostrophe, Comma, Period, Slash,
Keypad1, Keypad2, Keypad3, Keypad4, Keypad5, Keypad6, Keypad7, Keypad8, Keypad9, Keypad0,
Point, Enter, Add, Subtract, Multiply, Divide,
NumLock, CapsLock,
Up, Down, Left, Right,
Tab, Return, Spacebar, Menu,
Shift, Control, Alt, Super,
Limit,
};
static signed numberDecode(uint16_t scancode) {
for(unsigned i = 0; i < Count; i++) {
if(keyboard(i).belongsTo(scancode)) return i;
}
return -1;
}
static signed keyDecode(uint16_t scancode) {
for(unsigned i = 0; i < Count; i++) {
if(keyboard(i).isKey(scancode)) return scancode - keyboard(i).key(Escape);
}
return -1;
}
static signed modifierDecode(uint16_t scancode) {
for(unsigned i = 0; i < Count; i++) {
if(keyboard(i).isModifier(scancode)) return scancode - keyboard(i).key(Shift);
}
return -1;
}
static bool isAnyKey(uint16_t scancode) {
for(unsigned i = 0; i < Count; i++) {
if(keyboard(i).isKey(scancode)) return true;
}
return false;
}
static bool isAnyModifier(uint16_t scancode) {
for(unsigned i = 0; i < Count; i++) {
if(keyboard(i).isModifier(scancode)) return true;
}
return false;
}
static uint16_t decode(const char *name) {
string s(name);
if(!strbegin(name, "KB")) return 0;
ltrim(s, "KB");
unsigned id = strunsigned(s);
auto pos = strpos(s, "::");
if(!pos) return 0;
s = substr(s, pos() + 2);
for(unsigned i = 0; i < Limit; i++) {
if(s == KeyboardScancodeName[i]) return Base + Size * id + i;
}
return 0;
}
string encode(uint16_t code) const {
unsigned index = 0;
for(unsigned i = 0; i < Count; i++) {
if(code >= Base + Size * i && code < Base + Size * (i + 1)) {
index = code - (Base + Size * i);
break;
}
}
return string() << "KB" << ID << "::" << KeyboardScancodeName[index];
}
uint16_t operator[](Scancode code) const { return Base + ID * Size + code; }
uint16_t key(unsigned id) const { return Base + Size * ID + id; }
bool isKey(unsigned id) const { return id >= key(Escape) && id <= key(Menu); }
bool isModifier(unsigned id) const { return id >= key(Shift) && id <= key(Super); }
bool belongsTo(uint16_t scancode) const { return isKey(scancode) || isModifier(scancode); }
Keyboard(unsigned ID_) : ID(ID_) {}
};
inline Keyboard& keyboard(unsigned id) {
static Keyboard kb0(0), kb1(1), kb2(2), kb3(3), kb4(4), kb5(5), kb6(6), kb7(7);
switch(id) { default:
case 0: return kb0; case 1: return kb1; case 2: return kb2; case 3: return kb3;
case 4: return kb4; case 5: return kb5; case 6: return kb6; case 7: return kb7;
}
}
static const char MouseScancodeName[][64] = {
"Xaxis", "Yaxis", "Zaxis",
"Button0", "Button1", "Button2", "Button3", "Button4", "Button5", "Button6", "Button7",
};
struct Mouse;
Mouse& mouse(unsigned = 0);
struct Mouse {
const unsigned ID;
enum { Base = Keyboard::Base + Keyboard::Size * Keyboard::Count };
enum { Count = 8, Size = 16 };
enum { Axes = 3, Buttons = 8 };
enum Scancode {
Xaxis, Yaxis, Zaxis,
Button0, Button1, Button2, Button3, Button4, Button5, Button6, Button7,
Limit,
};
static signed numberDecode(uint16_t scancode) {
for(unsigned i = 0; i < Count; i++) {
if(mouse(i).belongsTo(scancode)) return i;
}
return -1;
}
static signed axisDecode(uint16_t scancode) {
for(unsigned i = 0; i < Count; i++) {
if(mouse(i).isAxis(scancode)) return scancode - mouse(i).axis(0);
}
return -1;
}
static signed buttonDecode(uint16_t scancode) {
for(unsigned i = 0; i < Count; i++) {
if(mouse(i).isButton(scancode)) return scancode - mouse(i).button(0);
}
return -1;
}
static bool isAnyAxis(uint16_t scancode) {
for(unsigned i = 0; i < Count; i++) {
if(mouse(i).isAxis(scancode)) return true;
}
return false;
}
static bool isAnyButton(uint16_t scancode) {
for(unsigned i = 0; i < Count; i++) {
if(mouse(i).isButton(scancode)) return true;
}
return false;
}
static uint16_t decode(const char *name) {
string s(name);
if(!strbegin(name, "MS")) return 0;
ltrim(s, "MS");
unsigned id = strunsigned(s);
auto pos = strpos(s, "::");
if(!pos) return 0;
s = substr(s, pos() + 2);
for(unsigned i = 0; i < Limit; i++) {
if(s == MouseScancodeName[i]) return Base + Size * id + i;
}
return 0;
}
string encode(uint16_t code) const {
unsigned index = 0;
for(unsigned i = 0; i < Count; i++) {
if(code >= Base + Size * i && code < Base + Size * (i + 1)) {
index = code - (Base + Size * i);
break;
}
}
return string() << "MS" << ID << "::" << MouseScancodeName[index];
}
uint16_t operator[](Scancode code) const { return Base + ID * Size + code; }
uint16_t axis(unsigned id) const { return Base + Size * ID + Xaxis + id; }
uint16_t button(unsigned id) const { return Base + Size * ID + Button0 + id; }
bool isAxis(unsigned id) const { return id >= axis(0) && id <= axis(2); }
bool isButton(unsigned id) const { return id >= button(0) && id <= button(7); }
bool belongsTo(uint16_t scancode) const { return isAxis(scancode) || isButton(scancode); }
Mouse(unsigned ID_) : ID(ID_) {}
};
inline Mouse& mouse(unsigned id) {
static Mouse ms0(0), ms1(1), ms2(2), ms3(3), ms4(4), ms5(5), ms6(6), ms7(7);
switch(id) { default:
case 0: return ms0; case 1: return ms1; case 2: return ms2; case 3: return ms3;
case 4: return ms4; case 5: return ms5; case 6: return ms6; case 7: return ms7;
}
}
static const char JoypadScancodeName[][64] = {
"Hat0", "Hat1", "Hat2", "Hat3", "Hat4", "Hat5", "Hat6", "Hat7",
"Axis0", "Axis1", "Axis2", "Axis3", "Axis4", "Axis5", "Axis6", "Axis7",
"Axis8", "Axis9", "Axis10", "Axis11", "Axis12", "Axis13", "Axis14", "Axis15",
"Button0", "Button1", "Button2", "Button3", "Button4", "Button5", "Button6", "Button7",
"Button8", "Button9", "Button10", "Button11", "Button12", "Button13", "Button14", "Button15",
"Button16", "Button17", "Button18", "Button19", "Button20", "Button21", "Button22", "Button23",
"Button24", "Button25", "Button26", "Button27", "Button28", "Button29", "Button30", "Button31",
};
struct Joypad;
Joypad& joypad(unsigned = 0);
struct Joypad {
const unsigned ID;
enum { Base = Mouse::Base + Mouse::Size * Mouse::Count };
enum { Count = 8, Size = 64 };
enum { Hats = 8, Axes = 16, Buttons = 32 };
enum Scancode {
Hat0, Hat1, Hat2, Hat3, Hat4, Hat5, Hat6, Hat7,
Axis0, Axis1, Axis2, Axis3, Axis4, Axis5, Axis6, Axis7,
Axis8, Axis9, Axis10, Axis11, Axis12, Axis13, Axis14, Axis15,
Button0, Button1, Button2, Button3, Button4, Button5, Button6, Button7,
Button8, Button9, Button10, Button11, Button12, Button13, Button14, Button15,
Button16, Button17, Button18, Button19, Button20, Button21, Button22, Button23,
Button24, Button25, Button26, Button27, Button28, Button29, Button30, Button31,
Limit,
};
enum Hat { HatCenter = 0, HatUp = 1, HatRight = 2, HatDown = 4, HatLeft = 8 };
static signed numberDecode(uint16_t scancode) {
for(unsigned i = 0; i < Count; i++) {
if(joypad(i).belongsTo(scancode)) return i;
}
return -1;
}
static signed hatDecode(uint16_t scancode) {
for(unsigned i = 0; i < Count; i++) {
if(joypad(i).isHat(scancode)) return scancode - joypad(i).hat(0);
}
return -1;
}
static signed axisDecode(uint16_t scancode) {
for(unsigned i = 0; i < Count; i++) {
if(joypad(i).isAxis(scancode)) return scancode - joypad(i).axis(0);
}
return -1;
}
static signed buttonDecode(uint16_t scancode) {
for(unsigned i = 0; i < Count; i++) {
if(joypad(i).isButton(scancode)) return scancode - joypad(i).button(0);
}
return -1;
}
static bool isAnyHat(uint16_t scancode) {
for(unsigned i = 0; i < Count; i++) {
if(joypad(i).isHat(scancode)) return true;
}
return false;
}
static bool isAnyAxis(uint16_t scancode) {
for(unsigned i = 0; i < Count; i++) {
if(joypad(i).isAxis(scancode)) return true;
}
return false;
}
static bool isAnyButton(uint16_t scancode) {
for(unsigned i = 0; i < Count; i++) {
if(joypad(i).isButton(scancode)) return true;
}
return false;
}
static uint16_t decode(const char *name) {
string s(name);
if(!strbegin(name, "JP")) return 0;
ltrim(s, "JP");
unsigned id = strunsigned(s);
auto pos = strpos(s, "::");
if(!pos) return 0;
s = substr(s, pos() + 2);
for(unsigned i = 0; i < Limit; i++) {
if(s == JoypadScancodeName[i]) return Base + Size * id + i;
}
return 0;
}
string encode(uint16_t code) const {
unsigned index = 0;
for(unsigned i = 0; i < Count; i++) {
if(code >= Base + Size * i && code < Base + Size * (i + 1)) {
index = code - (Base + Size * i);
}
}
return string() << "JP" << ID << "::" << JoypadScancodeName[index];
}
uint16_t operator[](Scancode code) const { return Base + ID * Size + code; }
uint16_t hat(unsigned id) const { return Base + Size * ID + Hat0 + id; }
uint16_t axis(unsigned id) const { return Base + Size * ID + Axis0 + id; }
uint16_t button(unsigned id) const { return Base + Size * ID + Button0 + id; }
bool isHat(unsigned id) const { return id >= hat(0) && id <= hat(7); }
bool isAxis(unsigned id) const { return id >= axis(0) && id <= axis(15); }
bool isButton(unsigned id) const { return id >= button(0) && id <= button(31); }
bool belongsTo(uint16_t scancode) const { return isHat(scancode) || isAxis(scancode) || isButton(scancode); }
Joypad(unsigned ID_) : ID(ID_) {}
};
inline Joypad& joypad(unsigned id) {
static Joypad jp0(0), jp1(1), jp2(2), jp3(3), jp4(4), jp5(5), jp6(6), jp7(7);
switch(id) { default:
case 0: return jp0; case 1: return jp1; case 2: return jp2; case 3: return jp3;
case 4: return jp4; case 5: return jp5; case 6: return jp6; case 7: return jp7;
}
}
struct Scancode {
enum { None = 0, Limit = Joypad::Base + Joypad::Size * Joypad::Count };
static uint16_t decode(const char *name) {
uint16_t code;
code = Keyboard::decode(name);
if(code) return code;
code = Mouse::decode(name);
if(code) return code;
code = Joypad::decode(name);
if(code) return code;
return None;
}
static string encode(uint16_t code) {
for(unsigned i = 0; i < Keyboard::Count; i++) {
if(keyboard(i).belongsTo(code)) return keyboard(i).encode(code);
}
for(unsigned i = 0; i < Mouse::Count; i++) {
if(mouse(i).belongsTo(code)) return mouse(i).encode(code);
}
for(unsigned i = 0; i < Joypad::Count; i++) {
if(joypad(i).belongsTo(code)) return joypad(i).encode(code);
}
return "None";
}
};
}
#endif

81
snesfilter/nall/lzss.hpp Normal file
View File

@@ -0,0 +1,81 @@
#ifndef NALL_LZSS_HPP
#define NALL_LZSS_HPP
#include <nall/array.hpp>
#include <nall/new.hpp>
#include <nall/stdint.hpp>
namespace nall {
class lzss {
public:
static bool encode(uint8_t *&output, unsigned &outlength, const uint8_t *input, unsigned inlength) {
output = new(zeromemory) uint8_t[inlength * 9 / 8 + 9];
unsigned i = 0, o = 0;
while(i < inlength) {
unsigned flagoffset = o++;
uint8_t flag = 0x00;
for(unsigned b = 0; b < 8 && i < inlength; b++) {
unsigned longest = 0, pointer;
for(unsigned index = 1; index < 4096; index++) {
unsigned count = 0;
while(true) {
if(count >= 15 + 3) break; //verify pattern match is not longer than max length
if(i + count >= inlength) break; //verify pattern match does not read past end of input
if(i + count < index) break; //verify read is not before start of input
if(input[i + count] != input[i + count - index]) break; //verify pattern still matches
count++;
}
if(count > longest) {
longest = count;
pointer = index;
}
}
if(longest < 3) output[o++] = input[i++];
else {
flag |= 1 << b;
uint16_t x = ((longest - 3) << 12) + pointer;
output[o++] = x;
output[o++] = x >> 8;
i += longest;
}
}
output[flagoffset] = flag;
}
outlength = o;
return true;
}
static bool decode(uint8_t *&output, const uint8_t *input, unsigned length) {
output = new(zeromemory) uint8_t[length];
unsigned i = 0, o = 0;
while(o < length) {
uint8_t flag = input[i++];
for(unsigned b = 0; b < 8 && o < length; b++) {
if(!(flag & (1 << b))) output[o++] = input[i++];
else {
uint16_t offset = input[i++];
offset += input[i++] << 8;
uint16_t lookuplength = (offset >> 12) + 3;
offset &= 4095;
for(unsigned index = 0; index < lookuplength && o + index < length; index++) {
output[o + index] = output[o + index - offset];
}
o += lookuplength;
}
}
}
return true;
}
};
}
#endif

View File

@@ -0,0 +1,40 @@
#ifndef NALL_MODULO_HPP
#define NALL_MODULO_HPP
#include <nall/serializer.hpp>
namespace nall {
template<typename T, int size> class modulo_array {
public:
inline T operator[](int index) const {
return buffer[size + index];
}
inline T read(int index) const {
return buffer[size + index];
}
inline void write(unsigned index, const T value) {
buffer[index] =
buffer[index + size] =
buffer[index + size + size] = value;
}
void serialize(serializer &s) {
s.array(buffer, size * 3);
}
modulo_array() {
buffer = new T[size * 3]();
}
~modulo_array() {
delete[] buffer;
}
private:
T *buffer;
};
}
#endif

View File

@@ -0,0 +1,80 @@
#ifndef NALL_PLATFORM_HPP
#define NALL_PLATFORM_HPP
#include <nall/utf8.hpp>
//=========================
//standard platform headers
//=========================
#include <limits>
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#if defined(_WIN32)
#include <io.h>
#include <direct.h>
#include <shlobj.h>
#undef interface
#else
#include <unistd.h>
#include <pwd.h>
#include <sys/stat.h>
#endif
//==================
//warning supression
//==================
//Visual C++
#if defined(_MSC_VER)
//disable libc "deprecation" warnings
#pragma warning(disable:4996)
#endif
//================
//POSIX compliance
//================
#if defined(_MSC_VER)
#define PATH_MAX _MAX_PATH
#define va_copy(dest, src) ((dest) = (src))
#endif
#if defined(_WIN32)
#define getcwd _getcwd
#define ftruncate _chsize
#define putenv _putenv
#define mkdir(n, m) _wmkdir(nall::utf16_t(n))
#define rmdir _rmdir
#define vsnprintf _vsnprintf
#define usleep(n) Sleep(n / 1000)
#endif
//================
//inline expansion
//================
#if defined(__GNUC__)
#define noinline __attribute__((noinline))
#define inline inline
#define alwaysinline inline __attribute__((always_inline))
#elif defined(_MSC_VER)
#define noinline __declspec(noinline)
#define inline inline
#define alwaysinline inline __forceinline
#else
#define noinline
#define inline inline
#define alwaysinline inline
#endif
#endif

View File

@@ -0,0 +1,109 @@
#ifndef NALL_PRIORITYQUEUE_HPP
#define NALL_PRIORITYQUEUE_HPP
#include <limits>
#include <nall/function.hpp>
#include <nall/serializer.hpp>
#include <nall/utility.hpp>
namespace nall {
template<typename type_t> void priority_queue_nocallback(type_t) {}
//priority queue implementation using binary min-heap array;
//does not require normalize() function.
//O(1) find (tick)
//O(log n) insert (enqueue)
//O(log n) remove (dequeue)
template<typename type_t> class priority_queue {
public:
inline void tick(unsigned ticks) {
basecounter += ticks;
while(heapsize && gte(basecounter, heap[0].counter)) callback(dequeue());
}
//counter is relative to current time (eg enqueue(64, ...) fires in 64 ticks);
//counter cannot exceed std::numeric_limits<unsigned>::max() >> 1.
void enqueue(unsigned counter, type_t event) {
unsigned child = heapsize++;
counter += basecounter;
while(child) {
unsigned parent = (child - 1) >> 1;
if(gte(counter, heap[parent].counter)) break;
heap[child].counter = heap[parent].counter;
heap[child].event = heap[parent].event;
child = parent;
}
heap[child].counter = counter;
heap[child].event = event;
}
type_t dequeue() {
type_t event(heap[0].event);
unsigned parent = 0;
unsigned counter = heap[--heapsize].counter;
while(true) {
unsigned child = (parent << 1) + 1;
if(child >= heapsize) break;
if(child + 1 < heapsize && gte(heap[child].counter, heap[child + 1].counter)) child++;
if(gte(heap[child].counter, counter)) break;
heap[parent].counter = heap[child].counter;
heap[parent].event = heap[child].event;
parent = child;
}
heap[parent].counter = counter;
heap[parent].event = heap[heapsize].event;
return event;
}
void reset() {
basecounter = 0;
heapsize = 0;
}
void serialize(serializer &s) {
s.integer(basecounter);
s.integer(heapsize);
for(unsigned n = 0; n < heapcapacity; n++) {
s.integer(heap[n].counter);
s.integer(heap[n].event);
}
}
priority_queue(unsigned size, function<void (type_t)> callback_ = &priority_queue_nocallback<type_t>)
: callback(callback_) {
heap = new heap_t[size];
heapcapacity = size;
reset();
}
~priority_queue() {
delete[] heap;
}
priority_queue& operator=(const priority_queue&) = delete;
priority_queue(const priority_queue&) = delete;
private:
function<void (type_t)> callback;
unsigned basecounter;
unsigned heapsize;
unsigned heapcapacity;
struct heap_t {
unsigned counter;
type_t event;
} *heap;
//return true if x is greater than or equal to y
inline bool gte(unsigned x, unsigned y) {
return x - y < (std::numeric_limits<unsigned>::max() >> 1);
}
};
}
#endif

View File

@@ -0,0 +1,91 @@
#ifndef NALL_PROPERTY_HPP
#define NALL_PROPERTY_HPP
//nall::property implements ownership semantics into container classes
//example: property<owner>::readonly<type> implies that only owner has full
//access to type; and all other code has readonly access.
//
//this code relies on extended friend semantics from C++0x to work, as it
//declares a friend class via a template paramter. it also exploits a bug in
//G++ 4.x to work even in C++98 mode.
//
//if compiling elsewhere, simply remove the friend class and private semantics
//property can be used either of two ways:
//struct foo {
// property<foo>::readonly<bool> x;
// property<foo>::readwrite<int> y;
//};
//-or-
//struct foo : property<foo> {
// readonly<bool> x;
// readwrite<int> y;
//};
//return types are const T& (byref) instead fo T (byval) to avoid major speed
//penalties for objects with expensive copy constructors
//operator-> provides access to underlying object type:
//readonly<Object> foo;
//foo->bar();
//... will call Object::bar();
//operator='s reference is constant so as to avoid leaking a reference handle
//that could bypass access restrictions
//both constant and non-constant operators are provided, though it may be
//necessary to cast first, for instance:
//struct foo : property<foo> { readonly<int> bar; } object;
//int main() { int value = const_cast<const foo&>(object); }
//writeonly is useful for objects that have non-const reads, but const writes.
//however, to avoid leaking handles, the interface is very restricted. the only
//way to write is via operator=, which requires conversion via eg copy
//constructor. example:
//struct foo {
// foo(bool value) { ... }
//};
//writeonly<foo> bar;
//bar = true;
namespace nall {
template<typename C> struct property {
template<typename T> struct traits { typedef T type; };
template<typename T> struct readonly {
const T* operator->() const { return &value; }
const T& operator()() const { return value; }
operator const T&() const { return value; }
private:
T* operator->() { return &value; }
operator T&() { return value; }
const T& operator=(const T& value_) { return value = value_; }
T value;
friend class traits<C>::type;
};
template<typename T> struct writeonly {
void operator=(const T& value_) { value = value_; }
private:
const T* operator->() const { return &value; }
const T& operator()() const { return value; }
operator const T&() const { return value; }
T* operator->() { return &value; }
operator T&() { return value; }
T value;
friend class traits<C>::type;
};
template<typename T> struct readwrite {
const T* operator->() const { return &value; }
const T& operator()() const { return value; }
operator const T&() const { return value; }
T* operator->() { return &value; }
operator T&() { return value; }
const T& operator=(const T& value_) { return value = value_; }
T value;
};
};
}
#endif

View File

@@ -0,0 +1,55 @@
# requires nall/Makefile
# imports:
# $(qtlibs) -- list of Qt components to link against
# exports the following symbols:
# $(moc) -- meta-object compiler
# $(rcc) -- resource compiler
# $(qtinc) -- includes for compiling
# $(qtlib) -- libraries for linking
ifeq ($(moc),)
moc := moc
endif
ifeq ($(rcc),)
rcc := rcc
endif
ifeq ($(platform),x)
qtinc := `pkg-config --cflags $(qtlibs)`
qtlib := `pkg-config --libs $(qtlibs)`
else ifeq ($(platform),osx)
qtinc := $(foreach lib,$(qtlibs),-I/Library/Frameworks/$(lib).framework/Versions/4/Headers)
qtlib := -L/Library/Frameworks
qtlib += $(foreach lib,$(qtlibs),-framework $(lib))
qtlib += -framework Carbon
qtlib += -framework Cocoa
qtlib += -framework OpenGL
qtlib += -framework AppKit
qtlib += -framework ApplicationServices
else ifeq ($(platform),win)
ifeq ($(qtpath),)
# find Qt install directory from PATH environment variable
qtpath := $(foreach path,$(subst ;, ,$(PATH)),$(if $(wildcard $(path)/$(moc).exe),$(path)))
qtpath := $(strip $(qtpath))
qtpath := $(subst \,/,$(qtpath))
qtpath := $(patsubst %/bin,%,$(qtpath))
endif
qtinc := -I$(qtpath)/include
qtinc += $(foreach lib,$(qtlibs),-I$(qtpath)/include/$(lib))
qtlib := -L$(qtpath)/lib
qtlib += -L$(qtpath)/plugins/imageformats
qtlib += $(foreach lib,$(qtlibs),-l$(lib)4)
qtlib += -lmingw32 -lqtmain -lcomdlg32 -loleaut32 -limm32 -lwinmm
qtlib += -lwinspool -lmsimg32 -lole32 -ladvapi32 -lws2_32 -luuid -lgdi32
qtlib += $(foreach lib,$(qtlibs),-l$(lib)4)
# optional image-file support:
# qtlib += -lqjpeg -lqmng
endif

View File

@@ -0,0 +1,41 @@
#ifndef NALL_QT_CHECKACTION_HPP
#define NALL_QT_CHECKACTION_HPP
namespace nall {
class CheckAction : public QAction {
Q_OBJECT
public:
bool isChecked() const;
void setChecked(bool);
void toggleChecked();
CheckAction(const QString&, QObject*);
protected slots:
protected:
bool checked;
};
inline bool CheckAction::isChecked() const {
return checked;
}
inline void CheckAction::setChecked(bool checked_) {
checked = checked_;
if(checked) setIcon(QIcon(":/16x16/item-check-on.png"));
else setIcon(QIcon(":/16x16/item-check-off.png"));
}
inline void CheckAction::toggleChecked() {
setChecked(!isChecked());
}
inline CheckAction::CheckAction(const QString &text, QObject *parent) : QAction(text, parent) {
setChecked(false);
}
}
#endif

View File

@@ -0,0 +1,10 @@
#ifndef NALL_QT_CONCEPT_HPP
#define NALL_QT_CONCEPT_HPP
#include <nall/concept.hpp>
namespace nall {
template<typename T> struct has_count<QList<T>> { enum { value = true }; };
}
#endif

View File

@@ -0,0 +1,392 @@
#ifndef NALL_QT_FILEDIALOG_HPP
#define NALL_QT_FILEDIALOG_HPP
#include <nall/platform.hpp>
#include <nall/string.hpp>
#include <nall/qt/window.moc.hpp>
namespace nall {
class FileDialog;
class NewFolderDialog : public Window {
Q_OBJECT
public:
void show();
NewFolderDialog(FileDialog*);
protected slots:
void createFolderAction();
protected:
FileDialog *parent;
QVBoxLayout *layout;
QLineEdit *folderNameEdit;
QHBoxLayout *controlLayout;
QPushButton *okButton;
QPushButton *cancelButton;
};
class FileView : public QListView {
Q_OBJECT
protected:
void keyPressEvent(QKeyEvent*);
signals:
void changed(const QModelIndex&);
void browseUp();
protected slots:
void currentChanged(const QModelIndex&, const QModelIndex&);
};
class FileDialog : public Window {
Q_OBJECT
public:
void showLoad();
void showSave();
void showFolder();
void setPath(string path);
void setNameFilters(const string &filters);
FileDialog();
signals:
void changed(const string&);
void activated(const string&);
void accepted(const string&);
void rejected();
protected slots:
void fileViewChange(const QModelIndex&);
void fileViewActivate(const QModelIndex&);
void pathBoxChanged();
void filterBoxChanged();
void createNewFolder();
void browseUp();
void acceptAction();
void rejectAction();
protected:
NewFolderDialog *newFolderDialog;
QVBoxLayout *layout;
QHBoxLayout *navigationLayout;
QComboBox *pathBox;
QPushButton *newFolderButton;
QPushButton *upFolderButton;
QHBoxLayout *browseLayout;
QFileSystemModel *fileSystemModel;
FileView *fileView;
QGroupBox *previewFrame;
QLineEdit *fileNameEdit;
QHBoxLayout *controlLayout;
QComboBox *filterBox;
QPushButton *optionsButton;
QPushButton *acceptButton;
QPushButton *rejectButton;
bool lock;
void createFolderAction(const string &name);
void closeEvent(QCloseEvent*);
friend class NewFolderDialog;
};
inline void NewFolderDialog::show() {
folderNameEdit->setText("");
Window::show();
folderNameEdit->setFocus();
}
inline void NewFolderDialog::createFolderAction() {
string name = folderNameEdit->text().toUtf8().constData();
if(name == "") {
folderNameEdit->setFocus();
} else {
parent->createFolderAction(name);
close();
}
}
inline NewFolderDialog::NewFolderDialog(FileDialog *fileDialog) : parent(fileDialog) {
setMinimumWidth(240);
setWindowTitle("Create New Folder");
layout = new QVBoxLayout;
layout->setAlignment(Qt::AlignTop);
layout->setMargin(5);
layout->setSpacing(5);
setLayout(layout);
folderNameEdit = new QLineEdit;
layout->addWidget(folderNameEdit);
controlLayout = new QHBoxLayout;
controlLayout->setAlignment(Qt::AlignRight);
layout->addLayout(controlLayout);
okButton = new QPushButton("Ok");
controlLayout->addWidget(okButton);
cancelButton = new QPushButton("Cancel");
controlLayout->addWidget(cancelButton);
connect(folderNameEdit, SIGNAL(returnPressed()), this, SLOT(createFolderAction()));
connect(okButton, SIGNAL(released()), this, SLOT(createFolderAction()));
connect(cancelButton, SIGNAL(released()), this, SLOT(close()));
}
inline void FileView::currentChanged(const QModelIndex &current, const QModelIndex &previous) {
QAbstractItemView::currentChanged(current, previous);
emit changed(current);
}
inline void FileView::keyPressEvent(QKeyEvent *event) {
//enhance consistency: force OS X to act like Windows and Linux; enter = activate item
if(event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) {
emit activated(currentIndex());
return;
}
//simulate popular file manager behavior; backspace = go up one directory
if(event->key() == Qt::Key_Backspace) {
emit browseUp();
return;
}
//fallback: unrecognized keypresses get handled by the widget itself
QListView::keyPressEvent(event);
}
inline void FileDialog::showLoad() {
acceptButton->setText("Load");
fileNameEdit->hide();
filterBox->show();
show();
}
inline void FileDialog::showSave() {
acceptButton->setText("Save");
fileNameEdit->show();
filterBox->show();
show();
}
inline void FileDialog::showFolder() {
acceptButton->setText("Choose");
fileNameEdit->hide();
filterBox->hide();
setNameFilters("Folders ()");
show();
}
inline void FileDialog::fileViewChange(const QModelIndex &index) {
string path = fileSystemModel->filePath(index).toUtf8().constData();
if(path == fileSystemModel->rootPath().toUtf8().constData()) path = "";
fileNameEdit->setText(notdir(path));
emit changed(path);
}
inline void FileDialog::fileViewActivate(const QModelIndex &index) {
string path = fileSystemModel->filePath(index).toUtf8().constData();
if(fileSystemModel->isDir(index)) {
emit activated(path);
setPath(path);
} else {
emit activated(path);
close();
}
}
inline void FileDialog::pathBoxChanged() {
if(lock) return;
setPath(pathBox->currentText().toUtf8().constData());
}
inline void FileDialog::filterBoxChanged() {
if(lock) return;
string filters = filterBox->currentText().toUtf8().constData();
if(filters.length() == 0) {
fileSystemModel->setNameFilters(QStringList() << "*");
} else {
filters = substr(filters, strpos(filters, "(")());
ltrim(filters, "(");
rtrim(filters, ")");
lstring part;
part.split(" ", filters);
QStringList list;
for(unsigned i = 0; i < part.size(); i++) list << part[i];
fileSystemModel->setNameFilters(list);
}
}
inline void FileDialog::createNewFolder() {
newFolderDialog->show();
}
inline void FileDialog::browseUp() {
if(pathBox->count() > 1) pathBox->setCurrentIndex(1);
}
inline void FileDialog::setPath(string path) {
lock = true;
newFolderDialog->close();
if(QDir(path).exists()) {
newFolderButton->setEnabled(true);
} else {
newFolderButton->setEnabled(false);
path = "";
}
fileSystemModel->setRootPath(path);
fileView->setRootIndex(fileSystemModel->index(path));
fileView->setCurrentIndex(fileView->rootIndex());
fileView->setFocus();
pathBox->clear();
if(path.length() > 0) {
QDir directory(path);
while(true) {
pathBox->addItem(directory.absolutePath());
if(directory.isRoot()) break;
directory.cdUp();
}
}
pathBox->addItem("<root>");
fileNameEdit->setText("");
lock = false;
}
inline void FileDialog::setNameFilters(const string &filters) {
lock = true;
lstring list;
list.split("\n", filters);
filterBox->clear();
for(unsigned i = 0; i < list.size(); i++) {
filterBox->addItem(list[i]);
}
lock = false;
filterBoxChanged();
}
inline void FileDialog::acceptAction() {
string path = fileSystemModel->rootPath().toUtf8().constData();
path << "/" << notdir(fileNameEdit->text().toUtf8().constData());
rtrim(path, "/");
if(QDir(path).exists()) {
emit accepted(path);
setPath(path);
} else {
emit accepted(path);
close();
}
}
inline void FileDialog::rejectAction() {
emit rejected();
close();
}
inline void FileDialog::createFolderAction(const string &name) {
string path = fileSystemModel->rootPath().toUtf8().constData();
path << "/" << notdir(name);
mkdir(path, 0755);
}
inline void FileDialog::closeEvent(QCloseEvent *event) {
newFolderDialog->close();
Window::closeEvent(event);
}
inline FileDialog::FileDialog() {
newFolderDialog = new NewFolderDialog(this);
resize(640, 360);
layout = new QVBoxLayout;
layout->setMargin(5);
layout->setSpacing(5);
setLayout(layout);
navigationLayout = new QHBoxLayout;
layout->addLayout(navigationLayout);
pathBox = new QComboBox;
pathBox->setEditable(true);
pathBox->setMinimumContentsLength(16);
pathBox->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLength);
pathBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
navigationLayout->addWidget(pathBox);
newFolderButton = new QPushButton;
newFolderButton->setIconSize(QSize(16, 16));
newFolderButton->setIcon(QIcon(":/16x16/folder-new.png"));
navigationLayout->addWidget(newFolderButton);
upFolderButton = new QPushButton;
upFolderButton->setIconSize(QSize(16, 16));
upFolderButton->setIcon(QIcon(":/16x16/go-up.png"));
navigationLayout->addWidget(upFolderButton);
browseLayout = new QHBoxLayout;
layout->addLayout(browseLayout);
fileSystemModel = new QFileSystemModel;
fileSystemModel->setFilter(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot);
fileSystemModel->setNameFilterDisables(false);
fileView = new FileView;
fileView->setMinimumWidth(320);
fileView->setModel(fileSystemModel);
fileView->setIconSize(QSize(16, 16));
browseLayout->addWidget(fileView);
previewFrame = new QGroupBox;
previewFrame->hide();
browseLayout->addWidget(previewFrame);
fileNameEdit = new QLineEdit;
layout->addWidget(fileNameEdit);
controlLayout = new QHBoxLayout;
controlLayout->setAlignment(Qt::AlignRight);
layout->addLayout(controlLayout);
filterBox = new QComboBox;
filterBox->setMinimumContentsLength(16);
filterBox->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLength);
filterBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
controlLayout->addWidget(filterBox);
optionsButton = new QPushButton("Options");
optionsButton->hide();
controlLayout->addWidget(optionsButton);
acceptButton = new QPushButton("Ok");
controlLayout->addWidget(acceptButton);
rejectButton = new QPushButton("Cancel");
controlLayout->addWidget(rejectButton);
lock = false;
connect(pathBox, SIGNAL(currentIndexChanged(int)), this, SLOT(pathBoxChanged()));
connect(newFolderButton, SIGNAL(released()), this, SLOT(createNewFolder()));
connect(upFolderButton, SIGNAL(released()), this, SLOT(browseUp()));
connect(fileView, SIGNAL(changed(const QModelIndex&)), this, SLOT(fileViewChange(const QModelIndex&)));
connect(fileView, SIGNAL(activated(const QModelIndex&)), this, SLOT(fileViewActivate(const QModelIndex&)));
connect(fileView, SIGNAL(browseUp()), this, SLOT(browseUp()));
connect(fileNameEdit, SIGNAL(returnPressed()), this, SLOT(acceptAction()));
connect(filterBox, SIGNAL(currentIndexChanged(int)), this, SLOT(filterBoxChanged()));
connect(acceptButton, SIGNAL(released()), this, SLOT(acceptAction()));
connect(rejectButton, SIGNAL(released()), this, SLOT(rejectAction()));
}
}
#endif

View File

@@ -0,0 +1,173 @@
#ifndef NALL_QT_HEXEDITOR_HPP
#define NALL_QT_HEXEDITOR_HPP
#include <nall/function.hpp>
#include <nall/stdint.hpp>
#include <nall/string.hpp>
namespace nall {
class HexEditor : public QTextEdit {
Q_OBJECT
public:
function<uint8_t (unsigned)> reader;
function<void (unsigned, uint8_t)> writer;
void setColumns(unsigned columns);
void setRows(unsigned rows);
void setOffset(unsigned offset);
void setSize(unsigned size);
unsigned lineWidth() const;
void refresh();
HexEditor();
protected slots:
void scrolled();
protected:
QHBoxLayout *layout;
QScrollBar *scrollBar;
unsigned editorColumns;
unsigned editorRows;
unsigned editorOffset;
unsigned editorSize;
bool lock;
void keyPressEvent(QKeyEvent*);
};
inline void HexEditor::keyPressEvent(QKeyEvent *event) {
QTextCursor cursor = textCursor();
unsigned x = cursor.position() % lineWidth();
unsigned y = cursor.position() / lineWidth();
int hexCode = -1;
switch(event->key()) {
case Qt::Key_0: hexCode = 0; break;
case Qt::Key_1: hexCode = 1; break;
case Qt::Key_2: hexCode = 2; break;
case Qt::Key_3: hexCode = 3; break;
case Qt::Key_4: hexCode = 4; break;
case Qt::Key_5: hexCode = 5; break;
case Qt::Key_6: hexCode = 6; break;
case Qt::Key_7: hexCode = 7; break;
case Qt::Key_8: hexCode = 8; break;
case Qt::Key_9: hexCode = 9; break;
case Qt::Key_A: hexCode = 10; break;
case Qt::Key_B: hexCode = 11; break;
case Qt::Key_C: hexCode = 12; break;
case Qt::Key_D: hexCode = 13; break;
case Qt::Key_E: hexCode = 14; break;
case Qt::Key_F: hexCode = 15; break;
}
if(cursor.hasSelection() == false && hexCode != -1) {
bool cursorOffsetValid = (x >= 11 && ((x - 11) % 3) != 2);
if(cursorOffsetValid) {
bool nibble = (x - 11) % 3; //0 = top nibble, 1 = bottom nibble
unsigned cursorOffset = y * editorColumns + ((x - 11) / 3);
unsigned effectiveOffset = editorOffset + cursorOffset;
if(effectiveOffset >= editorSize) effectiveOffset %= editorSize;
uint8_t data = reader ? reader(effectiveOffset) : 0x00;
data &= (nibble == 0 ? 0x0f : 0xf0);
data |= (nibble == 0 ? (hexCode << 4) : (hexCode << 0));
if(writer) writer(effectiveOffset, data);
refresh();
cursor.setPosition(y * lineWidth() + x + 1); //advance cursor
setTextCursor(cursor);
}
} else {
//allow navigation keys to move cursor, but block text input
setTextInteractionFlags(Qt::TextSelectableByKeyboard | Qt::TextSelectableByMouse);
QTextEdit::keyPressEvent(event);
setTextInteractionFlags(Qt::TextEditorInteraction);
}
}
inline void HexEditor::setColumns(unsigned columns) {
editorColumns = columns;
}
inline void HexEditor::setRows(unsigned rows) {
editorRows = rows;
scrollBar->setPageStep(editorRows);
}
inline void HexEditor::setOffset(unsigned offset) {
lock = true;
editorOffset = offset;
scrollBar->setSliderPosition(editorOffset / editorColumns);
lock = false;
}
inline void HexEditor::setSize(unsigned size) {
editorSize = size;
bool indivisible = (editorSize % editorColumns) != 0; //add one for incomplete row
scrollBar->setRange(0, editorSize / editorColumns + indivisible - editorRows);
}
inline unsigned HexEditor::lineWidth() const {
return 11 + 3 * editorColumns;
}
inline void HexEditor::refresh() {
string output;
char temp[256];
unsigned offset = editorOffset;
for(unsigned y = 0; y < editorRows; y++) {
if(offset >= editorSize) break;
sprintf(temp, "%.4x:%.4x", (offset >> 16) & 0xffff, (offset >> 0) & 0xffff);
output << "<font color='#808080'>" << temp << "</font>&nbsp;&nbsp;";
for(unsigned x = 0; x < editorColumns; x++) {
if(offset >= editorSize) break;
sprintf(temp, "%.2x", reader ? reader(offset) : 0x00);
offset++;
output << "<font color='" << ((x & 1) ? "#000080" : "#0000ff") << "'>" << temp << "</font>";
if(x != (editorColumns - 1)) output << "&nbsp;";
}
if(y != (editorRows - 1)) output << "<br>";
}
setHtml(output);
}
inline void HexEditor::scrolled() {
if(lock) return;
unsigned offset = scrollBar->sliderPosition();
editorOffset = offset * editorColumns;
refresh();
}
inline HexEditor::HexEditor() {
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
layout = new QHBoxLayout;
layout->setAlignment(Qt::AlignRight);
layout->setMargin(0);
layout->setSpacing(0);
setLayout(layout);
scrollBar = new QScrollBar(Qt::Vertical);
scrollBar->setSingleStep(1);
layout->addWidget(scrollBar);
lock = false;
connect(scrollBar, SIGNAL(actionTriggered(int)), this, SLOT(scrolled()));
setColumns(16);
setRows(16);
setSize(0);
setOffset(0);
}
}
#endif

View File

@@ -0,0 +1,41 @@
#ifndef NALL_QT_RADIOACTION_HPP
#define NALL_QT_RADIOACTION_HPP
namespace nall {
class RadioAction : public QAction {
Q_OBJECT
public:
bool isChecked() const;
void setChecked(bool);
void toggleChecked();
RadioAction(const QString&, QObject*);
protected slots:
protected:
bool checked;
};
inline bool RadioAction::isChecked() const {
return checked;
}
inline void RadioAction::setChecked(bool checked_) {
checked = checked_;
if(checked) setIcon(QIcon(":/16x16/item-radio-on.png"));
else setIcon(QIcon(":/16x16/item-radio-off.png"));
}
inline void RadioAction::toggleChecked() {
setChecked(!isChecked());
}
inline RadioAction::RadioAction(const QString &text, QObject *parent) : QAction(text, parent) {
setChecked(false);
}
}
#endif

View File

@@ -0,0 +1,105 @@
#ifndef NALL_QT_WINDOW_HPP
#define NALL_QT_WINDOW_HPP
#include <nall/base64.hpp>
#include <nall/string.hpp>
namespace nall {
class Window : public QWidget {
Q_OBJECT
public:
void setGeometryString(string *geometryString);
void setCloseOnEscape(bool);
void show();
void hide();
void shrink();
Window();
protected slots:
protected:
string *geometryString;
bool closeOnEscape;
void keyReleaseEvent(QKeyEvent *event);
void closeEvent(QCloseEvent *event);
};
inline void Window::setGeometryString(string *geometryString_) {
geometryString = geometryString_;
if(geometryString && isVisible() == false) {
uint8_t *data;
unsigned length;
base64::decode(data, length, *geometryString);
QByteArray array((const char*)data, length);
delete[] data;
restoreGeometry(array);
}
}
inline void Window::setCloseOnEscape(bool value) {
closeOnEscape = value;
}
inline void Window::show() {
if(geometryString && isVisible() == false) {
uint8_t *data;
unsigned length;
base64::decode(data, length, *geometryString);
QByteArray array((const char*)data, length);
delete[] data;
restoreGeometry(array);
}
QWidget::show();
QApplication::processEvents();
activateWindow();
raise();
}
inline void Window::hide() {
if(geometryString && isVisible() == true) {
char *data;
QByteArray geometry = saveGeometry();
base64::encode(data, (const uint8_t*)geometry.data(), geometry.length());
*geometryString = data;
delete[] data;
}
QWidget::hide();
}
inline void Window::shrink() {
if(isFullScreen()) return;
for(unsigned i = 0; i < 2; i++) {
resize(0, 0);
usleep(2000);
QApplication::processEvents();
}
}
inline void Window::keyReleaseEvent(QKeyEvent *event) {
if(closeOnEscape && (event->key() == Qt::Key_Escape)) close();
QWidget::keyReleaseEvent(event);
}
inline void Window::closeEvent(QCloseEvent *event) {
if(geometryString) {
char *data;
QByteArray geometry = saveGeometry();
base64::encode(data, (const uint8_t*)geometry.data(), geometry.length());
*geometryString = data;
delete[] data;
}
QWidget::closeEvent(event);
}
inline Window::Window() {
geometryString = 0;
closeOnEscape = true;
}
}
#endif

View File

@@ -0,0 +1,20 @@
#ifndef NALL_RANDOM_HPP
#define NALL_RANDOM_HPP
namespace nall {
//pseudo-random number generator
inline unsigned prng() {
static unsigned n = 0;
return n = (n >> 1) ^ (((n & 1) - 1) & 0xedb88320);
}
struct random_cyclic {
unsigned seed;
inline unsigned operator()() {
return seed = (seed >> 1) ^ (((seed & 1) - 1) & 0xedb88320);
}
random_cyclic() : seed(0) {}
};
}
#endif

View File

@@ -0,0 +1,80 @@
#ifndef NALL_SERIAL_HPP
#define NALL_SERIAL_HPP
#include <sys/ioctl.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <nall/stdint.hpp>
namespace nall {
class serial {
public:
//-1 on error, otherwise return bytes read
int read(uint8_t *data, unsigned length) {
if(port_open == false) return -1;
return ::read(port, (void*)data, length);
}
//-1 on error, otherwise return bytes written
int write(const uint8_t *data, unsigned length) {
if(port_open == false) return -1;
return ::write(port, (void*)data, length);
}
bool open(const char *portname, unsigned rate) {
close();
port = ::open(portname, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
if(port == -1) return false;
if(ioctl(port, TIOCEXCL) == -1) { close(); return false; }
if(fcntl(port, F_SETFL, 0) == -1) { close(); return false; }
if(tcgetattr(port, &original_attr) == -1) { close(); return false; }
termios attr = original_attr;
cfmakeraw(&attr);
cfsetspeed(&attr, rate);
attr.c_lflag &=~ (ECHO | ECHONL | ISIG | ICANON | IEXTEN);
attr.c_iflag &=~ (BRKINT | PARMRK | INPCK | ISTRIP | INLCR | IGNCR | ICRNL | IXON | IXOFF | IXANY);
attr.c_iflag |= (IGNBRK | IGNPAR);
attr.c_oflag &=~ (OPOST);
attr.c_cflag &=~ (CSIZE | CSTOPB | PARENB);
attr.c_cflag |= (CS8 | CREAD | CLOCAL);
attr.c_cc[VTIME] = attr.c_cc[VMIN] = 0;
if(tcsetattr(port, TCSANOW, &attr) == -1) { close(); return false; }
return port_open = true;
}
void close() {
if(port != -1) {
tcdrain(port);
if(port_open == true) {
tcsetattr(port, TCSANOW, &original_attr);
port_open = false;
}
::close(port);
port = -1;
}
}
serial() {
port = -1;
port_open = false;
}
~serial() {
close();
}
private:
int port;
bool port_open;
termios original_attr;
};
}
#endif

View File

@@ -0,0 +1,145 @@
#ifndef NALL_SERIALIZER_HPP
#define NALL_SERIALIZER_HPP
#include <type_traits>
#include <utility>
#include <nall/stdint.hpp>
#include <nall/utility.hpp>
namespace nall {
//serializer: a class designed to save and restore the state of classes.
//
//benefits:
//- data() will be portable in size (it is not necessary to specify type sizes.)
//- data() will be portable in endianness (always stored internally as little-endian.)
//- one serialize function can both save and restore class states.
//
//caveats:
//- only plain-old-data can be stored. complex classes must provide serialize(serializer&);
//- floating-point usage is not portable across platforms
class serializer {
public:
enum mode_t { Load, Save, Size };
mode_t mode() const {
return imode;
}
const uint8_t* data() const {
return idata;
}
unsigned size() const {
return isize;
}
unsigned capacity() const {
return icapacity;
}
template<typename T> void floatingpoint(T &value) {
enum { size = sizeof(T) };
//this is rather dangerous, and not cross-platform safe;
//but there is no standardized way to export FP-values
uint8_t *p = (uint8_t*)&value;
if(imode == Save) {
for(unsigned n = 0; n < size; n++) idata[isize++] = p[n];
} else if(imode == Load) {
for(unsigned n = 0; n < size; n++) p[n] = idata[isize++];
} else {
isize += size;
}
}
template<typename T> void integer(T &value) {
enum { size = std::is_same<bool, T>::value ? 1 : sizeof(T) };
if(imode == Save) {
for(unsigned n = 0; n < size; n++) idata[isize++] = value >> (n << 3);
} else if(imode == Load) {
value = 0;
for(unsigned n = 0; n < size; n++) value |= idata[isize++] << (n << 3);
} else if(imode == Size) {
isize += size;
}
}
template<typename T> void array(T &array) {
enum { size = sizeof(T) / sizeof(typename std::remove_extent<T>::type) };
for(unsigned n = 0; n < size; n++) integer(array[n]);
}
template<typename T> void array(T array, unsigned size) {
for(unsigned n = 0; n < size; n++) integer(array[n]);
}
//copy
serializer& operator=(const serializer &s) {
if(idata) delete[] idata;
imode = s.imode;
idata = new uint8_t[s.icapacity];
isize = s.isize;
icapacity = s.icapacity;
memcpy(idata, s.idata, s.icapacity);
return *this;
}
serializer(const serializer &s) : idata(0) {
operator=(s);
}
//move
serializer& operator=(serializer &&s) {
if(idata) delete[] idata;
imode = s.imode;
idata = s.idata;
isize = s.isize;
icapacity = s.icapacity;
s.idata = 0;
return *this;
}
serializer(serializer &&s) {
operator=(std::move(s));
}
//construction
serializer() {
imode = Size;
idata = 0;
isize = 0;
}
serializer(unsigned capacity) {
imode = Save;
idata = new uint8_t[capacity]();
isize = 0;
icapacity = capacity;
}
serializer(const uint8_t *data, unsigned capacity) {
imode = Load;
idata = new uint8_t[capacity];
isize = 0;
icapacity = capacity;
memcpy(idata, data, capacity);
}
~serializer() {
if(idata) delete[] idata;
}
private:
mode_t imode;
uint8_t *idata;
unsigned isize;
unsigned icapacity;
};
};
#endif

143
snesfilter/nall/sha256.hpp Normal file
View File

@@ -0,0 +1,143 @@
#ifndef NALL_SHA256_HPP
#define NALL_SHA256_HPP
//author: vladitx
namespace nall {
#define PTR(t, a) ((t*)(a))
#define SWAP32(x) ((uint32_t)( \
(((uint32_t)(x) & 0x000000ff) << 24) | \
(((uint32_t)(x) & 0x0000ff00) << 8) | \
(((uint32_t)(x) & 0x00ff0000) >> 8) | \
(((uint32_t)(x) & 0xff000000) >> 24) \
))
#define ST32(a, d) *PTR(uint32_t, a) = (d)
#define ST32BE(a, d) ST32(a, SWAP32(d))
#define LD32(a) *PTR(uint32_t, a)
#define LD32BE(a) SWAP32(LD32(a))
#define LSL32(x, n) ((uint32_t)(x) << (n))
#define LSR32(x, n) ((uint32_t)(x) >> (n))
#define ROR32(x, n) (LSR32(x, n) | LSL32(x, 32 - (n)))
//first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19
static const uint32_t T_H[8] = {
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
};
//first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311
static const uint32_t T_K[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
};
struct sha256_ctx {
uint8_t in[64];
unsigned inlen;
uint32_t w[64];
uint32_t h[8];
uint64_t len;
};
void sha256_init(sha256_ctx *p) {
memset(p, 0, sizeof(sha256_ctx));
memcpy(p->h, T_H, sizeof(T_H));
}
static void sha256_block(sha256_ctx *p) {
unsigned i;
uint32_t s0, s1;
uint32_t a, b, c, d, e, f, g, h;
uint32_t t1, t2, maj, ch;
for(i = 0; i < 16; i++) p->w[i] = LD32BE(p->in + i * 4);
for(i = 16; i < 64; i++) {
s0 = ROR32(p->w[i - 15], 7) ^ ROR32(p->w[i - 15], 18) ^ LSR32(p->w[i - 15], 3);
s1 = ROR32(p->w[i - 2], 17) ^ ROR32(p->w[i - 2], 19) ^ LSR32(p->w[i - 2], 10);
p->w[i] = p->w[i - 16] + s0 + p->w[i - 7] + s1;
}
a = p->h[0]; b = p->h[1]; c = p->h[2]; d = p->h[3];
e = p->h[4]; f = p->h[5]; g = p->h[6]; h = p->h[7];
for(i = 0; i < 64; i++) {
s0 = ROR32(a, 2) ^ ROR32(a, 13) ^ ROR32(a, 22);
maj = (a & b) ^ (a & c) ^ (b & c);
t2 = s0 + maj;
s1 = ROR32(e, 6) ^ ROR32(e, 11) ^ ROR32(e, 25);
ch = (e & f) ^ (~e & g);
t1 = h + s1 + ch + T_K[i] + p->w[i];
h = g; g = f; f = e; e = d + t1;
d = c; c = b; b = a; a = t1 + t2;
}
p->h[0] += a; p->h[1] += b; p->h[2] += c; p->h[3] += d;
p->h[4] += e; p->h[5] += f; p->h[6] += g; p->h[7] += h;
//next block
p->inlen = 0;
}
void sha256_chunk(sha256_ctx *p, const uint8_t *s, unsigned len) {
unsigned l;
p->len += len;
while(len) {
l = 64 - p->inlen;
l = (len < l) ? len : l;
memcpy(p->in + p->inlen, s, l);
s += l;
p->inlen += l;
len -= l;
if(p->inlen == 64) sha256_block(p);
}
}
void sha256_final(sha256_ctx *p) {
uint64_t len;
p->in[p->inlen++] = 0x80;
if(p->inlen > 56) {
memset(p->in + p->inlen, 0, 64 - p->inlen);
sha256_block(p);
}
memset(p->in + p->inlen, 0, 56 - p->inlen);
len = p->len << 3;
ST32BE(p->in + 56, len >> 32);
ST32BE(p->in + 60, len);
sha256_block(p);
}
void sha256_hash(sha256_ctx *p, uint8_t *s) {
uint32_t *t = (uint32_t*)s;
for(unsigned i = 0; i < 8; i++) ST32BE(t++, p->h[i]);
}
#undef PTR
#undef SWAP32
#undef ST32
#undef ST32BE
#undef LD32
#undef LD32BE
#undef LSL32
#undef LSR32
#undef ROR32
}
#endif

View File

@@ -0,0 +1,864 @@
#ifndef NALL_SNES_INFO_HPP
#define NALL_SNES_INFO_HPP
namespace nall {
class snes_information {
public:
string xml_memory_map;
inline snes_information(const uint8_t *data, unsigned size);
private:
inline void read_header(const uint8_t *data, unsigned size);
inline unsigned find_header(const uint8_t *data, unsigned size);
inline unsigned score_header(const uint8_t *data, unsigned size, unsigned addr);
inline unsigned gameboy_ram_size(const uint8_t *data, unsigned size);
inline bool gameboy_has_rtc(const uint8_t *data, unsigned size);
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 Mode {
ModeNormal,
ModeBsxSlotted,
ModeBsx,
ModeSufamiTurbo,
ModeSuperGameBoy,
};
enum Type {
TypeNormal,
TypeBsxSlotted,
TypeBsxBios,
TypeBsx,
TypeSufamiTurboBios,
TypeSufamiTurbo,
TypeSuperGameBoy1Bios,
TypeSuperGameBoy2Bios,
TypeGameBoy,
TypeUnknown,
};
enum Region {
NTSC,
PAL,
};
enum MemoryMapper {
LoROM,
HiROM,
ExLoROM,
ExHiROM,
SuperFXROM,
SA1ROM,
SPC7110ROM,
BSCLoROM,
BSCHiROM,
BSXROM,
STROM,
};
enum DSP1MemoryMapper {
DSP1Unmapped,
DSP1LoROM1MB,
DSP1LoROM2MB,
DSP1HiROM,
};
bool loaded; //is a base cartridge inserted?
unsigned crc32; //crc32 of all cartridges (base+slot(s))
unsigned rom_size;
unsigned ram_size;
Mode mode;
Type type;
Region region;
MemoryMapper mapper;
DSP1MemoryMapper dsp1_mapper;
bool has_bsx_slot;
bool has_superfx;
bool has_sa1;
bool has_srtc;
bool has_sdd1;
bool has_spc7110;
bool has_spc7110rtc;
bool has_cx4;
bool has_dsp1;
bool has_dsp2;
bool has_dsp3;
bool has_dsp4;
bool has_obc1;
bool has_st010;
bool has_st011;
bool has_st018;
};
snes_information::snes_information(const uint8_t *data, unsigned size) {
read_header(data, size);
string xml = "<?xml version='1.0' encoding='UTF-8'?>\n";
if(type == TypeBsx) {
xml << "<cartridge/>";
xml_memory_map = xml;
return;
}
if(type == TypeSufamiTurbo) {
xml << "<cartridge/>";
xml_memory_map = xml;
return;
}
if(type == TypeGameBoy) {
xml << "<cartridge rtc='" << gameboy_has_rtc(data, size) << "'>\n";
if(gameboy_ram_size(data, size) > 0) {
xml << " <ram size='" << strhex(gameboy_ram_size(data, size)) << "'/>\n";
}
xml << "</cartridge>\n";
xml_memory_map = xml;
return;
}
xml << "<cartridge";
if(region == NTSC) {
xml << " region='NTSC'";
} else {
xml << " region='PAL'";
}
xml << ">\n";
if(type == TypeSuperGameBoy1Bios) {
xml << " <rom>\n";
xml << " <map mode='linear' address='00-7f:8000-ffff'/>\n";
xml << " <map mode='linear' address='80-ff:8000-ffff'/>\n";
xml << " </rom>\n";
xml << " <supergameboy revision='1'>\n";
xml << " <mmio>\n";
xml << " <map address='00-3f:6000-7fff'/>\n";
xml << " <map address='80-bf:6000-7fff'/>\n";
xml << " </mmio>\n";
xml << " </supergameboy>\n";
} else if(type == TypeSuperGameBoy2Bios) {
xml << " <rom>\n";
xml << " <map mode='linear' address='00-7f:8000-ffff'/>\n";
xml << " <map mode='linear' address='80-ff:8000-ffff'/>\n";
xml << " </rom>\n";
xml << " <supergameboy revision='2'>\n";
xml << " <mmio>\n";
xml << " <map address='00-3f:6000-7fff'/>\n";
xml << " <map address='80-bf:6000-7fff'/>\n";
xml << " </mmio>\n";
xml << " </supergameboy>\n";
} else if(has_spc7110) {
xml << " <rom>\n";
xml << " <map mode='shadow' address='00-0f:8000-ffff'/>\n";
xml << " <map mode='shadow' address='80-bf:8000-ffff'/>\n";
xml << " <map mode='linear' address='c0-cf:0000-ffff'/>\n";
xml << " </rom>\n";
xml << " <spc7110>\n";
xml << " <mcu>\n";
xml << " <map address='d0-ff:0000-ffff' offset='100000' size='" << strhex(size - 0x100000) << "'/>\n";
xml << " </mcu>\n";
xml << " <ram size='" << strhex(ram_size) << "'>\n";
xml << " <map mode='linear' address='00:6000-7fff'/>\n";
xml << " <map mode='linear' address='30:6000-7fff'/>\n";
xml << " </ram>\n";
xml << " <mmio>\n";
xml << " <map address='00-3f:4800-483f'/>\n";
xml << " <map address='80-bf:4800-483f'/>\n";
xml << " </mmio>\n";
if(has_spc7110rtc) {
xml << " <rtc>\n";
xml << " <map address='00-3f:4840-4842'/>\n";
xml << " <map address='80-bf:4840-4842'/>\n";
xml << " </rtc>\n";
}
xml << " <dcu>\n";
xml << " <map address='50:0000-ffff'/>\n";
xml << " </dcu>\n";
xml << " </spc7110>\n";
} else if(mapper == LoROM) {
xml << " <rom>\n";
xml << " <map mode='linear' address='00-7f:8000-ffff'/>\n";
xml << " <map mode='linear' address='80-ff:8000-ffff'/>\n";
xml << " </rom>\n";
if(ram_size > 0) {
xml << " <ram size='" << strhex(ram_size) << "'>\n";
xml << " <map mode='linear' address='20-3f:6000-7fff'/>\n";
xml << " <map mode='linear' address='a0-bf:6000-7fff'/>\n";
if((rom_size > 0x200000) || (ram_size > 32 * 1024)) {
xml << " <map mode='linear' address='70-7f:0000-7fff'/>\n";
xml << " <map mode='linear' address='f0-ff:0000-7fff'/>\n";
} else {
xml << " <map mode='linear' address='70-7f:0000-ffff'/>\n";
xml << " <map mode='linear' address='f0-ff:0000-ffff'/>\n";
}
xml << " </ram>\n";
}
} else if(mapper == HiROM) {
xml << " <rom>\n";
xml << " <map mode='shadow' address='00-3f:8000-ffff'/>\n";
xml << " <map mode='linear' address='40-7f:0000-ffff'/>\n";
xml << " <map mode='shadow' address='80-bf:8000-ffff'/>\n";
xml << " <map mode='linear' address='c0-ff:0000-ffff'/>\n";
xml << " </rom>\n";
if(ram_size > 0) {
xml << " <ram size='" << strhex(ram_size) << "'>\n";
xml << " <map mode='linear' address='20-3f:6000-7fff'/>\n";
xml << " <map mode='linear' address='a0-bf:6000-7fff'/>\n";
if((rom_size > 0x200000) || (ram_size > 32 * 1024)) {
xml << " <map mode='linear' address='70-7f:0000-7fff'/>\n";
} else {
xml << " <map mode='linear' address='70-7f:0000-ffff'/>\n";
}
xml << " </ram>\n";
}
} else if(mapper == ExLoROM) {
xml << " <rom>\n";
xml << " <map mode='linear' address='00-3f:8000-ffff'/>\n";
xml << " <map mode='linear' address='40-7f:0000-ffff'/>\n";
xml << " <map mode='linear' address='80-bf:8000-ffff'/>\n";
xml << " </rom>\n";
if(ram_size > 0) {
xml << " <ram size='" << strhex(ram_size) << "'>\n";
xml << " <map mode='linear' address='20-3f:6000-7fff'/>\n";
xml << " <map mode='linear' address='a0-bf:6000-7fff'/>\n";
xml << " <map mode='linear' address='70-7f:0000-7fff'/>\n";
xml << " </ram>\n";
}
} else if(mapper == ExHiROM) {
xml << " <rom>\n";
xml << " <map mode='shadow' address='00-3f:8000-ffff' offset='400000'/>\n";
xml << " <map mode='linear' address='40-7f:0000-ffff' offset='400000'/>\n";
xml << " <map mode='shadow' address='80-bf:8000-ffff' offset='000000'/>\n";
xml << " <map mode='linear' address='c0-ff:0000-ffff' offset='000000'/>\n";
xml << " </rom>\n";
if(ram_size > 0) {
xml << " <ram size='" << strhex(ram_size) << "'>\n";
xml << " <map mode='linear' address='20-3f:6000-7fff'/>\n";
xml << " <map mode='linear' address='a0-bf:6000-7fff'/>\n";
if((rom_size > 0x200000) || (ram_size > 32 * 1024)) {
xml << " <map mode='linear' address='70-7f:0000-7fff'/>\n";
} else {
xml << " <map mode='linear' address='70-7f:0000-ffff'/>\n";
}
xml << " </ram>\n";
}
} else if(mapper == SuperFXROM) {
xml << " <superfx revision='2'>\n";
xml << " <rom>\n";
xml << " <map mode='linear' address='00-3f:8000-ffff'/>\n";
xml << " <map mode='linear' address='40-5f:0000-ffff'/>\n";
xml << " <map mode='linear' address='80-bf:8000-ffff'/>\n";
xml << " <map mode='linear' address='c0-df:0000-ffff'/>\n";
xml << " </rom>\n";
xml << " <ram size='" << strhex(ram_size) << "'>\n";
xml << " <map mode='linear' address='00-3f:6000-7fff' size='2000'/>\n";
xml << " <map mode='linear' address='60-7f:0000-ffff'/>\n";
xml << " <map mode='linear' address='80-bf:6000-7fff' size='2000'/>\n";
xml << " <map mode='linear' address='e0-ff:0000-ffff'/>\n";
xml << " </ram>\n";
xml << " <mmio>\n";
xml << " <map address='00-3f:3000-32ff'/>\n";
xml << " <map address='80-bf:3000-32ff'/>\n";
xml << " </mmio>\n";
xml << " </superfx>\n";
} else if(mapper == SA1ROM) {
xml << " <sa1>\n";
xml << " <rom>\n";
xml << " <map mode='linear' address='00-3f:8000-ffff'/>\n";
xml << " <map mode='linear' address='80-bf:8000-ffff'/>\n";
xml << " <map mode='linear' address='c0-ff:0000-ffff'/>\n";
xml << " </rom>\n";
xml << " <iram size='800'>\n";
xml << " <map mode='linear' address='00-3f:3000-37ff'/>\n";
xml << " <map mode='linear' address='80-bf:3000-37ff'/>\n";
xml << " </iram>\n";
xml << " <bwram size='" << strhex(ram_size) << "'>\n";
xml << " <map mode='linear' address='00-3f:6000-7fff'/>\n";
xml << " <map mode='linear' address='40-4f:0000-ffff'/>\n";
xml << " <map mode='linear' address='80-bf:6000-7fff'/>\n";
xml << " </bwram>\n";
xml << " <mmio>\n";
xml << " <map address='00-3f:2200-23ff'/>\n";
xml << " <map address='80-bf:2200-23ff'/>\n";
xml << " </mmio>\n";
xml << " </sa1>\n";
} else if(mapper == BSCLoROM) {
xml << " <rom>\n";
xml << " <map mode='linear' address='00-1f:8000-ffff' offset='000000'/>\n";
xml << " <map mode='linear' address='20-3f:8000-ffff' offset='100000'/>\n";
xml << " <map mode='linear' address='80-9f:8000-ffff' offset='200000'/>\n";
xml << " <map mode='linear' address='a0-bf:8000-ffff' offset='100000'/>\n";
xml << " </rom>\n";
xml << " <ram size='" << strhex(ram_size) << "'>\n";
xml << " <map mode='linear' address='70-7f:0000-7fff'/>\n";
xml << " <map mode='linear' address='f0-ff:0000-7fff'/>\n";
xml << " </ram>\n";
xml << " <bsx>\n";
xml << " <slot>\n";
xml << " <map mode='linear' address='c0-ef:0000-ffff'/>\n";
xml << " </slot>\n";
xml << " </bsx>\n";
} else if(mapper == BSCHiROM) {
xml << " <rom>\n";
xml << " <map mode='shadow' address='00-1f:8000-ffff'/>\n";
xml << " <map mode='linear' address='40-5f:0000-ffff'/>\n";
xml << " <map mode='shadow' address='80-9f:8000-ffff'/>\n";
xml << " <map mode='linear' address='c0-df:0000-ffff'/>\n";
xml << " </rom>\n";
xml << " <ram size='" << strhex(ram_size) << "'>\n";
xml << " <map mode='linear' address='20-3f:6000-7fff'/>\n";
xml << " <map mode='linear' address='a0-bf:6000-7fff'/>\n";
xml << " </ram>\n";
xml << " <bsx>\n";
xml << " <slot>\n";
xml << " <map mode='shadow' address='20-3f:8000-ffff'/>\n";
xml << " <map mode='linear' address='60-7f:0000-ffff'/>\n";
xml << " <map mode='shadow' address='a0-bf:8000-ffff'/>\n";
xml << " <map mode='linear' address='e0-ff:0000-ffff'/>\n";
xml << " </slot>\n";
xml << " </bsx>\n";
} else if(mapper == BSXROM) {
xml << " <rom>\n";
xml << " <map mode='linear' address='00-3f:8000-ffff'/>\n";
xml << " <map mode='linear' address='80-bf:8000-ffff'/>\n";
xml << " </rom>\n";
xml << " <bsx>\n";
xml << " <mmio>\n";
xml << " <map address='00-3f:5000-5fff'/>\n";
xml << " <map address='80-bf:5000-5fff'/>\n";
xml << " </mmio>\n";
xml << " </bsx>\n";
} else if(mapper == STROM) {
xml << " <rom>\n";
xml << " <map mode='linear' address='00-1f:8000-ffff'/>\n";
xml << " <map mode='linear' address='80-9f:8000-ffff'/>\n";
xml << " </rom>\n";
xml << " <sufamiturbo>\n";
xml << " <slot id='A'>\n";
xml << " <rom>\n";
xml << " <map mode='linear' address='20-3f:8000-ffff'/>\n";
xml << " <map mode='linear' address='a0-bf:8000-ffff'/>\n";
xml << " </rom>\n";
xml << " <ram>\n";
xml << " <map mode='linear' address='60-63:8000-ffff'/>\n";
xml << " <map mode='linear' address='e0-e3:8000-ffff'/>\n";
xml << " </ram>\n";
xml << " </slot>\n";
xml << " <slot id='B'>\n";
xml << " <rom>\n";
xml << " <map mode='linear' address='40-5f:8000-ffff'/>\n";
xml << " <map mode='linear' address='c0-df:8000-ffff'/>\n";
xml << " </rom>\n";
xml << " <ram>\n";
xml << " <map mode='linear' address='70-73:8000-ffff'/>\n";
xml << " <map mode='linear' address='f0-f3:8000-ffff'/>\n";
xml << " </ram>\n";
xml << " </slot>\n";
xml << " </sufamiturbo>\n";
}
if(has_srtc) {
xml << " <srtc>\n";
xml << " <mmio>\n";
xml << " <map address='00-3f:2800-2801'/>\n";
xml << " <map address='80-bf:2800-2801'/>\n";
xml << " </mmio>\n";
xml << " </srtc>\n";
}
if(has_sdd1) {
xml << " <sdd1>\n";
xml << " <mcu>\n";
xml << " <map address='c0-ff:0000-ffff'/>\n";
xml << " </mcu>\n";
xml << " <mmio>\n";
xml << " <map address='00-3f:4800-4807'/>\n";
xml << " <map address='80-bf:4800-4807'/>\n";
xml << " </mmio>\n";
xml << " </sdd1>\n";
}
if(has_cx4) {
xml << " <cx4>\n";
xml << " <mmio>\n";
xml << " <map address='00-3f:6000-7fff'/>\n";
xml << " <map address='80-bf:6000-7fff'/>\n";
xml << " </mmio>\n";
xml << " </cx4>\n";
}
if(has_dsp1) {
xml << " <necdsp program='DSP-1B'>\n";
if(dsp1_mapper == DSP1LoROM1MB) {
xml << " <dr>\n";
xml << " <map address='20-3f:8000-bfff'/>\n";
xml << " <map address='a0-bf:8000-bfff'/>\n";
xml << " </dr>\n";
xml << " <sr>\n";
xml << " <map address='20-3f:c000-ffff'/>\n";
xml << " <map address='a0-bf:c000-ffff'/>\n";
xml << " </sr>\n";
} else if(dsp1_mapper == DSP1LoROM2MB) {
xml << " <dr>\n";
xml << " <map address='60-6f:0000-3fff'/>\n";
xml << " <map address='e0-ef:0000-3fff'/>\n";
xml << " </dr>\n";
xml << " <sr>\n";
xml << " <map address='60-6f:4000-7fff'/>\n";
xml << " <map address='e0-ef:4000-7fff'/>\n";
xml << " </sr>\n";
} else if(dsp1_mapper == DSP1HiROM) {
xml << " <dr>\n";
xml << " <map address='00-1f:6000-6fff'/>\n";
xml << " <map address='80-9f:6000-6fff'/>\n";
xml << " </dr>\n";
xml << " <sr>\n";
xml << " <map address='00-1f:7000-7fff'/>\n";
xml << " <map address='80-9f:7000-7fff'/>\n";
xml << " </sr>\n";
}
xml << " </necdsp>\n";
}
if(has_dsp2) {
xml << " <necdsp program='DSP-2'>\n";
xml << " <dr>\n";
xml << " <map address='20-3f:8000-bfff'/>\n";
xml << " <map address='a0-bf:8000-bfff'/>\n";
xml << " </dr>\n";
xml << " <sr>\n";
xml << " <map address='20-3f:c000-ffff'/>\n";
xml << " <map address='a0-bf:c000-ffff'/>\n";
xml << " </sr>\n";
xml << " </necdsp>\n";
}
if(has_dsp3) {
xml << " <necdsp program='DSP-3'>\n";
xml << " <dr>\n";
xml << " <map address='20-3f:8000-bfff'/>\n";
xml << " <map address='a0-bf:8000-bfff'/>\n";
xml << " </dr>\n";
xml << " <sr>\n";
xml << " <map address='20-3f:c000-ffff'/>\n";
xml << " <map address='a0-bf:c000-ffff'/>\n";
xml << " </sr>\n";
xml << " </necdsp>\n";
}
if(has_dsp4) {
xml << " <necdsp program='DSP-4'>\n";
xml << " <dr>\n";
xml << " <map address='30-3f:8000-bfff'/>\n";
xml << " <map address='b0-bf:8000-bfff'/>\n";
xml << " </dr>\n";
xml << " <sr>\n";
xml << " <map address='30-3f:c000-ffff'/>\n";
xml << " <map address='b0-bf:c000-ffff'/>\n";
xml << " </sr>\n";
xml << " </necdsp>\n";
}
if(has_obc1) {
xml << " <obc1>\n";
xml << " <mmio>\n";
xml << " <map address='00-3f:6000-7fff'/>\n";
xml << " <map address='80-bf:6000-7fff'/>\n";
xml << " </mmio>\n";
xml << " </obc1>\n";
}
if(has_st010) {
xml << " <setadsp program='ST-0010'>\n";
xml << " <mmio>\n";
xml << " <map address='68-6f:0000-0fff'/>\n";
xml << " <map address='e8-ef:0000-0fff'/>\n";
xml << " </mmio>\n";
xml << " </setadsp>\n";
}
if(has_st011) {
//ST-0011 addresses not verified; chip is unsupported
xml << " <setadsp program='ST-0011'>\n";
xml << " <mmio>\n";
xml << " <map address='68-6f:0000-0fff'/>\n";
xml << " <map address='e8-ef:0000-0fff'/>\n";
xml << " </mmio>\n";
xml << " </setadsp>\n";
}
if(has_st018) {
xml << " <setarisc program='ST-0018'>\n";
xml << " <mmio>\n";
xml << " <map address='00-3f:3800-38ff'/>\n";
xml << " <map address='80-bf:3800-38ff'/>\n";
xml << " </mmio>\n";
xml << " </setarisc>\n";
}
xml << "</cartridge>\n";
xml_memory_map = xml;
}
void snes_information::read_header(const uint8_t *data, unsigned size) {
type = TypeUnknown;
mapper = LoROM;
dsp1_mapper = DSP1Unmapped;
region = NTSC;
rom_size = size;
ram_size = 0;
has_bsx_slot = false;
has_superfx = false;
has_sa1 = false;
has_srtc = false;
has_sdd1 = false;
has_spc7110 = false;
has_spc7110rtc = false;
has_cx4 = false;
has_dsp1 = false;
has_dsp2 = false;
has_dsp3 = false;
has_dsp4 = false;
has_obc1 = false;
has_st010 = false;
has_st011 = false;
has_st018 = false;
//=====================
//detect Game Boy carts
//=====================
if(size >= 0x0140) {
if(data[0x0104] == 0xce && data[0x0105] == 0xed && data[0x0106] == 0x66 && data[0x0107] == 0x66
&& data[0x0108] == 0xcc && data[0x0109] == 0x0d && data[0x010a] == 0x00 && data[0x010b] == 0x0b) {
type = TypeGameBoy;
return;
}
}
const unsigned index = find_header(data, size);
const uint8_t mapperid = data[index + Mapper];
const uint8_t rom_type = data[index + RomType];
const uint8_t rom_size = data[index + RomSize];
const uint8_t company = data[index + Company];
const uint8_t regionid = data[index + CartRegion] & 0x7f;
ram_size = 1024 << (data[index + RamSize] & 7);
if(ram_size == 1024) ram_size = 0; //no RAM present
//0, 1, 13 = NTSC; 2 - 12 = PAL
region = (regionid <= 1 || regionid >= 13) ? NTSC : PAL;
//=======================
//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) {
type = TypeBsx;
mapper = BSXROM;
region = NTSC; //BS-X only released in Japan
return;
}
}
}
}
//=========================
//detect Sufami Turbo carts
//=========================
if(!memcmp(data, "BANDAI SFC-ADX", 14)) {
if(!memcmp(data + 16, "SFC-ADX BACKUP", 14)) {
type = TypeSufamiTurboBios;
} else {
type = TypeSufamiTurbo;
}
mapper = STROM;
region = NTSC; //Sufami Turbo only released in Japan
return; //RAM size handled outside this routine
}
//==========================
//detect Super Game Boy BIOS
//==========================
if(!memcmp(data + index, "Super GAMEBOY2", 14)) {
type = TypeSuperGameBoy2Bios;
return;
}
if(!memcmp(data + index, "Super GAMEBOY", 13)) {
type = TypeSuperGameBoy1Bios;
return;
}
//=====================
//detect standard carts
//=====================
//detect presence of BS-X flash cartridge connector (reads extended header information)
if(data[index - 14] == 'Z') {
if(data[index - 11] == 'J') {
uint8_t n13 = data[index - 13];
if((n13 >= 'A' && n13 <= 'Z') || (n13 >= '0' && n13 <= '9')) {
if(company == 0x33 || (data[index - 10] == 0x00 && data[index - 4] == 0x00)) {
has_bsx_slot = true;
}
}
}
}
if(has_bsx_slot) {
if(!memcmp(data + index, "Satellaview BS-X ", 21)) {
//BS-X base cart
type = TypeBsxBios;
mapper = BSXROM;
region = NTSC; //BS-X only released in Japan
return; //RAM size handled internally by load_cart_bsx() -> BSXCart class
} else {
type = TypeBsxSlotted;
mapper = (index == 0x7fc0 ? BSCLoROM : BSCHiROM);
region = NTSC; //BS-X slotted cartridges only released in Japan
}
} else {
//standard cart
type = TypeNormal;
if(index == 0x7fc0 && size >= 0x401000) {
mapper = ExLoROM;
} else if(index == 0x7fc0 && mapperid == 0x32) {
mapper = ExLoROM;
} else if(index == 0x7fc0) {
mapper = LoROM;
} else if(index == 0xffc0) {
mapper = HiROM;
} else { //index == 0x40ffc0
mapper = ExHiROM;
}
}
if(mapperid == 0x20 && (rom_type == 0x13 || rom_type == 0x14 || rom_type == 0x15 || rom_type == 0x1a)) {
has_superfx = true;
mapper = SuperFXROM;
ram_size = 1024 << (data[index - 3] & 7);
if(ram_size == 1024) ram_size = 0;
}
if(mapperid == 0x23 && (rom_type == 0x32 || rom_type == 0x34 || rom_type == 0x35)) {
has_sa1 = true;
mapper = SA1ROM;
}
if(mapperid == 0x35 && rom_type == 0x55) {
has_srtc = true;
}
if(mapperid == 0x32 && (rom_type == 0x43 || rom_type == 0x45)) {
has_sdd1 = true;
}
if(mapperid == 0x3a && (rom_type == 0xf5 || rom_type == 0xf9)) {
has_spc7110 = true;
has_spc7110rtc = (rom_type == 0xf9);
mapper = SPC7110ROM;
}
if(mapperid == 0x20 && rom_type == 0xf3) {
has_cx4 = true;
}
if((mapperid == 0x20 || mapperid == 0x21) && rom_type == 0x03) {
has_dsp1 = true;
}
if(mapperid == 0x30 && rom_type == 0x05 && company != 0xb2) {
has_dsp1 = true;
}
if(mapperid == 0x31 && (rom_type == 0x03 || rom_type == 0x05)) {
has_dsp1 = true;
}
if(has_dsp1 == true) {
if((mapperid & 0x2f) == 0x20 && size <= 0x100000) {
dsp1_mapper = DSP1LoROM1MB;
} else if((mapperid & 0x2f) == 0x20) {
dsp1_mapper = DSP1LoROM2MB;
} else if((mapperid & 0x2f) == 0x21) {
dsp1_mapper = DSP1HiROM;
}
}
if(mapperid == 0x20 && rom_type == 0x05) {
has_dsp2 = true;
}
if(mapperid == 0x30 && rom_type == 0x05 && company == 0xb2) {
has_dsp3 = true;
}
if(mapperid == 0x30 && rom_type == 0x03) {
has_dsp4 = true;
}
if(mapperid == 0x30 && rom_type == 0x25) {
has_obc1 = true;
}
if(mapperid == 0x30 && rom_type == 0xf6 && rom_size >= 10) {
has_st010 = true;
}
if(mapperid == 0x30 && rom_type == 0xf6 && rom_size < 10) {
has_st011 = true;
}
if(mapperid == 0x30 && rom_type == 0xf5) {
has_st018 = true;
}
}
unsigned snes_information::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) {
return 0x007fc0;
} else if(score_hi >= score_ex) {
return 0x00ffc0;
} else {
return 0x40ffc0;
}
}
unsigned snes_information::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_t resetvector = data[addr + ResetVector] | (data[addr + ResetVector + 1] << 8);
uint16_t checksum = data[addr + Checksum ] | (data[addr + Checksum + 1] << 8);
uint16_t complement = data[addr + Complement ] | (data[addr + Complement + 1] << 8);
uint8_t resetop = data[(addr & ~0x7fff) | (resetvector & 0x7fff)]; //first opcode executed upon reset
uint8_t 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;
}
unsigned snes_information::gameboy_ram_size(const uint8_t *data, unsigned size) {
if(size < 512) return 0;
switch(data[0x0149]) {
case 0x00: return 0 * 1024;
case 0x01: return 8 * 1024;
case 0x02: return 8 * 1024;
case 0x03: return 32 * 1024;
case 0x04: return 128 * 1024;
case 0x05: return 128 * 1024;
default: return 128 * 1024;
}
}
bool snes_information::gameboy_has_rtc(const uint8_t *data, unsigned size) {
if(size < 512) return false;
if(data[0x0147] == 0x0f ||data[0x0147] == 0x10) return true;
return false;
}
}
#endif

62
snesfilter/nall/sort.hpp Normal file
View File

@@ -0,0 +1,62 @@
#ifndef NALL_SORT_HPP
#define NALL_SORT_HPP
#include <nall/utility.hpp>
//class: merge sort
//average: O(n log n)
//worst: O(n log n)
//memory: O(n)
//stack: O(log n)
//stable?: yes
//notes:
//there are two primary reasons for choosing merge sort
//over the (usually) faster quick sort*:
//1: it is a stable sort.
//2: it lacks O(n^2) worst-case overhead.
//(* which is also O(n log n) in the average case.)
namespace nall {
template<typename T>
void sort(T list[], unsigned length) {
if(length <= 1) return; //nothing to sort
//use insertion sort to quickly sort smaller blocks
if(length < 64) {
for(unsigned i = 0; i < length; i++) {
unsigned min = i;
for(unsigned j = i + 1; j < length; j++) {
if(list[j] < list[min]) min = j;
}
if(min != i) swap(list[i], list[min]);
}
return;
}
//split list in half and recursively sort both
unsigned middle = length / 2;
sort(list, middle);
sort(list + middle, length - middle);
//left and right are sorted here; perform merge sort
T *buffer = new T[length];
unsigned offset = 0;
unsigned left = 0;
unsigned right = middle;
while(left < middle && right < length) {
if(list[left] < list[right]) {
buffer[offset++] = list[left++];
} else {
buffer[offset++] = list[right++];
}
}
while(left < middle) buffer[offset++] = list[left++];
while(right < length) buffer[offset++] = list[right++];
for(unsigned i = 0; i < length; i++) list[i] = buffer[i];
delete[] buffer;
}
}
#endif

View File

@@ -0,0 +1,20 @@
#ifndef NALL_STATIC_HPP
#define NALL_STATIC_HPP
namespace nall {
template<bool C, typename T, typename F> struct static_if { typedef T type; };
template<typename T, typename F> struct static_if<false, T, F> { typedef F type; };
template<typename C, typename T, typename F> struct mp_static_if { typedef typename static_if<C::type, T, F>::type type; };
template<bool A, bool B> struct static_and { enum { value = false }; };
template<> struct static_and<true, true> { enum { value = true }; };
template<typename A, typename B> struct mp_static_and { enum { value = static_and<A::value, B::value>::value }; };
template<bool A, bool B> struct static_or { enum { value = false }; };
template<> struct static_or<false, true> { enum { value = true }; };
template<> struct static_or<true, false> { enum { value = true }; };
template<> struct static_or<true, true> { enum { value = true }; };
template<typename A, typename B> struct mp_static_or { enum { value = static_or<A::value, B::value>::value }; };
}
#endif

View File

@@ -0,0 +1,44 @@
#ifndef NALL_STDINT_HPP
#define NALL_STDINT_HPP
#include <nall/static.hpp>
#if defined(_MSC_VER)
typedef signed char int8_t;
typedef signed short int16_t;
typedef signed int int32_t;
typedef signed long long int64_t;
typedef int64_t intmax_t;
#if defined(_WIN64)
typedef int64_t intptr_t;
#else
typedef int32_t intptr_t;
#endif
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef unsigned long long uint64_t;
typedef uint64_t uintmax_t;
#if defined(_WIN64)
typedef uint64_t uintptr_t;
#else
typedef uint32_t uintptr_t;
#endif
#else
#include <stdint.h>
#endif
namespace nall {
static_assert(sizeof(int8_t) == 1, "int8_t is not of the correct size" );
static_assert(sizeof(int16_t) == 2, "int16_t is not of the correct size");
static_assert(sizeof(int32_t) == 4, "int32_t is not of the correct size");
static_assert(sizeof(int64_t) == 8, "int64_t is not of the correct size");
static_assert(sizeof(uint8_t) == 1, "int8_t is not of the correct size" );
static_assert(sizeof(uint16_t) == 2, "int16_t is not of the correct size");
static_assert(sizeof(uint32_t) == 4, "int32_t is not of the correct size");
static_assert(sizeof(uint64_t) == 8, "int64_t is not of the correct size");
}
#endif

View File

@@ -0,0 +1,29 @@
#ifndef NALL_STRING_HPP
#define NALL_STRING_HPP
#include <initializer_list>
#include <nall/utility.hpp>
#include <nall/string/base.hpp>
#include <nall/string/core.hpp>
#include <nall/string/cast.hpp>
#include <nall/string/compare.hpp>
#include <nall/string/convert.hpp>
#include <nall/string/filename.hpp>
#include <nall/string/match.hpp>
#include <nall/string/math.hpp>
#include <nall/string/strl.hpp>
#include <nall/string/strpos.hpp>
#include <nall/string/trim.hpp>
#include <nall/string/replace.hpp>
#include <nall/string/split.hpp>
#include <nall/string/utility.hpp>
#include <nall/string/variadic.hpp>
#include <nall/string/xml.hpp>
namespace nall {
template<> struct has_length<string> { enum { value = true }; };
template<> struct has_size<lstring> { enum { value = true }; };
}
#endif

View File

@@ -0,0 +1,136 @@
#ifndef NALL_STRING_BASE_HPP
#define NALL_STRING_BASE_HPP
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <nall/concept.hpp>
#include <nall/stdint.hpp>
#include <nall/utf8.hpp>
#include <nall/vector.hpp>
namespace nall {
class string;
template<typename T> inline string to_string(T);
class string {
public:
inline void reserve(unsigned);
inline unsigned length() const;
inline string& assign(const char*);
inline string& append(const char*);
template<typename T> inline string& operator= (T value);
template<typename T> inline string& operator<<(T value);
inline operator const char*() const;
inline char* operator()();
inline char& operator[](int);
inline bool operator==(const char*) const;
inline bool operator!=(const char*) const;
inline bool operator< (const char*) const;
inline bool operator<=(const char*) const;
inline bool operator> (const char*) const;
inline bool operator>=(const char*) const;
inline string& operator=(const string&);
inline string& operator=(string&&);
inline string();
inline string(const char*);
inline string(const string&);
inline string(string&&);
inline ~string();
inline bool readfile(const char*);
inline string& replace (const char*, const char*);
inline string& qreplace(const char*, const char*);
protected:
char *data;
unsigned size;
#if defined(QSTRING_H)
public:
inline operator QString() const;
#endif
};
class lstring : public linear_vector<string> {
public:
template<typename T> inline lstring& operator<<(T value);
inline int find(const char*);
inline void split (const char*, const char*, unsigned = 0);
inline void qsplit(const char*, const char*, unsigned = 0);
lstring();
lstring(std::initializer_list<string>);
};
//compare.hpp
inline char chrlower(char c);
inline char chrupper(char c);
inline int stricmp(const char *dest, const char *src);
inline bool strbegin (const char *str, const char *key);
inline bool stribegin(const char *str, const char *key);
inline bool strend (const char *str, const char *key);
inline bool striend(const char *str, const char *key);
//convert.hpp
inline char* strlower(char *str);
inline char* strupper(char *str);
inline char* strtr(char *dest, const char *before, const char *after);
inline uintmax_t strhex (const char *str);
inline intmax_t strsigned (const char *str);
inline uintmax_t strunsigned(const char *str);
inline uintmax_t strbin (const char *str);
inline double strdouble (const char *str);
//match.hpp
inline bool match(const char *pattern, const char *str);
//math.hpp
inline bool strint (const char *str, int &result);
inline bool strmath(const char *str, int &result);
//strl.hpp
inline unsigned strlcpy(char *dest, const char *src, unsigned length);
inline unsigned strlcat(char *dest, const char *src, unsigned length);
//trim.hpp
inline char* ltrim(char *str, const char *key = " ");
inline char* rtrim(char *str, const char *key = " ");
inline char* trim (char *str, const char *key = " ");
inline char* ltrim_once(char *str, const char *key = " ");
inline char* rtrim_once(char *str, const char *key = " ");
inline char* trim_once (char *str, const char *key = " ");
//utility.hpp
inline unsigned strlcpy(string &dest, const char *src, unsigned length);
inline unsigned strlcat(string &dest, const char *src, unsigned length);
inline string substr(const char *src, unsigned start = 0, unsigned length = 0);
inline string& strlower(string &str);
inline string& strupper(string &str);
inline string& strtr(string &dest, const char *before, const char *after);
inline string& ltrim(string &str, const char *key = " ");
inline string& rtrim(string &str, const char *key = " ");
inline string& trim (string &str, const char *key = " ");
inline string& ltrim_once(string &str, const char *key = " ");
inline string& rtrim_once(string &str, const char *key = " ");
inline string& trim_once (string &str, const char *key = " ");
template<unsigned length = 0, char padding = '0'> inline string strhex(uintmax_t value);
template<unsigned length = 0, char padding = '0'> inline string strsigned(intmax_t value);
template<unsigned length = 0, char padding = '0'> inline string strunsigned(uintmax_t value);
template<unsigned length = 0, char padding = '0'> inline string strbin(uintmax_t value);
inline unsigned strdouble(char *str, double value);
inline string strdouble(double value);
//variadic.hpp
template<typename... Args> inline string sprint(Args... args);
template<typename... Args> inline void print(Args... args);
};
#endif

View File

@@ -0,0 +1,32 @@
#ifndef NALL_STRING_CAST_HPP
#define NALL_STRING_CAST_HPP
namespace nall {
//this is needed, as C++0x does not support explicit template specialization inside classes
template<> inline string to_string<bool> (bool v) { return v ? "true" : "false"; }
template<> inline string to_string<signed int> (signed int v) { return strsigned(v); }
template<> inline string to_string<unsigned int> (unsigned int v) { return strunsigned(v); }
template<> inline string to_string<double> (double v) { return strdouble(v); }
template<> inline string to_string<char*> (char *v) { return v; }
template<> inline string to_string<const char*> (const char *v) { return v; }
template<> inline string to_string<string> (string v) { return v; }
template<> inline string to_string<const string&>(const string &v) { return v; }
template<typename T> string& string::operator= (T value) { return assign(to_string<T>(value)); }
template<typename T> string& string::operator<<(T value) { return append(to_string<T>(value)); }
template<typename T> lstring& lstring::operator<<(T value) {
operator[](size()).assign(to_string<T>(value));
return *this;
}
#if defined(QSTRING_H)
template<> inline string to_string<QString>(QString v) { return v.toUtf8().constData(); }
template<> inline string to_string<const QString&>(const QString &v) { return v.toUtf8().constData(); }
string::operator QString() const { return QString::fromUtf8(*this); }
#endif
}
#endif

View File

@@ -0,0 +1,72 @@
#ifndef NALL_STRING_COMPARE_HPP
#define NALL_STRING_COMPARE_HPP
namespace nall {
char chrlower(char c) {
return (c >= 'A' && c <= 'Z') ? c + ('a' - 'A') : c;
}
char chrupper(char c) {
return (c >= 'a' && c <= 'z') ? c - ('a' - 'A') : c;
}
int stricmp(const char *dest, const char *src) {
while(*dest) {
if(chrlower(*dest) != chrlower(*src)) break;
dest++;
src++;
}
return (int)chrlower(*dest) - (int)chrlower(*src);
}
bool strbegin(const char *str, const char *key) {
int i, ssl = strlen(str), ksl = strlen(key);
if(ksl > ssl) return false;
return (!memcmp(str, key, ksl));
}
bool stribegin(const char *str, const char *key) {
int ssl = strlen(str), ksl = strlen(key);
if(ksl > ssl) return false;
for(int i = 0; i < ksl; i++) {
if(str[i] >= 'A' && str[i] <= 'Z') {
if(str[i] != key[i] && str[i]+0x20 != key[i])return false;
} else if(str[i] >= 'a' && str[i] <= 'z') {
if(str[i] != key[i] && str[i]-0x20 != key[i])return false;
} else {
if(str[i] != key[i])return false;
}
}
return true;
}
bool strend(const char *str, const char *key) {
int ssl = strlen(str), ksl = strlen(key);
if(ksl > ssl) return false;
return (!memcmp(str + ssl - ksl, key, ksl));
}
bool striend(const char *str, const char *key) {
int ssl = strlen(str), ksl = strlen(key);
if(ksl > ssl) return false;
for(int i = ssl - ksl, z = 0; i < ssl; i++, z++) {
if(str[i] >= 'A' && str[i] <= 'Z') {
if(str[i] != key[z] && str[i]+0x20 != key[z])return false;
} else if(str[i] >= 'a' && str[i] <= 'z') {
if(str[i] != key[z] && str[i]-0x20 != key[z])return false;
} else {
if(str[i] != key[z])return false;
}
}
return true;
}
}
#endif

View File

@@ -0,0 +1,153 @@
#ifndef NALL_STRING_CONVERT_HPP
#define NALL_STRING_CONVERT_HPP
namespace nall {
char* strlower(char *str) {
if(!str) return 0;
int i = 0;
while(str[i]) {
str[i] = chrlower(str[i]);
i++;
}
return str;
}
char* strupper(char *str) {
if(!str) return 0;
int i = 0;
while(str[i]) {
str[i] = chrupper(str[i]);
i++;
}
return str;
}
char* strtr(char *dest, const char *before, const char *after) {
if(!dest || !before || !after) return dest;
int sl = strlen(dest), bsl = strlen(before), asl = strlen(after);
if(bsl != asl || bsl == 0) return dest; //patterns must be the same length for 1:1 replace
for(unsigned i = 0; i < sl; i++) {
for(unsigned l = 0; l < bsl; l++) {
if(dest[i] == before[l]) {
dest[i] = after[l];
break;
}
}
}
return dest;
}
uintmax_t strhex(const char *str) {
if(!str) return 0;
uintmax_t result = 0;
//skip hex identifiers 0x and $, if present
if(*str == '0' && (*(str + 1) == 'X' || *(str + 1) == 'x')) str += 2;
else if(*str == '$') str++;
while(*str) {
uint8_t x = *str++;
if(x >= '0' && x <= '9') x -= '0';
else if(x >= 'A' && x <= 'F') x -= 'A' - 10;
else if(x >= 'a' && x <= 'f') x -= 'a' - 10;
else break; //stop at first invalid character
result = result * 16 + x;
}
return result;
}
intmax_t strsigned(const char *str) {
if(!str) return 0;
intmax_t result = 0;
bool negate = false;
//check for negation
if(*str == '-') {
negate = true;
str++;
}
while(*str) {
uint8_t x = *str++;
if(x >= '0' && x <= '9') x -= '0';
else break; //stop at first invalid character
result = result * 10 + x;
}
return !negate ? result : -result;
}
uintmax_t strunsigned(const char *str) {
if(!str) return 0;
uintmax_t result = 0;
while(*str) {
uint8_t x = *str++;
if(x >= '0' && x <= '9') x -= '0';
else break; //stop at first invalid character
result = result * 10 + x;
}
return result;
}
uintmax_t strbin(const char *str) {
if(!str) return 0;
uintmax_t result = 0;
//skip bin identifiers 0b and %, if present
if(*str == '0' && (*(str + 1) == 'B' || *(str + 1) == 'b')) str += 2;
else if(*str == '%') str++;
while(*str) {
uint8_t x = *str++;
if(x == '0' || x == '1') x -= '0';
else break; //stop at first invalid character
result = result * 2 + x;
}
return result;
}
double strdouble(const char *str) {
if(!str) return 0.0;
bool negate = false;
//check for negation
if(*str == '-') {
negate = true;
str++;
}
intmax_t result_integral = 0;
while(*str) {
uint8_t x = *str++;
if(x >= '0' && x <= '9') x -= '0';
else if(x == '.' || x == ',') break; //break loop and read fractional part
else return (double)result_integral; //invalid value, assume no fractional part
result_integral = result_integral * 10 + x;
}
intmax_t result_fractional = 0;
while(*str) {
uint8_t x = *str++;
if(x >= '0' && x <= '9') x -= '0';
else break; //stop at first invalid character
result_fractional = result_fractional * 10 + x;
}
//calculate fractional portion
double result = (double)result_fractional;
while((uintmax_t)result > 0) result /= 10.0;
result += (double)result_integral;
return !negate ? result : -result;
}
}
#endif

View File

@@ -0,0 +1,133 @@
#ifndef NALL_STRING_CORE_HPP
#define NALL_STRING_CORE_HPP
namespace nall {
void string::reserve(unsigned size_) {
if(size_ > size) {
size = size_;
data = (char*)realloc(data, size + 1);
data[size] = 0;
}
}
unsigned string::length() const {
return strlen(data);
}
string& string::assign(const char *s) {
unsigned length = strlen(s);
reserve(length);
strcpy(data, s);
return *this;
}
string& string::append(const char *s) {
unsigned length = strlen(data) + strlen(s);
reserve(length);
strcat(data, s);
return *this;
}
string::operator const char*() const {
return data;
}
char* string::operator()() {
return data;
}
char& string::operator[](int index) {
reserve(index);
return data[index];
}
bool string::operator==(const char *str) const { return strcmp(data, str) == 0; }
bool string::operator!=(const char *str) const { return strcmp(data, str) != 0; }
bool string::operator< (const char *str) const { return strcmp(data, str) < 0; }
bool string::operator<=(const char *str) const { return strcmp(data, str) <= 0; }
bool string::operator> (const char *str) const { return strcmp(data, str) > 0; }
bool string::operator>=(const char *str) const { return strcmp(data, str) >= 0; }
string& string::operator=(const string &value) {
assign(value);
return *this;
}
string& string::operator=(string &&source) {
if(data) free(data);
size = source.size;
data = source.data;
source.data = 0;
source.size = 0;
return *this;
}
string::string() {
size = 64;
data = (char*)malloc(size + 1);
*data = 0;
}
string::string(const char *value) {
size = strlen(value);
data = strdup(value);
}
string::string(const string &value) {
size = strlen(value);
data = strdup(value);
}
string::string(string &&source) {
size = source.size;
data = source.data;
source.data = 0;
}
string::~string() {
free(data);
}
bool string::readfile(const char *filename) {
assign("");
#if !defined(_WIN32)
FILE *fp = fopen(filename, "rb");
#else
FILE *fp = _wfopen(utf16_t(filename), L"rb");
#endif
if(!fp) return false;
fseek(fp, 0, SEEK_END);
unsigned size = ftell(fp);
rewind(fp);
char *fdata = new char[size + 1];
unsigned unused = fread(fdata, 1, size, fp);
fclose(fp);
fdata[size] = 0;
assign(fdata);
delete[] fdata;
return true;
}
int lstring::find(const char *key) {
for(unsigned i = 0; i < size(); i++) {
if(operator[](i) == key) return i;
}
return -1;
}
inline lstring::lstring() {
}
inline lstring::lstring(std::initializer_list<string> list) {
for(const string *s = list.begin(); s != list.end(); ++s) {
operator<<(*s);
}
}
}
#endif

View File

@@ -0,0 +1,61 @@
#ifndef NALL_FILENAME_HPP
#define NALL_FILENAME_HPP
namespace nall {
// "foo/bar.c" -> "foo/", "bar.c" -> "./"
inline string dir(char const *name) {
string result = name;
for(signed i = strlen(result); i >= 0; i--) {
if(result[i] == '/' || result[i] == '\\') {
result[i + 1] = 0;
break;
}
if(i == 0) result = "./";
}
return result;
}
// "foo/bar.c" -> "bar.c"
inline string notdir(char const *name) {
for(signed i = strlen(name); i >= 0; i--) {
if(name[i] == '/' || name[i] == '\\') {
name += i + 1;
break;
}
}
string result = name;
return result;
}
// "foo/bar.c" -> "foo/bar"
inline string basename(char const *name) {
string result = name;
for(signed i = strlen(result); i >= 0; i--) {
if(result[i] == '/' || result[i] == '\\') {
//file has no extension
break;
}
if(result[i] == '.') {
result[i] = 0;
break;
}
}
return result;
}
// "foo/bar.c" -> "c"
inline string extension(char const *name) {
for(signed i = strlen(name); i >= 0; i--) {
if(name[i] == '.') {
name += i + 1;
break;
}
}
string result = name;
return result;
}
}
#endif

View File

@@ -0,0 +1,76 @@
#ifndef NALL_STRING_MATCH_HPP
#define NALL_STRING_MATCH_HPP
namespace nall {
bool match(const char *p, const char *s) {
const char *p_ = 0, *s_ = 0;
for(;;) {
if(!*s) {
while(*p == '*') p++;
return !*p;
}
//wildcard match
if(*p == '*') {
p_ = p++, s_ = s;
continue;
}
//any match
if(*p == '?') {
p++, s++;
continue;
}
//ranged match
if(*p == '{') {
#define pattern(name_, rule_) \
if(strbegin(p, name_)) { \
if(rule_) { \
p += sizeof(name_) - 1, s++; \
continue; \
} \
goto failure; \
}
pattern("{alpha}", (*s >= 'A' && *s <= 'Z') || (*s >= 'a' && *s <= 'z'))
pattern("{alphanumeric}", (*s >= 'A' && *s <= 'Z') || (*s >= 'a' && *s <= 'z') || (*s >= '0' && *s <= '9'))
pattern("{binary}", (*s == '0' || *s == '1'))
pattern("{hex}", (*s >= '0' && *s <= '9') || (*s >= 'A' && *s <= 'F') || (*s >= 'a' && *s <= 'f'))
pattern("{lowercase}", (*s >= 'a' && *s <= 'z'))
pattern("{numeric}", (*s >= '0' && *s <= '9'))
pattern("{uppercase}", (*s >= 'A' && *s <= 'Z'))
pattern("{whitespace}", (*s == ' ' || *s == '\t'))
#undef pattern
goto failure;
}
//reserved character match
if(*p == '\\') {
p++;
//fallthrough
}
//literal match
if(*p == *s) {
p++, *s++;
continue;
}
//attempt wildcard rematch
failure:
if(p_) {
p = p_, s = s_ + 1;
continue;
}
return false;
}
}
}
#endif

View File

@@ -0,0 +1,164 @@
#ifndef NALL_STRING_MATH_HPP
#define NALL_STRING_MATH_HPP
namespace nall {
static int eval_integer(const char *&s) {
if(!*s) throw "unrecognized_integer";
int value = 0, x = *s, y = *(s + 1);
//hexadecimal
if(x == '0' && (y == 'X' || y == 'x')) {
s += 2;
while(true) {
if(*s >= '0' && *s <= '9') { value = value * 16 + (*s++ - '0'); continue; }
if(*s >= 'A' && *s <= 'F') { value = value * 16 + (*s++ - 'A' + 10); continue; }
if(*s >= 'a' && *s <= 'f') { value = value * 16 + (*s++ - 'a' + 10); continue; }
return value;
}
}
//binary
if(x == '0' && (y == 'B' || y == 'b')) {
s += 2;
while(true) {
if(*s == '0' || *s == '1') { value = value * 2 + (*s++ - '0'); continue; }
return value;
}
}
//octal (or decimal '0')
if(x == '0') {
s += 1;
while(true) {
if(*s >= '0' && *s <= '7') { value = value * 8 + (*s++ - '0'); continue; }
return value;
}
}
//decimal
if(x >= '0' && x <= '9') {
while(true) {
if(*s >= '0' && *s <= '9') { value = value * 10 + (*s++ - '0'); continue; }
return value;
}
}
//char
if(x == '\'' && y != '\'') {
s += 1;
while(true) {
value = value * 256 + *s++;
if(*s == '\'') { s += 1; return value; }
if(!*s) throw "mismatched_char";
}
}
throw "unrecognized_integer";
}
static int eval(const char *&s, int depth = 0) {
while(*s == ' ' || *s == '\t') s++; //trim whitespace
if(!*s) throw "unrecognized_token";
int value = 0, x = *s, y = *(s + 1);
if(*s == '(') {
value = eval(++s, 1);
if(*s++ != ')') throw "mismatched_group";
}
else if(x == '!') value = !eval(++s, 13);
else if(x == '~') value = ~eval(++s, 13);
else if(x == '+') value = +eval(++s, 13);
else if(x == '-') value = -eval(++s, 13);
else if((x >= '0' && x <= '9') || x == '\'') value = eval_integer(s);
else throw "unrecognized_token";
while(true) {
while(*s == ' ' || *s == '\t') s++; //trim whitespace
if(!*s) break;
x = *s, y = *(s + 1);
if(depth >= 13) break;
if(x == '*') { value *= eval(++s, 13); continue; }
if(x == '/') { value /= eval(++s, 13); continue; }
if(x == '%') { value %= eval(++s, 13); continue; }
if(depth >= 12) break;
if(x == '+') { value += eval(++s, 12); continue; }
if(x == '-') { value -= eval(++s, 12); continue; }
if(depth >= 11) break;
if(x == '<' && y == '<') { value <<= eval(++++s, 11); continue; }
if(x == '>' && y == '>') { value >>= eval(++++s, 11); continue; }
if(depth >= 10) break;
if(x == '<' && y == '=') { value = value <= eval(++++s, 10); continue; }
if(x == '>' && y == '=') { value = value >= eval(++++s, 10); continue; }
if(x == '<') { value = value < eval(++s, 10); continue; }
if(x == '>') { value = value > eval(++s, 10); continue; }
if(depth >= 9) break;
if(x == '=' && y == '=') { value = value == eval(++++s, 9); continue; }
if(x == '!' && y == '=') { value = value != eval(++++s, 9); continue; }
if(depth >= 8) break;
if(x == '&' && y != '&') { value = value & eval(++s, 8); continue; }
if(depth >= 7) break;
if(x == '^' && y != '^') { value = value ^ eval(++s, 7); continue; }
if(depth >= 6) break;
if(x == '|' && y != '|') { value = value | eval(++s, 6); continue; }
if(depth >= 5) break;
if(x == '&' && y == '&') { value = eval(++++s, 5) && value; continue; }
if(depth >= 4) break;
if(x == '^' && y == '^') { value = (!eval(++++s, 4) != !value); continue; }
if(depth >= 3) break;
if(x == '|' && y == '|') { value = eval(++++s, 3) || value; continue; }
if(x == '?') {
int lhs = eval(++s, 2);
if(*s != ':') throw "mismatched_ternary";
int rhs = eval(++s, 2);
value = value ? lhs : rhs;
continue;
}
if(depth >= 2) break;
if(depth > 0 && x == ')') break;
throw "unrecognized_token";
}
return value;
}
bool strint(const char *s, int &result) {
try {
result = eval_integer(s);
return true;
} catch(const char*) {
result = 0;
return false;
}
}
bool strmath(const char *s, int &result) {
try {
result = eval(s);
return true;
} catch(const char*) {
result = 0;
return false;
}
}
}
#endif

View File

@@ -0,0 +1,103 @@
#ifndef NALL_STRING_REPLACE_HPP
#define NALL_STRING_REPLACE_HPP
namespace nall {
string& string::replace(const char *key, const char *token) {
int i, z, ksl = strlen(key), tsl = strlen(token), ssl = length();
unsigned int replace_count = 0, size = ssl;
char *buffer;
if(ksl <= ssl) {
if(tsl > ksl) { //the new string may be longer than the old string...
for(i = 0; i <= ssl - ksl;) { //so let's find out how big of a string we'll need...
if(!memcmp(data + i, key, ksl)) {
replace_count++;
i += ksl;
} else i++;
}
size = ssl + ((tsl - ksl) * replace_count);
reserve(size);
}
buffer = new char[size + 1];
for(i = z = 0; i < ssl;) {
if(i <= ssl - ksl) {
if(!memcmp(data + i, key, ksl)) {
memcpy(buffer + z, token, tsl);
z += tsl;
i += ksl;
} else buffer[z++] = data[i++];
} else buffer[z++] = data[i++];
}
buffer[z] = 0;
assign(buffer);
delete[] buffer;
}
return *this;
}
string& string::qreplace(const char *key, const char *token) {
int i, l, z, ksl = strlen(key), tsl = strlen(token), ssl = length();
unsigned int replace_count = 0, size = ssl;
uint8_t x;
char *buffer;
if(ksl <= ssl) {
if(tsl > ksl) {
for(i = 0; i <= ssl - ksl;) {
x = data[i];
if(x == '\"' || x == '\'') {
l = i;
i++;
while(data[i++] != x) {
if(i == ssl) {
i = l;
break;
}
}
}
if(!memcmp(data + i, key, ksl)) {
replace_count++;
i += ksl;
} else i++;
}
size = ssl + ((tsl - ksl) * replace_count);
reserve(size);
}
buffer = new char[size + 1];
for(i = z = 0; i < ssl;) {
x = data[i];
if(x == '\"' || x == '\'') {
l = i++;
while(data[i] != x && i < ssl)i++;
if(i >= ssl)i = l;
else {
memcpy(buffer + z, data + l, i - l);
z += i - l;
}
}
if(i <= ssl - ksl) {
if(!memcmp(data + i, key, ksl)) {
memcpy(buffer + z, token, tsl);
z += tsl;
i += ksl;
replace_count++;
} else buffer[z++] = data[i++];
} else buffer[z++] = data[i++];
}
buffer[z] = 0;
assign(buffer);
delete[] buffer;
}
return *this;
}
};
#endif

View File

@@ -0,0 +1,56 @@
#ifndef NALL_STRING_SPLIT_HPP
#define NALL_STRING_SPLIT_HPP
namespace nall {
void lstring::split(const char *key, const char *src, unsigned limit) {
reset();
int ssl = strlen(src), ksl = strlen(key);
int lp = 0, split_count = 0;
for(int i = 0; i <= ssl - ksl;) {
if(!memcmp(src + i, key, ksl)) {
strlcpy(operator[](split_count++), src + lp, i - lp + 1);
i += ksl;
lp = i;
if(!--limit) break;
} else i++;
}
operator[](split_count++) = src + lp;
}
void lstring::qsplit(const char *key, const char *src, unsigned limit) {
reset();
int ssl = strlen(src), ksl = strlen(key);
int lp = 0, split_count = 0;
for(int i = 0; i <= ssl - ksl;) {
uint8_t x = src[i];
if(x == '\"' || x == '\'') {
int z = i++; //skip opening quote
while(i < ssl && src[i] != x) i++;
if(i >= ssl) i = z; //failed match, rewind i
else {
i++; //skip closing quote
continue; //restart in case next char is also a quote
}
}
if(!memcmp(src + i, key, ksl)) {
strlcpy(operator[](split_count++), src + lp, i - lp + 1);
i += ksl;
lp = i;
if(!--limit) break;
} else i++;
}
operator[](split_count++) = src + lp;
}
};
#endif

View File

@@ -0,0 +1,52 @@
#ifndef NALL_STRING_STRL_HPP
#define NALL_STRING_STRL_HPP
namespace nall {
//strlcpy, strlcat based on OpenBSD implementation by Todd C. Miller
//return = strlen(src)
unsigned strlcpy(char *dest, const char *src, unsigned length) {
char *d = dest;
const char *s = src;
unsigned n = length;
if(n) {
while(--n && (*d++ = *s++)); //copy as many bytes as possible, or until null terminator reached
}
if(!n) {
if(length) *d = 0;
while(*s++); //traverse rest of s, so that s - src == strlen(src)
}
return (s - src - 1); //return length of copied string, sans null terminator
}
//return = strlen(src) + min(length, strlen(dest))
unsigned strlcat(char *dest, const char *src, unsigned length) {
char *d = dest;
const char *s = src;
unsigned n = length;
while(n-- && *d) d++; //find end of dest
unsigned dlength = d - dest;
n = length - dlength; //subtract length of dest from maximum string length
if(!n) return dlength + strlen(s);
while(*s) {
if(n != 1) {
*d++ = *s;
n--;
}
s++;
}
*d = 0;
return dlength + (s - src); //return length of resulting string, sans null terminator
}
}
#endif

View File

@@ -0,0 +1,41 @@
#ifndef NALL_STRING_STRPOS_HPP
#define NALL_STRING_STRPOS_HPP
//usage example:
//if(auto pos = strpos(str, key)) print(pos(), "\n");
//prints position of key within str, only if it is found
namespace nall {
optional<unsigned> inline strpos(const char *str, const char *key) {
unsigned ssl = strlen(str), ksl = strlen(key);
if(ksl > ssl) return { false, 0 };
for(unsigned i = 0; i <= ssl - ksl; i++) {
if(!memcmp(str + i, key, ksl)) return { true, i };
}
return { false, 0 };
}
optional<unsigned> inline qstrpos(const char *str, const char *key) {
unsigned ssl = strlen(str), ksl = strlen(key);
if(ksl > ssl) return { false, 0 };
for(unsigned i = 0; i <= ssl - ksl;) {
uint8_t x = str[i];
if(x == '\"' || x == '\'') {
uint8_t z = i++;
while(str[i] != x && i < ssl) i++;
if(i >= ssl) i = z;
}
if(!memcmp(str + i, key, ksl)) return { true, i };
i++;
}
return { false, 0 };
}
}
#endif

View File

@@ -0,0 +1,54 @@
#ifndef NALL_STRING_TRIM_HPP
#define NALL_STRING_TRIM_HPP
namespace nall {
char* ltrim(char *str, const char *key) {
if(!key || !*key) return str;
while(strbegin(str, key)) {
char *dest = str, *src = str + strlen(key);
while(true) {
*dest = *src++;
if(!*dest) break;
dest++;
}
}
return str;
}
char* rtrim(char *str, const char *key) {
if(!key || !*key) return str;
while(strend(str, key)) str[strlen(str) - strlen(key)] = 0;
return str;
}
char* trim(char *str, const char *key) {
return ltrim(rtrim(str, key), key);
}
char* ltrim_once(char *str, const char *key) {
if(!key || !*key) return str;
if(strbegin(str, key)) {
char *dest = str, *src = str + strlen(key);
while(true) {
*dest = *src++;
if(!*dest) break;
dest++;
}
}
return str;
}
char* rtrim_once(char *str, const char *key) {
if(!key || !*key) return str;
if(strend(str, key)) str[strlen(str) - strlen(key)] = 0;
return str;
}
char* trim_once(char *str, const char *key) {
return ltrim_once(rtrim_once(str, key), key);
}
}
#endif

View File

@@ -0,0 +1,169 @@
#ifndef NALL_STRING_UTILITY_HPP
#define NALL_STRING_UTILITY_HPP
namespace nall {
unsigned strlcpy(string &dest, const char *src, unsigned length) {
dest.reserve(length);
return strlcpy(dest(), src, length);
}
unsigned strlcat(string &dest, const char *src, unsigned length) {
dest.reserve(length);
return strlcat(dest(), src, length);
}
string substr(const char *src, unsigned start, unsigned length) {
string dest;
if(length == 0) {
//copy entire string
dest = src + start;
} else {
//copy partial string
strlcpy(dest, src + start, length + 1);
}
return dest;
}
/* very simplistic wrappers to return string& instead of char* type */
string& strlower(string &str) { strlower(str()); return str; }
string& strupper(string &str) { strupper(str()); return str; }
string& strtr(string &dest, const char *before, const char *after) { strtr(dest(), before, after); return dest; }
string& ltrim(string &str, const char *key) { ltrim(str(), key); return str; }
string& rtrim(string &str, const char *key) { rtrim(str(), key); return str; }
string& trim (string &str, const char *key) { trim (str(), key); return str; }
string& ltrim_once(string &str, const char *key) { ltrim_once(str(), key); return str; }
string& rtrim_once(string &str, const char *key) { rtrim_once(str(), key); return str; }
string& trim_once (string &str, const char *key) { trim_once (str(), key); return str; }
/* arithmetic <> string */
template<unsigned length, char padding> string strhex(uintmax_t value) {
string output;
unsigned offset = 0;
//render string backwards, as we do not know its length yet
do {
unsigned n = value & 15;
output[offset++] = n < 10 ? '0' + n : 'a' + n - 10;
value >>= 4;
} while(value);
while(offset < length) output[offset++] = padding;
output[offset--] = 0;
//reverse the string in-place
for(unsigned i = 0; i < (offset + 1) >> 1; i++) {
char temp = output[i];
output[i] = output[offset - i];
output[offset - i] = temp;
}
return output;
}
template<unsigned length, char padding> string strsigned(intmax_t value) {
string output;
unsigned offset = 0;
bool negative = value < 0;
if(negative) value = abs(value);
do {
unsigned n = value % 10;
output[offset++] = '0' + n;
value /= 10;
} while(value);
while(offset < length) output[offset++] = padding;
if(negative) output[offset++] = '-';
output[offset--] = 0;
for(unsigned i = 0; i < (offset + 1) >> 1; i++) {
char temp = output[i];
output[i] = output[offset - i];
output[offset - i] = temp;
}
return output;
}
template<unsigned length, char padding> string strunsigned(uintmax_t value) {
string output;
unsigned offset = 0;
do {
unsigned n = value % 10;
output[offset++] = '0' + n;
value /= 10;
} while(value);
while(offset < length) output[offset++] = padding;
output[offset--] = 0;
for(unsigned i = 0; i < (offset + 1) >> 1; i++) {
char temp = output[i];
output[i] = output[offset - i];
output[offset - i] = temp;
}
return output;
}
template<unsigned length, char padding> string strbin(uintmax_t value) {
string output;
unsigned offset = 0;
do {
unsigned n = value & 1;
output[offset++] = '0' + n;
value >>= 1;
} while(value);
while(offset < length) output[offset++] = padding;
output[offset--] = 0;
for(unsigned i = 0; i < (offset + 1) >> 1; i++) {
char temp = output[i];
output[i] = output[offset - i];
output[offset - i] = temp;
}
return output;
}
//using sprintf is certainly not the most ideal method to convert
//a double to a string ... but attempting to parse a double by
//hand, digit-by-digit, results in subtle rounding errors.
unsigned strdouble(char *str, double value) {
char buffer[256];
sprintf(buffer, "%f", value);
//remove excess 0's in fraction (2.500000 -> 2.5)
for(char *p = buffer; *p; p++) {
if(*p == '.') {
char *p = buffer + strlen(buffer) - 1;
while(*p == '0') {
if(*(p - 1) != '.') *p = 0; //... but not for eg 1.0 -> 1.
p--;
}
break;
}
}
unsigned length = strlen(buffer);
if(str) strcpy(str, buffer);
return length + 1;
}
string strdouble(double value) {
string temp;
temp.reserve(strdouble(0, value));
strdouble(temp(), value);
return temp;
}
}
#endif

View File

@@ -0,0 +1,27 @@
#ifndef NALL_STRING_VARIADIC_HPP
#define NALL_STRING_VARIADIC_HPP
namespace nall {
static void isprint(string &output) {
}
template<typename T, typename... Args>
static void isprint(string &output, T value, Args... args) {
output << to_string<T>(value);
isprint(output, args...);
}
template<typename... Args> inline string sprint(Args... args) {
string output;
isprint(output, args...);
return output;
}
template<typename... Args> inline void print(Args... args) {
printf("%s", (const char*)sprint(args...));
}
}
#endif

View File

@@ -0,0 +1,265 @@
#ifndef NALL_STRING_XML_HPP
#define NALL_STRING_XML_HPP
//XML subset parser
//version 0.05
namespace nall {
struct xml_attribute {
string name;
string content;
virtual string parse() const;
};
struct xml_element : xml_attribute {
string parse() const;
linear_vector<xml_attribute> attribute;
linear_vector<xml_element> element;
protected:
void parse_doctype(const char *&data);
bool parse_head(string data);
bool parse_body(const char *&data);
friend xml_element xml_parse(const char *data);
};
inline string xml_attribute::parse() const {
string data;
unsigned offset = 0;
const char *source = content;
while(*source) {
if(*source == '&') {
if(strbegin(source, "&lt;")) { data[offset++] = '<'; source += 4; continue; }
if(strbegin(source, "&gt;")) { data[offset++] = '>'; source += 4; continue; }
if(strbegin(source, "&amp;")) { data[offset++] = '&'; source += 5; continue; }
if(strbegin(source, "&apos;")) { data[offset++] = '\''; source += 6; continue; }
if(strbegin(source, "&quot;")) { data[offset++] = '"'; source += 6; continue; }
}
//reject illegal characters
if(*source == '&') return "";
if(*source == '<') return "";
if(*source == '>') return "";
data[offset++] = *source++;
}
data[offset] = 0;
return data;
}
inline string xml_element::parse() const {
string data;
unsigned offset = 0;
const char *source = content;
while(*source) {
if(*source == '&') {
if(strbegin(source, "&lt;")) { data[offset++] = '<'; source += 4; continue; }
if(strbegin(source, "&gt;")) { data[offset++] = '>'; source += 4; continue; }
if(strbegin(source, "&amp;")) { data[offset++] = '&'; source += 5; continue; }
if(strbegin(source, "&apos;")) { data[offset++] = '\''; source += 6; continue; }
if(strbegin(source, "&quot;")) { data[offset++] = '"'; source += 6; continue; }
}
if(strbegin(source, "<!--")) {
if(auto pos = strpos(source, "-->")) {
source += pos() + 3;
continue;
} else {
return "";
}
}
if(strbegin(source, "<![CDATA[")) {
if(auto pos = strpos(source, "]]>")) {
string cdata = substr(source, 9, pos() - 9);
data << cdata;
offset += strlen(cdata);
source += offset + 3;
continue;
} else {
return "";
}
}
//reject illegal characters
if(*source == '&') return "";
if(*source == '<') return "";
if(*source == '>') return "";
data[offset++] = *source++;
}
data[offset] = 0;
return data;
}
inline void xml_element::parse_doctype(const char *&data) {
name = "!DOCTYPE";
const char *content_begin = data;
signed counter = 0;
while(*data) {
char value = *data++;
if(value == '<') counter++;
if(value == '>') counter--;
if(counter < 0) {
content = substr(content_begin, 0, data - content_begin - 1);
return;
}
}
throw "...";
}
inline bool xml_element::parse_head(string data) {
data.qreplace("\t", " ");
data.qreplace("\r", " ");
data.qreplace("\n", " ");
while(qstrpos(data, " ")) data.qreplace(" ", " ");
data.qreplace(" =", "=");
data.qreplace("= ", "=");
rtrim(data);
lstring part;
part.qsplit(" ", data);
name = part[0];
if(name == "") throw "...";
for(unsigned i = 1; i < part.size(); i++) {
lstring side;
side.qsplit("=", part[i]);
if(side.size() != 2) throw "...";
xml_attribute attr;
attr.name = side[0];
attr.content = side[1];
if(strbegin(attr.content, "\"") && strend(attr.content, "\"")) trim_once(attr.content, "\"");
else if(strbegin(attr.content, "'") && strend(attr.content, "'")) trim_once(attr.content, "'");
else throw "...";
attribute.append(attr);
}
}
inline bool xml_element::parse_body(const char *&data) {
while(true) {
if(!*data) return false;
if(*data++ != '<') continue;
if(*data == '/') return false;
if(strbegin(data, "!DOCTYPE") == true) {
parse_doctype(data);
return true;
}
if(strbegin(data, "!--")) {
if(auto offset = strpos(data, "-->")) {
data += offset() + 3;
continue;
} else {
throw "...";
}
}
if(strbegin(data, "![CDATA[")) {
if(auto offset = strpos(data, "]]>")) {
data += offset() + 3;
continue;
} else {
throw "...";
}
}
auto offset = strpos(data, ">");
if(!offset) throw "...";
string tag = substr(data, 0, offset());
data += offset() + 1;
const char *content_begin = data;
bool self_terminating = false;
if(strend(tag, "?") == true) {
self_terminating = true;
rtrim_once(tag, "?");
} else if(strend(tag, "/") == true) {
self_terminating = true;
rtrim_once(tag, "/");
}
parse_head(tag);
if(self_terminating) return true;
while(*data) {
unsigned index = element.size();
xml_element node;
if(node.parse_body(data) == false) {
if(*data == '/') {
signed length = data - content_begin - 1;
if(length > 0) content = substr(content_begin, 0, length);
data++;
auto offset = strpos(data, ">");
if(!offset) throw "...";
tag = substr(data, 0, offset());
data += offset() + 1;
tag.replace("\t", " ");
tag.replace("\r", " ");
tag.replace("\n", " ");
while(strpos(tag, " ")) tag.replace(" ", " ");
rtrim(tag);
if(name != tag) throw "...";
return true;
}
} else {
element.append(node);
}
}
}
}
//ensure there is only one root element
inline bool xml_validate(xml_element &document) {
unsigned root_counter = 0;
for(unsigned i = 0; i < document.element.size(); i++) {
string &name = document.element[i].name;
if(strbegin(name, "?")) continue;
if(strbegin(name, "!")) continue;
if(++root_counter > 1) return false;
}
return true;
}
inline xml_element xml_parse(const char *data) {
xml_element self;
try {
while(*data) {
xml_element node;
if(node.parse_body(data) == false) {
break;
} else {
self.element.append(node);
}
}
if(xml_validate(self) == false) throw "...";
return self;
} catch(const char*) {
xml_element empty;
return empty;
}
}
}
#endif

190
snesfilter/nall/ups.hpp Normal file
View File

@@ -0,0 +1,190 @@
#ifndef NALL_UPS_HPP
#define NALL_UPS_HPP
#include <stdio.h>
#include <nall/algorithm.hpp>
#include <nall/crc32.hpp>
#include <nall/file.hpp>
#include <nall/stdint.hpp>
namespace nall {
class ups {
public:
enum result {
ok,
patch_unreadable,
patch_unwritable,
patch_invalid,
input_invalid,
output_invalid,
patch_crc32_invalid,
input_crc32_invalid,
output_crc32_invalid,
};
ups::result create(const char *patch_fn, const uint8_t *x_data, unsigned x_size, const uint8_t *y_data, unsigned y_size) {
if(!fp.open(patch_fn, file::mode_write)) return patch_unwritable;
crc32 = ~0;
uint32_t x_crc32 = crc32_calculate(x_data, x_size);
uint32_t y_crc32 = crc32_calculate(y_data, y_size);
//header
write('U');
write('P');
write('S');
write('1');
encptr(x_size);
encptr(y_size);
//body
unsigned max_size = max(x_size, y_size);
unsigned relative = 0;
for(unsigned i = 0; i < max_size;) {
uint8_t x = i < x_size ? x_data[i] : 0x00;
uint8_t y = i < y_size ? y_data[i] : 0x00;
if(x == y) {
i++;
continue;
}
encptr(i++ - relative);
write(x ^ y);
while(true) {
if(i >= max_size) {
write(0x00);
break;
}
x = i < x_size ? x_data[i] : 0x00;
y = i < y_size ? y_data[i] : 0x00;
i++;
write(x ^ y);
if(x == y) break;
}
relative = i;
}
//footer
for(unsigned i = 0; i < 4; i++) write(x_crc32 >> (i << 3));
for(unsigned i = 0; i < 4; i++) write(y_crc32 >> (i << 3));
uint32_t p_crc32 = ~crc32;
for(unsigned i = 0; i < 4; i++) write(p_crc32 >> (i << 3));
fp.close();
return ok;
}
ups::result apply(const uint8_t *p_data, unsigned p_size, const uint8_t *x_data, unsigned x_size, uint8_t *&y_data, unsigned &y_size) {
if(p_size < 18) return patch_invalid;
p_buffer = p_data;
crc32 = ~0;
//header
if(read() != 'U') return patch_invalid;
if(read() != 'P') return patch_invalid;
if(read() != 'S') return patch_invalid;
if(read() != '1') return patch_invalid;
unsigned px_size = decptr();
unsigned py_size = decptr();
//mirror
if(x_size != px_size && x_size != py_size) return input_invalid;
y_size = (x_size == px_size) ? py_size : px_size;
y_data = new uint8_t[y_size]();
for(unsigned i = 0; i < x_size && i < y_size; i++) y_data[i] = x_data[i];
for(unsigned i = x_size; i < y_size; i++) y_data[i] = 0x00;
//body
unsigned relative = 0;
while(p_buffer < p_data + p_size - 12) {
relative += decptr();
while(true) {
uint8_t x = read();
if(x && relative < y_size) {
uint8_t y = relative < x_size ? x_data[relative] : 0x00;
y_data[relative] = x ^ y;
}
relative++;
if(!x) break;
}
}
//footer
unsigned px_crc32 = 0, py_crc32 = 0, pp_crc32 = 0;
for(unsigned i = 0; i < 4; i++) px_crc32 |= read() << (i << 3);
for(unsigned i = 0; i < 4; i++) py_crc32 |= read() << (i << 3);
uint32_t p_crc32 = ~crc32;
for(unsigned i = 0; i < 4; i++) pp_crc32 |= read() << (i << 3);
uint32_t x_crc32 = crc32_calculate(x_data, x_size);
uint32_t y_crc32 = crc32_calculate(y_data, y_size);
if(px_size != py_size) {
if(x_size == px_size && x_crc32 != px_crc32) return input_crc32_invalid;
if(x_size == py_size && x_crc32 != py_crc32) return input_crc32_invalid;
if(y_size == px_size && y_crc32 != px_crc32) return output_crc32_invalid;
if(y_size == py_size && y_crc32 != py_crc32) return output_crc32_invalid;
} else {
if(x_crc32 != px_crc32 && x_crc32 != py_crc32) return input_crc32_invalid;
if(y_crc32 != px_crc32 && y_crc32 != py_crc32) return output_crc32_invalid;
if(x_crc32 == y_crc32 && px_crc32 != py_crc32) return output_crc32_invalid;
if(x_crc32 != y_crc32 && px_crc32 == py_crc32) return output_crc32_invalid;
}
if(p_crc32 != pp_crc32) return patch_crc32_invalid;
return ok;
}
private:
file fp;
uint32_t crc32;
const uint8_t *p_buffer;
uint8_t read() {
uint8_t n = *p_buffer++;
crc32 = crc32_adjust(crc32, n);
return n;
}
void write(uint8_t n) {
fp.write(n);
crc32 = crc32_adjust(crc32, n);
}
void encptr(uint64_t offset) {
while(true) {
uint64_t x = offset & 0x7f;
offset >>= 7;
if(offset == 0) {
write(0x80 | x);
break;
}
write(x);
offset--;
}
}
uint64_t decptr() {
uint64_t offset = 0, shift = 1;
while(true) {
uint8_t x = read();
offset += (x & 0x7f) * shift;
if(x & 0x80) break;
shift <<= 7;
offset += shift;
}
return offset;
}
};
}
#endif

72
snesfilter/nall/utf8.hpp Normal file
View File

@@ -0,0 +1,72 @@
#ifndef NALL_UTF8_HPP
#define NALL_UTF8_HPP
//UTF-8 <> UTF-16 conversion
//used only for Win32; Linux, etc use UTF-8 internally
#if defined(_WIN32)
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0501
#undef NOMINMAX
#define NOMINMAX
#include <windows.h>
#undef interface
namespace nall {
//UTF-8 to UTF-16
class utf16_t {
public:
operator wchar_t*() {
return buffer;
}
operator const wchar_t*() const {
return buffer;
}
utf16_t(const char *s = "") {
if(!s) s = "";
unsigned length = MultiByteToWideChar(CP_UTF8, 0, s, -1, 0, 0);
buffer = new wchar_t[length + 1]();
MultiByteToWideChar(CP_UTF8, 0, s, -1, buffer, length);
}
~utf16_t() {
delete[] buffer;
}
private:
wchar_t *buffer;
};
//UTF-16 to UTF-8
class utf8_t {
public:
operator char*() {
return buffer;
}
operator const char*() const {
return buffer;
}
utf8_t(const wchar_t *s = L"") {
if(!s) s = L"";
unsigned length = WideCharToMultiByte(CP_UTF8, 0, s, -1, 0, 0, (const char*)0, (BOOL*)0);
buffer = new char[length + 1]();
WideCharToMultiByte(CP_UTF8, 0, s, -1, buffer, length, (const char*)0, (BOOL*)0);
}
~utf8_t() {
delete[] buffer;
}
private:
char *buffer;
};
}
#endif //if defined(_WIN32)
#endif

View File

@@ -0,0 +1,39 @@
#ifndef NALL_UTILITY_HPP
#define NALL_UTILITY_HPP
#include <type_traits>
#include <utility>
namespace nall {
template<bool C, typename T = bool> struct enable_if { typedef T type; };
template<typename T> struct enable_if<false, T> {};
template<typename C, typename T = bool> struct mp_enable_if : enable_if<C::value, T> {};
template<typename T> inline void swap(T &x, T &y) {
T temp(std::move(x));
x = std::move(y);
y = std::move(temp);
}
template<typename T> struct base_from_member {
T value;
base_from_member(T value_) : value(value_) {}
};
template<typename T> class optional {
bool valid;
T value;
public:
inline operator bool() const { return valid; }
inline const T& operator()() const { if(!valid) throw; return value; }
inline optional(bool valid, const T &value) : valid(valid), value(value) {}
};
template<typename T> inline T* allocate(unsigned size, const T &value) {
T *array = new T[size];
for(unsigned i = 0; i < size; i++) array[i] = value;
return array;
}
}
#endif

View File

@@ -0,0 +1,92 @@
#ifndef NALL_VARINT_HPP
#define NALL_VARINT_HPP
#include <nall/bit.hpp>
#include <nall/static.hpp>
#include <nall/traits.hpp>
namespace nall {
template<unsigned bits> class uint_t {
private:
enum { bytes = (bits + 7) >> 3 }; //minimum number of bytes needed to store value
typedef typename static_if<
sizeof(int) >= bytes,
unsigned int,
typename static_if<
sizeof(long) >= bytes,
unsigned long,
typename static_if<
sizeof(long long) >= bytes,
unsigned long long,
void
>::type
>::type
>::type T;
static_assert<!is_void<T>::value> uint_assert;
T data;
public:
inline operator T() const { return data; }
inline T operator ++(int) { T r = data; data = uclip<bits>(data + 1); return r; }
inline T operator --(int) { T r = data; data = uclip<bits>(data - 1); return r; }
inline T operator ++() { return data = uclip<bits>(data + 1); }
inline T operator --() { return data = uclip<bits>(data - 1); }
inline T operator =(const T i) { return data = uclip<bits>(i); }
inline T operator |=(const T i) { return data = uclip<bits>(data | i); }
inline T operator ^=(const T i) { return data = uclip<bits>(data ^ i); }
inline T operator &=(const T i) { return data = uclip<bits>(data & i); }
inline T operator<<=(const T i) { return data = uclip<bits>(data << i); }
inline T operator>>=(const T i) { return data = uclip<bits>(data >> i); }
inline T operator +=(const T i) { return data = uclip<bits>(data + i); }
inline T operator -=(const T i) { return data = uclip<bits>(data - i); }
inline T operator *=(const T i) { return data = uclip<bits>(data * i); }
inline T operator /=(const T i) { return data = uclip<bits>(data / i); }
inline T operator %=(const T i) { return data = uclip<bits>(data % i); }
inline uint_t() : data(0) {}
inline uint_t(const T i) : data(uclip<bits>(i)) {}
};
template<unsigned bits> class int_t {
private:
enum { bytes = (bits + 7) >> 3 }; //minimum number of bytes needed to store value
typedef typename static_if<
sizeof(int) >= bytes,
signed int,
typename static_if<
sizeof(long) >= bytes,
signed long,
typename static_if<
sizeof(long long) >= bytes,
signed long long,
void
>::type
>::type
>::type T;
static_assert<!is_void<T>::value> int_assert;
T data;
public:
inline operator T() const { return data; }
inline T operator ++(int) { T r = data; data = sclip<bits>(data + 1); return r; }
inline T operator --(int) { T r = data; data = sclip<bits>(data - 1); return r; }
inline T operator ++() { return data = sclip<bits>(data + 1); }
inline T operator --() { return data = sclip<bits>(data - 1); }
inline T operator =(const T i) { return data = sclip<bits>(i); }
inline T operator |=(const T i) { return data = sclip<bits>(data | i); }
inline T operator ^=(const T i) { return data = sclip<bits>(data ^ i); }
inline T operator &=(const T i) { return data = sclip<bits>(data & i); }
inline T operator<<=(const T i) { return data = sclip<bits>(data << i); }
inline T operator>>=(const T i) { return data = sclip<bits>(data >> i); }
inline T operator +=(const T i) { return data = sclip<bits>(data + i); }
inline T operator -=(const T i) { return data = sclip<bits>(data - i); }
inline T operator *=(const T i) { return data = sclip<bits>(data * i); }
inline T operator /=(const T i) { return data = sclip<bits>(data / i); }
inline T operator %=(const T i) { return data = sclip<bits>(data % i); }
inline int_t() : data(0) {}
inline int_t(const T i) : data(sclip<bits>(i)) {}
};
}
#endif

281
snesfilter/nall/vector.hpp Normal file
View File

@@ -0,0 +1,281 @@
#ifndef NALL_VECTOR_HPP
#define NALL_VECTOR_HPP
#include <initializer_list>
#include <new>
#include <type_traits>
#include <utility>
#include <nall/algorithm.hpp>
#include <nall/bit.hpp>
#include <nall/concept.hpp>
#include <nall/foreach.hpp>
#include <nall/utility.hpp>
namespace nall {
//linear_vector
//memory: O(capacity * 2)
//
//linear_vector uses placement new + manual destructor calls to create a
//contiguous block of memory for all objects. accessing individual elements
//is fast, though resizing the array incurs significant overhead.
//reserve() overhead is reduced from quadratic time to amortized constant time
//by resizing twice as much as requested.
//
//if objects hold memory address references to themselves (introspection), a
//valid copy constructor will be needed to keep pointers valid.
template<typename T> class linear_vector {
protected:
T *pool;
unsigned poolsize, objectsize;
public:
unsigned size() const { return objectsize; }
unsigned capacity() const { return poolsize; }
void reset() {
if(pool) {
for(unsigned i = 0; i < objectsize; i++) pool[i].~T();
free(pool);
}
pool = 0;
poolsize = 0;
objectsize = 0;
}
void reserve(unsigned newsize) {
newsize = bit::round(newsize); //round to nearest power of two (for amortized growth)
T *poolcopy = (T*)malloc(newsize * sizeof(T));
for(unsigned i = 0; i < min(objectsize, newsize); i++) new(poolcopy + i) T(pool[i]);
for(unsigned i = 0; i < objectsize; i++) pool[i].~T();
free(pool);
pool = poolcopy;
poolsize = newsize;
objectsize = min(objectsize, newsize);
}
void resize(unsigned newsize) {
if(newsize > poolsize) reserve(newsize);
if(newsize < objectsize) {
//vector is shrinking; destroy excess objects
for(unsigned i = newsize; i < objectsize; i++) pool[i].~T();
} else if(newsize > objectsize) {
//vector is expanding; allocate new objects
for(unsigned i = objectsize; i < newsize; i++) new(pool + i) T;
}
objectsize = newsize;
}
void append(const T data) {
if(objectsize + 1 > poolsize) reserve(objectsize + 1);
new(pool + objectsize++) T(data);
}
template<typename U> void insert(unsigned index, const U list) {
linear_vector<T> merged;
for(unsigned i = 0; i < index; i++) merged.append(pool[i]);
foreach(item, list) merged.append(item);
for(unsigned i = index; i < objectsize; i++) merged.append(pool[i]);
operator=(merged);
}
void insert(unsigned index, const T item) {
insert(index, linear_vector<T>{ item });
}
void remove(unsigned index, unsigned count = 1) {
for(unsigned i = index; count + i < objectsize; i++) {
pool[i] = pool[count + i];
}
if(count + index >= objectsize) resize(index); //every element >= index was removed
else resize(objectsize - count);
}
inline T& operator[](unsigned index) {
if(index >= objectsize) resize(index + 1);
return pool[index];
}
inline const T& operator[](unsigned index) const {
if(index >= objectsize) throw "vector[] out of bounds";
return pool[index];
}
//copy
inline linear_vector<T>& operator=(const linear_vector<T> &source) {
reset();
reserve(source.capacity());
resize(source.size());
for(unsigned i = 0; i < source.size(); i++) operator[](i) = source.operator[](i);
return *this;
}
linear_vector(const linear_vector<T> &source) : pool(0), poolsize(0), objectsize(0) {
operator=(source);
}
//move
inline linear_vector<T>& operator=(linear_vector<T> &&source) {
reset();
pool = source.pool;
poolsize = source.poolsize;
objectsize = source.objectsize;
source.pool = 0;
source.reset();
return *this;
}
linear_vector(linear_vector<T> &&source) : pool(0), poolsize(0), objectsize(0) {
operator=(std::move(source));
}
//construction
linear_vector() : pool(0), poolsize(0), objectsize(0) {
}
linear_vector(std::initializer_list<T> list) : pool(0), poolsize(0), objectsize(0) {
for(const T *p = list.begin(); p != list.end(); ++p) append(*p);
}
~linear_vector() {
reset();
}
};
//pointer_vector
//memory: O(1)
//
//pointer_vector keeps an array of pointers to each vector object. this adds
//significant overhead to individual accesses, but allows for optimal memory
//utilization.
//
//by guaranteeing that the base memory address of each objects never changes,
//this avoids the need for an object to have a valid copy constructor.
template<typename T> class pointer_vector {
protected:
T **pool;
unsigned poolsize, objectsize;
public:
unsigned size() const { return objectsize; }
unsigned capacity() const { return poolsize; }
void reset() {
if(pool) {
for(unsigned i = 0; i < objectsize; i++) { if(pool[i]) delete pool[i]; }
free(pool);
}
pool = 0;
poolsize = 0;
objectsize = 0;
}
void reserve(unsigned newsize) {
newsize = bit::round(newsize); //round to nearest power of two (for amortized growth)
for(unsigned i = newsize; i < objectsize; i++) {
if(pool[i]) { delete pool[i]; pool[i] = 0; }
}
pool = (T**)realloc(pool, newsize * sizeof(T*));
for(unsigned i = poolsize; i < newsize; i++) pool[i] = 0;
poolsize = newsize;
objectsize = min(objectsize, newsize);
}
void resize(unsigned newsize) {
if(newsize > poolsize) reserve(newsize);
for(unsigned i = newsize; i < objectsize; i++) {
if(pool[i]) { delete pool[i]; pool[i] = 0; }
}
objectsize = newsize;
}
void append(const T data) {
if(objectsize + 1 > poolsize) reserve(objectsize + 1);
pool[objectsize++] = new T(data);
}
template<typename U> void insert(unsigned index, const U list) {
pointer_vector<T> merged;
for(unsigned i = 0; i < index; i++) merged.append(*pool[i]);
foreach(item, list) merged.append(item);
for(unsigned i = index; i < objectsize; i++) merged.append(*pool[i]);
operator=(merged);
}
void insert(unsigned index, const T item) {
insert(index, pointer_vector<T>{ item });
}
void remove(unsigned index, unsigned count = 1) {
for(unsigned i = index; count + i < objectsize; i++) {
*pool[i] = *pool[count + i];
}
if(count + index >= objectsize) resize(index); //every element >= index was removed
else resize(objectsize - count);
}
inline T& operator[](unsigned index) {
if(index >= objectsize) resize(index + 1);
if(!pool[index]) pool[index] = new T;
return *pool[index];
}
inline const T& operator[](unsigned index) const {
if(index >= objectsize || !pool[index]) throw "vector[] out of bounds";
return *pool[index];
}
//copy
inline pointer_vector<T>& operator=(const pointer_vector<T> &source) {
reset();
reserve(source.capacity());
resize(source.size());
for(unsigned i = 0; i < source.size(); i++) operator[](i) = source.operator[](i);
return *this;
}
pointer_vector(const pointer_vector<T> &source) : pool(0), poolsize(0), objectsize(0) {
operator=(source);
}
//move
inline pointer_vector<T>& operator=(pointer_vector<T> &&source) {
reset();
pool = source.pool;
poolsize = source.poolsize;
objectsize = source.objectsize;
source.pool = 0;
source.reset();
return *this;
}
pointer_vector(pointer_vector<T> &&source) : pool(0), poolsize(0), objectsize(0) {
operator=(std::move(source));
}
//construction
pointer_vector() : pool(0), poolsize(0), objectsize(0) {
}
pointer_vector(std::initializer_list<T> list) : pool(0), poolsize(0), objectsize(0) {
for(const T *p = list.begin(); p != list.end(); ++p) append(*p);
}
~pointer_vector() {
reset();
}
};
template<typename T> struct has_size<linear_vector<T>> { enum { value = true }; };
template<typename T> struct has_size<pointer_vector<T>> { enum { value = true }; };
}
#endif

380
snesfilter/ntsc/ntsc.cpp Normal file
View File

@@ -0,0 +1,380 @@
#include "snes_ntsc/snes_ntsc.h"
#include "snes_ntsc/snes_ntsc.c"
#include "ntsc.moc.hpp"
#include "ntsc.moc"
void NTSCFilter::bind(configuration &config) {
config.attach(hue = 0.0, "snesfilter.ntsc.hue");
config.attach(saturation = 0.0, "snesfilter.ntsc.saturation");
config.attach(contrast = 0.0, "snesfilter.ntsc.contrast");
config.attach(brightness = 0.0, "snesfilter.ntsc.brightness");
config.attach(sharpness = 0.0, "snesfilter.ntsc.sharpness");
config.attach(gamma = 0.0, "snesfilter.ntsc.gamma");
config.attach(resolution = 0.0, "snesfilter.ntsc.resolution");
config.attach(artifacts = 0.0, "snesfilter.ntsc.artifacts");
config.attach(fringing = 0.0, "snesfilter.ntsc.fringing");
config.attach(bleed = 0.0, "snesfilter.ntsc.bleed");
config.attach(mergeFields = true, "snesfilter.ntsc.mergeFields");
}
void NTSCFilter::size(unsigned &outwidth, unsigned &outheight, unsigned width, unsigned height) {
outwidth = SNES_NTSC_OUT_WIDTH(256);
outheight = height;
}
void NTSCFilter::render(
uint32_t *output, unsigned outpitch,
const uint16_t *input, unsigned pitch, unsigned width, unsigned height
) {
if(!ntsc) return;
pitch >>= 1;
outpitch >>= 2;
if(width <= 256) {
snes_ntsc_blit (ntsc, input, pitch, burst, width, height, output, outpitch << 2);
} else {
snes_ntsc_blit_hires(ntsc, input, pitch, burst, width, height, output, outpitch << 2);
}
burst ^= burst_toggle;
}
QWidget* NTSCFilter::settings() {
if(!widget) {
widget = new QWidget;
widget->setWindowTitle("NTSC Filter Configuration");
layout = new QVBoxLayout;
layout->setAlignment(Qt::AlignTop);
widget->setLayout(layout);
gridLayout = new QGridLayout;
layout->addLayout(gridLayout);
basicSettings = new QLabel("<b>Basic settings:</b>");
gridLayout->addWidget(basicSettings, 0, 0, 1, 3);
hueLabel = new QLabel("Hue:");
gridLayout->addWidget(hueLabel, 1, 0);
hueValue = new QLabel;
hueValue->setMinimumWidth(hueValue->fontMetrics().width("-100.0"));
hueValue->setAlignment(Qt::AlignHCenter);
gridLayout->addWidget(hueValue, 1, 1);
hueSlider = new QSlider(Qt::Horizontal);
hueSlider->setMinimum(-100);
hueSlider->setMaximum(+100);
gridLayout->addWidget(hueSlider, 1, 2);
saturationLabel = new QLabel("Saturation:");
gridLayout->addWidget(saturationLabel, 2, 0);
saturationValue = new QLabel;
saturationValue->setAlignment(Qt::AlignHCenter);
gridLayout->addWidget(saturationValue, 2, 1);
saturationSlider = new QSlider(Qt::Horizontal);
saturationSlider->setMinimum(-100);
saturationSlider->setMaximum(+100);
gridLayout->addWidget(saturationSlider, 2, 2);
contrastLabel = new QLabel("Contrast:");
gridLayout->addWidget(contrastLabel, 3, 0);
contrastValue = new QLabel;
contrastValue->setAlignment(Qt::AlignHCenter);
gridLayout->addWidget(contrastValue, 3, 1);
contrastSlider = new QSlider(Qt::Horizontal);
contrastSlider->setMinimum(-100);
contrastSlider->setMaximum(+100);
gridLayout->addWidget(contrastSlider, 3, 2);
brightnessLabel = new QLabel("Brightness:");
gridLayout->addWidget(brightnessLabel, 4, 0);
brightnessValue = new QLabel;
brightnessValue->setAlignment(Qt::AlignHCenter);
gridLayout->addWidget(brightnessValue, 4, 1);
brightnessSlider = new QSlider(Qt::Horizontal);
brightnessSlider->setMinimum(-100);
brightnessSlider->setMaximum(+100);
gridLayout->addWidget(brightnessSlider, 4, 2);
sharpnessLabel = new QLabel("Sharpness:");
gridLayout->addWidget(sharpnessLabel, 5, 0);
sharpnessValue = new QLabel;
sharpnessValue->setAlignment(Qt::AlignHCenter);
gridLayout->addWidget(sharpnessValue, 5, 1);
sharpnessSlider = new QSlider(Qt::Horizontal);
sharpnessSlider->setMinimum(-100);
sharpnessSlider->setMaximum(+100);
gridLayout->addWidget(sharpnessSlider, 5, 2);
advancedSettings = new QLabel("<b>Advanced settings:</b>");
gridLayout->addWidget(advancedSettings, 6, 0, 1, 3);
gammaLabel = new QLabel("Gamma:");
gridLayout->addWidget(gammaLabel, 7, 0);
gammaValue = new QLabel;
gammaValue->setAlignment(Qt::AlignHCenter);
gridLayout->addWidget(gammaValue, 7, 1);
gammaSlider = new QSlider(Qt::Horizontal);
gammaSlider->setMinimum(-100);
gammaSlider->setMaximum(+100);
gridLayout->addWidget(gammaSlider, 7, 2);
resolutionLabel = new QLabel("Resolution:");
gridLayout->addWidget(resolutionLabel, 8, 0);
resolutionValue = new QLabel;
resolutionValue->setAlignment(Qt::AlignHCenter);
gridLayout->addWidget(resolutionValue, 8, 1);
resolutionSlider = new QSlider(Qt::Horizontal);
resolutionSlider->setMinimum(-100);
resolutionSlider->setMaximum(+100);
gridLayout->addWidget(resolutionSlider, 8, 2);
artifactsLabel = new QLabel("Artifacts:");
gridLayout->addWidget(artifactsLabel, 9, 0);
artifactsValue = new QLabel;
artifactsValue->setAlignment(Qt::AlignHCenter);
gridLayout->addWidget(artifactsValue, 9, 1);
artifactsSlider = new QSlider(Qt::Horizontal);
artifactsSlider->setMinimum(-100);
artifactsSlider->setMaximum(+100);
gridLayout->addWidget(artifactsSlider, 9, 2);
fringingLabel = new QLabel("Fringing:");
gridLayout->addWidget(fringingLabel, 10, 0);
fringingValue = new QLabel;
fringingValue->setAlignment(Qt::AlignHCenter);
gridLayout->addWidget(fringingValue, 10, 1);
fringingSlider = new QSlider(Qt::Horizontal);
fringingSlider->setMinimum(-100);
fringingSlider->setMaximum(+100);
gridLayout->addWidget(fringingSlider, 10, 2);
bleedLabel = new QLabel("Color bleed:");
gridLayout->addWidget(bleedLabel, 11, 0);
bleedValue = new QLabel;
bleedValue->setAlignment(Qt::AlignHCenter);
gridLayout->addWidget(bleedValue, 11, 1);
bleedSlider = new QSlider(Qt::Horizontal);
bleedSlider->setMinimum(-100);
bleedSlider->setMaximum(+100);
gridLayout->addWidget(bleedSlider, 11, 2);
mergeFieldsBox = new QCheckBox("Merge even and odd fields to reduce flicker");
gridLayout->addWidget(mergeFieldsBox, 12, 0, 1, 3);
presets = new QLabel("<b>Presets:</b>");
gridLayout->addWidget(presets, 13, 0, 1, 3);
controlLayout = new QHBoxLayout;
layout->addLayout(controlLayout);
rfPreset = new QPushButton("RF");
controlLayout->addWidget(rfPreset);
compositePreset = new QPushButton("Composite");
controlLayout->addWidget(compositePreset);
svideoPreset = new QPushButton("S-Video");
controlLayout->addWidget(svideoPreset);
rgbPreset = new QPushButton("RGB");
controlLayout->addWidget(rgbPreset);
monoPreset = new QPushButton("Monochrome");
controlLayout->addWidget(monoPreset);
spacer = new QWidget;
spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
spacer->setMinimumWidth(50);
controlLayout->addWidget(spacer);
ok = new QPushButton("Ok");
controlLayout->addWidget(ok);
blockSignals = true;
loadSettingsFromConfig();
syncUiToSettings();
initialize();
connect(hueSlider, SIGNAL(valueChanged(int)), this, SLOT(syncSettingsToUi()));
connect(saturationSlider, SIGNAL(valueChanged(int)), this, SLOT(syncSettingsToUi()));
connect(contrastSlider, SIGNAL(valueChanged(int)), this, SLOT(syncSettingsToUi()));
connect(brightnessSlider, SIGNAL(valueChanged(int)), this, SLOT(syncSettingsToUi()));
connect(sharpnessSlider, SIGNAL(valueChanged(int)), this, SLOT(syncSettingsToUi()));
connect(gammaSlider, SIGNAL(valueChanged(int)), this, SLOT(syncSettingsToUi()));
connect(resolutionSlider, SIGNAL(valueChanged(int)), this, SLOT(syncSettingsToUi()));
connect(artifactsSlider, SIGNAL(valueChanged(int)), this, SLOT(syncSettingsToUi()));
connect(fringingSlider, SIGNAL(valueChanged(int)), this, SLOT(syncSettingsToUi()));
connect(bleedSlider, SIGNAL(valueChanged(int)), this, SLOT(syncSettingsToUi()));
connect(mergeFieldsBox, SIGNAL(stateChanged(int)), this, SLOT(syncSettingsToUi()));
connect(rfPreset, SIGNAL(released()), this, SLOT(setRfPreset()));
connect(compositePreset, SIGNAL(released()), this, SLOT(setCompositePreset()));
connect(svideoPreset, SIGNAL(released()), this, SLOT(setSvideoPreset()));
connect(rgbPreset, SIGNAL(released()), this, SLOT(setRgbPreset()));
connect(monoPreset, SIGNAL(released()), this, SLOT(setMonoPreset()));
connect(ok, SIGNAL(released()), widget, SLOT(hide()));
blockSignals = false;
}
return widget;
}
void NTSCFilter::initialize() {
burst = 0;
burst_toggle = (setup.merge_fields ? 0 : 1); //don't toggle burst when fields are merged
snes_ntsc_init(ntsc, &setup);
}
void NTSCFilter::loadSettingsFromConfig() {
setup.hue = hue;
setup.saturation = saturation;
setup.contrast = contrast;
setup.brightness = brightness;
setup.sharpness = sharpness;
setup.gamma = gamma;
setup.resolution = resolution;
setup.artifacts = artifacts;
setup.fringing = fringing;
setup.bleed = bleed;
setup.merge_fields = mergeFields;
}
void NTSCFilter::syncUiToSettings() {
blockSignals = true;
hue = setup.hue;
saturation = setup.saturation;
contrast = setup.contrast;
brightness = setup.brightness;
sharpness = setup.sharpness;
gamma = setup.gamma;
resolution = setup.resolution;
artifacts = setup.artifacts;
fringing = setup.fringing;
bleed = setup.bleed;
mergeFields = setup.merge_fields;
hueValue->setText(string() << hue);
hueSlider->setSliderPosition(hue * 100);
saturationValue->setText(string() << saturation);
saturationSlider->setSliderPosition(saturation * 100);
contrastValue->setText(string() << contrast);
contrastSlider->setSliderPosition(contrast * 100);
brightnessValue->setText(string() << brightness);
brightnessSlider->setSliderPosition(brightness * 100);
sharpnessValue->setText(string() << sharpness);
sharpnessSlider->setSliderPosition(sharpness * 100);
gammaValue->setText(string() << gamma);
gammaSlider->setSliderPosition(gamma * 100);
resolutionValue->setText(string() << resolution);
resolutionSlider->setSliderPosition(resolution * 100);
artifactsValue->setText(string() << artifacts);
artifactsSlider->setSliderPosition(artifacts * 100);
fringingValue->setText(string() << fringing);
fringingSlider->setSliderPosition(fringing * 100);
bleedValue->setText(string() << bleed);
bleedSlider->setSliderPosition(bleed * 100);
mergeFieldsBox->setChecked(mergeFields);
blockSignals = false;
}
void NTSCFilter::syncSettingsToUi() {
if(blockSignals) return;
hue = hueSlider->sliderPosition() / 100.0;
saturation = saturationSlider->sliderPosition() / 100.0;
contrast = contrastSlider->sliderPosition() / 100.0;
brightness = brightnessSlider->sliderPosition() / 100.0;
sharpness = sharpnessSlider->sliderPosition() / 100.0;
gamma = gammaSlider->sliderPosition() / 100.0;
resolution = resolutionSlider->sliderPosition() / 100.0;
artifacts = artifactsSlider->sliderPosition() / 100.0;
fringing = fringingSlider->sliderPosition() / 100.0;
bleed = bleedSlider->sliderPosition() / 100.0;
mergeFields = mergeFieldsBox->isChecked();
loadSettingsFromConfig();
syncUiToSettings();
initialize();
}
void NTSCFilter::setRfPreset() {
static snes_ntsc_setup_t defaults;
setup = defaults;
syncUiToSettings();
initialize();
}
void NTSCFilter::setCompositePreset() {
setup = snes_ntsc_composite;
syncUiToSettings();
initialize();
}
void NTSCFilter::setSvideoPreset() {
setup = snes_ntsc_svideo;
syncUiToSettings();
initialize();
}
void NTSCFilter::setRgbPreset() {
setup = snes_ntsc_rgb;
syncUiToSettings();
initialize();
}
void NTSCFilter::setMonoPreset() {
setup = snes_ntsc_monochrome;
syncUiToSettings();
initialize();
}
NTSCFilter::NTSCFilter() : widget(0) {
ntsc = (snes_ntsc_t*)malloc(sizeof *ntsc);
static snes_ntsc_setup_t defaults;
setup = defaults;
initialize();
}
NTSCFilter::~NTSCFilter() {
if(ntsc) free(ntsc);
}

View File

@@ -0,0 +1,91 @@
class NTSCFilter : public QObject {
Q_OBJECT
public:
void bind(configuration&);
void size(unsigned&, unsigned&, unsigned, unsigned);
void render(uint32_t*, unsigned, const uint16_t*, unsigned, unsigned, unsigned);
QWidget* settings();
NTSCFilter();
~NTSCFilter();
private:
void initialize();
void loadSettingsFromConfig();
void syncUiToSettings();
private slots:
void syncSettingsToUi();
void setRfPreset();
void setCompositePreset();
void setSvideoPreset();
void setRgbPreset();
void setMonoPreset();
private:
QWidget *widget;
QVBoxLayout *layout;
QGridLayout *gridLayout;
QLabel *basicSettings;
QLabel *hueLabel;
QLabel *hueValue;
QSlider *hueSlider;
QLabel *saturationLabel;
QLabel *saturationValue;
QSlider *saturationSlider;
QLabel *contrastLabel;
QLabel *contrastValue;
QSlider *contrastSlider;
QLabel *brightnessLabel;
QLabel *brightnessValue;
QSlider *brightnessSlider;
QLabel *sharpnessLabel;
QLabel *sharpnessValue;
QSlider *sharpnessSlider;
QLabel *advancedSettings;
QLabel *gammaLabel;
QLabel *gammaValue;
QSlider *gammaSlider;
QLabel *resolutionLabel;
QLabel *resolutionValue;
QSlider *resolutionSlider;
QLabel *artifactsLabel;
QLabel *artifactsValue;
QSlider *artifactsSlider;
QLabel *fringingLabel;
QLabel *fringingValue;
QSlider *fringingSlider;
QLabel *bleedLabel;
QLabel *bleedValue;
QSlider *bleedSlider;
QCheckBox *mergeFieldsBox;
QLabel *presets;
QHBoxLayout *controlLayout;
QPushButton *rfPreset;
QPushButton *compositePreset;
QPushButton *svideoPreset;
QPushButton *rgbPreset;
QPushButton *monoPreset;
QWidget *spacer;
QPushButton *ok;
bool blockSignals;
struct snes_ntsc_t *ntsc;
snes_ntsc_setup_t setup;
int burst, burst_toggle;
//settings
double hue;
double saturation;
double contrast;
double brightness;
double sharpness;
double gamma;
double resolution;
double artifacts;
double fringing;
double bleed;
bool mergeFields;
} filter_ntsc;

View File

@@ -0,0 +1,251 @@
/* snes_ntsc 0.2.2. http://www.slack.net/~ant/ */
#include "snes_ntsc.h"
/* Copyright (C) 2006-2007 Shay Green. This module is free software; you
can redistribute it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version. This
module is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details. You should have received a copy of the GNU Lesser General Public
License along with this module; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */
snes_ntsc_setup_t const snes_ntsc_monochrome = { 0,-1, 0, 0,.2, 0,.2,-.2,-.2,-1, 1, 0, 0 };
snes_ntsc_setup_t const snes_ntsc_composite = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0 };
snes_ntsc_setup_t const snes_ntsc_svideo = { 0, 0, 0, 0,.2, 0,.2, -1, -1, 0, 1, 0, 0 };
snes_ntsc_setup_t const snes_ntsc_rgb = { 0, 0, 0, 0,.2, 0,.7, -1, -1,-1, 1, 0, 0 };
#define alignment_count 3
#define burst_count 3
#define rescale_in 8
#define rescale_out 7
#define artifacts_mid 1.0f
#define fringing_mid 1.0f
#define std_decoder_hue 0
#define rgb_bits 7 /* half normal range to allow for doubled hires pixels */
#define gamma_size 32
#include "snes_ntsc_impl.h"
/* 3 input pixels -> 8 composite samples */
pixel_info_t const snes_ntsc_pixels [alignment_count] = {
{ PIXEL_OFFSET( -4, -9 ), { 1, 1, .6667f, 0 } },
{ PIXEL_OFFSET( -2, -7 ), { .3333f, 1, 1, .3333f } },
{ PIXEL_OFFSET( 0, -5 ), { 0, .6667f, 1, 1 } },
};
static void merge_kernel_fields( snes_ntsc_rgb_t* io )
{
int n;
for ( n = burst_size; n; --n )
{
snes_ntsc_rgb_t p0 = io [burst_size * 0] + rgb_bias;
snes_ntsc_rgb_t p1 = io [burst_size * 1] + rgb_bias;
snes_ntsc_rgb_t p2 = io [burst_size * 2] + rgb_bias;
/* merge colors without losing precision */
io [burst_size * 0] =
((p0 + p1 - ((p0 ^ p1) & snes_ntsc_rgb_builder)) >> 1) - rgb_bias;
io [burst_size * 1] =
((p1 + p2 - ((p1 ^ p2) & snes_ntsc_rgb_builder)) >> 1) - rgb_bias;
io [burst_size * 2] =
((p2 + p0 - ((p2 ^ p0) & snes_ntsc_rgb_builder)) >> 1) - rgb_bias;
++io;
}
}
static void correct_errors( snes_ntsc_rgb_t color, snes_ntsc_rgb_t* out )
{
int n;
for ( n = burst_count; n; --n )
{
unsigned i;
for ( i = 0; i < rgb_kernel_size / 2; i++ )
{
snes_ntsc_rgb_t error = color -
out [i ] - out [(i+12)%14+14] - out [(i+10)%14+28] -
out [i + 7] - out [i + 5 +14] - out [i + 3 +28];
DISTRIBUTE_ERROR( i+3+28, i+5+14, i+7 );
}
out += alignment_count * rgb_kernel_size;
}
}
void snes_ntsc_init( snes_ntsc_t* ntsc, snes_ntsc_setup_t const* setup )
{
int merge_fields;
int entry;
init_t impl;
if ( !setup )
setup = &snes_ntsc_composite;
init( &impl, setup );
merge_fields = setup->merge_fields;
if ( setup->artifacts <= -1 && setup->fringing <= -1 )
merge_fields = 1;
for ( entry = 0; entry < snes_ntsc_palette_size; entry++ )
{
/* Reduce number of significant bits of source color. Clearing the
low bits of R and B were least notictable. Modifying green was too
noticeable. */
int ir = entry >> 8 & 0x1E;
int ig = entry >> 4 & 0x1F;
int ib = entry << 1 & 0x1E;
#if SNES_NTSC_BSNES_COLORTBL
if ( setup->bsnes_colortbl )
{
int bgr15 = (ib << 10) | (ig << 5) | ir;
unsigned long rgb16 = setup->bsnes_colortbl [bgr15];
ir = rgb16 >> 11 & 0x1E;
ig = rgb16 >> 6 & 0x1F;
ib = rgb16 & 0x1E;
}
#endif
{
float rr = impl.to_float [ir];
float gg = impl.to_float [ig];
float bb = impl.to_float [ib];
float y, i, q = RGB_TO_YIQ( rr, gg, bb, y, i );
int r, g, b = YIQ_TO_RGB( y, i, q, impl.to_rgb, int, r, g );
snes_ntsc_rgb_t rgb = PACK_RGB( r, g, b );
snes_ntsc_rgb_t* out = ntsc->table [entry];
gen_kernel( &impl, y, i, q, out );
if ( merge_fields )
merge_kernel_fields( out );
correct_errors( rgb, out );
}
}
}
#ifndef SNES_NTSC_NO_BLITTERS
void snes_ntsc_blit( snes_ntsc_t const* ntsc, SNES_NTSC_IN_T const* input, long in_row_width,
int burst_phase, int in_width, int in_height, void* rgb_out, long out_pitch )
{
int chunk_count = (in_width - 1) / snes_ntsc_in_chunk;
for ( ; in_height; --in_height )
{
SNES_NTSC_IN_T const* line_in = input;
SNES_NTSC_BEGIN_ROW( ntsc, burst_phase,
snes_ntsc_black, snes_ntsc_black, SNES_NTSC_ADJ_IN( *line_in ) );
snes_ntsc_out_t* restrict line_out = (snes_ntsc_out_t*) rgb_out;
int n;
++line_in;
for ( n = chunk_count; n; --n )
{
/* order of input and output pixels must not be altered */
SNES_NTSC_COLOR_IN( 0, SNES_NTSC_ADJ_IN( line_in [0] ) );
SNES_NTSC_RGB_OUT( 0, line_out [0], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_RGB_OUT( 1, line_out [1], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_COLOR_IN( 1, SNES_NTSC_ADJ_IN( line_in [1] ) );
SNES_NTSC_RGB_OUT( 2, line_out [2], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_RGB_OUT( 3, line_out [3], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_COLOR_IN( 2, SNES_NTSC_ADJ_IN( line_in [2] ) );
SNES_NTSC_RGB_OUT( 4, line_out [4], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_RGB_OUT( 5, line_out [5], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_RGB_OUT( 6, line_out [6], SNES_NTSC_OUT_DEPTH );
line_in += 3;
line_out += 7;
}
/* finish final pixels */
SNES_NTSC_COLOR_IN( 0, snes_ntsc_black );
SNES_NTSC_RGB_OUT( 0, line_out [0], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_RGB_OUT( 1, line_out [1], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_COLOR_IN( 1, snes_ntsc_black );
SNES_NTSC_RGB_OUT( 2, line_out [2], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_RGB_OUT( 3, line_out [3], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_COLOR_IN( 2, snes_ntsc_black );
SNES_NTSC_RGB_OUT( 4, line_out [4], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_RGB_OUT( 5, line_out [5], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_RGB_OUT( 6, line_out [6], SNES_NTSC_OUT_DEPTH );
burst_phase = (burst_phase + 1) % snes_ntsc_burst_count;
input += in_row_width;
rgb_out = (char*) rgb_out + out_pitch;
}
}
void snes_ntsc_blit_hires( snes_ntsc_t const* ntsc, SNES_NTSC_IN_T const* input, long in_row_width,
int burst_phase, int in_width, int in_height, void* rgb_out, long out_pitch )
{
int chunk_count = (in_width - 2) / (snes_ntsc_in_chunk * 2);
for ( ; in_height; --in_height )
{
SNES_NTSC_IN_T const* line_in = input;
SNES_NTSC_HIRES_ROW( ntsc, burst_phase,
snes_ntsc_black, snes_ntsc_black, snes_ntsc_black,
SNES_NTSC_ADJ_IN( line_in [0] ),
SNES_NTSC_ADJ_IN( line_in [1] ) );
snes_ntsc_out_t* restrict line_out = (snes_ntsc_out_t*) rgb_out;
int n;
line_in += 2;
for ( n = chunk_count; n; --n )
{
/* twice as many input pixels per chunk */
SNES_NTSC_COLOR_IN( 0, SNES_NTSC_ADJ_IN( line_in [0] ) );
SNES_NTSC_HIRES_OUT( 0, line_out [0], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_COLOR_IN( 1, SNES_NTSC_ADJ_IN( line_in [1] ) );
SNES_NTSC_HIRES_OUT( 1, line_out [1], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_COLOR_IN( 2, SNES_NTSC_ADJ_IN( line_in [2] ) );
SNES_NTSC_HIRES_OUT( 2, line_out [2], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_COLOR_IN( 3, SNES_NTSC_ADJ_IN( line_in [3] ) );
SNES_NTSC_HIRES_OUT( 3, line_out [3], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_COLOR_IN( 4, SNES_NTSC_ADJ_IN( line_in [4] ) );
SNES_NTSC_HIRES_OUT( 4, line_out [4], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_COLOR_IN( 5, SNES_NTSC_ADJ_IN( line_in [5] ) );
SNES_NTSC_HIRES_OUT( 5, line_out [5], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_HIRES_OUT( 6, line_out [6], SNES_NTSC_OUT_DEPTH );
line_in += 6;
line_out += 7;
}
SNES_NTSC_COLOR_IN( 0, snes_ntsc_black );
SNES_NTSC_HIRES_OUT( 0, line_out [0], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_COLOR_IN( 1, snes_ntsc_black );
SNES_NTSC_HIRES_OUT( 1, line_out [1], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_COLOR_IN( 2, snes_ntsc_black );
SNES_NTSC_HIRES_OUT( 2, line_out [2], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_COLOR_IN( 3, snes_ntsc_black );
SNES_NTSC_HIRES_OUT( 3, line_out [3], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_COLOR_IN( 4, snes_ntsc_black );
SNES_NTSC_HIRES_OUT( 4, line_out [4], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_COLOR_IN( 5, snes_ntsc_black );
SNES_NTSC_HIRES_OUT( 5, line_out [5], SNES_NTSC_OUT_DEPTH );
SNES_NTSC_HIRES_OUT( 6, line_out [6], SNES_NTSC_OUT_DEPTH );
burst_phase = (burst_phase + 1) % snes_ntsc_burst_count;
input += in_row_width;
rgb_out = (char*) rgb_out + out_pitch;
}
}
#endif

View File

@@ -0,0 +1,228 @@
/* SNES NTSC video filter */
/* snes_ntsc 0.2.2 */
#ifndef SNES_NTSC_H
#define SNES_NTSC_H
#include "snes_ntsc_config.h"
#ifdef __cplusplus
extern "C" {
#endif
/* Image parameters, ranging from -1.0 to 1.0. Actual internal values shown
in parenthesis and should remain fairly stable in future versions. */
typedef struct snes_ntsc_setup_t
{
/* Basic parameters */
double hue; /* -1 = -180 degrees +1 = +180 degrees */
double saturation; /* -1 = grayscale (0.0) +1 = oversaturated colors (2.0) */
double contrast; /* -1 = dark (0.5) +1 = light (1.5) */
double brightness; /* -1 = dark (0.5) +1 = light (1.5) */
double sharpness; /* edge contrast enhancement/blurring */
/* Advanced parameters */
double gamma; /* -1 = dark (1.5) +1 = light (0.5) */
double resolution; /* image resolution */
double artifacts; /* artifacts caused by color changes */
double fringing; /* color artifacts caused by brightness changes */
double bleed; /* color bleed (color resolution reduction) */
int merge_fields; /* if 1, merges even and odd fields together to reduce flicker */
float const* decoder_matrix; /* optional RGB decoder matrix, 6 elements */
unsigned long const* bsnes_colortbl; /* undocumented; set to 0 */
} snes_ntsc_setup_t;
/* Video format presets */
extern snes_ntsc_setup_t const snes_ntsc_composite; /* color bleeding + artifacts */
extern snes_ntsc_setup_t const snes_ntsc_svideo; /* color bleeding only */
extern snes_ntsc_setup_t const snes_ntsc_rgb; /* crisp image */
extern snes_ntsc_setup_t const snes_ntsc_monochrome;/* desaturated + artifacts */
/* Initializes and adjusts parameters. Can be called multiple times on the same
snes_ntsc_t object. Can pass NULL for either parameter. */
typedef struct snes_ntsc_t snes_ntsc_t;
void snes_ntsc_init( snes_ntsc_t* ntsc, snes_ntsc_setup_t const* setup );
/* Filters one or more rows of pixels. Input pixel format is set by SNES_NTSC_IN_FORMAT
and output RGB depth is set by SNES_NTSC_OUT_DEPTH. Both default to 16-bit RGB.
In_row_width is the number of pixels to get to the next input row. Out_pitch
is the number of *bytes* to get to the next output row. */
void snes_ntsc_blit( snes_ntsc_t const* ntsc, SNES_NTSC_IN_T const* input,
long in_row_width, int burst_phase, int in_width, int in_height,
void* rgb_out, long out_pitch );
void snes_ntsc_blit_hires( snes_ntsc_t const* ntsc, SNES_NTSC_IN_T const* input,
long in_row_width, int burst_phase, int in_width, int in_height,
void* rgb_out, long out_pitch );
/* Number of output pixels written by low-res blitter for given input width. Width
might be rounded down slightly; use SNES_NTSC_IN_WIDTH() on result to find rounded
value. Guaranteed not to round 256 down at all. */
#define SNES_NTSC_OUT_WIDTH( in_width ) \
((((in_width) - 1) / snes_ntsc_in_chunk + 1) * snes_ntsc_out_chunk)
/* Number of low-res input pixels that will fit within given output width. Might be
rounded down slightly; use SNES_NTSC_OUT_WIDTH() on result to find rounded
value. */
#define SNES_NTSC_IN_WIDTH( out_width ) \
(((out_width) / snes_ntsc_out_chunk - 1) * snes_ntsc_in_chunk + 1)
/* Interface for user-defined custom blitters */
enum { snes_ntsc_in_chunk = 3 }; /* number of input pixels read per chunk */
enum { snes_ntsc_out_chunk = 7 }; /* number of output pixels generated per chunk */
enum { snes_ntsc_black = 0 }; /* palette index for black */
enum { snes_ntsc_burst_count = 3 }; /* burst phase cycles through 0, 1, and 2 */
/* Begins outputting row and starts three pixels. First pixel will be cut off a bit.
Use snes_ntsc_black for unused pixels. Declares variables, so must be before first
statement in a block (unless you're using C++). */
#define SNES_NTSC_BEGIN_ROW( ntsc, burst, pixel0, pixel1, pixel2 ) \
char const* ktable = \
(char const*) (ntsc)->table + burst * (snes_ntsc_burst_size * sizeof (snes_ntsc_rgb_t));\
SNES_NTSC_BEGIN_ROW_6_( pixel0, pixel1, pixel2, SNES_NTSC_IN_FORMAT, ktable )
/* Begins input pixel */
#define SNES_NTSC_COLOR_IN( index, color ) \
SNES_NTSC_COLOR_IN_( index, color, SNES_NTSC_IN_FORMAT, ktable )
/* Generates output pixel. Bits can be 24, 16, 15, 14, 32 (treated as 24), or 0:
24: RRRRRRRR GGGGGGGG BBBBBBBB (8-8-8 RGB)
16: RRRRRGGG GGGBBBBB (5-6-5 RGB)
15: RRRRRGG GGGBBBBB (5-5-5 RGB)
14: BBBBBGG GGGRRRRR (5-5-5 BGR, native SNES format)
0: xxxRRRRR RRRxxGGG GGGGGxxB BBBBBBBx (native internal format; x = junk bits) */
#define SNES_NTSC_RGB_OUT( index, rgb_out, bits ) \
SNES_NTSC_RGB_OUT_14_( index, rgb_out, bits, 1 )
/* Hires equivalents */
#define SNES_NTSC_HIRES_ROW( ntsc, burst, pixel1, pixel2, pixel3, pixel4, pixel5 ) \
char const* ktable = \
(char const*) (ntsc)->table + burst * (snes_ntsc_burst_size * sizeof (snes_ntsc_rgb_t));\
unsigned const snes_ntsc_pixel1_ = (pixel1);\
snes_ntsc_rgb_t const* kernel1 = SNES_NTSC_IN_FORMAT( ktable, snes_ntsc_pixel1_ );\
unsigned const snes_ntsc_pixel2_ = (pixel2);\
snes_ntsc_rgb_t const* kernel2 = SNES_NTSC_IN_FORMAT( ktable, snes_ntsc_pixel2_ );\
unsigned const snes_ntsc_pixel3_ = (pixel3);\
snes_ntsc_rgb_t const* kernel3 = SNES_NTSC_IN_FORMAT( ktable, snes_ntsc_pixel3_ );\
unsigned const snes_ntsc_pixel4_ = (pixel4);\
snes_ntsc_rgb_t const* kernel4 = SNES_NTSC_IN_FORMAT( ktable, snes_ntsc_pixel4_ );\
unsigned const snes_ntsc_pixel5_ = (pixel5);\
snes_ntsc_rgb_t const* kernel5 = SNES_NTSC_IN_FORMAT( ktable, snes_ntsc_pixel5_ );\
snes_ntsc_rgb_t const* kernel0 = kernel1;\
snes_ntsc_rgb_t const* kernelx0;\
snes_ntsc_rgb_t const* kernelx1 = kernel1;\
snes_ntsc_rgb_t const* kernelx2 = kernel1;\
snes_ntsc_rgb_t const* kernelx3 = kernel1;\
snes_ntsc_rgb_t const* kernelx4 = kernel1;\
snes_ntsc_rgb_t const* kernelx5 = kernel1
#define SNES_NTSC_HIRES_OUT( x, rgb_out, bits ) {\
snes_ntsc_rgb_t raw_ =\
kernel0 [ x ] + kernel2 [(x+5)%7+14] + kernel4 [(x+3)%7+28] +\
kernelx0 [(x+7)%7+7] + kernelx2 [(x+5)%7+21] + kernelx4 [(x+3)%7+35] +\
kernel1 [(x+6)%7 ] + kernel3 [(x+4)%7+14] + kernel5 [(x+2)%7+28] +\
kernelx1 [(x+6)%7+7] + kernelx3 [(x+4)%7+21] + kernelx5 [(x+2)%7+35];\
SNES_NTSC_CLAMP_( raw_, 0 );\
SNES_NTSC_RGB_OUT_( rgb_out, (bits), 0 );\
}
/* private */
enum { snes_ntsc_entry_size = 128 };
enum { snes_ntsc_palette_size = 0x2000 };
typedef unsigned long snes_ntsc_rgb_t;
struct snes_ntsc_t {
snes_ntsc_rgb_t table [snes_ntsc_palette_size] [snes_ntsc_entry_size];
};
enum { snes_ntsc_burst_size = snes_ntsc_entry_size / snes_ntsc_burst_count };
#define SNES_NTSC_RGB16( ktable, n ) \
(snes_ntsc_rgb_t const*) (ktable + ((n & 0x001E) | (n >> 1 & 0x03E0) | (n >> 2 & 0x3C00)) * \
(snes_ntsc_entry_size / 2 * sizeof (snes_ntsc_rgb_t)))
#define SNES_NTSC_BGR15( ktable, n ) \
(snes_ntsc_rgb_t const*) (ktable + ((n << 9 & 0x3C00) | (n & 0x03E0) | (n >> 10 & 0x001E)) * \
(snes_ntsc_entry_size / 2 * sizeof (snes_ntsc_rgb_t)))
/* common 3->7 ntsc macros */
#define SNES_NTSC_BEGIN_ROW_6_( pixel0, pixel1, pixel2, ENTRY, table ) \
unsigned const snes_ntsc_pixel0_ = (pixel0);\
snes_ntsc_rgb_t const* kernel0 = ENTRY( table, snes_ntsc_pixel0_ );\
unsigned const snes_ntsc_pixel1_ = (pixel1);\
snes_ntsc_rgb_t const* kernel1 = ENTRY( table, snes_ntsc_pixel1_ );\
unsigned const snes_ntsc_pixel2_ = (pixel2);\
snes_ntsc_rgb_t const* kernel2 = ENTRY( table, snes_ntsc_pixel2_ );\
snes_ntsc_rgb_t const* kernelx0;\
snes_ntsc_rgb_t const* kernelx1 = kernel0;\
snes_ntsc_rgb_t const* kernelx2 = kernel0
#define SNES_NTSC_RGB_OUT_14_( x, rgb_out, bits, shift ) {\
snes_ntsc_rgb_t raw_ =\
kernel0 [x ] + kernel1 [(x+12)%7+14] + kernel2 [(x+10)%7+28] +\
kernelx0 [(x+7)%14] + kernelx1 [(x+ 5)%7+21] + kernelx2 [(x+ 3)%7+35];\
SNES_NTSC_CLAMP_( raw_, shift );\
SNES_NTSC_RGB_OUT_( rgb_out, bits, shift );\
}
/* common ntsc macros */
#define snes_ntsc_rgb_builder ((1L << 21) | (1 << 11) | (1 << 1))
#define snes_ntsc_clamp_mask (snes_ntsc_rgb_builder * 3 / 2)
#define snes_ntsc_clamp_add (snes_ntsc_rgb_builder * 0x101)
#define SNES_NTSC_CLAMP_( io, shift ) {\
snes_ntsc_rgb_t sub = (io) >> (9-(shift)) & snes_ntsc_clamp_mask;\
snes_ntsc_rgb_t clamp = snes_ntsc_clamp_add - sub;\
io |= clamp;\
clamp -= sub;\
io &= clamp;\
}
#define SNES_NTSC_COLOR_IN_( index, color, ENTRY, table ) {\
unsigned color_;\
kernelx##index = kernel##index;\
kernel##index = (color_ = (color), ENTRY( table, color_ ));\
}
/* x is always zero except in snes_ntsc library */
/* original routine */
/*
#define SNES_NTSC_RGB_OUT_( rgb_out, bits, x ) {\
if ( bits == 16 )\
rgb_out = (raw_>>(13-x)& 0xF800)|(raw_>>(8-x)&0x07E0)|(raw_>>(4-x)&0x001F);\
if ( bits == 24 || bits == 32 )\
rgb_out = (raw_>>(5-x)&0xFF0000)|(raw_>>(3-x)&0xFF00)|(raw_>>(1-x)&0xFF);\
if ( bits == 15 )\
rgb_out = (raw_>>(14-x)& 0x7C00)|(raw_>>(9-x)&0x03E0)|(raw_>>(4-x)&0x001F);\
if ( bits == 14 )\
rgb_out = (raw_>>(24-x)& 0x001F)|(raw_>>(9-x)&0x03E0)|(raw_<<(6+x)&0x7C00);\
if ( bits == 0 )\
rgb_out = raw_ << x;\
}
*/
/* custom bsnes routine -- hooks into bsnes colortable */
#define SNES_NTSC_RGB_OUT_( rgb_out, bits, x ) {\
if ( bits == 16 ) {\
rgb_out = (raw_>>(13-x)& 0xF800)|(raw_>>(8-x)&0x07E0)|(raw_>>(4-x)&0x001F);\
rgb_out = ((rgb_out&0xf800)>>11)|((rgb_out&0x07c0)>>1)|((rgb_out&0x001f)<<10);\
rgb_out = colortable[rgb_out];\
} else if ( bits == 24 || bits == 32 ) {\
rgb_out = (raw_>>(5-x)&0xFF0000)|(raw_>>(3-x)&0xFF00)|(raw_>>(1-x)&0xFF);\
rgb_out = ((rgb_out&0xf80000)>>19)|((rgb_out&0x00f800)>>6)|((rgb_out&0x0000f8)<<7);\
rgb_out = colortable[rgb_out];\
} else if ( bits == 15 ) {\
rgb_out = (raw_>>(14-x)& 0x7C00)|(raw_>>(9-x)&0x03E0)|(raw_>>(4-x)&0x001F);\
rgb_out = ((rgb_out&0x7c00)>>10)|((rgb_out&0x03e0))|((rgb_out&0x001f)<<10);\
rgb_out = colortable[rgb_out];\
} else {\
rgb_out = raw_ << x;\
}\
}
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,26 @@
/* Configure library by modifying this file */
#ifndef SNES_NTSC_CONFIG_H
#define SNES_NTSC_CONFIG_H
/* Format of source pixels */
/* #define SNES_NTSC_IN_FORMAT SNES_NTSC_RGB16 */
#define SNES_NTSC_IN_FORMAT SNES_NTSC_BGR15
/* The following affect the built-in blitter only; a custom blitter can
handle things however it wants. */
/* Bits per pixel of output. Can be 15, 16, 32, or 24 (same as 32). */
#define SNES_NTSC_OUT_DEPTH 32
/* Type of input pixel values */
#define SNES_NTSC_IN_T unsigned short
/* Each raw pixel input value is passed through this. You might want to mask
the pixel index if you use the high bits as flags, etc. */
#define SNES_NTSC_ADJ_IN( in ) in
/* For each pixel, this is the basic operation:
output_color = SNES_NTSC_ADJ_IN( SNES_NTSC_IN_T ) */
#endif

View File

@@ -0,0 +1,439 @@
/* snes_ntsc 0.2.2. http://www.slack.net/~ant/ */
/* Common implementation of NTSC filters */
#include <assert.h>
#include <math.h>
/* Copyright (C) 2006 Shay Green. This module is free software; you
can redistribute it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version. This
module is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details. You should have received a copy of the GNU Lesser General Public
License along with this module; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */
#define DISABLE_CORRECTION 0
#undef PI
#define PI 3.14159265358979323846f
#ifndef LUMA_CUTOFF
#define LUMA_CUTOFF 0.20
#endif
#ifndef gamma_size
#define gamma_size 1
#endif
#ifndef rgb_bits
#define rgb_bits 8
#endif
#ifndef artifacts_max
#define artifacts_max (artifacts_mid * 1.5f)
#endif
#ifndef fringing_max
#define fringing_max (fringing_mid * 2)
#endif
#ifndef STD_HUE_CONDITION
#define STD_HUE_CONDITION( setup ) 1
#endif
#define ext_decoder_hue (std_decoder_hue + 15)
#define rgb_unit (1 << rgb_bits)
#define rgb_offset (rgb_unit * 2 + 0.5f)
enum { burst_size = snes_ntsc_entry_size / burst_count };
enum { kernel_half = 16 };
enum { kernel_size = kernel_half * 2 + 1 };
typedef struct init_t
{
float to_rgb [burst_count * 6];
float to_float [gamma_size];
float contrast;
float brightness;
float artifacts;
float fringing;
float kernel [rescale_out * kernel_size * 2];
} init_t;
#define ROTATE_IQ( i, q, sin_b, cos_b ) {\
float t;\
t = i * cos_b - q * sin_b;\
q = i * sin_b + q * cos_b;\
i = t;\
}
static void init_filters( init_t* impl, snes_ntsc_setup_t const* setup )
{
#if rescale_out > 1
float kernels [kernel_size * 2];
#else
float* const kernels = impl->kernel;
#endif
/* generate luma (y) filter using sinc kernel */
{
/* sinc with rolloff (dsf) */
float const rolloff = 1 + (float) setup->sharpness * (float) 0.032;
float const maxh = 32;
float const pow_a_n = (float) pow( rolloff, maxh );
float sum;
int i;
/* quadratic mapping to reduce negative (blurring) range */
float to_angle = (float) setup->resolution + 1;
to_angle = PI / maxh * (float) LUMA_CUTOFF * (to_angle * to_angle + 1);
kernels [kernel_size * 3 / 2] = maxh; /* default center value */
for ( i = 0; i < kernel_half * 2 + 1; i++ )
{
int x = i - kernel_half;
float angle = x * to_angle;
/* instability occurs at center point with rolloff very close to 1.0 */
if ( x || pow_a_n > (float) 1.056 || pow_a_n < (float) 0.981 )
{
float rolloff_cos_a = rolloff * (float) cos( angle );
float num = 1 - rolloff_cos_a -
pow_a_n * (float) cos( maxh * angle ) +
pow_a_n * rolloff * (float) cos( (maxh - 1) * angle );
float den = 1 - rolloff_cos_a - rolloff_cos_a + rolloff * rolloff;
float dsf = num / den;
kernels [kernel_size * 3 / 2 - kernel_half + i] = dsf - (float) 0.5;
}
}
/* apply blackman window and find sum */
sum = 0;
for ( i = 0; i < kernel_half * 2 + 1; i++ )
{
float x = PI * 2 / (kernel_half * 2) * i;
float blackman = 0.42f - 0.5f * (float) cos( x ) + 0.08f * (float) cos( x * 2 );
sum += (kernels [kernel_size * 3 / 2 - kernel_half + i] *= blackman);
}
/* normalize kernel */
sum = 1.0f / sum;
for ( i = 0; i < kernel_half * 2 + 1; i++ )
{
int x = kernel_size * 3 / 2 - kernel_half + i;
kernels [x] *= sum;
assert( kernels [x] == kernels [x] ); /* catch numerical instability */
}
}
/* generate chroma (iq) filter using gaussian kernel */
{
float const cutoff_factor = -0.03125f;
float cutoff = (float) setup->bleed;
int i;
if ( cutoff < 0 )
{
/* keep extreme value accessible only near upper end of scale (1.0) */
cutoff *= cutoff;
cutoff *= cutoff;
cutoff *= cutoff;
cutoff *= -30.0f / 0.65f;
}
cutoff = cutoff_factor - 0.65f * cutoff_factor * cutoff;
for ( i = -kernel_half; i <= kernel_half; i++ )
kernels [kernel_size / 2 + i] = (float) exp( i * i * cutoff );
/* normalize even and odd phases separately */
for ( i = 0; i < 2; i++ )
{
float sum = 0;
int x;
for ( x = i; x < kernel_size; x += 2 )
sum += kernels [x];
sum = 1.0f / sum;
for ( x = i; x < kernel_size; x += 2 )
{
kernels [x] *= sum;
assert( kernels [x] == kernels [x] ); /* catch numerical instability */
}
}
}
/*
printf( "luma:\n" );
for ( i = kernel_size; i < kernel_size * 2; i++ )
printf( "%f\n", kernels [i] );
printf( "chroma:\n" );
for ( i = 0; i < kernel_size; i++ )
printf( "%f\n", kernels [i] );
*/
/* generate linear rescale kernels */
#if rescale_out > 1
{
float weight = 1.0f;
float* out = impl->kernel;
int n = rescale_out;
do
{
float remain = 0;
int i;
weight -= 1.0f / rescale_in;
for ( i = 0; i < kernel_size * 2; i++ )
{
float cur = kernels [i];
float m = cur * weight;
*out++ = m + remain;
remain = cur - m;
}
}
while ( --n );
}
#endif
}
static float const default_decoder [6] =
{ 0.956f, 0.621f, -0.272f, -0.647f, -1.105f, 1.702f };
static void init( init_t* impl, snes_ntsc_setup_t const* setup )
{
impl->brightness = (float) setup->brightness * (0.5f * rgb_unit) + rgb_offset;
impl->contrast = (float) setup->contrast * (0.5f * rgb_unit) + rgb_unit;
#ifdef default_palette_contrast
if ( !setup->palette )
impl->contrast *= default_palette_contrast;
#endif
impl->artifacts = (float) setup->artifacts;
if ( impl->artifacts > 0 )
impl->artifacts *= artifacts_max - artifacts_mid;
impl->artifacts = impl->artifacts * artifacts_mid + artifacts_mid;
impl->fringing = (float) setup->fringing;
if ( impl->fringing > 0 )
impl->fringing *= fringing_max - fringing_mid;
impl->fringing = impl->fringing * fringing_mid + fringing_mid;
init_filters( impl, setup );
/* generate gamma table */
if ( gamma_size > 1 )
{
float const to_float = 1.0f / (gamma_size - (gamma_size > 1));
float const gamma = 1.1333f - (float) setup->gamma * 0.5f;
/* match common PC's 2.2 gamma to TV's 2.65 gamma */
int i;
for ( i = 0; i < gamma_size; i++ )
impl->to_float [i] =
(float) pow( i * to_float, gamma ) * impl->contrast + impl->brightness;
}
/* setup decoder matricies */
{
float hue = (float) setup->hue * PI + PI / 180 * ext_decoder_hue;
float sat = (float) setup->saturation + 1;
float const* decoder = setup->decoder_matrix;
if ( !decoder )
{
decoder = default_decoder;
if ( STD_HUE_CONDITION( setup ) )
hue += PI / 180 * (std_decoder_hue - ext_decoder_hue);
}
{
float s = (float) sin( hue ) * sat;
float c = (float) cos( hue ) * sat;
float* out = impl->to_rgb;
int n;
n = burst_count;
do
{
float const* in = decoder;
int n = 3;
do
{
float i = *in++;
float q = *in++;
*out++ = i * c - q * s;
*out++ = i * s + q * c;
}
while ( --n );
if ( burst_count <= 1 )
break;
ROTATE_IQ( s, c, 0.866025f, -0.5f ); /* +120 degrees */
}
while ( --n );
}
}
}
/* kernel generation */
#define RGB_TO_YIQ( r, g, b, y, i ) (\
(y = (r) * 0.299f + (g) * 0.587f + (b) * 0.114f),\
(i = (r) * 0.596f - (g) * 0.275f - (b) * 0.321f),\
((r) * 0.212f - (g) * 0.523f + (b) * 0.311f)\
)
#define YIQ_TO_RGB( y, i, q, to_rgb, type, r, g ) (\
r = (type) (y + to_rgb [0] * i + to_rgb [1] * q),\
g = (type) (y + to_rgb [2] * i + to_rgb [3] * q),\
(type) (y + to_rgb [4] * i + to_rgb [5] * q)\
)
#define PACK_RGB( r, g, b ) ((r) << 21 | (g) << 11 | (b) << 1)
enum { rgb_kernel_size = burst_size / alignment_count };
enum { rgb_bias = rgb_unit * 2 * snes_ntsc_rgb_builder };
typedef struct pixel_info_t
{
int offset;
float negate;
float kernel [4];
} pixel_info_t;
#if rescale_in > 1
#define PIXEL_OFFSET_( ntsc, scaled ) \
(kernel_size / 2 + ntsc + (scaled != 0) + (rescale_out - scaled) % rescale_out + \
(kernel_size * 2 * scaled))
#define PIXEL_OFFSET( ntsc, scaled ) \
PIXEL_OFFSET_( ((ntsc) - (scaled) / rescale_out * rescale_in),\
(((scaled) + rescale_out * 10) % rescale_out) ),\
(1.0f - (((ntsc) + 100) & 2))
#else
#define PIXEL_OFFSET( ntsc, scaled ) \
(kernel_size / 2 + (ntsc) - (scaled)),\
(1.0f - (((ntsc) + 100) & 2))
#endif
extern pixel_info_t const snes_ntsc_pixels [alignment_count];
/* Generate pixel at all burst phases and column alignments */
static void gen_kernel( init_t* impl, float y, float i, float q, snes_ntsc_rgb_t* out )
{
/* generate for each scanline burst phase */
float const* to_rgb = impl->to_rgb;
int burst_remain = burst_count;
y -= rgb_offset;
do
{
/* Encode yiq into *two* composite signals (to allow control over artifacting).
Convolve these with kernels which: filter respective components, apply
sharpening, and rescale horizontally. Convert resulting yiq to rgb and pack
into integer. Based on algorithm by NewRisingSun. */
pixel_info_t const* pixel = snes_ntsc_pixels;
int alignment_remain = alignment_count;
do
{
/* negate is -1 when composite starts at odd multiple of 2 */
float const yy = y * impl->fringing * pixel->negate;
float const ic0 = (i + yy) * pixel->kernel [0];
float const qc1 = (q + yy) * pixel->kernel [1];
float const ic2 = (i - yy) * pixel->kernel [2];
float const qc3 = (q - yy) * pixel->kernel [3];
float const factor = impl->artifacts * pixel->negate;
float const ii = i * factor;
float const yc0 = (y + ii) * pixel->kernel [0];
float const yc2 = (y - ii) * pixel->kernel [2];
float const qq = q * factor;
float const yc1 = (y + qq) * pixel->kernel [1];
float const yc3 = (y - qq) * pixel->kernel [3];
float const* k = &impl->kernel [pixel->offset];
int n;
++pixel;
for ( n = rgb_kernel_size; n; --n )
{
float i = k[0]*ic0 + k[2]*ic2;
float q = k[1]*qc1 + k[3]*qc3;
float y = k[kernel_size+0]*yc0 + k[kernel_size+1]*yc1 +
k[kernel_size+2]*yc2 + k[kernel_size+3]*yc3 + rgb_offset;
if ( rescale_out <= 1 )
k--;
else if ( k < &impl->kernel [kernel_size * 2 * (rescale_out - 1)] )
k += kernel_size * 2 - 1;
else
k -= kernel_size * 2 * (rescale_out - 1) + 2;
{
int r, g, b = YIQ_TO_RGB( y, i, q, to_rgb, int, r, g );
*out++ = PACK_RGB( r, g, b ) - rgb_bias;
}
}
}
while ( alignment_count > 1 && --alignment_remain );
if ( burst_count <= 1 )
break;
to_rgb += 6;
ROTATE_IQ( i, q, -0.866025f, -0.5f ); /* -120 degrees */
}
while ( --burst_remain );
}
static void correct_errors( snes_ntsc_rgb_t color, snes_ntsc_rgb_t* out );
#if DISABLE_CORRECTION
#define CORRECT_ERROR( a ) { out [i] += rgb_bias; }
#define DISTRIBUTE_ERROR( a, b, c ) { out [i] += rgb_bias; }
#else
#define CORRECT_ERROR( a ) { out [a] += error; }
#define DISTRIBUTE_ERROR( a, b, c ) {\
snes_ntsc_rgb_t fourth = (error + 2 * snes_ntsc_rgb_builder) >> 2;\
fourth &= (rgb_bias >> 1) - snes_ntsc_rgb_builder;\
fourth -= rgb_bias >> 2;\
out [a] += fourth;\
out [b] += fourth;\
out [c] += fourth;\
out [i] += error - (fourth * 3);\
}
#endif
#define RGB_PALETTE_OUT( rgb, out_ )\
{\
unsigned char* out = (out_);\
snes_ntsc_rgb_t clamped = (rgb);\
SNES_NTSC_CLAMP_( clamped, (8 - rgb_bits) );\
out [0] = (unsigned char) (clamped >> 21);\
out [1] = (unsigned char) (clamped >> 11);\
out [2] = (unsigned char) (clamped >> 1);\
}
/* blitter related */
#ifndef restrict
#if defined (__GNUC__)
#define restrict __restrict__
#elif defined (_MSC_VER) && _MSC_VER > 1300
#define restrict __restrict
#else
/* no support for restricted pointers */
#define restrict
#endif
#endif
#include <limits.h>
#if SNES_NTSC_OUT_DEPTH <= 16
#if USHRT_MAX == 0xFFFF
typedef unsigned short snes_ntsc_out_t;
#else
#error "Need 16-bit int type"
#endif
#else
#if UINT_MAX == 0xFFFFFFFF
typedef unsigned int snes_ntsc_out_t;
#elif ULONG_MAX == 0xFFFFFFFF
typedef unsigned long snes_ntsc_out_t;
#else
#error "Need 32-bit int type"
#endif
#endif

View File

@@ -0,0 +1,38 @@
#include "pixellate2x.hpp"
void Pixellate2xFilter::size(unsigned &outwidth, unsigned &outheight, unsigned width, unsigned height) {
outwidth = (width <= 256) ? width * 2 : width;
outheight = (height <= 240) ? height * 2 : height;
}
void Pixellate2xFilter::render(
uint32_t *output, unsigned outpitch,
const uint16_t *input, unsigned pitch, unsigned width, unsigned height
) {
pitch >>= 1;
outpitch >>= 2;
uint32_t *out0 = output;
uint32_t *out1 = output + outpitch;
for(unsigned y = 0; y < height; y++) {
for(unsigned x = 0; x < width; x++) {
uint32_t p = colortable[*input++];
*out0++ = p;
if(height <= 240) *out1++ = p;
if(width > 256) continue;
*out0++ = p;
if(height <= 240) *out1++ = p;
}
input += pitch - width;
if(height <= 240) {
out0 += outpitch + outpitch - 512;
out1 += outpitch + outpitch - 512;
} else {
out0 += outpitch - 512;
}
}
}

View File

@@ -0,0 +1,5 @@
class Pixellate2xFilter {
public:
void size(unsigned&, unsigned&, unsigned, unsigned);
void render(uint32_t*, unsigned, const uint16_t*, unsigned, unsigned, unsigned);
} filter_pixellate2x;

View File

@@ -0,0 +1,53 @@
#include "scale2x.hpp"
void Scale2xFilter::size(unsigned &outwidth, unsigned &outheight, unsigned width, unsigned height) {
if(width > 256 || height > 240) return filter_direct.size(outwidth, outheight, width, height);
outwidth = width * 2;
outheight = height * 2;
}
void Scale2xFilter::render(
uint32_t *output, unsigned outpitch,
const uint16_t *input, unsigned pitch, unsigned width, unsigned height
) {
if(width > 256 || height > 240) {
filter_direct.render(output, outpitch, input, pitch, width, height);
return;
}
pitch >>= 1;
outpitch >>= 2;
uint32_t *out0 = output;
uint32_t *out1 = output + outpitch;
for(unsigned y = 0; y < height; y++) {
int prevline = (y == 0 ? 0 : pitch);
int nextline = (y == height - 1 ? 0 : pitch);
for(unsigned x = 0; x < width; x++) {
uint16_t A = *(input - prevline);
uint16_t B = (x > 0) ? *(input - 1) : *input;
uint16_t C = *input;
uint16_t D = (x < 255) ? *(input + 1) : *input;
uint16_t E = *(input++ + nextline);
uint32_t c = colortable[C];
if(A != E && B != D) {
*out0++ = (A == B ? colortable[A] : c);
*out0++ = (A == D ? colortable[A] : c);
*out1++ = (E == B ? colortable[E] : c);
*out1++ = (E == D ? colortable[E] : c);
} else {
*out0++ = c;
*out0++ = c;
*out1++ = c;
*out1++ = c;
}
}
input += pitch - width;
out0 += outpitch + outpitch - 512;
out1 += outpitch + outpitch - 512;
}
}

View File

@@ -0,0 +1,5 @@
class Scale2xFilter {
public:
void size(unsigned&, unsigned&, unsigned, unsigned);
void render(uint32_t*, unsigned, const uint16_t*, unsigned, unsigned, unsigned);
} filter_scale2x;

83
snesfilter/snesfilter.cpp Normal file
View File

@@ -0,0 +1,83 @@
#include "snesfilter.hpp"
#if defined(_WIN32)
#define dllexport __declspec(dllexport)
#else
#define dllexport
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define QT_CORE_LIB
#include <QtGui>
#include <nall/config.hpp>
#include <nall/platform.hpp>
#include <nall/string.hpp>
using namespace nall;
const uint32_t *colortable;
configuration *config;
#include "direct/direct.cpp"
#include "pixellate2x/pixellate2x.cpp"
#include "scale2x/scale2x.cpp"
#include "2xsai/2xsai.cpp"
#include "lq2x/lq2x.cpp"
#include "hq2x/hq2x.cpp"
#include "ntsc/ntsc.cpp"
dllexport const char* snesfilter_supported() {
return "Pixellate2x;Scale2x;2xSaI;Super 2xSaI;Super Eagle;LQ2x;HQ2x;NTSC";
}
dllexport void snesfilter_configuration(configuration &config_) {
config = &config_;
if(config) {
filter_ntsc.bind(*config);
}
}
dllexport void snesfilter_colortable(const uint32_t *colortable_) {
colortable = colortable_;
}
dllexport void snesfilter_size(unsigned filter, unsigned &outwidth, unsigned &outheight, unsigned width, unsigned height) {
switch(filter) {
default: return filter_direct.size(outwidth, outheight, width, height);
case 1: return filter_pixellate2x.size(outwidth, outheight, width, height);
case 2: return filter_scale2x.size(outwidth, outheight, width, height);
case 3: return filter_2xsai.size(outwidth, outheight, width, height);
case 4: return filter_super2xsai.size(outwidth, outheight, width, height);
case 5: return filter_supereagle.size(outwidth, outheight, width, height);
case 6: return filter_lq2x.size(outwidth, outheight, width, height);
case 7: return filter_hq2x.size(outwidth, outheight, width, height);
case 8: return filter_ntsc.size(outwidth, outheight, width, height);
}
}
dllexport void snesfilter_render(
unsigned filter, uint32_t *output, unsigned outpitch,
const uint16_t *input, unsigned pitch, unsigned width, unsigned height
) {
switch(filter) {
default: return filter_direct.render(output, outpitch, input, pitch, width, height);
case 1: return filter_pixellate2x.render(output, outpitch, input, pitch, width, height);
case 2: return filter_scale2x.render(output, outpitch, input, pitch, width, height);
case 3: return filter_2xsai.render(output, outpitch, input, pitch, width, height);
case 4: return filter_super2xsai.render(output, outpitch, input, pitch, width, height);
case 5: return filter_supereagle.render(output, outpitch, input, pitch, width, height);
case 6: return filter_lq2x.render(output, outpitch, input, pitch, width, height);
case 7: return filter_hq2x.render(output, outpitch, input, pitch, width, height);
case 8: return filter_ntsc.render(output, outpitch, input, pitch, width, height);
}
}
dllexport QWidget* snesfilter_settings(unsigned filter) {
switch(filter) {
default: return 0;
case 8: return filter_ntsc.settings();
}
}

12
snesfilter/snesfilter.hpp Normal file
View File

@@ -0,0 +1,12 @@
#include <stdint.h>
class QWidget;
namespace nall { class configuration; }
extern "C" {
const char* snesfilter_supported();
void snesfilter_configuration(nall::configuration&);
void snesfilter_colortable(const uint32_t*);
void snesfilter_size(unsigned, unsigned&, unsigned&, unsigned, unsigned);
void snesfilter_render(unsigned, uint32_t*, unsigned, const uint16_t*, unsigned, unsigned, unsigned);
QWidget* snesfilter_settings(unsigned);
}

2
snesfilter/sync.sh Normal file
View File

@@ -0,0 +1,2 @@
rm -r nall
cp -r ../nall ./nall

77
snesreader/7z_C/7zAlloc.c Normal file
View File

@@ -0,0 +1,77 @@
/* 7zAlloc.c -- Allocation functions
2008-10-04 : Igor Pavlov : Public domain */
#include <stdlib.h>
#include "7zAlloc.h"
/* #define _SZ_ALLOC_DEBUG */
/* use _SZ_ALLOC_DEBUG to debug alloc/free operations */
#ifdef _SZ_ALLOC_DEBUG
#ifdef _WIN32
#include <windows.h>
#endif
#include <stdio.h>
int g_allocCount = 0;
int g_allocCountTemp = 0;
#endif
void *SzAlloc(void *p, size_t size)
{
p = p;
if (size == 0)
return 0;
#ifdef _SZ_ALLOC_DEBUG
fprintf(stderr, "\nAlloc %10d bytes; count = %10d", size, g_allocCount);
g_allocCount++;
#endif
return malloc(size);
}
void SzFree(void *p, void *address)
{
p = p;
#ifdef _SZ_ALLOC_DEBUG
if (address != 0)
{
g_allocCount--;
fprintf(stderr, "\nFree; count = %10d", g_allocCount);
}
#endif
free(address);
}
void *SzAllocTemp(void *p, size_t size)
{
p = p;
if (size == 0)
return 0;
#ifdef _SZ_ALLOC_DEBUG
fprintf(stderr, "\nAlloc_temp %10d bytes; count = %10d", size, g_allocCountTemp);
g_allocCountTemp++;
#ifdef _WIN32
return HeapAlloc(GetProcessHeap(), 0, size);
#endif
#endif
return malloc(size);
}
void SzFreeTemp(void *p, void *address)
{
p = p;
#ifdef _SZ_ALLOC_DEBUG
if (address != 0)
{
g_allocCountTemp--;
fprintf(stderr, "\nFree_temp; count = %10d", g_allocCountTemp);
}
#ifdef _WIN32
HeapFree(GetProcessHeap(), 0, address);
return;
#endif
#endif
free(address);
}

23
snesreader/7z_C/7zAlloc.h Normal file
View File

@@ -0,0 +1,23 @@
/* 7zAlloc.h -- Allocation functions
2008-10-04 : Igor Pavlov : Public domain */
#ifndef __7Z_ALLOC_H
#define __7Z_ALLOC_H
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
void *SzAlloc(void *p, size_t size);
void SzFree(void *p, void *address);
void *SzAllocTemp(void *p, size_t size);
void SzFreeTemp(void *p, void *address);
#ifdef __cplusplus
}
#endif
#endif

36
snesreader/7z_C/7zBuf.c Normal file
View File

@@ -0,0 +1,36 @@
/* 7zBuf.c -- Byte Buffer
2008-03-28
Igor Pavlov
Public domain */
#include "7zBuf.h"
void Buf_Init(CBuf *p)
{
p->data = 0;
p->size = 0;
}
int Buf_Create(CBuf *p, size_t size, ISzAlloc *alloc)
{
p->size = 0;
if (size == 0)
{
p->data = 0;
return 1;
}
p->data = (Byte *)alloc->Alloc(alloc, size);
if (p->data != 0)
{
p->size = size;
return 1;
}
return 0;
}
void Buf_Free(CBuf *p, ISzAlloc *alloc)
{
alloc->Free(alloc, p->data);
p->data = 0;
p->size = 0;
}

31
snesreader/7z_C/7zBuf.h Normal file
View File

@@ -0,0 +1,31 @@
/* 7zBuf.h -- Byte Buffer
2008-10-04 : Igor Pavlov : Public domain */
#ifndef __7Z_BUF_H
#define __7Z_BUF_H
#include "Types.h"
typedef struct
{
Byte *data;
size_t size;
} CBuf;
void Buf_Init(CBuf *p);
int Buf_Create(CBuf *p, size_t size, ISzAlloc *alloc);
void Buf_Free(CBuf *p, ISzAlloc *alloc);
typedef struct
{
Byte *data;
size_t size;
size_t pos;
} CDynBuf;
void DynBuf_Construct(CDynBuf *p);
void DynBuf_SeekToBeg(CDynBuf *p);
int DynBuf_Write(CDynBuf *p, const Byte *buf, size_t size, ISzAlloc *alloc);
void DynBuf_Free(CDynBuf *p, ISzAlloc *alloc);
#endif

194
snesreader/7z_C/7zC.txt Normal file
View File

@@ -0,0 +1,194 @@
7z ANSI-C Decoder 4.62
----------------------
7z ANSI-C provides 7z/LZMA decoding.
7z ANSI-C version is simplified version ported from C++ code.
LZMA is default and general compression method of 7z format
in 7-Zip compression program (www.7-zip.org). LZMA provides high
compression ratio and very fast decompression.
LICENSE
-------
7z ANSI-C Decoder is part of the LZMA SDK.
LZMA SDK is written and placed in the public domain by Igor Pavlov.
Files
---------------------
7zDecode.* - Low level 7z decoding
7zExtract.* - High level 7z decoding
7zHeader.* - .7z format constants
7zIn.* - .7z archive opening
7zItem.* - .7z structures
7zMain.c - Test application
How To Use
----------
You must download 7-Zip program from www.7-zip.org.
You can create .7z archive with 7z.exe or 7za.exe:
7za.exe a archive.7z *.htm -r -mx -m0fb=255
If you have big number of files in archive, and you need fast extracting,
you can use partly-solid archives:
7za.exe a archive.7z *.htm -ms=512K -r -mx -m0fb=255 -m0d=512K
In that example 7-Zip will use 512KB solid blocks. So it needs to decompress only
512KB for extracting one file from such archive.
Limitations of current version of 7z ANSI-C Decoder
---------------------------------------------------
- It reads only "FileName", "Size", "LastWriteTime" and "CRC" information for each file in archive.
- It supports only LZMA and Copy (no compression) methods with BCJ or BCJ2 filters.
- It converts original UTF-16 Unicode file names to UTF-8 Unicode file names.
These limitations will be fixed in future versions.
Using 7z ANSI-C Decoder Test application:
-----------------------------------------
Usage: 7zDec <command> <archive_name>
<Command>:
e: Extract files from archive
l: List contents of archive
t: Test integrity of archive
Example:
7zDec l archive.7z
lists contents of archive.7z
7zDec e archive.7z
extracts files from archive.7z to current folder.
How to use .7z Decoder
----------------------
Memory allocation
~~~~~~~~~~~~~~~~~
7z Decoder uses two memory pools:
1) Temporary pool
2) Main pool
Such scheme can allow you to avoid fragmentation of allocated blocks.
Steps for using 7z decoder
--------------------------
Use code at 7zMain.c as example.
1) Declare variables:
inStream /* implements ILookInStream interface */
CSzArEx db; /* 7z archive database structure */
ISzAlloc allocImp; /* memory functions for main pool */
ISzAlloc allocTempImp; /* memory functions for temporary pool */
2) call CrcGenerateTable(); function to initialize CRC structures.
3) call SzArEx_Init(&db); function to initialize db structures.
4) call SzArEx_Open(&db, inStream, &allocMain, &allocTemp) to open archive
This function opens archive "inStream" and reads headers to "db".
All items in "db" will be allocated with "allocMain" functions.
SzArEx_Open function allocates and frees temporary structures by "allocTemp" functions.
5) List items or Extract items
Listing code:
~~~~~~~~~~~~~
{
UInt32 i;
for (i = 0; i < db.db.NumFiles; i++)
{
CFileItem *f = db.db.Files + i;
printf("%10d %s\n", (int)f->Size, f->Name);
}
}
Extracting code:
~~~~~~~~~~~~~~~~
SZ_RESULT SzAr_Extract(
CArchiveDatabaseEx *db,
ILookInStream *inStream,
UInt32 fileIndex, /* index of file */
UInt32 *blockIndex, /* index of solid block */
Byte **outBuffer, /* pointer to pointer to output buffer (allocated with allocMain) */
size_t *outBufferSize, /* buffer size for output buffer */
size_t *offset, /* offset of stream for required file in *outBuffer */
size_t *outSizeProcessed, /* size of file in *outBuffer */
ISzAlloc *allocMain,
ISzAlloc *allocTemp);
If you need to decompress more than one file, you can send these values from previous call:
blockIndex,
outBuffer,
outBufferSize,
You can consider "outBuffer" as cache of solid block. If your archive is solid,
it will increase decompression speed.
After decompressing you must free "outBuffer":
allocImp.Free(outBuffer);
6) call SzArEx_Free(&db, allocImp.Free) to free allocated items in "db".
Memory requirements for .7z decoding
------------------------------------
Memory usage for Archive opening:
- Temporary pool:
- Memory for uncompressed .7z headers
- some other temporary blocks
- Main pool:
- Memory for database:
Estimated size of one file structures in solid archive:
- Size (4 or 8 Bytes)
- CRC32 (4 bytes)
- LastWriteTime (8 bytes)
- Some file information (4 bytes)
- File Name (variable length) + pointer + allocation structures
Memory usage for archive Decompressing:
- Temporary pool:
- Memory for LZMA decompressing structures
- Main pool:
- Memory for decompressed solid block
- Memory for temprorary buffers, if BCJ2 fileter is used. Usually these
temprorary buffers can be about 15% of solid block size.
7z Decoder doesn't allocate memory for compressed blocks.
Instead of this, you must allocate buffer with desired
size before calling 7z Decoder. Use 7zMain.c as example.
Defines
-------
_SZ_ALLOC_DEBUG - define it if you want to debug alloc/free operations to stderr.
---
http://www.7-zip.org
http://www.7-zip.org/sdk.html
http://www.7-zip.org/support.html

35
snesreader/7z_C/7zCrc.c Normal file
View File

@@ -0,0 +1,35 @@
/* 7zCrc.c -- CRC32 calculation
2008-08-05
Igor Pavlov
Public domain */
#include "7zCrc.h"
#define kCrcPoly 0xEDB88320
UInt32 g_CrcTable[256];
void MY_FAST_CALL CrcGenerateTable(void)
{
UInt32 i;
for (i = 0; i < 256; i++)
{
UInt32 r = i;
int j;
for (j = 0; j < 8; j++)
r = (r >> 1) ^ (kCrcPoly & ~((r & 1) - 1));
g_CrcTable[i] = r;
}
}
UInt32 MY_FAST_CALL CrcUpdate(UInt32 v, const void *data, size_t size)
{
const Byte *p = (const Byte *)data;
for (; size > 0 ; size--, p++)
v = CRC_UPDATE_BYTE(v, *p);
return v;
}
UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size)
{
return CrcUpdate(CRC_INIT_VAL, data, size) ^ 0xFFFFFFFF;
}

32
snesreader/7z_C/7zCrc.h Normal file
View File

@@ -0,0 +1,32 @@
/* 7zCrc.h -- CRC32 calculation
2008-03-13
Igor Pavlov
Public domain */
#ifndef __7Z_CRC_H
#define __7Z_CRC_H
#include <stddef.h>
#include "Types.h"
#ifdef __cplusplus
extern "C" {
#endif
extern UInt32 g_CrcTable[];
void MY_FAST_CALL CrcGenerateTable(void);
#define CRC_INIT_VAL 0xFFFFFFFF
#define CRC_GET_DIGEST(crc) ((crc) ^ 0xFFFFFFFF)
#define CRC_UPDATE_BYTE(crc, b) (g_CrcTable[((crc) ^ (b)) & 0xFF] ^ ((crc) >> 8))
UInt32 MY_FAST_CALL CrcUpdate(UInt32 crc, const void *data, size_t size);
UInt32 MY_FAST_CALL CrcCalc(const void *data, size_t size);
#ifdef __cplusplus
}
#endif
#endif

257
snesreader/7z_C/7zDecode.c Normal file
View File

@@ -0,0 +1,257 @@
/* 7zDecode.c -- Decoding from 7z folder
2008-11-23 : Igor Pavlov : Public domain */
#include <string.h>
#include "Bcj2.h"
#include "Bra.h"
#include "LzmaDec.h"
#include "7zDecode.h"
#define k_Copy 0
#define k_LZMA 0x30101
#define k_BCJ 0x03030103
#define k_BCJ2 0x0303011B
static SRes SzDecodeLzma(CSzCoderInfo *coder, UInt64 inSize, ILookInStream *inStream,
Byte *outBuffer, SizeT outSize, ISzAlloc *allocMain)
{
CLzmaDec state;
SRes res = SZ_OK;
LzmaDec_Construct(&state);
RINOK(LzmaDec_AllocateProbs(&state, coder->Props.data, (unsigned)coder->Props.size, allocMain));
state.dic = outBuffer;
state.dicBufSize = outSize;
LzmaDec_Init(&state);
for (;;)
{
Byte *inBuf = NULL;
size_t lookahead = (1 << 18);
if (lookahead > inSize)
lookahead = (size_t)inSize;
res = inStream->Look((void *)inStream, (void **)&inBuf, &lookahead);
if (res != SZ_OK)
break;
{
SizeT inProcessed = (SizeT)lookahead, dicPos = state.dicPos;
ELzmaStatus status;
res = LzmaDec_DecodeToDic(&state, outSize, inBuf, &inProcessed, LZMA_FINISH_END, &status);
lookahead -= inProcessed;
inSize -= inProcessed;
if (res != SZ_OK)
break;
if (state.dicPos == state.dicBufSize || (inProcessed == 0 && dicPos == state.dicPos))
{
if (state.dicBufSize != outSize || lookahead != 0 ||
(status != LZMA_STATUS_FINISHED_WITH_MARK &&
status != LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK))
res = SZ_ERROR_DATA;
break;
}
res = inStream->Skip((void *)inStream, inProcessed);
if (res != SZ_OK)
break;
}
}
LzmaDec_FreeProbs(&state, allocMain);
return res;
}
static SRes SzDecodeCopy(UInt64 inSize, ILookInStream *inStream, Byte *outBuffer)
{
while (inSize > 0)
{
void *inBuf;
size_t curSize = (1 << 18);
if (curSize > inSize)
curSize = (size_t)inSize;
RINOK(inStream->Look((void *)inStream, (void **)&inBuf, &curSize));
if (curSize == 0)
return SZ_ERROR_INPUT_EOF;
memcpy(outBuffer, inBuf, curSize);
outBuffer += curSize;
inSize -= curSize;
RINOK(inStream->Skip((void *)inStream, curSize));
}
return SZ_OK;
}
#define IS_UNSUPPORTED_METHOD(m) ((m) != k_Copy && (m) != k_LZMA)
#define IS_UNSUPPORTED_CODER(c) (IS_UNSUPPORTED_METHOD(c.MethodID) || c.NumInStreams != 1 || c.NumOutStreams != 1)
#define IS_NO_BCJ(c) (c.MethodID != k_BCJ || c.NumInStreams != 1 || c.NumOutStreams != 1)
#define IS_NO_BCJ2(c) (c.MethodID != k_BCJ2 || c.NumInStreams != 4 || c.NumOutStreams != 1)
static
SRes CheckSupportedFolder(const CSzFolder *f)
{
if (f->NumCoders < 1 || f->NumCoders > 4)
return SZ_ERROR_UNSUPPORTED;
if (IS_UNSUPPORTED_CODER(f->Coders[0]))
return SZ_ERROR_UNSUPPORTED;
if (f->NumCoders == 1)
{
if (f->NumPackStreams != 1 || f->PackStreams[0] != 0 || f->NumBindPairs != 0)
return SZ_ERROR_UNSUPPORTED;
return SZ_OK;
}
if (f->NumCoders == 2)
{
if (IS_NO_BCJ(f->Coders[1]) ||
f->NumPackStreams != 1 || f->PackStreams[0] != 0 ||
f->NumBindPairs != 1 ||
f->BindPairs[0].InIndex != 1 || f->BindPairs[0].OutIndex != 0)
return SZ_ERROR_UNSUPPORTED;
return SZ_OK;
}
if (f->NumCoders == 4)
{
if (IS_UNSUPPORTED_CODER(f->Coders[1]) ||
IS_UNSUPPORTED_CODER(f->Coders[2]) ||
IS_NO_BCJ2(f->Coders[3]))
return SZ_ERROR_UNSUPPORTED;
if (f->NumPackStreams != 4 ||
f->PackStreams[0] != 2 ||
f->PackStreams[1] != 6 ||
f->PackStreams[2] != 1 ||
f->PackStreams[3] != 0 ||
f->NumBindPairs != 3 ||
f->BindPairs[0].InIndex != 5 || f->BindPairs[0].OutIndex != 0 ||
f->BindPairs[1].InIndex != 4 || f->BindPairs[1].OutIndex != 1 ||
f->BindPairs[2].InIndex != 3 || f->BindPairs[2].OutIndex != 2)
return SZ_ERROR_UNSUPPORTED;
return SZ_OK;
}
return SZ_ERROR_UNSUPPORTED;
}
static
UInt64 GetSum(const UInt64 *values, UInt32 index)
{
UInt64 sum = 0;
UInt32 i;
for (i = 0; i < index; i++)
sum += values[i];
return sum;
}
static
SRes SzDecode2(const UInt64 *packSizes, const CSzFolder *folder,
ILookInStream *inStream, UInt64 startPos,
Byte *outBuffer, SizeT outSize, ISzAlloc *allocMain,
Byte *tempBuf[])
{
UInt32 ci;
SizeT tempSizes[3] = { 0, 0, 0};
SizeT tempSize3 = 0;
Byte *tempBuf3 = 0;
RINOK(CheckSupportedFolder(folder));
for (ci = 0; ci < folder->NumCoders; ci++)
{
CSzCoderInfo *coder = &folder->Coders[ci];
if (coder->MethodID == k_Copy || coder->MethodID == k_LZMA)
{
UInt32 si = 0;
UInt64 offset;
UInt64 inSize;
Byte *outBufCur = outBuffer;
SizeT outSizeCur = outSize;
if (folder->NumCoders == 4)
{
UInt32 indices[] = { 3, 2, 0 };
UInt64 unpackSize = folder->UnpackSizes[ci];
si = indices[ci];
if (ci < 2)
{
Byte *temp;
outSizeCur = (SizeT)unpackSize;
if (outSizeCur != unpackSize)
return SZ_ERROR_MEM;
temp = (Byte *)IAlloc_Alloc(allocMain, outSizeCur);
if (temp == 0 && outSizeCur != 0)
return SZ_ERROR_MEM;
outBufCur = tempBuf[1 - ci] = temp;
tempSizes[1 - ci] = outSizeCur;
}
else if (ci == 2)
{
if (unpackSize > outSize) /* check it */
return SZ_ERROR_PARAM;
tempBuf3 = outBufCur = outBuffer + (outSize - (size_t)unpackSize);
tempSize3 = outSizeCur = (SizeT)unpackSize;
}
else
return SZ_ERROR_UNSUPPORTED;
}
offset = GetSum(packSizes, si);
inSize = packSizes[si];
RINOK(LookInStream_SeekTo(inStream, startPos + offset));
if (coder->MethodID == k_Copy)
{
if (inSize != outSizeCur) /* check it */
return SZ_ERROR_DATA;
RINOK(SzDecodeCopy(inSize, inStream, outBufCur));
}
else
{
RINOK(SzDecodeLzma(coder, inSize, inStream, outBufCur, outSizeCur, allocMain));
}
}
else if (coder->MethodID == k_BCJ)
{
UInt32 state;
if (ci != 1)
return SZ_ERROR_UNSUPPORTED;
x86_Convert_Init(state);
x86_Convert(outBuffer, outSize, 0, &state, 0);
}
else if (coder->MethodID == k_BCJ2)
{
UInt64 offset = GetSum(packSizes, 1);
UInt64 s3Size = packSizes[1];
SRes res;
if (ci != 3)
return SZ_ERROR_UNSUPPORTED;
RINOK(LookInStream_SeekTo(inStream, startPos + offset));
tempSizes[2] = (SizeT)s3Size;
if (tempSizes[2] != s3Size)
return SZ_ERROR_MEM;
tempBuf[2] = (Byte *)IAlloc_Alloc(allocMain, tempSizes[2]);
if (tempBuf[2] == 0 && tempSizes[2] != 0)
return SZ_ERROR_MEM;
res = SzDecodeCopy(s3Size, inStream, tempBuf[2]);
RINOK(res)
res = Bcj2_Decode(
tempBuf3, tempSize3,
tempBuf[0], tempSizes[0],
tempBuf[1], tempSizes[1],
tempBuf[2], tempSizes[2],
outBuffer, outSize);
RINOK(res)
}
else
return SZ_ERROR_UNSUPPORTED;
}
return SZ_OK;
}
SRes SzDecode(const UInt64 *packSizes, const CSzFolder *folder,
ILookInStream *inStream, UInt64 startPos,
Byte *outBuffer, size_t outSize, ISzAlloc *allocMain)
{
Byte *tempBuf[3] = { 0, 0, 0};
int i;
SRes res = SzDecode2(packSizes, folder, inStream, startPos,
outBuffer, (SizeT)outSize, allocMain, tempBuf);
for (i = 0; i < 3; i++)
IAlloc_Free(allocMain, tempBuf[i]);
return res;
}

View File

@@ -0,0 +1,13 @@
/* 7zDecode.h -- Decoding from 7z folder
2008-11-23 : Igor Pavlov : Public domain */
#ifndef __7Z_DECODE_H
#define __7Z_DECODE_H
#include "7zItem.h"
SRes SzDecode(const UInt64 *packSizes, const CSzFolder *folder,
ILookInStream *stream, UInt64 startPos,
Byte *outBuffer, size_t outSize, ISzAlloc *allocMain);
#endif

View File

@@ -0,0 +1,93 @@
/* 7zExtract.c -- Extracting from 7z archive
2008-11-23 : Igor Pavlov : Public domain */
#include "7zCrc.h"
#include "7zDecode.h"
#include "7zExtract.h"
SRes SzAr_Extract(
const CSzArEx *p,
ILookInStream *inStream,
UInt32 fileIndex,
UInt32 *blockIndex,
Byte **outBuffer,
size_t *outBufferSize,
size_t *offset,
size_t *outSizeProcessed,
ISzAlloc *allocMain,
ISzAlloc *allocTemp)
{
UInt32 folderIndex = p->FileIndexToFolderIndexMap[fileIndex];
SRes res = SZ_OK;
*offset = 0;
*outSizeProcessed = 0;
if (folderIndex == (UInt32)-1)
{
IAlloc_Free(allocMain, *outBuffer);
*blockIndex = folderIndex;
*outBuffer = 0;
*outBufferSize = 0;
return SZ_OK;
}
if (*outBuffer == 0 || *blockIndex != folderIndex)
{
CSzFolder *folder = p->db.Folders + folderIndex;
UInt64 unpackSizeSpec = SzFolder_GetUnpackSize(folder);
size_t unpackSize = (size_t)unpackSizeSpec;
UInt64 startOffset = SzArEx_GetFolderStreamPos(p, folderIndex, 0);
if (unpackSize != unpackSizeSpec)
return SZ_ERROR_MEM;
*blockIndex = folderIndex;
IAlloc_Free(allocMain, *outBuffer);
*outBuffer = 0;
RINOK(LookInStream_SeekTo(inStream, startOffset));
if (res == SZ_OK)
{
*outBufferSize = unpackSize;
if (unpackSize != 0)
{
*outBuffer = (Byte *)IAlloc_Alloc(allocMain, unpackSize);
if (*outBuffer == 0)
res = SZ_ERROR_MEM;
}
if (res == SZ_OK)
{
res = SzDecode(p->db.PackSizes +
p->FolderStartPackStreamIndex[folderIndex], folder,
inStream, startOffset,
*outBuffer, unpackSize, allocTemp);
if (res == SZ_OK)
{
if (folder->UnpackCRCDefined)
{
if (CrcCalc(*outBuffer, unpackSize) != folder->UnpackCRC)
res = SZ_ERROR_CRC;
}
}
}
}
}
if (res == SZ_OK)
{
UInt32 i;
CSzFileItem *fileItem = p->db.Files + fileIndex;
*offset = 0;
for (i = p->FolderStartFileIndex[folderIndex]; i < fileIndex; i++)
*offset += (UInt32)p->db.Files[i].Size;
*outSizeProcessed = (size_t)fileItem->Size;
if (*offset + *outSizeProcessed > *outBufferSize)
return SZ_ERROR_FAIL;
{
if (fileItem->FileCRCDefined)
{
if (CrcCalc(*outBuffer + *offset, *outSizeProcessed) != fileItem->FileCRC)
res = SZ_ERROR_CRC;
}
}
}
return res;
}

View File

@@ -0,0 +1,49 @@
/* 7zExtract.h -- Extracting from 7z archive
2008-11-23 : Igor Pavlov : Public domain */
#ifndef __7Z_EXTRACT_H
#define __7Z_EXTRACT_H
#include "7zIn.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
SzExtract extracts file from archive
*outBuffer must be 0 before first call for each new archive.
Extracting cache:
If you need to decompress more than one file, you can send
these values from previous call:
*blockIndex,
*outBuffer,
*outBufferSize
You can consider "*outBuffer" as cache of solid block. If your archive is solid,
it will increase decompression speed.
If you use external function, you can declare these 3 cache variables
(blockIndex, outBuffer, outBufferSize) as static in that external function.
Free *outBuffer and set *outBuffer to 0, if you want to flush cache.
*/
SRes SzAr_Extract(
const CSzArEx *db,
ILookInStream *inStream,
UInt32 fileIndex, /* index of file */
UInt32 *blockIndex, /* index of solid block */
Byte **outBuffer, /* pointer to pointer to output buffer (allocated with allocMain) */
size_t *outBufferSize, /* buffer size for output buffer */
size_t *offset, /* offset of stream for required file in *outBuffer */
size_t *outSizeProcessed, /* size of file in *outBuffer */
ISzAlloc *allocMain,
ISzAlloc *allocTemp);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,6 @@
/* 7zHeader.c -- 7z Headers
2008-10-04 : Igor Pavlov : Public domain */
#include "7zHeader.h"
Byte k7zSignature[k7zSignatureSize] = {'7', 'z', 0xBC, 0xAF, 0x27, 0x1C};

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