libgambatte/libretro/msvc/msvc-2003-xbox1/msvc-2003-xbox1.vcproj 000664 001750 001750 00000101713 12720365247 025171 0 ustar 00sergio sergio 000000 000000
libgambatte/libretro/jni/Android.mk 000664 001750 001750 00000001221 12720365247 020474 0 ustar 00sergio sergio 000000 000000 LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := libretro
ifeq ($(TARGET_ARCH),arm)
LOCAL_CXXFLAGS += -DANDROID_ARM
LOCAL_ARM_MODE := arm
endif
ifeq ($(TARGET_ARCH),x86)
LOCAL_CXXFLAGS += -DANDROID_X86
endif
ifeq ($(TARGET_ARCH),mips)
LOCAL_CXXFLAGS += -DANDROID_MIPS
endif
CORE_DIR := ../../src
include ../../Makefile.common
LOCAL_SRC_FILES := $(SOURCES_CXX) $(SOURCES_C)
LOCAL_CXXFLAGS += -DINLINE=inline -DHAVE_STDINT_H -DHAVE_INTTYPES_H -D__LIBRETRO__
LOCAL_C_INCLUDES = $(CORE_DIR) $(CORE_DIR)/../include $(CORE_DIR)/../../common $(CORE_DIR)/../../common/resample $(CORE_DIR)/../libretro
include $(BUILD_SHARED_LIBRARY)
libgambatte/libretro/blipper.h 000664 001750 001750 00000013265 12720365247 017624 0 ustar 00sergio sergio 000000 000000 /*
* Copyright (C) 2013 - Hans-Kristian Arntzen
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and
* associated documentation files (the "Software"),
* to deal in the Software without restriction,
* including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef BLIPPER_H__
#define BLIPPER_H__
/* Compile time configurables. */
#ifndef BLIPPER_LOG_PERFORMANCE
#define BLIPPER_LOG_PERFORMANCE 0
#endif
#ifndef BLIPPER_FIXED_POINT
#define BLIPPER_FIXED_POINT 1
#endif
/* Set to float or double.
* long double is unlikely to provide any improved precision. */
#ifndef BLIPPER_REAL_T
#define BLIPPER_REAL_T float
#endif
/* Allows including several implementations in one lib. */
#if BLIPPER_FIXED_POINT
#define BLIPPER_MANGLE(x) x##_fixed
#else
#define BLIPPER_MANGLE(x) x##_##BLIPPER_REAL_T
#endif
#ifdef __cplusplus
extern "C" {
#endif
#include
typedef struct blipper blipper_t;
typedef BLIPPER_REAL_T blipper_real_t;
#if BLIPPER_FIXED_POINT
#ifdef HAVE_STDINT_H
#include
typedef int16_t blipper_sample_t;
typedef int32_t blipper_long_sample_t;
#else
#if SHRT_MAX == 0x7fff
typedef short blipper_sample_t;
#elif INT_MAX == 0x7fff
typedef int blipper_sample_t;
#else
#error "Cannot find suitable type for blipper_sampler_t."
#endif
#if INT_MAX == 0x7fffffffl
typedef int blipper_long_sample_t;
#elif LONG_MAX == 0x7fffffffl
typedef long blipper_long_sample_t;
#else
#error "Cannot find suitable type for blipper_long_sample_t."
#endif
#endif
#else
typedef BLIPPER_REAL_T blipper_sample_t;
typedef BLIPPER_REAL_T blipper_long_sample_t; /* Meaningless for float version. */
#endif
/* Create a new blipper.
* taps: Number of filter taps per impulse.
*
* cutoff: Cutoff frequency in the passband. Has a range of [0, 1].
*
* beta: Beta used for Kaiser window.
*
* decimation: Sets decimation rate. Must be power-of-two (2^n).
* The input sampling rate is then output_rate * 2^decimation.
* buffer_samples: The maximum number of processed output samples that can be
* buffered up by blipper.
*
* filter_bank: An optional filter which has already been created by
* blipper_create_filter_bank(). blipper_new() does not take ownership
* of the buffer and must be freed by caller.
* If non-NULL, cutoff and beta will be ignored.
*
* Some sane values:
* taps = 64, cutoff = 0.85, beta = 8.0
*/
#define blipper_new BLIPPER_MANGLE(blipper_new)
blipper_t *blipper_new(unsigned taps, double cutoff, double beta,
unsigned decimation, unsigned buffer_samples, const blipper_sample_t *filter_bank);
/* Reset the blipper to its initiate state. */
#define blipper_reset BLIPPER_MANGLE(blipper_reset)
void blipper_reset(blipper_t *blip);
/* Create a filter which can be passed to blipper_new() in filter_bank.
* Arguments to decimation and taps must match. */
#define blipper_create_filter_bank BLIPPER_MANGLE(blipper_create_filter_bank)
blipper_sample_t *blipper_create_filter_bank(unsigned decimation,
unsigned taps, double cutoff, double beta);
/* Frees the blipper. blip can be NULL (no-op). */
#define blipper_free BLIPPER_MANGLE(blipper_free)
void blipper_free(blipper_t *blip);
/* Data pushing interfaces. One of these should be used exclusively. */
/* Push a single delta, which occurs clock_step input samples after the
* last time a delta was pushed. The delta value is the difference signal
* between the new sample and the previous.
* It is unnecessary to pass a delta of 0.
* If the deltas are known beforehand (e.g. when synthesizing a waveform),
* this is a more efficient interface than blipper_push_samples().
*
* The caller must ensure not to push deltas in a way that can destabilize
* the final integration.
*/
#define blipper_push_delta BLIPPER_MANGLE(blipper_push_delta)
void blipper_push_delta(blipper_t *blip, blipper_long_sample_t delta, unsigned clocks_step);
/* Push raw samples. blipper will find the deltas themself and push them.
* stride is the number of samples between each sample to be used.
* This can be used to push interleaved stereo data to two independent
* blippers.
*/
#define blipper_push_samples BLIPPER_MANGLE(blipper_push_samples)
void blipper_push_samples(blipper_t *blip, const blipper_sample_t *delta,
unsigned samples, unsigned stride);
/* Returns the number of samples available for reading using
* blipper_read().
*/
#define blipper_read_avail BLIPPER_MANGLE(blipper_read_avail)
unsigned blipper_read_avail(blipper_t *blip);
/* Reads processed samples. The caller must ensure to not read
* more than what is returned from blipper_read_avail().
* As in blipper_push_samples(), stride is the number of samples
* between each output sample in output.
* Can be used to write to an interleaved stereo buffer.
*/
#define blipper_read BLIPPER_MANGLE(blipper_read)
void blipper_read(blipper_t *blip, blipper_sample_t *output, unsigned samples,
unsigned stride);
#ifdef __cplusplus
}
#endif
#endif
libgambatte/libretro/link.T 000664 001750 001750 00000000047 12720365247 017072 0 ustar 00sergio sergio 000000 000000 {
global: retro_*;
local: *;
};
libgambatte/libretro/msvc/msvc-2003-xbox1/stdint.h 000664 001750 001750 00000017100 12720365247 023025 0 ustar 00sergio sergio 000000 000000 // ISO C9x compliant stdint.h for Microsoft Visual Studio
// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124
//
// Copyright (c) 2006-2008 Alexander Chemeris
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. The name of the author may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef __RARCH_STDINT_H
#define __RARCH_STDINT_H
#if _MSC_VER && (_MSC_VER < 1600)
//pre-MSVC 2010 needs an implementation of stdint.h
#if _MSC_VER > 1000
#pragma once
#endif
#include
// For Visual Studio 6 in C++ mode and for many Visual Studio versions when
// compiling for ARM we should wrap include with 'extern "C++" {}'
// or compiler give many errors like this:
// error C2733: second C linkage of overloaded function 'wmemchr' not allowed
#ifdef __cplusplus
extern "C" {
#endif
# include
#ifdef __cplusplus
}
#endif
// Define _W64 macros to mark types changing their size, like intptr_t.
#ifndef _W64
# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300
# define _W64 __w64
# else
# define _W64
# endif
#endif
// 7.18.1 Integer types
// 7.18.1.1 Exact-width integer types
// Visual Studio 6 and Embedded Visual C++ 4 doesn't
// realize that, e.g. char has the same size as __int8
// so we give up on __intX for them.
#if (_MSC_VER < 1300)
typedef signed char int8_t;
typedef signed short int16_t;
typedef signed int int32_t;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
#else
typedef signed __int8 int8_t;
typedef signed __int16 int16_t;
typedef signed __int32 int32_t;
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
#endif
typedef signed __int64 int64_t;
typedef unsigned __int64 uint64_t;
// 7.18.1.2 Minimum-width integer types
typedef int8_t int_least8_t;
typedef int16_t int_least16_t;
typedef int32_t int_least32_t;
typedef int64_t int_least64_t;
typedef uint8_t uint_least8_t;
typedef uint16_t uint_least16_t;
typedef uint32_t uint_least32_t;
typedef uint64_t uint_least64_t;
// 7.18.1.3 Fastest minimum-width integer types
typedef int8_t int_fast8_t;
typedef int16_t int_fast16_t;
typedef int32_t int_fast32_t;
typedef int64_t int_fast64_t;
typedef uint8_t uint_fast8_t;
typedef uint16_t uint_fast16_t;
typedef uint32_t uint_fast32_t;
typedef uint64_t uint_fast64_t;
// 7.18.1.4 Integer types capable of holding object pointers
#ifdef _WIN64 // [
typedef signed __int64 intptr_t;
typedef unsigned __int64 uintptr_t;
#else // _WIN64 ][
typedef _W64 signed int intptr_t;
typedef _W64 unsigned int uintptr_t;
#endif // _WIN64 ]
// 7.18.1.5 Greatest-width integer types
typedef int64_t intmax_t;
typedef uint64_t uintmax_t;
// 7.18.2 Limits of specified-width integer types
#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259
// 7.18.2.1 Limits of exact-width integer types
#define INT8_MIN ((int8_t)_I8_MIN)
#define INT8_MAX _I8_MAX
#define INT16_MIN ((int16_t)_I16_MIN)
#define INT16_MAX _I16_MAX
#define INT32_MIN ((int32_t)_I32_MIN)
#define INT32_MAX _I32_MAX
#define INT64_MIN ((int64_t)_I64_MIN)
#define INT64_MAX _I64_MAX
#define UINT8_MAX _UI8_MAX
#define UINT16_MAX _UI16_MAX
#define UINT32_MAX _UI32_MAX
#define UINT64_MAX _UI64_MAX
// 7.18.2.2 Limits of minimum-width integer types
#define INT_LEAST8_MIN INT8_MIN
#define INT_LEAST8_MAX INT8_MAX
#define INT_LEAST16_MIN INT16_MIN
#define INT_LEAST16_MAX INT16_MAX
#define INT_LEAST32_MIN INT32_MIN
#define INT_LEAST32_MAX INT32_MAX
#define INT_LEAST64_MIN INT64_MIN
#define INT_LEAST64_MAX INT64_MAX
#define UINT_LEAST8_MAX UINT8_MAX
#define UINT_LEAST16_MAX UINT16_MAX
#define UINT_LEAST32_MAX UINT32_MAX
#define UINT_LEAST64_MAX UINT64_MAX
// 7.18.2.3 Limits of fastest minimum-width integer types
#define INT_FAST8_MIN INT8_MIN
#define INT_FAST8_MAX INT8_MAX
#define INT_FAST16_MIN INT16_MIN
#define INT_FAST16_MAX INT16_MAX
#define INT_FAST32_MIN INT32_MIN
#define INT_FAST32_MAX INT32_MAX
#define INT_FAST64_MIN INT64_MIN
#define INT_FAST64_MAX INT64_MAX
#define UINT_FAST8_MAX UINT8_MAX
#define UINT_FAST16_MAX UINT16_MAX
#define UINT_FAST32_MAX UINT32_MAX
#define UINT_FAST64_MAX UINT64_MAX
// 7.18.2.4 Limits of integer types capable of holding object pointers
#ifdef _WIN64 // [
# define INTPTR_MIN INT64_MIN
# define INTPTR_MAX INT64_MAX
# define UINTPTR_MAX UINT64_MAX
#else // _WIN64 ][
# define INTPTR_MIN INT32_MIN
# define INTPTR_MAX INT32_MAX
# define UINTPTR_MAX UINT32_MAX
#endif // _WIN64 ]
// 7.18.2.5 Limits of greatest-width integer types
#define INTMAX_MIN INT64_MIN
#define INTMAX_MAX INT64_MAX
#define UINTMAX_MAX UINT64_MAX
// 7.18.3 Limits of other integer types
#ifdef _WIN64 // [
# define PTRDIFF_MIN _I64_MIN
# define PTRDIFF_MAX _I64_MAX
#else // _WIN64 ][
# define PTRDIFF_MIN _I32_MIN
# define PTRDIFF_MAX _I32_MAX
#endif // _WIN64 ]
#define SIG_ATOMIC_MIN INT_MIN
#define SIG_ATOMIC_MAX INT_MAX
#ifndef SIZE_MAX // [
# ifdef _WIN64 // [
# define SIZE_MAX _UI64_MAX
# else // _WIN64 ][
# define SIZE_MAX _UI32_MAX
# endif // _WIN64 ]
#endif // SIZE_MAX ]
// WCHAR_MIN and WCHAR_MAX are also defined in
#ifndef WCHAR_MIN // [
# define WCHAR_MIN 0
#endif // WCHAR_MIN ]
#ifndef WCHAR_MAX // [
# define WCHAR_MAX _UI16_MAX
#endif // WCHAR_MAX ]
#define WINT_MIN 0
#define WINT_MAX _UI16_MAX
#endif // __STDC_LIMIT_MACROS ]
// 7.18.4 Limits of other integer types
#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260
// 7.18.4.1 Macros for minimum-width integer constants
#define INT8_C(val) val##i8
#define INT16_C(val) val##i16
#define INT32_C(val) val##i32
#define INT64_C(val) val##i64
#define UINT8_C(val) val##ui8
#define UINT16_C(val) val##ui16
#define UINT32_C(val) val##ui32
#define UINT64_C(val) val##ui64
// 7.18.4.2 Macros for greatest-width integer constants
#define INTMAX_C INT64_C
#define UINTMAX_C UINT64_C
#endif // __STDC_CONSTANT_MACROS ]
#else
//sanity for everything else
#include
#endif
#endif
libgambatte/libretro/msvc/msvc-2003-xbox1.bat 000664 001750 001750 00000003042 12720365247 022037 0 ustar 00sergio sergio 000000 000000 @SET VSINSTALLDIR=C:\Program Files\Microsoft Visual Studio .NET 2003\Common7\IDE
@SET VCINSTALLDIR=C:\Program Files\Microsoft Visual Studio .NET 2003
@SET FrameworkDir=C:\WINDOWS\Microsoft.NET\Framework
@SET FrameworkVersion=v1.1.4322
@SET FrameworkSDKDir=C:\Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1
@rem Root of Visual Studio common files.
@if "%VSINSTALLDIR%"=="" goto Usage
@if "%VCINSTALLDIR%"=="" set VCINSTALLDIR=%VSINSTALLDIR%
@rem
@rem Root of Visual Studio ide installed files.
@rem
@set DevEnvDir=%VSINSTALLDIR%
@rem
@rem Root of Visual C++ installed files.
@rem
@set MSVCDir=%VCINSTALLDIR%\VC7
@rem
@echo Setting environment for using Microsoft Visual Studio .NET 2003 tools.
@echo (If you have another version of Visual Studio or Visual C++ installed and wish
@echo to use its tools from the command line, run vcvars32.bat for that version.)
@rem
@REM %VCINSTALLDIR%\Common7\Tools dir is added only for real setup.
@set PATH=%DevEnvDir%;%MSVCDir%\BIN;%VCINSTALLDIR%\Common7\Tools;%VCINSTALLDIR%\Common7\Tools\bin\prerelease;%VCINSTALLDIR%\Common7\Tools\bin;%FrameworkSDKDir%\bin;%FrameworkDir%\%FrameworkVersion%;%PATH%;
@set INCLUDE=%MSVCDir%\ATLMFC\INCLUDE;%MSVCDir%\INCLUDE;%FrameworkSDKDir%\include;%INCLUDE%;%XDK%\xbox\include
@set LIB=%MSVCDir%\ATLMFC\LIB;%MSVCDir%\LIB;%MSVCDir%\PlatformSDK\lib;%XDK%\lib;%XDK%\xbox\lib;%LIB%
@goto end
:Usage
@echo. VSINSTALLDIR variable is not set.
@echo.
@echo SYNTAX: %0
@goto end
:end
devenv /clean Release_LTCG msvc-2003-xbox1.sln
devenv /build Release_LTCG msvc-2003-xbox1.sln
exit
libgambatte/libretro/msvc/msvc-2010.sln 000664 001750 001750 00000001552 12720365247 021030 0 ustar 00sergio sergio 000000 000000 
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "msvc-2010", "msvc-2010/msvc-2010.vcxproj", "{A79F81F6-3FEE-48AA-9157-24EB772B624E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
Release|Win32 = Release|Win32
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A79F81F6-3FEE-48AA-9157-24EB772B624E}.Debug|Win32.ActiveCfg = Debug|Win32
{A79F81F6-3FEE-48AA-9157-24EB772B624E}.Debug|Win32.Build.0 = Debug|Win32
{A79F81F6-3FEE-48AA-9157-24EB772B624E}.Release|Win32.ActiveCfg = Release|Win32
{A79F81F6-3FEE-48AA-9157-24EB772B624E}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
libgambatte/libretro/blipper.c 000664 001750 001750 00000030432 12720365247 017612 0 ustar 00sergio sergio 000000 000000 /*
* Copyright (C) 2013 - Hans-Kristian Arntzen
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and
* associated documentation files (the "Software"),
* to deal in the Software without restriction,
* including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "blipper.h"
#include
#include
#include
#include
#if BLIPPER_LOG_PERFORMANCE
#include
static double get_time(void)
{
struct timespec tv;
clock_gettime(CLOCK_MONOTONIC, &tv);
return tv.tv_sec + tv.tv_nsec / 1000000000.0;
}
#endif
struct blipper
{
blipper_long_sample_t *output_buffer;
unsigned output_avail;
unsigned output_buffer_samples;
blipper_sample_t *filter_bank;
unsigned phase;
unsigned phases;
unsigned phases_log2;
unsigned taps;
blipper_long_sample_t integrator;
blipper_sample_t last_sample;
#if BLIPPER_LOG_PERFORMANCE
double total_time;
double integrator_time;
unsigned long total_samples;
#endif
int owns_filter;
};
void blipper_free(blipper_t *blip)
{
if (blip)
{
#if BLIPPER_LOG_PERFORMANCE
fprintf(stderr, "[blipper]: Processed %lu samples, using %.6f seconds blipping and %.6f seconds integrating.\n", blip->total_samples, blip->total_time, blip->integrator_time);
#endif
if (blip->owns_filter)
free(blip->filter_bank);
free(blip->output_buffer);
free(blip);
}
}
static double besseli0(double x)
{
unsigned i;
double sum = 0.0;
double factorial = 1.0;
double factorial_mult = 0.0;
double x_pow = 1.0;
double two_div_pow = 1.0;
double x_sqr = x * x;
/* Approximate. This is an infinite sum.
* Luckily, it converges rather fast. */
for (i = 0; i < 18; i++)
{
sum += x_pow * two_div_pow / (factorial * factorial);
factorial_mult += 1.0;
x_pow *= x_sqr;
two_div_pow *= 0.25;
factorial *= factorial_mult;
}
return sum;
}
static double sinc(double v)
{
if (fabs(v) < 0.00001)
return 1.0;
else
return sin(v) / v;
}
/* index range = [-1, 1) */
static double kaiser_window(double index, double beta)
{
return besseli0(beta * sqrt(1.0 - index * index));
}
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
static blipper_real_t *blipper_create_sinc(unsigned phases, unsigned taps,
double cutoff, double beta)
{
unsigned i, filter_len;
double sidelobes, window_mod;
blipper_real_t *filter;
filter = (blipper_real_t*)malloc(phases * taps * sizeof(*filter));
if (!filter)
return NULL;
sidelobes = taps / 2.0;
window_mod = 1.0 / kaiser_window(0.0, beta);
filter_len = phases * taps;
for (i = 0; i < filter_len; i++)
{
double sinc_phase;
double window_phase = (double)i / filter_len; /* [0, 1) */
window_phase = 2.0 * window_phase - 1.0; /* [-1, 1) */
sinc_phase = window_phase * sidelobes; /* [-taps / 2, taps / 2) */
filter[i] = cutoff * sinc(M_PI * sinc_phase * cutoff) *
kaiser_window(window_phase, beta) * window_mod;
}
return filter;
}
/* We differentiate and integrate at different sample rates.
* Differentiation is D(z) = 1 - z^-1 and happens when delta impulses
* are convolved. Integration step after decimation by D is 1 / (1 - z^-D).
*
* If our sinc filter is S(z) we'd have a response of
* S(z) * (1 - z^-1) / (1 - z^-D) after blipping.
*
* Compensate by prefiltering S(z) with the inverse (1 - z^-D) / (1 - z^-1).
* This filtering creates a finite length filter, albeit slightly longer.
*
* phases is the same as decimation rate. */
static blipper_real_t *blipper_prefilter_sinc(blipper_real_t *filter, unsigned phases,
unsigned taps)
{
unsigned i;
float filter_amp = 0.75f / phases;
blipper_real_t *tmp_filter;
blipper_real_t *new_filter = (blipper_real_t*)malloc((phases * taps + phases) * sizeof(*filter));
if (!new_filter)
goto error;
tmp_filter = (blipper_real_t*)realloc(filter, (phases * taps + phases) * sizeof(*filter));
if (!tmp_filter)
goto error;
filter = tmp_filter;
/* Integrate. */
new_filter[0] = filter[0];
for (i = 1; i < phases * taps; i++)
new_filter[i] = new_filter[i - 1] + filter[i];
for (i = phases * taps; i < phases * taps + phases; i++)
new_filter[i] = new_filter[phases * taps - 1];
taps++;
/* Differentiate with offset of D. */
memcpy(filter, new_filter, phases * sizeof(*filter));
for (i = phases; i < phases * taps; i++)
filter[i] = new_filter[i] - new_filter[i - phases];
/* blipper_prefilter_sinc() boosts the gain of the sinc.
* Have to compensate for this. Attenuate a bit more to ensure
* we don't clip, especially in fixed point. */
for (i = 0; i < phases * taps; i++)
filter[i] *= filter_amp;
free(new_filter);
return filter;
error:
free(new_filter);
free(filter);
return NULL;
}
/* Creates a polyphase filter bank.
* Interleaves the filter for cache coherency and possibilities
* for SIMD processing. */
static blipper_real_t *blipper_interleave_sinc(blipper_real_t *filter, unsigned phases,
unsigned taps)
{
unsigned t, p;
blipper_real_t *new_filter = (blipper_real_t*)malloc(phases * taps * sizeof(*filter));
if (!new_filter)
goto error;
for (t = 0; t < taps; t++)
for (p = 0; p < phases; p++)
new_filter[p * taps + t] = filter[t * phases + p];
free(filter);
return new_filter;
error:
free(new_filter);
free(filter);
return NULL;
}
#if BLIPPER_FIXED_POINT
static blipper_sample_t *blipper_quantize_sinc(blipper_real_t *filter, unsigned taps)
{
unsigned t;
blipper_sample_t *filt = (blipper_sample_t*)malloc(taps * sizeof(*filt));
if (!filt)
goto error;
for (t = 0; t < taps; t++)
filt[t] = (blipper_sample_t)floor(filter[t] * 0x7fff + 0.5);
free(filter);
return filt;
error:
free(filter);
free(filt);
return NULL;
}
#endif
blipper_sample_t *blipper_create_filter_bank(unsigned phases, unsigned taps,
double cutoff, double beta)
{
blipper_real_t *sinc_filter;
/* blipper_prefilter_sinc() will add one tap.
* To keep number of taps as expected, compensate for it here
* to keep the interface more obvious. */
if (taps <= 1)
return 0;
taps--;
sinc_filter = blipper_create_sinc(phases, taps, cutoff, beta);
if (!sinc_filter)
return 0;
sinc_filter = blipper_prefilter_sinc(sinc_filter, phases, taps);
if (!sinc_filter)
return 0;
taps++;
sinc_filter = blipper_interleave_sinc(sinc_filter, phases, taps);
if (!sinc_filter)
return 0;
#if BLIPPER_FIXED_POINT
return blipper_quantize_sinc(sinc_filter, phases * taps);
#else
return sinc_filter;
#endif
}
static unsigned log2_int(unsigned v)
{
unsigned ret;
v >>= 1;
for (ret = 0; v; v >>= 1, ret++);
return ret;
}
void blipper_reset(blipper_t *blip)
{
blip->phase = 0;
memset(blip->output_buffer, 0,
(blip->output_avail + blip->taps) * sizeof(*blip->output_buffer));
blip->output_avail = 0;
blip->last_sample = 0;
blip->integrator = 0;
}
blipper_t *blipper_new(unsigned taps, double cutoff, double beta,
unsigned decimation, unsigned buffer_samples,
const blipper_sample_t *filter_bank)
{
blipper_t *blip = NULL;
/* Sanity check. Not strictly required to be supported in C. */
if ((-3 >> 2) != -1)
{
fprintf(stderr, "Integer right shift not supported.\n");
return NULL;
}
if ((decimation & (decimation - 1)) != 0)
{
fprintf(stderr, "[blipper]: Decimation factor must be POT.\n");
return NULL;
}
blip = (blipper_t*)calloc(1, sizeof(*blip));
if (!blip)
return NULL;
blip->phases = decimation;
blip->phases_log2 = log2_int(decimation);
blip->taps = taps;
if (!filter_bank)
{
blip->filter_bank = blipper_create_filter_bank(blip->phases, taps, cutoff, beta);
if (!blip->filter_bank)
goto error;
blip->owns_filter = 1;
}
else
blip->filter_bank = (blipper_sample_t*)filter_bank;
blip->output_buffer = (blipper_long_sample_t*)calloc(buffer_samples + blip->taps,
sizeof(*blip->output_buffer));
if (!blip->output_buffer)
goto error;
blip->output_buffer_samples = buffer_samples + blip->taps;
return blip;
error:
blipper_free(blip);
return NULL;
}
void blipper_push_delta(blipper_t *blip, blipper_long_sample_t delta, unsigned clocks_step)
{
unsigned target_output, filter_phase, taps, i;
const blipper_sample_t *response;
blipper_long_sample_t *target;
blip->phase += clocks_step;
target_output = (blip->phase + blip->phases - 1) >> blip->phases_log2;
filter_phase = (target_output << blip->phases_log2) - blip->phase;
response = blip->filter_bank + blip->taps * filter_phase;
target = blip->output_buffer + target_output;
taps = blip->taps;
for (i = 0; i < taps; i++)
target[i] += delta * response[i];
blip->output_avail = target_output;
}
void blipper_push_samples(blipper_t *blip, const blipper_sample_t *data,
unsigned samples, unsigned stride)
{
unsigned s;
unsigned clocks_skip = 0;
blipper_sample_t last = blip->last_sample;
#if BLIPPER_LOG_PERFORMANCE
double t0 = get_time();
#endif
for (s = 0; s < samples; s++, data += stride)
{
blipper_sample_t val = *data;
if (val != last)
{
blipper_push_delta(blip, (blipper_long_sample_t)val - (blipper_long_sample_t)last, clocks_skip + 1);
clocks_skip = 0;
last = val;
}
else
clocks_skip++;
}
blip->phase += clocks_skip;
blip->output_avail = (blip->phase + blip->phases - 1) >> blip->phases_log2;
blip->last_sample = last;
#if BLIPPER_LOG_PERFORMANCE
blip->total_time += get_time() - t0;
blip->total_samples += samples;
#endif
}
unsigned blipper_read_avail(blipper_t *blip)
{
return blip->output_avail;
}
void blipper_read(blipper_t *blip, blipper_sample_t *output, unsigned samples,
unsigned stride)
{
unsigned s;
blipper_long_sample_t sum = blip->integrator;
const blipper_long_sample_t *out = blip->output_buffer;
#if BLIPPER_LOG_PERFORMANCE
double t0 = get_time();
#endif
#if BLIPPER_FIXED_POINT
for (s = 0; s < samples; s++, output += stride)
{
blipper_long_sample_t quant;
/* Cannot overflow. Also add a leaky integrator.
Mitigates DC shift numerical instability which is
inherent for integrators. */
sum += (out[s] >> 1) - (sum >> 9);
/* Rounded. With leaky integrator, this cannot overflow. */
quant = (sum + 0x4000) >> 15;
/* Clamp. quant can potentially have range [-0x10000, 0xffff] here.
* In both cases, top 16-bits will have a uniform bit pattern which can be exploited. */
if ((blipper_sample_t)quant != quant)
{
quant = (quant >> 16) ^ 0x7fff;
sum = quant << 15;
}
*output = quant;
}
#else
for (s = 0; s < samples; s++, output += stride)
{
/* Leaky integrator, same as fixed point (1.0f / 512.0f) */
sum += out[s] - sum * 0.00195f;
*output = sum;
}
#endif
/* Don't bother with ring buffering.
* The entire buffer should be read out ideally anyways. */
memmove(blip->output_buffer, blip->output_buffer + samples,
(blip->output_avail + blip->taps - samples) * sizeof(*out));
memset(blip->output_buffer + blip->taps, 0, samples * sizeof(*out));
blip->output_avail -= samples;
blip->phase -= samples << blip->phases_log2;
blip->integrator = sum;
#if BLIPPER_LOG_PERFORMANCE
blip->integrator_time += get_time() - t0;
#endif
}
libgambatte/libretro/msvc/msvc-2010-360.bat 000664 001750 001750 00000007767 12720365247 021326 0 ustar 00sergio sergio 000000 000000 @echo off
@echo Setting environment for using Microsoft Visual Studio 2010 x86 tools.
@call :GetVSCommonToolsDir
@if "%VS100COMNTOOLS%"=="" goto error_no_VS100COMNTOOLSDIR
@call "%VS100COMNTOOLS%VCVarsQueryRegistry.bat" 32bit No64bit
@if "%VSINSTALLDIR%"=="" goto error_no_VSINSTALLDIR
@if "%FrameworkDir32%"=="" goto error_no_FrameworkDIR32
@if "%FrameworkVersion32%"=="" goto error_no_FrameworkVer32
@if "%Framework35Version%"=="" goto error_no_Framework35Version
@set FrameworkDir=%FrameworkDir32%
@set FrameworkVersion=%FrameworkVersion32%
@if not "%WindowsSdkDir%" == "" (
@set "PATH=%WindowsSdkDir%bin\NETFX 4.0 Tools;%WindowsSdkDir%bin;%PATH%"
@set "INCLUDE=%WindowsSdkDir%include;%INCLUDE%"
@set "LIB=%WindowsSdkDir%lib;%LIB%"
)
@rem
@rem Root of Visual Studio IDE installed files.
@rem
@set DevEnvDir=%VSINSTALLDIR%Common7\IDE\
@rem PATH
@rem ----
@if exist "%VSINSTALLDIR%Team Tools\Performance Tools" (
@set "PATH=%VSINSTALLDIR%Team Tools\Performance Tools;%PATH%"
)
@if exist "%ProgramFiles%\HTML Help Workshop" set PATH=%ProgramFiles%\HTML Help Workshop;%PATH%
@if exist "%ProgramFiles(x86)%\HTML Help Workshop" set PATH=%ProgramFiles(x86)%\HTML Help Workshop;%PATH%
@if exist "%VCINSTALLDIR%VCPackages" set PATH=%VCINSTALLDIR%VCPackages;%PATH%
@set PATH=%FrameworkDir%%Framework35Version%;%PATH%
@set PATH=%FrameworkDir%%FrameworkVersion%;%PATH%
@set PATH=%VSINSTALLDIR%Common7\Tools;%PATH%
@if exist "%VCINSTALLDIR%BIN" set PATH=%VCINSTALLDIR%BIN;%PATH%
@set PATH=%DevEnvDir%;%PATH%
@if exist "%VSINSTALLDIR%VSTSDB\Deploy" (
@set "PATH=%VSINSTALLDIR%VSTSDB\Deploy;%PATH%"
)
@if not "%FSHARPINSTALLDIR%" == "" (
@set "PATH=%FSHARPINSTALLDIR%;%PATH%"
)
@rem INCLUDE
@rem -------
@if exist "%VCINSTALLDIR%ATLMFC\INCLUDE" set INCLUDE=%VCINSTALLDIR%ATLMFC\INCLUDE;%INCLUDE%
@if exist "%VCINSTALLDIR%INCLUDE" set INCLUDE=%VCINSTALLDIR%INCLUDE;%INCLUDE%
@rem LIB
@rem ---
@if exist "%VCINSTALLDIR%ATLMFC\LIB" set LIB=%VCINSTALLDIR%ATLMFC\LIB;%LIB%
@if exist "%VCINSTALLDIR%LIB" set LIB=%VCINSTALLDIR%LIB;%LIB%
@rem LIBPATH
@rem -------
@if exist "%VCINSTALLDIR%ATLMFC\LIB" set LIBPATH=%VCINSTALLDIR%ATLMFC\LIB;%LIBPATH%
@if exist "%VCINSTALLDIR%LIB" set LIBPATH=%VCINSTALLDIR%LIB;%LIBPATH%
@set LIBPATH=%FrameworkDir%%Framework35Version%;%LIBPATH%
@set LIBPATH=%FrameworkDir%%FrameworkVersion%;%LIBPATH%
@goto end
@REM -----------------------------------------------------------------------
:GetVSCommonToolsDir
@set VS100COMNTOOLS=
@call :GetVSCommonToolsDirHelper32 HKLM > nul 2>&1
@if errorlevel 1 call :GetVSCommonToolsDirHelper32 HKCU > nul 2>&1
@if errorlevel 1 call :GetVSCommonToolsDirHelper64 HKLM > nul 2>&1
@if errorlevel 1 call :GetVSCommonToolsDirHelper64 HKCU > nul 2>&1
@exit /B 0
:GetVSCommonToolsDirHelper32
@for /F "tokens=1,2*" %%i in ('reg query "%1\SOFTWARE\Microsoft\VisualStudio\SxS\VS7" /v "10.0"') DO (
@if "%%i"=="10.0" (
@SET "VS100COMNTOOLS=%%k"
)
)
@if "%VS100COMNTOOLS%"=="" exit /B 1
@SET "VS100COMNTOOLS=%VS100COMNTOOLS%Common7\Tools\"
@exit /B 0
:GetVSCommonToolsDirHelper64
@for /F "tokens=1,2*" %%i in ('reg query "%1\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\SxS\VS7" /v "10.0"') DO (
@if "%%i"=="10.0" (
@SET "VS100COMNTOOLS=%%k"
)
)
@if "%VS100COMNTOOLS%"=="" exit /B 1
@SET "VS100COMNTOOLS=%VS100COMNTOOLS%Common7\Tools\"
@exit /B 0
@REM -----------------------------------------------------------------------
:error_no_VS100COMNTOOLSDIR
@echo ERROR: Cannot determine the location of the VS Common Tools folder.
@goto end
:error_no_VSINSTALLDIR
@echo ERROR: Cannot determine the location of the VS installation.
@goto end
:error_no_FrameworkDIR32
@echo ERROR: Cannot determine the location of the .NET Framework 32bit installation.
@goto end
:error_no_FrameworkVer32
@echo ERROR: Cannot determine the version of the .NET Framework 32bit installation.
@goto end
:error_no_Framework35Version
@echo ERROR: Cannot determine the .NET Framework 3.5 version.
@goto end
:end
msbuild msvc-2010-360.sln /p:Configuration=Release_LTCG /target:clean
msbuild msvc-2010-360.sln /p:Configuration=Release_LTCG
exit
libgambatte/src/sound/length_counter.cpp 000664 001750 001750 00000004451 12720365247 021634 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2007 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#include "length_counter.h"
#include "master_disabler.h"
#include
namespace gambatte {
LengthCounter::LengthCounter(MasterDisabler &disabler, unsigned const mask)
: disableMaster_(disabler)
, lengthCounter_(0)
, lengthMask_(mask)
{
nr1Change(0, 0, 0);
}
void LengthCounter::event() {
counter_ = counter_disabled;
lengthCounter_ = 0;
disableMaster_();
}
void LengthCounter::nr1Change(unsigned const newNr1, unsigned const nr4, unsigned long const cc) {
lengthCounter_ = (~newNr1 & lengthMask_) + 1;
counter_ = (nr4 & 0x40)
? ((cc >> 13) + lengthCounter_) << 13
: static_cast(counter_disabled);
}
void LengthCounter::nr4Change(unsigned const oldNr4, unsigned const newNr4, unsigned long const cc) {
if (counter_ != counter_disabled)
lengthCounter_ = (counter_ >> 13) - (cc >> 13);
{
unsigned dec = 0;
if (newNr4 & 0x40) {
dec = ~cc >> 12 & 1;
if (!(oldNr4 & 0x40) && lengthCounter_) {
if (!(lengthCounter_ -= dec))
disableMaster_();
}
}
if ((newNr4 & 0x80) && !lengthCounter_)
lengthCounter_ = lengthMask_ + 1 - dec;
}
if ((newNr4 & 0x40) && lengthCounter_)
counter_ = ((cc >> 13) + lengthCounter_) << 13;
else
counter_ = counter_disabled;
}
void LengthCounter::saveState(SaveState::SPU::LCounter &lstate) const {
lstate.counter = counter_;
lstate.lengthCounter = lengthCounter_;
}
void LengthCounter::loadState(SaveState::SPU::LCounter const &lstate, unsigned long const cc) {
counter_ = std::max(lstate.counter, cc);
lengthCounter_ = lstate.lengthCounter;
}
}
libgambatte/src/mem/memptrs.h 000664 001750 001750 00000011314 12720365247 017372 0 ustar 00sergio sergio 000000 000000 /***************************************************************************
* Copyright (C) 2007-2010 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* This program 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 General Public License version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef MEMPTRS_H
#define MEMPTRS_H
namespace gambatte
{
enum OamDmaSrc { oam_dma_src_rom,
oam_dma_src_sram,
oam_dma_src_vram,
oam_dma_src_wram,
oam_dma_src_invalid,
oam_dma_src_off, };
class MemPtrs
{
public:
enum RamFlag
{
READ_EN = 1,
WRITE_EN = 2,
RTC_EN = 4
};
MemPtrs();
~MemPtrs();
void reset(unsigned rombanks, unsigned rambanks, unsigned wrambanks);
const unsigned char * rmem(unsigned area) const
{
return rmem_[area];
}
unsigned char * wmem(unsigned area) const
{
return wmem_[area];
}
unsigned char * vramdata() const
{
return rambankdata_ - 0x4000;
}
unsigned char * vramdataend() const
{
return rambankdata_;
}
unsigned char * romdata() const
{
return memchunk_ + 0x4000;
}
unsigned char * romdata(unsigned area) const
{
return romdata_[area];
}
unsigned char * romdataend() const
{
return rambankdata_ - 0x4000;
}
unsigned char * wramdata(unsigned area) const
{
return wramdata_[area];
}
unsigned char * wramdataend() const
{
return wramdataend_;
}
unsigned char * rambankdata() const
{
return rambankdata_;
}
unsigned char * rambankdataend() const
{
return wramdata_[0];
}
const unsigned char * rdisabledRam() const
{
return rdisabledRamw();
}
const unsigned char * rsrambankptr() const
{
return rsrambankptr_;
}
unsigned char * wsrambankptr() const
{
return wsrambankptr_;
}
unsigned char * vrambankptr() const
{
return vrambankptr_;
}
OamDmaSrc oamDmaSrc() const
{
return oamDmaSrc_;
}
void setRombank0(unsigned bank);
void setRombank(unsigned bank);
void setRambank(unsigned ramFlags, unsigned rambank);
void setVrambank(unsigned bank) { vrambankptr_ = vramdata() + bank * 0x2000ul - 0x8000; }
void setWrambank(unsigned bank);
void setOamDmaSrc(OamDmaSrc oamDmaSrc);
private:
unsigned char *romdata_[2];
unsigned char *wramdata_[2];
const unsigned char *rmem_[0x10];
unsigned char *wmem_[0x10];
unsigned char *vrambankptr_;
unsigned char *rsrambankptr_;
unsigned char *wsrambankptr_;
unsigned char *memchunk_;
unsigned char *rambankdata_;
unsigned char *wramdataend_;
OamDmaSrc oamDmaSrc_;
MemPtrs(const MemPtrs &);
MemPtrs & operator=(const MemPtrs &);
void disconnectOamDmaAreas();
unsigned char * rdisabledRamw() const { return wramdataend_ ; }
unsigned char * wdisabledRam() const { return wramdataend_ + 0x2000; }
};
inline bool isCgb(const MemPtrs &memptrs)
{
return memptrs.wramdataend() - memptrs.wramdata(0) == 0x8000;
}
}
#endif
libgambatte/src/sound/channel2.h 000664 001750 001750 00000003434 12720365247 017753 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2007 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#ifndef SOUND_CHANNEL2_H
#define SOUND_CHANNEL2_H
#include "duty_unit.h"
#include "envelope_unit.h"
#include "gbint.h"
#include "length_counter.h"
#include "static_output_tester.h"
namespace gambatte {
struct SaveState;
class Channel2 {
public:
Channel2();
void setNr1(unsigned data);
void setNr2(unsigned data);
void setNr3(unsigned data);
void setNr4(unsigned data);
void setSo(unsigned long soMask);
bool isActive() const { return master_; }
void update(uint_least32_t *buf, unsigned long soBaseVol, unsigned long cycles);
void reset();
void saveState(SaveState &state);
void loadState(SaveState const &state);
private:
friend class StaticOutputTester;
StaticOutputTester staticOutputTest_;
DutyMasterDisabler disableMaster_;
LengthCounter lengthCounter_;
DutyUnit dutyUnit_;
EnvelopeUnit envelopeUnit_;
SoundUnit *nextEventUnit;
unsigned long cycleCounter_;
unsigned long soMask_;
unsigned long prevOut_;
unsigned char nr4_;
bool master_;
void setEvent();
};
}
#endif
libgambatte/src/mem/rtc.h 000664 001750 001750 00000006122 12720365247 016474 0 ustar 00sergio sergio 000000 000000 /***************************************************************************
* Copyright (C) 2007 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* This program 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 General Public License version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef RTC_H
#define RTC_H
#include
#include
namespace gambatte
{
struct SaveState;
class Rtc
{
public:
Rtc();
const unsigned char* getActive() const
{
return activeData_;
}
uint64_t& getBaseTime()
{
return baseTime_;
}
void setBaseTime(const uint64_t baseTime)
{
baseTime_ = baseTime;
}
void latch(const unsigned data)
{
if (!lastLatchData_ && data == 1)
doLatch();
lastLatchData_ = data;
}
void saveState(SaveState &state) const;
void loadState(const SaveState &state);
void set(const bool enabled, unsigned bank)
{
bank &= 0xF;
bank -= 8;
this->enabled_ = enabled;
this->index_ = bank;
doSwapActive();
}
void write(const unsigned data)
{
(this->*activeSet_)(data);
*activeData_ = data;
}
private:
unsigned char *activeData_;
void (Rtc::*activeSet_)(unsigned);
uint64_t baseTime_;
uint64_t haltTime_;
unsigned char index_;
unsigned char dataDh_;
unsigned char dataDl_;
unsigned char dataH_;
unsigned char dataM_;
unsigned char dataS_;
bool enabled_;
bool lastLatchData_;
void doLatch();
void doSwapActive();
void setDh(unsigned new_dh);
void setDl(unsigned new_lowdays);
void setH(unsigned new_hours);
void setM(unsigned new_minutes);
void setS(unsigned new_seconds);
};
}
#endif
libgambatte/src/sound/master_disabler.h 000664 001750 001750 00000002043 12720365247 021414 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2007 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#ifndef MASTER_DISABLER_H
#define MASTER_DISABLER_H
namespace gambatte {
class MasterDisabler {
public:
explicit MasterDisabler(bool &master) : master_(master) {}
virtual ~MasterDisabler() {}
virtual void operator()() { master_ = false; }
private:
bool &master_;
};
}
#endif
libgambatte/src/interrupter.cpp 000664 001750 001750 00000004241 12720365247 020044 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2007 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#include "interrupter.h"
#include "gambatte-memory.h"
namespace gambatte {
Interrupter::Interrupter(unsigned short &sp, unsigned short &pc)
: sp_(sp)
, pc_(pc)
{
}
unsigned long Interrupter::interrupt(unsigned const address, unsigned long cc, Memory &memory) {
cc += 8;
sp_ = (sp_ - 1) & 0xFFFF;
memory.write(sp_, pc_ >> 8, cc);
cc += 4;
sp_ = (sp_ - 1) & 0xFFFF;
memory.write(sp_, pc_ & 0xFF, cc);
pc_ = address;
cc += 8;
if (address == 0x40 && !gsCodes_.empty())
applyVblankCheats(cc, memory);
return cc;
}
static int asHex(char c) {
return c >= 'A' ? c - 'A' + 0xA : c - '0';
}
void Interrupter::setGameShark(std::string const &codes) {
std::string code;
gsCodes_.clear();
for (std::size_t pos = 0; pos < codes.length(); pos += code.length() + 1) {
code = codes.substr(pos, codes.find(';', pos) - pos);
if (code.length() >= 8) {
GsCode gs;
gs.type = asHex(code[0]) << 4 | asHex(code[1]);
gs.value = (asHex(code[2]) << 4 | asHex(code[3])) & 0xFF;
gs.address = ( asHex(code[4]) << 4
| asHex(code[5])
| asHex(code[6]) << 12
| asHex(code[7]) << 8) & 0xFFFF;
gsCodes_.push_back(gs);
}
}
}
void Interrupter::applyVblankCheats(unsigned long const cc, Memory &memory) {
for (std::size_t i = 0, size = gsCodes_.size(); i < size; ++i) {
if (gsCodes_[i].type == 0x01)
memory.write(gsCodes_[i].address, gsCodes_[i].value, cc);
}
}
}
libgambatte/libretro/ 000700 001750 001750 00000000000 12720366157 015774 5 ustar 00sergio sergio 000000 000000 libgambatte/src/video/lyc_irq.h 000664 001750 001750 00000003451 12720365247 017700 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2007 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#ifndef VIDEO_LYC_IRQ_H
#define VIDEO_LYC_IRQ_H
namespace gambatte {
struct SaveState;
class LyCounter;
class LycIrq {
public:
LycIrq();
void doEvent(unsigned char *ifreg, LyCounter const &lyCounter);
unsigned lycReg() const { return lycRegSrc_; }
void loadState(SaveState const &state);
void saveState(SaveState &state) const;
unsigned long time() const { return time_; }
void setCgb(bool cgb) { cgb_ = cgb; }
void lcdReset();
void reschedule(LyCounter const &lyCounter, unsigned long cc);
void statRegChange(unsigned statReg, LyCounter const &lyCounter, unsigned long cc) {
regChange(statReg, lycRegSrc_, lyCounter, cc);
}
void lycRegChange(unsigned lycReg, LyCounter const &lyCounter, unsigned long cc) {
regChange(statRegSrc_, lycReg, lyCounter, cc);
}
private:
unsigned long time_;
unsigned char lycRegSrc_;
unsigned char statRegSrc_;
unsigned char lycReg_;
unsigned char statReg_;
bool cgb_;
void regChange(unsigned statReg, unsigned lycReg,
LyCounter const &lyCounter, unsigned long cc);
};
}
#endif
libgambatte/src/sound.h 000664 001750 001750 00000005652 12720365247 016265 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2007 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#ifndef SOUND_H
#define SOUND_H
#include
#include
#include "sound/channel1.h"
#include "sound/channel2.h"
#include "sound/channel3.h"
#include "sound/channel4.h"
namespace gambatte {
class PSG {
public:
PSG();
void init(bool cgb);
void reset();
void setStatePtrs(SaveState &state);
void saveState(SaveState &state);
void loadState(SaveState const &state);
void generateSamples(unsigned long cycleCounter, bool doubleSpeed);
void resetCounter(unsigned long newCc, unsigned long oldCc, bool doubleSpeed);
std::size_t fillBuffer();
void setBuffer(uint_least32_t *buf) { buffer_ = buf; bufferPos_ = 0; }
bool isEnabled() const { return enabled_; }
void setEnabled(bool value) { enabled_ = value; }
void setNr10(unsigned data) { ch1_.setNr0(data); }
void setNr11(unsigned data) { ch1_.setNr1(data); }
void setNr12(unsigned data) { ch1_.setNr2(data); }
void setNr13(unsigned data) { ch1_.setNr3(data); }
void setNr14(unsigned data) { ch1_.setNr4(data); }
void setNr21(unsigned data) { ch2_.setNr1(data); }
void setNr22(unsigned data) { ch2_.setNr2(data); }
void setNr23(unsigned data) { ch2_.setNr3(data); }
void setNr24(unsigned data) { ch2_.setNr4(data); }
void setNr30(unsigned data) { ch3_.setNr0(data); }
void setNr31(unsigned data) { ch3_.setNr1(data); }
void setNr32(unsigned data) { ch3_.setNr2(data); }
void setNr33(unsigned data) { ch3_.setNr3(data); }
void setNr34(unsigned data) { ch3_.setNr4(data); }
unsigned waveRamRead(unsigned index) const { return ch3_.waveRamRead(index); }
void waveRamWrite(unsigned index, unsigned data) { ch3_.waveRamWrite(index, data); }
void setNr41(unsigned data) { ch4_.setNr1(data); }
void setNr42(unsigned data) { ch4_.setNr2(data); }
void setNr43(unsigned data) { ch4_.setNr3(data); }
void setNr44(unsigned data) { ch4_.setNr4(data); }
void setSoVolume(unsigned nr50);
void mapSo(unsigned nr51);
unsigned getStatus() const;
private:
Channel1 ch1_;
Channel2 ch2_;
Channel3 ch3_;
Channel4 ch4_;
uint_least32_t *buffer_;
std::size_t bufferPos_;
unsigned long lastUpdate_;
unsigned long soVol_;
uint_least32_t rsum_;
bool enabled_;
void accumulateChannels(unsigned long cycles);
};
}
#endif
libgambatte/src/mem/memptrs.cpp 000664 001750 001750 00000013450 12720365247 017730 0 ustar 00sergio sergio 000000 000000 /***************************************************************************
* Copyright (C) 2007-2010 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* This program 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 General Public License version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "memptrs.h"
#include
#include
namespace gambatte
{
MemPtrs::MemPtrs()
: rmem_()
, wmem_()
, romdata_()
, wramdata_()
, vrambankptr_(0)
, rsrambankptr_(0)
, wsrambankptr_(0)
,memchunk_(0)
, rambankdata_(0)
, wramdataend_(0)
, oamDmaSrc_(oam_dma_src_off)
{
}
MemPtrs::~MemPtrs()
{
delete []memchunk_;
}
void MemPtrs::reset(const unsigned rombanks, const unsigned rambanks, const unsigned wrambanks)
{
delete []memchunk_;
memchunk_ = new unsigned char[
0x4000
+ rombanks * 0x4000ul + 0x4000
+ rambanks * 0x2000ul
+ wrambanks * 0x1000ul
+ 0x4000];
romdata_[0] = romdata();
rambankdata_ = romdata_[0] + rombanks * 0x4000ul + 0x4000;
wramdata_[0] = rambankdata_ + rambanks * 0x2000ul;
wramdataend_ = wramdata_[0] + wrambanks * 0x1000ul;
std::memset(rdisabledRamw(), 0xFF, 0x2000);
oamDmaSrc_ = oam_dma_src_off;
rmem_[0x3] = rmem_[0x2] = rmem_[0x1] = rmem_[0x0] = romdata_[0];
rmem_[0xC] = wmem_[0xC] = wramdata_[0] - 0xC000;
rmem_[0xE] = wmem_[0xE] = wramdata_[0] - 0xE000;
setRombank(1);
setRambank(0, 0);
setVrambank(0);
setWrambank(1);
}
void MemPtrs::setRombank0(const unsigned bank)
{
romdata_[0] = romdata() + bank * 0x4000ul;
rmem_[0x3] = rmem_[0x2] = rmem_[0x1] = rmem_[0x0] = romdata_[0];
disconnectOamDmaAreas();
}
void MemPtrs::setRombank(const unsigned bank)
{
romdata_[1] = romdata() + bank * 0x4000ul - 0x4000;
rmem_[0x7] = rmem_[0x6] = rmem_[0x5] = rmem_[0x4] = romdata_[1];
disconnectOamDmaAreas();
}
void MemPtrs::setRambank(const unsigned flags, const unsigned rambank)
{
unsigned char *const srambankptr = (flags & RTC_EN)
? 0
: (rambankdata() != rambankdataend()
? rambankdata_ + rambank * 0x2000ul - 0xA000 : wdisabledRam() - 0xA000);
rsrambankptr_ = (flags & READ_EN) && srambankptr != wdisabledRam() - 0xA000 ? srambankptr : rdisabledRamw() - 0xA000;
wsrambankptr_ = (flags & WRITE_EN) ? srambankptr : wdisabledRam() - 0xA000;
rmem_[0xB] = rmem_[0xA] = rsrambankptr_;
wmem_[0xB] = wmem_[0xA] = wsrambankptr_;
disconnectOamDmaAreas();
}
void MemPtrs::setWrambank(const unsigned bank)
{
wramdata_[1] = wramdata_[0] + ((bank & 0x07) ? (bank & 0x07) : 1) * 0x1000;
rmem_[0xD] = wmem_[0xD] = wramdata_[1] - 0xD000;
disconnectOamDmaAreas();
}
void MemPtrs::setOamDmaSrc(const OamDmaSrc oamDmaSrc)
{
rmem_[0x3] = rmem_[0x2] = rmem_[0x1] = rmem_[0x0] = romdata_[0];
rmem_[0x7] = rmem_[0x6] = rmem_[0x5] = rmem_[0x4] = romdata_[1];
rmem_[0xB] = rmem_[0xA] = rsrambankptr_;
wmem_[0xB] = wmem_[0xA] = wsrambankptr_;
rmem_[0xC] = wmem_[0xC] = wramdata_[0] - 0xC000;
rmem_[0xD] = wmem_[0xD] = wramdata_[1] - 0xD000;
rmem_[0xE] = wmem_[0xE] = wramdata_[0] - 0xE000;
oamDmaSrc_ = oamDmaSrc;
disconnectOamDmaAreas();
}
void MemPtrs::disconnectOamDmaAreas()
{
if (isCgb(*this))
{
switch (oamDmaSrc_)
{
case oam_dma_src_rom: // fall through
case oam_dma_src_sram:
case oam_dma_src_invalid:
std::fill(rmem_, rmem_ + 8, static_cast(0));
rmem_[0xB] = rmem_[0xA] = 0;
wmem_[0xB] = wmem_[0xA] = 0;
break;
case oam_dma_src_vram:
break;
case oam_dma_src_wram:
rmem_[0xE] = rmem_[0xD] = rmem_[0xC] = 0;
wmem_[0xE] = wmem_[0xD] = wmem_[0xC] = 0;
break;
case oam_dma_src_off:
break;
}
}
else
{
switch (oamDmaSrc_)
{
case oam_dma_src_rom: // fall through
case oam_dma_src_sram:
case oam_dma_src_wram:
case oam_dma_src_invalid:
std::fill(rmem_, rmem_ + 8, static_cast(0));
rmem_[0xB] = rmem_[0xA] = 0;
wmem_[0xB] = wmem_[0xA] = 0;
rmem_[0xE] = rmem_[0xD] = rmem_[0xC] = 0;
wmem_[0xE] = wmem_[0xD] = wmem_[0xC] = 0;
break;
case oam_dma_src_vram:
break;
case oam_dma_src_off:
break;
}
}
}
}
libgambatte/src/sound/envelope_unit.cpp 000664 001750 001750 00000004364 12720365247 021473 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2007 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#include "envelope_unit.h"
#include
namespace gambatte {
EnvelopeUnit::VolOnOffEvent EnvelopeUnit::nullEvent_;
EnvelopeUnit::EnvelopeUnit(VolOnOffEvent &volOnOffEvent)
: volOnOffEvent_(volOnOffEvent)
, nr2_(0)
, volume_(0)
{
}
void EnvelopeUnit::reset() {
counter_ = counter_disabled;
}
void EnvelopeUnit::saveState(SaveState::SPU::Env &estate) const {
estate.counter = counter_;
estate.volume = volume_;
}
void EnvelopeUnit::loadState(SaveState::SPU::Env const &estate, unsigned nr2, unsigned long cc) {
counter_ = std::max(estate.counter, cc);
volume_ = estate.volume;
nr2_ = nr2;
}
void EnvelopeUnit::event() {
unsigned long const period = nr2_ & 7;
if (period) {
unsigned newVol = volume_;
if (nr2_ & 8)
++newVol;
else
--newVol;
if (newVol < 0x10U) {
volume_ = newVol;
if (volume_ < 2)
volOnOffEvent_(counter_);
counter_ += period << 15;
} else
counter_ = counter_disabled;
} else
counter_ += 8ul << 15;
}
bool EnvelopeUnit::nr2Change(unsigned const newNr2) {
if (!(nr2_ & 7) && counter_ != counter_disabled)
++volume_;
else if (!(nr2_ & 8))
volume_ += 2;
if ((nr2_ ^ newNr2) & 8)
volume_ = 0x10 - volume_;
volume_ &= 0xF;
nr2_ = newNr2;
return !(newNr2 & 0xF8);
}
bool EnvelopeUnit::nr4Init(unsigned long const cc) {
unsigned long period = (nr2_ & 7) ? nr2_ & 7 : 8;
if (((cc + 2) & 0x7000) == 0x0000)
++period;
counter_ = cc - ((cc - 0x1000) & 0x7FFF) + period * 0x8000;
volume_ = nr2_ >> 4;
return !(nr2_ & 0xF8);
}
}
libgambatte/src/counterdef.h 000664 001750 001750 00000000163 12720365247 017263 0 ustar 00sergio sergio 000000 000000 #ifndef COUNTERDEF_H
#define COUNTERDEF_H
namespace gambatte {
enum { disabled_time = 0xfffffffful };
}
#endif
libgambatte/libretro/jni/Application.mk 000664 001750 001750 00000000051 12720365247 021357 0 ustar 00sergio sergio 000000 000000 APP_STL := gnustl_static
APP_ABI := all
libgambatte/src/gambatte.cpp 000664 001750 001750 00000011006 12720365247 017242 0 ustar 00sergio sergio 000000 000000 /***************************************************************************
* Copyright (C) 2007 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* This program 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 General Public License version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "gambatte.h"
#include "cpu.h"
#include "savestate.h"
#include "statesaver.h"
#include "initstate.h"
#include
namespace gambatte {
struct GB::Priv {
CPU cpu;
int stateNo;
bool gbaCgbMode;
Priv() : stateNo(1), gbaCgbMode(false) {}
void on_load_succeeded(unsigned flags);
};
GB::GB() : p_(new Priv) {}
GB::~GB() {
delete p_;
}
long GB::runFor(gambatte::video_pixel_t *const videoBuf, const int pitch,
gambatte::uint_least32_t *const soundBuf, unsigned &samples) {
p_->cpu.setVideoBuffer(videoBuf, pitch);
p_->cpu.setSoundBuffer(soundBuf);
const long cyclesSinceBlit = p_->cpu.runFor(samples * 2);
samples = p_->cpu.fillSoundBuffer();
return cyclesSinceBlit < 0 ? cyclesSinceBlit : static_cast(samples) - (cyclesSinceBlit >> 1);
}
void GB::reset() {
SaveState state;
p_->cpu.setStatePtrs(state);
setInitState(state, p_->cpu.isCgb(), p_->gbaCgbMode);
p_->cpu.loadState(state);
}
void GB::setInputGetter(InputGetter *getInput) {
p_->cpu.setInputGetter(getInput);
}
void GB::Priv::on_load_succeeded(unsigned flags)
{
SaveState state;
cpu.setStatePtrs(state);
setInitState(state, cpu.isCgb(), gbaCgbMode = flags & GBA_CGB);
cpu.loadState(state);
stateNo = 1;
}
void *GB::savedata_ptr() { return p_->cpu.savedata_ptr(); }
unsigned GB::savedata_size() { return p_->cpu.savedata_size(); }
void *GB::rtcdata_ptr() { return p_->cpu.rtcdata_ptr(); }
unsigned GB::rtcdata_size() { return p_->cpu.rtcdata_size(); }
int GB::load(const void *romdata, unsigned romsize, const unsigned flags) {
const int failed = p_->cpu.load(romdata, romsize, flags & FORCE_DMG, flags & MULTICART_COMPAT);
if (!failed)
p_->on_load_succeeded(flags);
return failed;
}
bool GB::isCgb() const {
return p_->cpu.isCgb();
}
bool GB::isLoaded() const {
return true;
}
void GB::setDmgPaletteColor(unsigned palNum, unsigned colorNum, unsigned rgb32) {
p_->cpu.setDmgPaletteColor(palNum, colorNum, rgb32);
}
void GB::loadState(const void *data) {
SaveState state;
p_->cpu.setStatePtrs(state);
if (StateSaver::loadState(state, data)) {
p_->cpu.loadState(state);
}
}
void GB::saveState(void *data) {
SaveState state;
p_->cpu.setStatePtrs(state);
p_->cpu.saveState(state);
StateSaver::saveState(state, data);
}
size_t GB::stateSize() const {
SaveState state;
p_->cpu.setStatePtrs(state);
p_->cpu.saveState(state);
return StateSaver::stateSize(state);
}
void GB::setColorCorrection(bool enable) {
p_->cpu.mem_.display_setColorCorrection(enable);
}
video_pixel_t GB::gbcToRgb32(const unsigned bgr15) {
return p_->cpu.mem_.display_gbcToRgb32(bgr15);
}
void GB::setGameGenie(const std::string &codes) {
p_->cpu.setGameGenie(codes);
}
void GB::setGameShark(const std::string &codes) {
p_->cpu.setGameShark(codes);
}
void GB::clearCheats() {
p_->cpu.clearCheats();
}
#ifdef __LIBRETRO__
void *GB::vram_ptr() const {
return p_->cpu.vram_ptr();
}
void *GB::rambank0_ptr() const {
return p_->cpu.rambank0_ptr();
}
void *GB::rambank1_ptr() const {
return p_->cpu.rambank1_ptr();
}
void *GB::rombank0_ptr() const {
return p_->cpu.rombank0_ptr();
}
void *GB::rombank1_ptr() const {
return p_->cpu.rombank1_ptr();
}
#endif
}
libgambatte/src/video/sprite_mapper.h 000664 001750 001750 00000010303 12720365247 021102 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2007 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#ifndef SPRITE_MAPPER_H
#define SPRITE_MAPPER_H
#include "ly_counter.h"
#include "../savestate.h"
namespace gambatte {
class NextM0Time;
class SpriteMapper {
public:
SpriteMapper(NextM0Time &nextM0Time,
LyCounter const &lyCounter,
unsigned char const *oamram);
void reset(unsigned char const *oamram, bool cgb);
unsigned long doEvent(unsigned long time);
bool largeSprites(unsigned spNo) const { return oamReader_.largeSprites(spNo); }
unsigned numSprites(unsigned ly) const { return num_[ly] & ~need_sorting_mask; }
void oamChange(unsigned long cc) { oamReader_.change(cc); }
void oamChange(unsigned char const *oamram, unsigned long cc) { oamReader_.change(oamram, cc); }
unsigned char const * oamram() const { return oamReader_.oam(); }
unsigned char const * posbuf() const { return oamReader_.spritePosBuf(); }
void preSpeedChange(unsigned long cc) { oamReader_.update(cc); }
void postSpeedChange(unsigned long cc) { oamReader_.change(cc); }
void resetCycleCounter(unsigned long oldCc, unsigned long newCc) {
oamReader_.update(oldCc);
oamReader_.resetCycleCounter(oldCc, newCc);
}
void setLargeSpritesSource(bool src) { oamReader_.setLargeSpritesSrc(src); }
unsigned char const * sprites(unsigned ly) const {
if (num_[ly] & need_sorting_mask)
sortLine(ly);
return spritemap_ + ly * 10;
}
void setStatePtrs(SaveState &state) { oamReader_.setStatePtrs(state); }
void enableDisplay(unsigned long cc) { oamReader_.enableDisplay(cc); }
void saveState(SaveState &state) const { oamReader_.saveState(state); }
void loadState(SaveState const &state, unsigned char const *oamram) {
oamReader_.loadState(state, oamram);
mapSprites();
}
bool inactivePeriodAfterDisplayEnable(unsigned long cc) const {
return oamReader_.inactivePeriodAfterDisplayEnable(cc);
}
static unsigned long schedule(LyCounter const &lyCounter, unsigned long cc) {
return lyCounter.nextLineCycle(80, cc);
}
private:
class OamReader {
public:
OamReader(LyCounter const &lyCounter, unsigned char const *oamram);
void reset(unsigned char const *oamram, bool cgb);
void change(unsigned long cc);
void change(unsigned char const *oamram, unsigned long cc) { change(cc); oamram_ = oamram; }
bool changed() const { return lastChange_ != 0xFF; }
bool largeSprites(unsigned spNo) const { return szbuf_[spNo]; }
unsigned char const * oam() const { return oamram_; }
void resetCycleCounter(unsigned long oldCc, unsigned long newCc) { lu_ -= oldCc - newCc; }
void setLargeSpritesSrc(bool src) { largeSpritesSrc_ = src; }
void update(unsigned long cc);
unsigned char const * spritePosBuf() const { return buf_; }
void setStatePtrs(SaveState &state);
void enableDisplay(unsigned long cc);
void saveState(SaveState &state) const { state.ppu.enableDisplayM0Time = lu_; }
void loadState(SaveState const &ss, unsigned char const *oamram);
bool inactivePeriodAfterDisplayEnable(unsigned long cc) const { return cc < lu_; }
unsigned lineTime() const { return lyCounter_.lineTime(); }
private:
unsigned char buf_[80];
bool szbuf_[40];
LyCounter const &lyCounter_;
unsigned char const *oamram_;
unsigned long lu_;
unsigned char lastChange_;
bool largeSpritesSrc_;
bool cgb_;
};
enum { need_sorting_mask = 0x80 };
mutable unsigned char spritemap_[144 * 10];
mutable unsigned char num_[144];
NextM0Time &nextM0Time_;
OamReader oamReader_;
void clearMap();
void mapSprites();
void sortLine(unsigned ly) const;
};
}
#endif
libgambatte/libretro/msvc/msvc-2010-360/msvc-2010-360.vcxproj 000664 001750 001750 00000037241 12720365247 024077 0 ustar 00sergio sergio 000000 000000 
CodeAnalysisXbox 360DebugXbox 360ProfileXbox 360Profile_FastCapXbox 360ReleaseXbox 360Release_LTCGXbox 360{A79F81F6-3FEE-48AA-9157-24EB772B624E}Xbox360Projgambatte-360StaticLibraryMultiByteStaticLibraryMultiByteStaticLibraryMultiByteStaticLibraryMultiByteStaticLibraryMultiBytetrueStaticLibrarytrueMultiByte$(OutDir)msvc-2010-360$(TargetExt)$(OutDir)msvc-2010-360$(TargetExt)$(OutDir)msvc-2010-360$(TargetExt)$(OutDir)msvc-2010-360$(TargetExt)$(OutDir)msvc-2010-360$(TargetExt)$(OutDir)msvc-2010-360$(TargetExt)NotUsingLevel3ProgramDatabaseDisabledfalsetruefalse$(OutDir)$(ProjectName).pchMultiThreadedDebug_DEBUG;_XBOX;_XBOX360;_LIB;%(PreprocessorDefinitions);HAVE_STDINT_HCallcap..\..\..\include;..\..\..\src\;..\..\..\src\video;..\..\..\src\file;..\..\..\src\sound;..\..\..\src\mem;..\..\..\..\common;..\libsnes;..\..\..\..\common\resampletrueNotUsingLevel4ProgramDatabaseDisabledfalsetrueAnalyzeOnlyfalse$(OutDir)$(ProjectName).pchMultiThreadedDebug_DEBUG;_XBOX;_XBOX360;_LIB;%(PreprocessorDefinitions);HAVE_STDINT_HCallcap..\..\..\include;..\..\..\src\;..\..\..\src\video;..\..\..\src\file;..\..\..\src\sound;..\..\..\src\mem;..\..\..\..\common;..\libsnes;..\..\..\..\common\resampletrueLevel3NotUsingFulltruefalsetrueProgramDatabaseSizefalse$(OutDir)$(ProjectName).pchMultiThreadedNDEBUG;_XBOX;_XBOX360;PROFILE;_LIB;%(PreprocessorDefinitions);HAVE_STDINT_HCallcap..\..\..\include;..\..\..\src\;..\..\..\src\video;..\..\..\src\file;..\..\..\src\sound;..\..\..\src\mem;..\..\..\..\common;..\libsnes;..\..\..\..\common\resampletruefalsexapilib.lib;%(IgnoreSpecificDefaultLibraries)trueLevel3NotUsingFulltruefalsetrueProgramDatabaseFastcapSizefalse$(OutDir)$(ProjectName).pchMultiThreadedNDEBUG;_XBOX;_XBOX360;PROFILE;FASTCAP;_LIB;%(PreprocessorDefinitions);HAVE_STDINT_H..\..\..\include;..\..\..\src\;..\..\..\src\video;..\..\..\src\file;..\..\..\src\sound;..\..\..\src\mem;..\..\..\..\common;..\libsnes;..\..\..\..\common\resampletruefalsetrueLevel3NotUsingFulltruetrueProgramDatabaseSizefalsefalse$(OutDir)$(ProjectName).pchMultiThreadedNDEBUG;_XBOX;_XBOX360;_LIB;%(PreprocessorDefinitions);HAVE_STDINT_H..\..\..\include;..\..\..\src\;..\..\..\src\video;..\..\..\src\file;..\..\..\src\sound;..\..\..\src\mem;..\..\..\..\common;..\libsnes;..\..\..\..\common\resampletruetruetrueLevel3NotUsingFulltruetrueProgramDatabaseSizefalsefalse$(OutDir)$(ProjectName).pchMultiThreadedNDEBUG;_XBOX;_XBOX360;LTCG;_LIB;%(PreprocessorDefinitions);HAVE_STDINT_H..\..\..\include;..\..\..\src\;..\..\..\src\video;..\..\..\src\file;..\..\..\src\sound;..\..\..\src\mem;..\..\..\..\common;..\libsnes;..\..\..\..\common\resampletruetruetrue
libgambatte/src/sound/ 000700 001750 001750 00000000000 12720366137 016067 5 ustar 00sergio sergio 000000 000000 COPYING 000664 001750 001750 00000043103 12720365247 012746 0 ustar 00sergio sergio 000000 000000 GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
libgambatte/src/video/ 000700 001750 001750 00000000000 12720366137 016045 5 ustar 00sergio sergio 000000 000000 libgambatte/src/video/next_m0_time.cpp 000664 001750 001750 00000000245 12720365247 021157 0 ustar 00sergio sergio 000000 000000 #include "next_m0_time.h"
#include "ppu.h"
void gambatte::NextM0Time::predictNextM0Time(PPU const &ppu) {
predictedNextM0Time_ = ppu.predictedNextXposTime(167);
}
libgambatte/src/video/lyc_irq.cpp 000664 001750 001750 00000006225 12720365247 020235 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2007 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#include "lyc_irq.h"
#include "counterdef.h"
#include "lcddef.h"
#include "ly_counter.h"
#include "savestate.h"
#include
namespace gambatte {
LycIrq::LycIrq()
: time_(disabled_time)
, lycRegSrc_(0)
, statRegSrc_(0)
, lycReg_(0)
, statReg_(0)
, cgb_(false)
{
}
static unsigned long schedule(unsigned statReg,
unsigned lycReg, LyCounter const &lyCounter, unsigned long cc) {
return (statReg & lcdstat_lycirqen) && lycReg < 154
? lyCounter.nextFrameCycle(lycReg ? lycReg * 456 : 153 * 456 + 8, cc)
: static_cast(disabled_time);
}
void LycIrq::regChange(unsigned const statReg,
unsigned const lycReg, LyCounter const &lyCounter, unsigned long const cc) {
unsigned long const timeSrc = schedule(statReg, lycReg, lyCounter, cc);
statRegSrc_ = statReg;
lycRegSrc_ = lycReg;
time_ = std::min(time_, timeSrc);
if (cgb_) {
if (time_ - cc > 8 || (timeSrc != time_ && time_ - cc > 4U - lyCounter.isDoubleSpeed() * 4U))
lycReg_ = lycReg;
if (time_ - cc > 4U - lyCounter.isDoubleSpeed() * 4U)
statReg_ = statReg;
} else {
if (time_ - cc > 4 || timeSrc != time_)
lycReg_ = lycReg;
if (time_ - cc > 4 || lycReg_ != 0)
statReg_ = statReg;
statReg_ = (statReg_ & lcdstat_lycirqen) | (statReg & ~lcdstat_lycirqen);
}
}
static bool lycIrqBlockedByM2OrM1StatIrq(unsigned ly, unsigned statreg) {
return ly - 1u < 144u - 1u
? statreg & lcdstat_m2irqen
: statreg & lcdstat_m1irqen;
}
void LycIrq::doEvent(unsigned char *const ifreg, LyCounter const &lyCounter) {
if ((statReg_ | statRegSrc_) & lcdstat_lycirqen) {
unsigned cmpLy = lyCounter.time() - time_ < lyCounter.lineTime() ? 0 : lyCounter.ly();
if (lycReg_ == cmpLy && !lycIrqBlockedByM2OrM1StatIrq(lycReg_, statReg_))
*ifreg |= 2;
}
lycReg_ = lycRegSrc_;
statReg_ = statRegSrc_;
time_ = schedule(statReg_, lycReg_, lyCounter, time_);
}
void LycIrq::loadState(SaveState const &state) {
lycRegSrc_ = state.mem.ioamhram.get()[0x145];
statRegSrc_ = state.mem.ioamhram.get()[0x141];
lycReg_ = state.ppu.lyc;
statReg_ = statRegSrc_;
}
void LycIrq::saveState(SaveState &state) const {
state.ppu.lyc = lycReg_;
}
void LycIrq::reschedule(LyCounter const &lyCounter, unsigned long cc) {
time_ = std::min(schedule(statReg_ , lycReg_ , lyCounter, cc),
schedule(statRegSrc_, lycRegSrc_, lyCounter, cc));
}
void LycIrq::lcdReset() {
statReg_ = statRegSrc_;
lycReg_ = lycRegSrc_;
}
}
libgambatte/src/tima.cpp 000664 001750 001750 00000010207 12720365247 016412 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2007 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#include "tima.h"
#include "savestate.h"
static unsigned char const timaClock[4] = { 10, 4, 6, 8 };
namespace gambatte {
Tima::Tima()
: lastUpdate_(0)
, tmatime_(disabled_time)
, tima_(0)
, tma_(0)
, tac_(0)
{
}
void Tima::saveState(SaveState &state) const {
state.mem.timaLastUpdate = lastUpdate_;
state.mem.tmatime = tmatime_;
}
void Tima::loadState(SaveState const &state, TimaInterruptRequester timaIrq) {
lastUpdate_ = state.mem.timaLastUpdate;
tmatime_ = state.mem.tmatime;
tima_ = state.mem.ioamhram.get()[0x105];
tma_ = state.mem.ioamhram.get()[0x106];
tac_ = state.mem.ioamhram.get()[0x107];
unsigned long nextIrqEventTime = disabled_time;
if (tac_ & 4) {
nextIrqEventTime = tmatime_ != disabled_time && tmatime_ > state.cpu.cycleCounter
? tmatime_
: lastUpdate_ + ((256u - tima_) << timaClock[tac_ & 3]) + 3;
}
timaIrq.setNextIrqEventTime(nextIrqEventTime);
}
void Tima::resetCc(unsigned long const oldCc, unsigned long const newCc, TimaInterruptRequester timaIrq) {
if (tac_ & 0x04) {
updateIrq(oldCc, timaIrq);
updateTima(oldCc);
unsigned long const dec = oldCc - newCc;
lastUpdate_ -= dec;
timaIrq.setNextIrqEventTime(timaIrq.nextIrqEventTime() - dec);
if (tmatime_ != disabled_time)
tmatime_ -= dec;
}
}
void Tima::updateTima(unsigned long const cc) {
unsigned long const ticks = (cc - lastUpdate_) >> timaClock[tac_ & 3];
lastUpdate_ += ticks << timaClock[tac_ & 3];
if (cc >= tmatime_) {
if (cc >= tmatime_ + 4)
tmatime_ = disabled_time;
tima_ = tma_;
}
unsigned long tmp = tima_ + ticks;
while (tmp > 0x100)
tmp -= 0x100 - tma_;
if (tmp == 0x100) {
tmp = 0;
tmatime_ = lastUpdate_ + 3;
if (cc >= tmatime_) {
if (cc >= tmatime_ + 4)
tmatime_ = disabled_time;
tmp = tma_;
}
}
tima_ = tmp;
}
void Tima::setTima(unsigned const data, unsigned long const cc, TimaInterruptRequester timaIrq) {
if (tac_ & 0x04) {
updateIrq(cc, timaIrq);
updateTima(cc);
if (tmatime_ - cc < 4)
tmatime_ = disabled_time;
timaIrq.setNextIrqEventTime(lastUpdate_ + ((256u - data) << timaClock[tac_ & 3]) + 3);
}
tima_ = data;
}
void Tima::setTma(unsigned const data, unsigned long const cc, TimaInterruptRequester timaIrq) {
if (tac_ & 0x04) {
updateIrq(cc, timaIrq);
updateTima(cc);
}
tma_ = data;
}
void Tima::setTac(unsigned const data, unsigned long const cc, TimaInterruptRequester timaIrq) {
if (tac_ ^ data) {
unsigned long nextIrqEventTime = timaIrq.nextIrqEventTime();
if (tac_ & 0x04) {
updateIrq(cc, timaIrq);
updateTima(cc);
lastUpdate_ -= (1u << (timaClock[tac_ & 3] - 1)) + 3;
tmatime_ -= (1u << (timaClock[tac_ & 3] - 1)) + 3;
nextIrqEventTime -= (1u << (timaClock[tac_ & 3] - 1)) + 3;
if (cc >= nextIrqEventTime)
timaIrq.flagIrq();
updateTima(cc);
tmatime_ = disabled_time;
nextIrqEventTime = disabled_time;
}
if (data & 4) {
lastUpdate_ = (cc >> timaClock[data & 3]) << timaClock[data & 3];
nextIrqEventTime = lastUpdate_ + ((256u - tima_) << timaClock[data & 3]) + 3;
}
timaIrq.setNextIrqEventTime(nextIrqEventTime);
}
tac_ = data;
}
unsigned Tima::tima(unsigned long cc) {
if (tac_ & 0x04)
updateTima(cc);
return tima_;
}
void Tima::doIrqEvent(TimaInterruptRequester timaIrq) {
timaIrq.flagIrq();
timaIrq.setNextIrqEventTime(timaIrq.nextIrqEventTime()
+ ((256u - tma_) << timaClock[tac_ & 3]));
}
}
libgambatte/src/video/m0_irq.h 000664 001750 001750 00000002334 12720365247 017424 0 ustar 00sergio sergio 000000 000000 #ifndef M0_IRQ_H
#define M0_IRQ_H
#include "lcddef.h"
#include "../savestate.h"
namespace gambatte {
class M0Irq {
public:
M0Irq()
: statReg_(0)
, lycReg_(0)
{
}
void lcdReset(unsigned statReg, unsigned lycReg) {
statReg_ = statReg;
lycReg_ = lycReg;
}
void statRegChange(unsigned statReg,
unsigned long nextM0IrqTime, unsigned long cc, bool cgb) {
if (nextM0IrqTime - cc > cgb * 2U)
statReg_ = statReg;
}
void lycRegChange(unsigned lycReg,
unsigned long nextM0IrqTime, unsigned long cc,
bool ds, bool cgb) {
if (nextM0IrqTime - cc > cgb * 5 + 1U - ds)
lycReg_ = lycReg;
}
void doEvent(unsigned char *ifreg, unsigned ly, unsigned statReg, unsigned lycReg) {
if (((statReg_ | statReg) & lcdstat_m0irqen)
&& (!(statReg_ & lcdstat_lycirqen) || ly != lycReg_)) {
*ifreg |= 2;
}
statReg_ = statReg;
lycReg_ = lycReg;
}
void saveState(SaveState &state) const {
state.ppu.m0lyc = lycReg_;
}
void loadState(SaveState const &state) {
lycReg_ = state.ppu.m0lyc;
statReg_ = state.mem.ioamhram.get()[0x141];
}
unsigned statReg() const { return statReg_; }
private:
unsigned char statReg_;
unsigned char lycReg_;
};
}
#endif
libgambatte/src/cpu.cpp 000664 001750 001750 00000127562 12720365247 016264 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2007 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#include "cpu.h"
#include "gambatte-memory.h"
#include "savestate.h"
namespace gambatte {
CPU::CPU()
: mem_(Interrupter(sp, pc_))
, cycleCounter_(0)
, pc_(0x100)
, sp(0xFFFE)
, hf1(0xF)
, hf2(0xF)
, zf(0)
, cf(0x100)
, a_(0x01)
, b(0x00)
, c(0x13)
, d(0x00)
, e(0xD8)
, h(0x01)
, l(0x4D)
, skip_(false)
{
}
long CPU::runFor(unsigned long const cycles) {
process(cycles);
long const csb = mem_.cyclesSinceBlit(cycleCounter_);
if (cycleCounter_ & 0x80000000)
cycleCounter_ = mem_.resetCounters(cycleCounter_);
return csb;
}
enum { hf2_hcf = 0x200, hf2_subf = 0x400, hf2_incf = 0x800 };
static unsigned updateHf2FromHf1(unsigned const hf1, unsigned hf2) {
unsigned lhs = hf1 & 0xF;
unsigned rhs = (hf2 & 0xF) + (hf2 >> 8 & 1);
if (hf2 & hf2_incf) {
lhs = rhs;
rhs = 1;
}
unsigned res = (hf2 & hf2_subf)
? lhs - rhs
: (lhs + rhs) << 5;
hf2 |= res & hf2_hcf;
return hf2;
}
static inline unsigned toF(unsigned hf2, unsigned cf, unsigned zf) {
return ((hf2 & (hf2_subf | hf2_hcf)) | (cf & 0x100)) >> 4
| ((zf & 0xFF) ? 0 : 0x80);
}
static inline unsigned zfFromF(unsigned f) { return ~f & 0x80; }
static inline unsigned hf2FromF(unsigned f) { return f << 4 & (hf2_subf | hf2_hcf); }
static inline unsigned cfFromF(unsigned f) { return f << 4 & 0x100; }
void CPU::setStatePtrs(SaveState &state) {
mem_.setStatePtrs(state);
}
void CPU::saveState(SaveState &state) {
cycleCounter_ = mem_.saveState(state, cycleCounter_);
hf2 = updateHf2FromHf1(hf1, hf2);
state.cpu.cycleCounter = cycleCounter_;
state.cpu.pc = pc_;
state.cpu.sp = sp;
state.cpu.a = a_;
state.cpu.b = b;
state.cpu.c = c;
state.cpu.d = d;
state.cpu.e = e;
state.cpu.f = toF(hf2, cf, zf);
state.cpu.h = h;
state.cpu.l = l;
state.cpu.skip = skip_;
}
void CPU::loadState(SaveState const &state) {
mem_.loadState(state);
cycleCounter_ = state.cpu.cycleCounter;
pc_ = state.cpu.pc & 0xFFFF;
sp = state.cpu.sp & 0xFFFF;
a_ = state.cpu.a & 0xFF;
b = state.cpu.b & 0xFF;
c = state.cpu.c & 0xFF;
d = state.cpu.d & 0xFF;
e = state.cpu.e & 0xFF;
zf = zfFromF(state.cpu.f);
hf2 = hf2FromF(state.cpu.f);
cf = cfFromF(state.cpu.f);
h = state.cpu.h & 0xFF;
l = state.cpu.l & 0xFF;
skip_ = state.cpu.skip;
}
// The main reasons for the use of macros is to more conveniently be able to tweak
// which variables are local and which are not, combined with the fact that at the
// time they were written GCC had a tendency to not be able to keep hot variables
// in regs if you took an address/reference in an inline function.
#define bc() ( b << 8 | c )
#define de() ( d << 8 | e )
#define hl() ( h << 8 | l )
#define READ(dest, addr) do { (dest) = mem_.read(addr, cycleCounter); cycleCounter += 4; } while (0)
#define PC_READ(dest) do { (dest) = mem_.read(pc, cycleCounter); pc = (pc + 1) & 0xFFFF; cycleCounter += 4; } while (0)
#define FF_READ(dest, addr) do { (dest) = mem_.ff_read(addr, cycleCounter); cycleCounter += 4; } while (0)
#define WRITE(addr, data) do { mem_.write(addr, data, cycleCounter); cycleCounter += 4; } while (0)
#define FF_WRITE(addr, data) do { mem_.ff_write(addr, data, cycleCounter); cycleCounter += 4; } while (0)
#define PC_MOD(data) do { pc = data; cycleCounter += 4; } while (0)
#define PUSH(r1, r2) do { \
sp = (sp - 1) & 0xFFFF; \
WRITE(sp, (r1)); \
sp = (sp - 1) & 0xFFFF; \
WRITE(sp, (r2)); \
} while (0)
// CB OPCODES (Shifts, rotates and bits):
// swap r (8 cycles):
// Swap upper and lower nibbles of 8-bit register, reset flags, check zero flag:
#define swap_r(r) do { \
cf = hf2 = 0; \
zf = (r); \
(r) = (zf << 4 | zf >> 4) & 0xFF; \
} while (0)
// rlc r (8 cycles):
// Rotate 8-bit register left, store old bit7 in CF. Reset SF and HCF, Check ZF:
#define rlc_r(r) do { \
cf = (r) << 1; \
zf = cf | cf >> 8; \
(r) = zf & 0xFF; \
hf2 = 0; \
} while (0)
// rl r (8 cycles):
// Rotate 8-bit register left through CF, store old bit7 in CF, old CF value becomes bit0. Reset SF and HCF, Check ZF:
#define rl_r(r) do { \
unsigned const oldcf = cf >> 8 & 1; \
cf = (r) << 1; \
zf = cf | oldcf; \
(r) = zf & 0xFF; \
hf2 = 0; \
} while (0)
// rrc r (8 cycles):
// Rotate 8-bit register right, store old bit0 in CF. Reset SF and HCF, Check ZF:
#define rrc_r(r) do { \
zf = (r); \
cf = zf << 8; \
(r) = (zf | cf) >> 1 & 0xFF; \
hf2 = 0; \
} while (0)
// rr r (8 cycles):
// Rotate 8-bit register right through CF, store old bit0 in CF, old CF value becomes bit7. Reset SF and HCF, Check ZF:
#define rr_r(r) do { \
unsigned const oldcf = cf & 0x100; \
cf = (r) << 8; \
(r) = zf = ((r) | oldcf) >> 1; \
hf2 = 0; \
} while (0)
// sla r (8 cycles):
// Shift 8-bit register left, store old bit7 in CF. Reset SF and HCF, Check ZF:
#define sla_r(r) do { \
zf = cf = (r) << 1; \
(r) = zf & 0xFF; \
hf2 = 0; \
} while (0)
// sra r (8 cycles):
// Shift 8-bit register right, store old bit0 in CF. bit7=old bit7. Reset SF and HCF, Check ZF:
#define sra_r(r) do { \
cf = (r) << 8; \
zf = (r) >> 1; \
(r) = zf | ((r) & 0x80); \
hf2 = 0; \
} while (0)
// srl r (8 cycles):
// Shift 8-bit register right, store old bit0 in CF. Reset SF and HCF, Check ZF:
#define srl_r(r) do { \
zf = (r); \
cf = (r) << 8; \
zf >>= 1; \
(r) = zf; \
hf2 = 0; \
} while (0)
// bit n,r (8 cycles):
// bit n,(hl) (12 cycles):
// Test bitn in 8-bit value, check ZF, unset SF, set HCF:
#define bitn_u8(bitmask, u8) do { \
zf = (u8) & (bitmask); \
hf2 = hf2_hcf; \
} while (0)
#define bit0_u8(u8) bitn_u8(0x01, (u8))
#define bit1_u8(u8) bitn_u8(0x02, (u8))
#define bit2_u8(u8) bitn_u8(0x04, (u8))
#define bit3_u8(u8) bitn_u8(0x08, (u8))
#define bit4_u8(u8) bitn_u8(0x10, (u8))
#define bit5_u8(u8) bitn_u8(0x20, (u8))
#define bit6_u8(u8) bitn_u8(0x40, (u8))
#define bit7_u8(u8) bitn_u8(0x80, (u8))
// set n,r (8 cycles):
// Set bitn of 8-bit register:
#define set0_r(r) ( (r) |= 0x01 )
#define set1_r(r) ( (r) |= 0x02 )
#define set2_r(r) ( (r) |= 0x04 )
#define set3_r(r) ( (r) |= 0x08 )
#define set4_r(r) ( (r) |= 0x10 )
#define set5_r(r) ( (r) |= 0x20 )
#define set6_r(r) ( (r) |= 0x40 )
#define set7_r(r) ( (r) |= 0x80 )
// set n,(hl) (16 cycles):
// Set bitn of value at address stored in HL:
#define setn_mem_hl(n) do { \
unsigned const hl = hl(); \
unsigned val; \
READ(val, hl); \
val |= 1 << (n); \
WRITE(hl, val); \
} while (0)
// res n,r (8 cycles):
// Unset bitn of 8-bit register:
#define res0_r(r) ( (r) &= 0xFE )
#define res1_r(r) ( (r) &= 0xFD )
#define res2_r(r) ( (r) &= 0xFB )
#define res3_r(r) ( (r) &= 0xF7 )
#define res4_r(r) ( (r) &= 0xEF )
#define res5_r(r) ( (r) &= 0xDF )
#define res6_r(r) ( (r) &= 0xBF )
#define res7_r(r) ( (r) &= 0x7F )
// res n,(hl) (16 cycles):
// Unset bitn of value at address stored in HL:
#define resn_mem_hl(n) do { \
unsigned const hl = hl(); \
unsigned val; \
READ(val, hl); \
val &= ~(1 << (n)); \
WRITE(hl, val); \
} while (0)
// 16-BIT LOADS:
// ld rr,nn (12 cycles)
// set rr to 16-bit value of next 2 bytes in memory
#define ld_rr_nn(r1, r2) do { \
PC_READ(r2); \
PC_READ(r1); \
} while (0)
// push rr (16 cycles):
// Push value of register pair onto stack:
#define push_rr(r1, r2) do { \
PUSH(r1, r2); \
cycleCounter += 4; \
} while (0)
// pop rr (12 cycles):
// Pop two bytes off stack into register pair:
#define pop_rr(r1, r2) do { \
READ(r2, sp); \
sp = (sp + 1) & 0xFFFF; \
READ(r1, sp); \
sp = (sp + 1) & 0xFFFF; \
} while (0)
// 8-BIT ALU:
// add a,r (4 cycles):
// add a,(addr) (8 cycles):
// Add 8-bit value to A, check flags:
#define add_a_u8(u8) do { \
hf1 = a; \
hf2 = u8; \
zf = cf = a + hf2; \
a = zf & 0xFF; \
} while (0)
// adc a,r (4 cycles):
// adc a,(addr) (8 cycles):
// Add 8-bit value+CF to A, check flags:
#define adc_a_u8(u8) do { \
hf1 = a; \
hf2 = (cf & 0x100) | (u8); \
zf = cf = (cf >> 8 & 1) + (u8) + a; \
a = zf & 0xFF; \
} while (0)
// sub a,r (4 cycles):
// sub a,(addr) (8 cycles):
// Subtract 8-bit value from A, check flags:
#define sub_a_u8(u8) do { \
hf1 = a; \
hf2 = u8; \
zf = cf = a - hf2; \
a = zf & 0xFF; \
hf2 |= hf2_subf; \
} while (0)
// sbc a,r (4 cycles):
// sbc a,(addr) (8 cycles):
// Subtract CF and 8-bit value from A, check flags:
#define sbc_a_u8(u8) do { \
hf1 = a; \
hf2 = hf2_subf | (cf & 0x100) | (u8); \
zf = cf = a - ((cf >> 8) & 1) - (u8); \
a = zf & 0xFF; \
} while (0)
// and a,r (4 cycles):
// and a,(addr) (8 cycles):
// bitwise and 8-bit value into A, check flags:
#define and_a_u8(u8) do { \
hf2 = hf2_hcf; \
cf = 0; \
a &= (u8); \
zf = a; \
} while (0)
// or a,r (4 cycles):
// or a,(hl) (8 cycles):
// bitwise or 8-bit value into A, check flags:
#define or_a_u8(u8) do { \
cf = hf2 = 0; \
a |= (u8); \
zf = a; \
} while (0)
// xor a,r (4 cycles):
// xor a,(hl) (8 cycles):
// bitwise xor 8-bit value into A, check flags:
#define xor_a_u8(u8) do { \
cf = hf2 = 0; \
a ^= (u8); \
zf = a; \
} while (0)
// cp a,r (4 cycles):
// cp a,(addr) (8 cycles):
// Compare (subtract without storing result) 8-bit value to A, check flags:
#define cp_a_u8(u8) do { \
hf1 = a; \
hf2 = u8; \
zf = cf = a - hf2; \
hf2 |= hf2_subf; \
} while (0)
// inc r (4 cycles):
// Increment value of 8-bit register, check flags except CF:
#define inc_r(r) do { \
hf2 = (r) | hf2_incf; \
zf = (r) + 1; \
(r) = zf & 0xFF; \
} while (0)
// dec r (4 cycles):
// Decrement value of 8-bit register, check flags except CF:
#define dec_r(r) do { \
hf2 = (r) | hf2_incf | hf2_subf; \
zf = (r) - 1; \
(r) = zf & 0xFF; \
} while (0)
// 16-BIT ARITHMETIC
// add hl,rr (8 cycles):
// add 16-bit register to HL, check flags except ZF:
#define add_hl_rr(rh, rl) do { \
cf = l + (rl); \
l = cf & 0xFF; \
hf1 = h; \
hf2 = (cf & 0x100) | (rh); \
cf = h + (cf >> 8) + (rh); \
h = cf & 0xFF; \
cycleCounter += 4; \
} while (0)
// inc rr (8 cycles):
// Increment 16-bit register:
#define inc_rr(rh, rl) do { \
unsigned const lowinc = (rl) + 1; \
(rl) = lowinc & 0xFF; \
(rh) = ((rh) + (lowinc >> 8)) & 0xFF; \
cycleCounter += 4; \
} while (0)
// dec rr (8 cycles):
// Decrement 16-bit register:
#define dec_rr(rh, rl) do { \
unsigned const lowdec = (rl) - 1; \
(rl) = lowdec & 0xFF; \
(rh) = ((rh) - (lowdec >> 8 & 1)) & 0xFF; \
cycleCounter += 4; \
} while (0)
#define sp_plus_n(sumout) do { \
unsigned disp; \
PC_READ(disp); \
disp = (disp ^ 0x80) - 0x80; \
\
unsigned const res = sp + disp; \
cf = sp ^ disp ^ res; \
hf2 = cf << 5 & hf2_hcf; \
zf = 1; \
cycleCounter += 4; \
(sumout) = res & 0xFFFF; \
} while (0)
// JUMPS:
// jp nn (16 cycles):
// Jump to address stored in the next two bytes in memory:
#define jp_nn() do { \
unsigned imm0, imm1; \
PC_READ(imm0); \
PC_READ(imm1); \
PC_MOD(imm1 << 8 | imm0); \
} while (0)
// jr disp (12 cycles):
// Jump to value of next (signed) byte in memory+current address:
#define jr_disp() do { \
unsigned disp; \
PC_READ(disp); \
disp = (disp ^ 0x80) - 0x80; \
PC_MOD((pc + disp) & 0xFFFF); \
} while (0)
// CALLS, RESTARTS AND RETURNS:
// call nn (24 cycles):
// Jump to 16-bit immediate operand and push return address onto stack:
#define call_nn() do { \
unsigned const npc = (pc + 2) & 0xFFFF; \
jp_nn(); \
PUSH(npc >> 8, npc & 0xFF); \
} while (0)
// rst n (16 Cycles):
// Push present address onto stack, jump to address n (one of 00h,08h,10h,18h,20h,28h,30h,38h):
#define rst_n(n) do { \
PUSH(pc >> 8, pc & 0xFF); \
PC_MOD(n); \
} while (0)
// ret (16 cycles):
// Pop two bytes from the stack and jump to that address:
#define ret() do { \
unsigned low, high; \
pop_rr(high, low); \
PC_MOD(high << 8 | low); \
} while (0)
void CPU::process(unsigned long const cycles) {
mem_.setEndtime(cycleCounter_, cycles);
mem_.updateInput();
unsigned char a = a_;
unsigned long cycleCounter = cycleCounter_;
while (mem_.isActive()) {
unsigned short pc = pc_;
if (mem_.halted()) {
if (cycleCounter < mem_.nextEventTime()) {
unsigned long cycles = mem_.nextEventTime() - cycleCounter;
cycleCounter += cycles + (-cycles & 3);
}
} else while (cycleCounter < mem_.nextEventTime()) {
unsigned char opcode;
PC_READ(opcode);
if (skip_) {
pc = (pc - 1) & 0xFFFF;
skip_ = false;
}
switch (opcode) {
case 0x00:
break;
case 0x01:
ld_rr_nn(b, c);
break;
case 0x02:
WRITE(bc(), a);
break;
case 0x03:
inc_rr(b, c);
break;
case 0x04:
inc_r(b);
break;
case 0x05:
dec_r(b);
break;
case 0x06:
PC_READ(b);
break;
// rlca (4 cycles):
// Rotate 8-bit register A left, store old bit7 in CF. Reset SF, HCF, ZF:
case 0x07:
cf = a << 1;
a = (cf | cf >> 8) & 0xFF;
hf2 = 0;
zf = 1;
break;
// ld (nn),SP (20 cycles):
// Put value of SP into address given by next 2 bytes in memory:
case 0x08:
{
unsigned imml, immh;
PC_READ(imml);
PC_READ(immh);
unsigned const addr = immh << 8 | imml;
WRITE(addr, sp & 0xFF);
WRITE((addr + 1) & 0xFFFF, sp >> 8);
}
break;
case 0x09:
add_hl_rr(b, c);
break;
case 0x0A:
READ(a, bc());
break;
case 0x0B:
dec_rr(b, c);
break;
case 0x0C:
inc_r(c);
break;
case 0x0D:
dec_r(c);
break;
case 0x0E:
PC_READ(c);
break;
// rrca (4 cycles):
// Rotate 8-bit register A right, store old bit0 in CF. Reset SF, HCF, ZF:
case 0x0F:
cf = a << 8 | a;
a = cf >> 1 & 0xFF;
hf2 = 0;
zf = 1;
break;
// stop (4 cycles):
// Halt CPU and LCD display until button pressed:
case 0x10:
pc = (pc + 1) & 0xFFFF;
cycleCounter = mem_.stop(cycleCounter);
if (cycleCounter < mem_.nextEventTime()) {
unsigned long cycles = mem_.nextEventTime() - cycleCounter;
cycleCounter += cycles + (-cycles & 3);
}
break;
case 0x11:
ld_rr_nn(d, e);
break;
case 0x12:
WRITE(de(), a);
break;
case 0x13:
inc_rr(d, e);
break;
case 0x14:
inc_r(d);
break;
case 0x15:
dec_r(d);
break;
case 0x16:
PC_READ(d);
break;
// rla (4 cycles):
// Rotate 8-bit register A left through CF, store old bit7 in CF,
// old CF value becomes bit0. Reset SF, HCF, ZF:
case 0x17:
{
unsigned oldcf = cf >> 8 & 1;
cf = a << 1;
a = (cf | oldcf) & 0xFF;
}
hf2 = 0;
zf = 1;
break;
case 0x18:
jr_disp();
break;
case 0x19:
add_hl_rr(d, e);
break;
case 0x1A:
READ(a, de());
break;
case 0x1B:
dec_rr(d, e);
break;
case 0x1C:
inc_r(e);
break;
case 0x1D:
dec_r(e);
break;
case 0x1E:
PC_READ(e);
break;
// rra (4 cycles):
// Rotate 8-bit register A right through CF, store old bit0 in CF,
// old CF value becomes bit7. Reset SF, HCF, ZF:
case 0x1F:
{
unsigned oldcf = cf & 0x100;
cf = a << 8;
a = (a | oldcf) >> 1;
}
hf2 = 0;
zf = 1;
break;
// jr nz,disp (12;8 cycles):
// Jump to value of next (signed) byte in memory+current address if ZF is unset:
case 0x20:
if (zf & 0xFF) {
jr_disp();
} else {
PC_MOD((pc + 1) & 0xFFFF);
}
break;
case 0x21: ld_rr_nn(h, l); break;
// ldi (hl),a (8 cycles):
// Put A into memory address in hl. Increment HL:
case 0x22:
{
unsigned addr = hl();
WRITE(addr, a);
addr = (addr + 1) & 0xFFFF;
l = addr;
h = addr >> 8;
}
break;
case 0x23:
inc_rr(h, l);
break;
case 0x24:
inc_r(h);
break;
case 0x25:
dec_r(h);
break;
case 0x26:
PC_READ(h);
break;
// daa (4 cycles):
// Adjust register A to correctly represent a BCD. Check ZF, HF and CF:
case 0x27:
hf2 = updateHf2FromHf1(hf1, hf2);
{
unsigned correction = (cf & 0x100) ? 0x60 : 0x00;
if (hf2 & hf2_hcf)
correction |= 0x06;
if (!(hf2 &= hf2_subf)) {
if ((a & 0x0F) > 0x09)
correction |= 0x06;
if (a > 0x99)
correction |= 0x60;
a += correction;
} else
a -= correction;
cf = correction << 2 & 0x100;
zf = a;
a &= 0xFF;
}
break;
// jr z,disp (12;8 cycles):
// Jump to value of next (signed) byte in memory+current address if ZF is set:
case 0x28:
if (zf & 0xFF) {
PC_MOD((pc + 1) & 0xFFFF);
} else {
jr_disp();
}
break;
case 0x29:
add_hl_rr(h, l);
break;
// ldi a,(hl) (8 cycles):
// Put value at address in hl into A. Increment HL:
case 0x2A:
{
unsigned addr = hl();
READ(a, addr);
addr = (addr + 1) & 0xFFFF;
l = addr;
h = addr >> 8;
}
break;
case 0x2B:
dec_rr(h, l);
break;
case 0x2C:
inc_r(l);
break;
case 0x2D:
dec_r(l);
break;
case 0x2E:
PC_READ(l);
break;
// cpl (4 cycles):
// Complement register A. (Flip all bits), set SF and HCF:
case 0x2F:
hf2 = hf2_subf | hf2_hcf;
a ^= 0xFF;
break;
// jr nc,disp (12;8 cycles):
// Jump to value of next (signed) byte in memory+current address if CF is unset:
case 0x30:
if (cf & 0x100) {
PC_MOD((pc + 1) & 0xFFFF);
} else {
jr_disp();
}
break;
// ld sp,nn (12 cycles)
// set sp to 16-bit value of next 2 bytes in memory
case 0x31:
{
unsigned imml, immh;
PC_READ(imml);
PC_READ(immh);
sp = immh << 8 | imml;
}
break;
// ldd (hl),a (8 cycles):
// Put A into memory address in hl. Decrement HL:
case 0x32:
{
unsigned addr = hl();
WRITE(addr, a);
addr = (addr - 1) & 0xFFFF;
l = addr;
h = addr >> 8;
}
break;
case 0x33:
sp = (sp + 1) & 0xFFFF;
cycleCounter += 4;
break;
// inc (hl) (12 cycles):
// Increment value at address in hl, check flags except CF:
case 0x34:
{
unsigned const addr = hl();
READ(hf2, addr);
zf = hf2 + 1;
WRITE(addr, zf & 0xFF);
hf2 |= hf2_incf;
}
break;
// dec (hl) (12 cycles):
// Decrement value at address in hl, check flags except CF:
case 0x35:
{
unsigned const addr = hl();
READ(hf2, addr);
zf = hf2 - 1;
WRITE(addr, zf & 0xFF);
hf2 |= hf2_incf | hf2_subf;
}
break;
// ld (hl),n (12 cycles):
// set memory at address in hl to value of next byte in memory:
case 0x36:
{
unsigned imm;
PC_READ(imm);
WRITE(hl(), imm);
}
break;
// scf (4 cycles):
// Set CF. Unset SF and HCF:
case 0x37:
cf = 0x100;
hf2 = 0;
break;
// jr c,disp (12;8 cycles):
// Jump to value of next (signed) byte in memory+current address if CF is set:
case 0x38:
if (cf & 0x100) {
jr_disp();
} else {
PC_MOD((pc + 1) & 0xFFFF);
}
break;
// add hl,sp (8 cycles):
// add SP to HL, check flags except ZF:
case 0x39:
cf = l + sp;
l = cf & 0xFF;
hf1 = h;
hf2 = ((cf ^ sp) & 0x100) | sp >> 8;
cf >>= 8;
cf += h;
h = cf & 0xFF;
cycleCounter += 4;
break;
// ldd a,(hl) (8 cycles):
// Put value at address in hl into A. Decrement HL:
case 0x3A:
{
unsigned addr = hl();
a = mem_.read(addr, cycleCounter);
cycleCounter += 4;
addr = (addr - 1) & 0xFFFF;
l = addr;
h = addr >> 8;
}
break;
case 0x3B:
sp = (sp - 1) & 0xFFFF;
cycleCounter += 4;
break;
case 0x3C:
inc_r(a);
break;
case 0x3D:
dec_r(a);
break;
case 0x3E:
PC_READ(a);
break;
// ccf (4 cycles):
// Complement CF (unset if set vv.) Unset SF and HCF.
case 0x3F:
cf ^= 0x100;
hf2 = 0;
break;
case 0x40: /*b = b;*/ break;
case 0x41: b = c; break;
case 0x42: b = d; break;
case 0x43: b = e; break;
case 0x44: b = h; break;
case 0x45: b = l; break;
case 0x46: READ(b, hl()); break;
case 0x47: b = a; break;
case 0x48: c = b; break;
case 0x49: /*c = c;*/ break;
case 0x4A: c = d; break;
case 0x4B: c = e; break;
case 0x4C: c = h; break;
case 0x4D: c = l; break;
case 0x4E: READ(c, hl()); break;
case 0x4F: c = a; break;
case 0x50: d = b; break;
case 0x51: d = c; break;
case 0x52: /*d = d;*/ break;
case 0x53: d = e; break;
case 0x54: d = h; break;
case 0x55: d = l; break;
case 0x56: READ(d, hl()); break;
case 0x57: d = a; break;
case 0x58: e = b; break;
case 0x59: e = c; break;
case 0x5A: e = d; break;
case 0x5B: /*e = e;*/ break;
case 0x5C: e = h; break;
case 0x5D: e = l; break;
case 0x5E: READ(e, hl()); break;
case 0x5F: e = a; break;
case 0x60: h = b; break;
case 0x61: h = c; break;
case 0x62: h = d; break;
case 0x63: h = e; break;
case 0x64: /*h = h;*/ break;
case 0x65: h = l; break;
case 0x66: READ(h, hl()); break;
case 0x67: h = a; break;
case 0x68: l = b; break;
case 0x69: l = c; break;
case 0x6A: l = d; break;
case 0x6B: l = e; break;
case 0x6C: l = h; break;
case 0x6D: /*l = l;*/ break;
case 0x6E: READ(l, hl()); break;
case 0x6F: l = a; break;
case 0x70: WRITE(hl(), b); break;
case 0x71: WRITE(hl(), c); break;
case 0x72: WRITE(hl(), d); break;
case 0x73: WRITE(hl(), e); break;
case 0x74: WRITE(hl(), h); break;
case 0x75: WRITE(hl(), l); break;
// halt (4 cycles):
case 0x76:
if (!mem_.ime()
&& ( mem_.ff_read(0x0F, cycleCounter)
& mem_.ff_read(0xFF, cycleCounter) & 0x1F)) {
if (mem_.isCgb())
cycleCounter += 4;
else
skip_ = true;
} else {
mem_.halt();
if (cycleCounter < mem_.nextEventTime()) {
unsigned long cycles = mem_.nextEventTime() - cycleCounter;
cycleCounter += cycles + (-cycles & 3);
}
}
break;
case 0x77: WRITE(hl(), a); break;
case 0x78: a = b; break;
case 0x79: a = c; break;
case 0x7A: a = d; break;
case 0x7B: a = e; break;
case 0x7C: a = h; break;
case 0x7D: a = l; break;
case 0x7E: READ(a, hl()); break;
case 0x7F: /*a = a;*/ break;
case 0x80: add_a_u8(b); break;
case 0x81: add_a_u8(c); break;
case 0x82: add_a_u8(d); break;
case 0x83: add_a_u8(e); break;
case 0x84: add_a_u8(h); break;
case 0x85: add_a_u8(l); break;
case 0x86: { unsigned data; READ(data, hl()); add_a_u8(data); } break;
case 0x87: add_a_u8(a); break;
case 0x88: adc_a_u8(b); break;
case 0x89: adc_a_u8(c); break;
case 0x8A: adc_a_u8(d); break;
case 0x8B: adc_a_u8(e); break;
case 0x8C: adc_a_u8(h); break;
case 0x8D: adc_a_u8(l); break;
case 0x8E: { unsigned data; READ(data, hl()); adc_a_u8(data); } break;
case 0x8F: adc_a_u8(a); break;
case 0x90: sub_a_u8(b); break;
case 0x91: sub_a_u8(c); break;
case 0x92: sub_a_u8(d); break;
case 0x93: sub_a_u8(e); break;
case 0x94: sub_a_u8(h); break;
case 0x95: sub_a_u8(l); break;
case 0x96: { unsigned data; READ(data, hl()); sub_a_u8(data); } break;
// A-A is always 0:
case 0x97:
hf2 = hf2_subf;
cf = zf = a = 0;
break;
case 0x98: sbc_a_u8(b); break;
case 0x99: sbc_a_u8(c); break;
case 0x9A: sbc_a_u8(d); break;
case 0x9B: sbc_a_u8(e); break;
case 0x9C: sbc_a_u8(h); break;
case 0x9D: sbc_a_u8(l); break;
case 0x9E: { unsigned data; READ(data, hl()); sbc_a_u8(data); } break;
case 0x9F: sbc_a_u8(a); break;
case 0xA0: and_a_u8(b); break;
case 0xA1: and_a_u8(c); break;
case 0xA2: and_a_u8(d); break;
case 0xA3: and_a_u8(e); break;
case 0xA4: and_a_u8(h); break;
case 0xA5: and_a_u8(l); break;
case 0xA6: { unsigned data; READ(data, hl()); and_a_u8(data); } break;
// A&A will always be A:
case 0xA7:
zf = a;
cf = 0;
hf2 = hf2_hcf;
break;
case 0xA8: xor_a_u8(b); break;
case 0xA9: xor_a_u8(c); break;
case 0xAA: xor_a_u8(d); break;
case 0xAB: xor_a_u8(e); break;
case 0xAC: xor_a_u8(h); break;
case 0xAD: xor_a_u8(l); break;
case 0xAE: { unsigned data; READ(data, hl()); xor_a_u8(data); } break;
// A^A will always be 0:
case 0xAF: cf = hf2 = zf = a = 0; break;
case 0xB0: or_a_u8(b); break;
case 0xB1: or_a_u8(c); break;
case 0xB2: or_a_u8(d); break;
case 0xB3: or_a_u8(e); break;
case 0xB4: or_a_u8(h); break;
case 0xB5: or_a_u8(l); break;
case 0xB6: { unsigned data; READ(data, hl()); or_a_u8(data); } break;
// A|A will always be A:
case 0xB7:
zf = a;
hf2 = cf = 0;
break;
case 0xB8: cp_a_u8(b); break;
case 0xB9: cp_a_u8(c); break;
case 0xBA: cp_a_u8(d); break;
case 0xBB: cp_a_u8(e); break;
case 0xBC: cp_a_u8(h); break;
case 0xBD: cp_a_u8(l); break;
case 0xBE: { unsigned data; READ(data, hl()); cp_a_u8(data); } break;
// A always equals A:
case 0xBF:
cf = zf = 0;
hf2 = hf2_subf;
break;
// ret nz (20;8 cycles):
// Pop two bytes from the stack and jump to that address, if ZF is unset:
case 0xC0:
cycleCounter += 4;
if (zf & 0xFF)
ret();
break;
case 0xC1:
pop_rr(b, c);
break;
// jp nz,nn (16;12 cycles):
// Jump to address stored in next two bytes in memory if ZF is unset:
case 0xC2:
if (zf & 0xFF) {
jp_nn();
} else {
PC_MOD((pc + 2) & 0xFFFF);
cycleCounter += 4;
}
break;
case 0xC3:
jp_nn();
break;
// call nz,nn (24;12 cycles):
// Push address of next instruction onto stack and then jump to
// address stored in next two bytes in memory, if ZF is unset:
case 0xC4:
if (zf & 0xFF) {
call_nn();
} else {
PC_MOD((pc + 2) & 0xFFFF);
cycleCounter += 4;
}
break;
case 0xC5:
push_rr(b, c);
break;
case 0xC6:
{
unsigned data;
PC_READ(data);
add_a_u8(data);
}
break;
case 0xC7:
rst_n(0x00);
break;
// ret z (20;8 cycles):
// Pop two bytes from the stack and jump to that address, if ZF is set:
case 0xC8:
cycleCounter += 4;
if (!(zf & 0xFF))
ret();
break;
// ret (16 cycles):
// Pop two bytes from the stack and jump to that address:
case 0xC9:
ret();
break;
// jp z,nn (16;12 cycles):
// Jump to address stored in next two bytes in memory if ZF is set:
case 0xCA:
if (zf & 0xFF) {
PC_MOD((pc + 2) & 0xFFFF);
cycleCounter += 4;
} else {
jp_nn();
}
break;
// CB OPCODES (Shifts, rotates and bits):
case 0xCB:
PC_READ(opcode);
switch (opcode) {
case 0x00: rlc_r(b); break;
case 0x01: rlc_r(c); break;
case 0x02: rlc_r(d); break;
case 0x03: rlc_r(e); break;
case 0x04: rlc_r(h); break;
case 0x05: rlc_r(l); break;
// rlc (hl) (16 cycles):
// Rotate 8-bit value stored at address in HL left, store old bit7 in CF.
// Reset SF and HCF. Check ZF:
case 0x06:
{
unsigned const addr = hl();
READ(cf, addr);
cf <<= 1;
zf = cf | (cf >> 8);
WRITE(addr, zf & 0xFF);
hf2 = 0;
}
break;
case 0x07: rlc_r(a); break;
case 0x08: rrc_r(b); break;
case 0x09: rrc_r(c); break;
case 0x0A: rrc_r(d); break;
case 0x0B: rrc_r(e); break;
case 0x0C: rrc_r(h); break;
case 0x0D: rrc_r(l); break;
// rrc (hl) (16 cycles):
// Rotate 8-bit value stored at address in HL right, store old bit0 in CF.
// Reset SF and HCF. Check ZF:
case 0x0E:
{
unsigned const addr = hl();
READ(zf, addr);
cf = zf << 8;
WRITE(addr, (zf | cf) >> 1 & 0xFF);
hf2 = 0;
}
break;
case 0x0F: rrc_r(a); break;
case 0x10: rl_r(b); break;
case 0x11: rl_r(c); break;
case 0x12: rl_r(d); break;
case 0x13: rl_r(e); break;
case 0x14: rl_r(h); break;
case 0x15: rl_r(l); break;
// rl (hl) (16 cycles):
// Rotate 8-bit value stored at address in HL left thorugh CF,
// store old bit7 in CF, old CF value becoms bit0. Reset SF and HCF. Check ZF:
case 0x16:
{
unsigned const addr = hl();
unsigned const oldcf = cf >> 8 & 1;
READ(cf, addr);
cf <<= 1;
zf = cf | oldcf;
WRITE(addr, zf & 0xFF);
hf2 = 0;
}
break;
case 0x17: rl_r(a); break;
case 0x18: rr_r(b); break;
case 0x19: rr_r(c); break;
case 0x1A: rr_r(d); break;
case 0x1B: rr_r(e); break;
case 0x1C: rr_r(h); break;
case 0x1D: rr_r(l); break;
// rr (hl) (16 cycles):
// Rotate 8-bit value stored at address in HL right thorugh CF,
// store old bit0 in CF, old CF value becoms bit7. Reset SF and HCF. Check ZF:
case 0x1E:
{
unsigned const addr = hl();
READ(zf, addr);
unsigned const oldcf = cf & 0x100;
cf = zf << 8;
zf = (zf | oldcf) >> 1;
WRITE(addr, zf);
hf2 = 0;
}
break;
case 0x1F: rr_r(a); break;
case 0x20: sla_r(b); break;
case 0x21: sla_r(c); break;
case 0x22: sla_r(d); break;
case 0x23: sla_r(e); break;
case 0x24: sla_r(h); break;
case 0x25: sla_r(l); break;
// sla (hl) (16 cycles):
// Shift 8-bit value stored at address in HL left, store old bit7 in CF.
// Reset SF and HCF. Check ZF:
case 0x26:
{
unsigned const addr = hl();
READ(cf, addr);
cf <<= 1;
zf = cf;
WRITE(addr, zf & 0xFF);
hf2 = 0;
}
break;
case 0x27: sla_r(a); break;
case 0x28: sra_r(b); break;
case 0x29: sra_r(c); break;
case 0x2A: sra_r(d); break;
case 0x2B: sra_r(e); break;
case 0x2C: sra_r(h); break;
case 0x2D: sra_r(l); break;
// sra (hl) (16 cycles):
// Shift 8-bit value stored at address in HL right, store old bit0 in CF,
// bit7=old bit7. Reset SF and HCF. Check ZF:
case 0x2E:
{
unsigned const addr = hl();
READ(cf, addr);
zf = cf >> 1;
WRITE(addr, zf | (cf & 0x80));
cf <<= 8;
hf2 = 0;
}
break;
case 0x2F: sra_r(a); break;
case 0x30: swap_r(b); break;
case 0x31: swap_r(c); break;
case 0x32: swap_r(d); break;
case 0x33: swap_r(e); break;
case 0x34: swap_r(h); break;
case 0x35: swap_r(l); break;
// swap (hl) (16 cycles):
// Swap upper and lower nibbles of 8-bit value stored at address in HL,
// reset flags, check zero flag:
case 0x36:
{
unsigned const addr = hl();
READ(zf, addr);
WRITE(addr, (zf << 4 | zf >> 4) & 0xFF);
cf = hf2 = 0;
}
break;
case 0x37: swap_r(a); break;
case 0x38: srl_r(b); break;
case 0x39: srl_r(c); break;
case 0x3A: srl_r(d); break;
case 0x3B: srl_r(e); break;
case 0x3C: srl_r(h); break;
case 0x3D: srl_r(l); break;
// srl (hl) (16 cycles):
// Shift 8-bit value stored at address in HL right,
// store old bit0 in CF. Reset SF and HCF. Check ZF:
case 0x3E:
{
unsigned const addr = hl();
READ(cf, addr);
zf = cf >> 1;
WRITE(addr, zf);
cf <<= 8;
hf2 = 0;
}
break;
case 0x3F: srl_r(a); break;
case 0x40: bit0_u8(b); break;
case 0x41: bit0_u8(c); break;
case 0x42: bit0_u8(d); break;
case 0x43: bit0_u8(e); break;
case 0x44: bit0_u8(h); break;
case 0x45: bit0_u8(l); break;
case 0x46: { unsigned data; READ(data, hl()); bit0_u8(data); } break;
case 0x47: bit0_u8(a); break;
case 0x48: bit1_u8(b); break;
case 0x49: bit1_u8(c); break;
case 0x4A: bit1_u8(d); break;
case 0x4B: bit1_u8(e); break;
case 0x4C: bit1_u8(h); break;
case 0x4D: bit1_u8(l); break;
case 0x4E: { unsigned data; READ(data, hl()); bit1_u8(data); } break;
case 0x4F: bit1_u8(a); break;
case 0x50: bit2_u8(b); break;
case 0x51: bit2_u8(c); break;
case 0x52: bit2_u8(d); break;
case 0x53: bit2_u8(e); break;
case 0x54: bit2_u8(h); break;
case 0x55: bit2_u8(l); break;
case 0x56: { unsigned data; READ(data, hl()); bit2_u8(data); } break;
case 0x57: bit2_u8(a); break;
case 0x58: bit3_u8(b); break;
case 0x59: bit3_u8(c); break;
case 0x5A: bit3_u8(d); break;
case 0x5B: bit3_u8(e); break;
case 0x5C: bit3_u8(h); break;
case 0x5D: bit3_u8(l); break;
case 0x5E: { unsigned data; READ(data, hl()); bit3_u8(data); } break;
case 0x5F: bit3_u8(a); break;
case 0x60: bit4_u8(b); break;
case 0x61: bit4_u8(c); break;
case 0x62: bit4_u8(d); break;
case 0x63: bit4_u8(e); break;
case 0x64: bit4_u8(h); break;
case 0x65: bit4_u8(l); break;
case 0x66: { unsigned data; READ(data, hl()); bit4_u8(data); } break;
case 0x67: bit4_u8(a); break;
case 0x68: bit5_u8(b); break;
case 0x69: bit5_u8(c); break;
case 0x6A: bit5_u8(d); break;
case 0x6B: bit5_u8(e); break;
case 0x6C: bit5_u8(h); break;
case 0x6D: bit5_u8(l); break;
case 0x6E: { unsigned data; READ(data, hl()); bit5_u8(data); } break;
case 0x6F: bit5_u8(a); break;
case 0x70: bit6_u8(b); break;
case 0x71: bit6_u8(c); break;
case 0x72: bit6_u8(d); break;
case 0x73: bit6_u8(e); break;
case 0x74: bit6_u8(h); break;
case 0x75: bit6_u8(l); break;
case 0x76: { unsigned data; READ(data, hl()); bit6_u8(data); } break;
case 0x77: bit6_u8(a); break;
case 0x78: bit7_u8(b); break;
case 0x79: bit7_u8(c); break;
case 0x7A: bit7_u8(d); break;
case 0x7B: bit7_u8(e); break;
case 0x7C: bit7_u8(h); break;
case 0x7D: bit7_u8(l); break;
case 0x7E: { unsigned data; READ(data, hl()); bit7_u8(data); } break;
case 0x7F: bit7_u8(a); break;
case 0x80: res0_r(b); break;
case 0x81: res0_r(c); break;
case 0x82: res0_r(d); break;
case 0x83: res0_r(e); break;
case 0x84: res0_r(h); break;
case 0x85: res0_r(l); break;
case 0x86: resn_mem_hl(0); break;
case 0x87: res0_r(a); break;
case 0x88: res1_r(b); break;
case 0x89: res1_r(c); break;
case 0x8A: res1_r(d); break;
case 0x8B: res1_r(e); break;
case 0x8C: res1_r(h); break;
case 0x8D: res1_r(l); break;
case 0x8E: resn_mem_hl(1); break;
case 0x8F: res1_r(a); break;
case 0x90: res2_r(b); break;
case 0x91: res2_r(c); break;
case 0x92: res2_r(d); break;
case 0x93: res2_r(e); break;
case 0x94: res2_r(h); break;
case 0x95: res2_r(l); break;
case 0x96: resn_mem_hl(2); break;
case 0x97: res2_r(a); break;
case 0x98: res3_r(b); break;
case 0x99: res3_r(c); break;
case 0x9A: res3_r(d); break;
case 0x9B: res3_r(e); break;
case 0x9C: res3_r(h); break;
case 0x9D: res3_r(l); break;
case 0x9E: resn_mem_hl(3); break;
case 0x9F: res3_r(a); break;
case 0xA0: res4_r(b); break;
case 0xA1: res4_r(c); break;
case 0xA2: res4_r(d); break;
case 0xA3: res4_r(e); break;
case 0xA4: res4_r(h); break;
case 0xA5: res4_r(l); break;
case 0xA6: resn_mem_hl(4); break;
case 0xA7: res4_r(a); break;
case 0xA8: res5_r(b); break;
case 0xA9: res5_r(c); break;
case 0xAA: res5_r(d); break;
case 0xAB: res5_r(e); break;
case 0xAC: res5_r(h); break;
case 0xAD: res5_r(l); break;
case 0xAE: resn_mem_hl(5); break;
case 0xAF: res5_r(a); break;
case 0xB0: res6_r(b); break;
case 0xB1: res6_r(c); break;
case 0xB2: res6_r(d); break;
case 0xB3: res6_r(e); break;
case 0xB4: res6_r(h); break;
case 0xB5: res6_r(l); break;
case 0xB6: resn_mem_hl(6); break;
case 0xB7: res6_r(a); break;
case 0xB8: res7_r(b); break;
case 0xB9: res7_r(c); break;
case 0xBA: res7_r(d); break;
case 0xBB: res7_r(e); break;
case 0xBC: res7_r(h); break;
case 0xBD: res7_r(l); break;
case 0xBE: resn_mem_hl(7); break;
case 0xBF: res7_r(a); break;
case 0xC0: set0_r(b); break;
case 0xC1: set0_r(c); break;
case 0xC2: set0_r(d); break;
case 0xC3: set0_r(e); break;
case 0xC4: set0_r(h); break;
case 0xC5: set0_r(l); break;
case 0xC6: setn_mem_hl(0); break;
case 0xC7: set0_r(a); break;
case 0xC8: set1_r(b); break;
case 0xC9: set1_r(c); break;
case 0xCA: set1_r(d); break;
case 0xCB: set1_r(e); break;
case 0xCC: set1_r(h); break;
case 0xCD: set1_r(l); break;
case 0xCE: setn_mem_hl(1); break;
case 0xCF: set1_r(a); break;
case 0xD0: set2_r(b); break;
case 0xD1: set2_r(c); break;
case 0xD2: set2_r(d); break;
case 0xD3: set2_r(e); break;
case 0xD4: set2_r(h); break;
case 0xD5: set2_r(l); break;
case 0xD6: setn_mem_hl(2); break;
case 0xD7: set2_r(a); break;
case 0xD8: set3_r(b); break;
case 0xD9: set3_r(c); break;
case 0xDA: set3_r(d); break;
case 0xDB: set3_r(e); break;
case 0xDC: set3_r(h); break;
case 0xDD: set3_r(l); break;
case 0xDE: setn_mem_hl(3); break;
case 0xDF: set3_r(a); break;
case 0xE0: set4_r(b); break;
case 0xE1: set4_r(c); break;
case 0xE2: set4_r(d); break;
case 0xE3: set4_r(e); break;
case 0xE4: set4_r(h); break;
case 0xE5: set4_r(l); break;
case 0xE6: setn_mem_hl(4); break;
case 0xE7: set4_r(a); break;
case 0xE8: set5_r(b); break;
case 0xE9: set5_r(c); break;
case 0xEA: set5_r(d); break;
case 0xEB: set5_r(e); break;
case 0xEC: set5_r(h); break;
case 0xED: set5_r(l); break;
case 0xEE: setn_mem_hl(5); break;
case 0xEF: set5_r(a); break;
case 0xF0: set6_r(b); break;
case 0xF1: set6_r(c); break;
case 0xF2: set6_r(d); break;
case 0xF3: set6_r(e); break;
case 0xF4: set6_r(h); break;
case 0xF5: set6_r(l); break;
case 0xF6: setn_mem_hl(6); break;
case 0xF7: set6_r(a); break;
case 0xF8: set7_r(b); break;
case 0xF9: set7_r(c); break;
case 0xFA: set7_r(d); break;
case 0xFB: set7_r(e); break;
case 0xFC: set7_r(h); break;
case 0xFD: set7_r(l); break;
case 0xFE: setn_mem_hl(7); break;
case 0xFF: set7_r(a); break;
}
break;
// call z,nn (24;12 cycles):
// Push address of next instruction onto stack and then jump to
// address stored in next two bytes in memory, if ZF is set:
case 0xCC:
if (zf & 0xFF) {
PC_MOD((pc + 2) & 0xFFFF);
cycleCounter += 4;
} else {
call_nn();
}
break;
case 0xCD:
call_nn();
break;
case 0xCE:
{
unsigned data;
PC_READ(data);
adc_a_u8(data);
}
break;
case 0xCF:
rst_n(0x08);
break;
// ret nc (20;8 cycles):
// Pop two bytes from the stack and jump to that address, if CF is unset:
case 0xD0:
cycleCounter += 4;
if (!(cf & 0x100))
ret();
break;
case 0xD1:
pop_rr(d, e);
break;
// jp nc,nn (16;12 cycles):
// Jump to address stored in next two bytes in memory if CF is unset:
case 0xD2:
if (cf & 0x100) {
PC_MOD((pc + 2) & 0xFFFF);
cycleCounter += 4;
} else {
jp_nn();
}
break;
case 0xD3: // not specified. should freeze.
break;
// call nc,nn (24;12 cycles):
// Push address of next instruction onto stack and then jump to
// address stored in next two bytes in memory, if CF is unset:
case 0xD4:
if (cf & 0x100) {
PC_MOD((pc + 2) & 0xFFFF);
cycleCounter += 4;
} else {
call_nn();
}
break;
case 0xD5:
push_rr(d, e);
break;
case 0xD6:
{
unsigned data;
PC_READ(data);
sub_a_u8(data);
}
break;
case 0xD7:
rst_n(0x10);
break;
// ret c (20;8 cycles):
// Pop two bytes from the stack and jump to that address, if CF is set:
case 0xD8:
cycleCounter += 4;
if (cf & 0x100)
ret();
break;
// reti (16 cycles):
// Pop two bytes from the stack and jump to that address, then enable interrupts:
case 0xD9:
{
unsigned sl, sh;
pop_rr(sh, sl);
mem_.ei(cycleCounter);
PC_MOD(sh << 8 | sl);
}
break;
// jp c,nn (16;12 cycles):
// Jump to address stored in next two bytes in memory if CF is set:
case 0xDA:
if (cf & 0x100) {
jp_nn();
} else {
PC_MOD((pc + 2) & 0xFFFF);
cycleCounter += 4;
}
break;
case 0xDB: // not specified. should freeze.
break;
// call z,nn (24;12 cycles):
// Push address of next instruction onto stack and then jump to
// address stored in next two bytes in memory, if CF is set:
case 0xDC:
if (cf & 0x100) {
call_nn();
} else {
PC_MOD((pc + 2) & 0xFFFF);
cycleCounter += 4;
}
break;
case 0xDE:
{
unsigned data;
PC_READ(data);
sbc_a_u8(data);
}
break;
case 0xDF:
rst_n(0x18);
break;
// ld ($FF00+n),a (12 cycles):
// Put value in A into address (0xFF00 + next byte in memory):
case 0xE0:
{
unsigned imm;
PC_READ(imm);
FF_WRITE(imm, a);
}
break;
case 0xE1:
pop_rr(h, l);
break;
// ld ($FF00+C),a (8 ycles):
// Put A into address (0xFF00 + register C):
case 0xE2:
FF_WRITE(c, a);
break;
case 0xE3: // not specified. should freeze.
break;
case 0xE4: // not specified. should freeze.
break;
case 0xE5:
push_rr(h, l);
break;
case 0xE6:
{
unsigned data;
PC_READ(data);
and_a_u8(data);
}
break;
case 0xE7:
rst_n(0x20);
break;
// add sp,n (16 cycles):
// Add next (signed) byte in memory to SP, reset ZF and SF, check HCF and CF:
case 0xE8:
sp_plus_n(sp);
cycleCounter += 4;
break;
// jp hl (4 cycles):
// Jump to address in hl:
case 0xE9:
pc = hl();
break;
// ld (nn),a (16 cycles):
// set memory at address given by the next 2 bytes to value in A:
// Incrementing PC before call, because of possible interrupt.
case 0xEA:
{
unsigned imml, immh;
PC_READ(imml);
PC_READ(immh);
WRITE(immh << 8 | imml, a);
}
break;
case 0xEB: // not specified. should freeze.
break;
case 0xEC: // not specified. should freeze.
break;
case 0xED: // not specified. should freeze.
break;
case 0xEE:
{
unsigned data;
PC_READ(data);
xor_a_u8(data);
}
break;
case 0xEF:
rst_n(0x28);
break;
// ld a,($FF00+n) (12 cycles):
// Put value at address (0xFF00 + next byte in memory) into A:
case 0xF0:
{
unsigned imm;
PC_READ(imm);
FF_READ(a, imm);
}
break;
case 0xF1:
{
unsigned F;
pop_rr(a, F);
zf = zfFromF(F);
hf2 = hf2FromF(F);
cf = cfFromF(F);
}
break;
// ld a,($FF00+C) (8 cycles):
// Put value at address (0xFF00 + register C) into A:
case 0xF2:
FF_READ(a, c);
break;
// di (4 cycles):
case 0xF3:
mem_.di();
break;
case 0xF4: // not specified. should freeze.
break;
case 0xF5:
hf2 = updateHf2FromHf1(hf1, hf2);
{
unsigned F = toF(hf2, cf, zf);
push_rr(a, F);
}
break;
case 0xF6:
{
unsigned data;
PC_READ(data);
or_a_u8(data);
}
break;
case 0xF7:
rst_n(0x30);
break;
// ldhl sp,n (12 cycles):
// Put (sp+next (signed) byte in memory) into hl (unsets ZF and SF, may enable HF and CF):
case 0xF8:
{
unsigned sum;
sp_plus_n(sum);
l = sum & 0xFF;
h = sum >> 8;
}
break;
// ld sp,hl (8 cycles):
// Put value in HL into SP
case 0xF9:
sp = hl();
cycleCounter += 4;
break;
// ld a,(nn) (16 cycles):
// set A to value in memory at address given by the 2 next bytes.
case 0xFA:
{
unsigned imml, immh;
PC_READ(imml);
PC_READ(immh);
READ(a, immh << 8 | imml);
}
break;
// ei (4 cycles):
// Enable Interrupts after next instruction:
case 0xFB:
mem_.ei(cycleCounter);
break;
case 0xFC: // not specified. should freeze.
break;
case 0xFD: // not specified. should freeze
break;
case 0xFE:
{
unsigned data;
PC_READ(data);
cp_a_u8(data);
}
break;
case 0xFF:
rst_n(0x38);
break;
}
}
pc_ = pc;
cycleCounter = mem_.event(cycleCounter);
}
a_ = a;
cycleCounter_ = cycleCounter;
}
}
libgambatte/libretro/control 000664 001750 001750 00000000330 12720365247 017406 0 ustar 00sergio sergio 000000 000000 Package: com.libretro.gambatte
Name: gambatte
Depends:
Version: 0.0.1
Architecture: iphoneos-arm
Description: Libretro iOS core of Gambatte
Maintainer: libretro
Author: libretro
Section: System
Tag: role::developer
libgambatte/src/cpu.h 000664 001750 001750 00000005776 12720365247 015733 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2007 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#ifndef CPU_H
#define CPU_H
#include "gambatte.h"
#include "gambatte-memory.h"
#include "savestate.h"
namespace gambatte {
class CPU {
public:
CPU();
long runFor(unsigned long cycles);
void setStatePtrs(SaveState &state);
void saveState(SaveState &state);
void loadState(SaveState const &state);
#if 0
void loadSavedata() { mem_.loadSavedata(); }
void saveSavedata() { mem_.saveSavedata(); }
#endif
#ifdef __LIBRETRO__
void *savedata_ptr() { return mem_.savedata_ptr(); }
unsigned savedata_size() { return mem_.savedata_size(); }
void *rtcdata_ptr() { return mem_.rtcdata_ptr(); }
unsigned rtcdata_size() { return mem_.rtcdata_size(); }
void clearCheats() { mem_.clearCheats(); }
void *vram_ptr() const { return mem_.vram_ptr(); }
void *rambank0_ptr() const { return mem_.rambank0_ptr(); }
void *rambank1_ptr() const { return mem_.rambank1_ptr(); }
void *rombank0_ptr() const { return mem_.rombank0_ptr(); }
void *rombank1_ptr() const { return mem_.rombank1_ptr(); }
#endif
void setVideoBuffer(video_pixel_t *videoBuf, std::ptrdiff_t pitch) {
mem_.setVideoBuffer(videoBuf, pitch);
}
void setInputGetter(InputGetter *getInput) {
mem_.setInputGetter(getInput);
}
void setSaveDir(std::string const &sdir) {
mem_.setSaveDir(sdir);
}
std::string const saveBasePath() const {
return mem_.saveBasePath();
}
int load(const void *romdata, unsigned int romsize, bool forceDmg, bool multicartCompat) {
return mem_.loadROM(romdata, romsize, forceDmg, multicartCompat);
}
#if 0
bool loaded() const { return mem_.loaded(); }
#endif
void setSoundBuffer(uint_least32_t *buf) { mem_.setSoundBuffer(buf); }
std::size_t fillSoundBuffer() { return mem_.fillSoundBuffer(cycleCounter_); }
bool isCgb() const { return mem_.isCgb(); }
void setDmgPaletteColor(int palNum, int colorNum, unsigned long rgb32) {
mem_.setDmgPaletteColor(palNum, colorNum, rgb32);
}
void setGameGenie(std::string const &codes) { mem_.setGameGenie(codes); }
void setGameShark(std::string const &codes) { mem_.setGameShark(codes); }
Memory mem_;
private:
unsigned long cycleCounter_;
unsigned short pc_;
unsigned short sp;
unsigned hf1, hf2, zf, cf;
unsigned char a_, b, c, d, e, /*f,*/ h, l;
bool skip_;
void process(unsigned long cycles);
};
}
#endif
libgambatte/libretro/msvc/msvc-2010/libretro.def 000664 001750 001750 00000001011 12720365247 022602 0 ustar 00sergio sergio 000000 000000 LIBRARY "msvc-2010"
EXPORTS
retro_set_environment
retro_set_video_refresh
retro_set_audio_sample
retro_set_audio_sample_batch
retro_set_input_poll
retro_set_input_state
retro_init
retro_deinit
retro_api_version
retro_get_system_info
retro_get_system_av_info
retro_set_controller_port_device
retro_reset
retro_run
retro_serialize_size
retro_serialize
retro_unserialize
retro_cheat_reset
retro_cheat_set
retro_load_game
retro_load_game_special
retro_unload_game
retro_get_region
retro_get_memory_data
retro_get_memory_size
libgambatte/libretro/msvc/msvc-2010-360/ 000700 001750 001750 00000000000 12720366137 020600 5 ustar 00sergio sergio 000000 000000 libgambatte/src/gambatte-memory.cpp 000664 001750 001750 00000061756 12720365247 020571 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2007 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#include "gambatte-memory.h"
#include "inputgetter.h"
#include "savestate.h"
#include "sound.h"
#include "video.h"
#include
namespace gambatte {
Memory::Memory(Interrupter const &interrupter)
: getInput_(0)
, divLastUpdate_(0)
, lastOamDmaUpdate_(disabled_time)
, lcd_(ioamhram_, 0, VideoInterruptRequester(intreq_))
, interrupter_(interrupter)
, dmaSource_(0)
, dmaDestination_(0)
, oamDmaPos_(0xFE)
, serialCnt_(0)
, blanklcd_(false)
{
intreq_.setEventTime(144 * 456ul);
intreq_.setEventTime(0);
}
void Memory::setStatePtrs(SaveState &state) {
state.mem.ioamhram.set(ioamhram_, sizeof ioamhram_);
cart_.setStatePtrs(state);
lcd_.setStatePtrs(state);
psg_.setStatePtrs(state);
}
unsigned long Memory::saveState(SaveState &state, unsigned long cc) {
cc = resetCounters(cc);
nontrivial_ff_read(0x05, cc);
nontrivial_ff_read(0x0F, cc);
nontrivial_ff_read(0x26, cc);
state.mem.divLastUpdate = divLastUpdate_;
state.mem.nextSerialtime = intreq_.eventTime(intevent_serial);
state.mem.unhaltTime = intreq_.eventTime(intevent_unhalt);
state.mem.lastOamDmaUpdate = lastOamDmaUpdate_;
state.mem.dmaSource = dmaSource_;
state.mem.dmaDestination = dmaDestination_;
state.mem.oamDmaPos = oamDmaPos_;
intreq_.saveState(state);
cart_.saveState(state);
tima_.saveState(state);
lcd_.saveState(state);
psg_.saveState(state);
return cc;
}
static int serialCntFrom(unsigned long cyclesUntilDone, bool cgbFast) {
return cgbFast ? (cyclesUntilDone + 0xF) >> 4 : (cyclesUntilDone + 0x1FF) >> 9;
}
void Memory::loadState(SaveState const &state) {
psg_.loadState(state);
lcd_.loadState(state, state.mem.oamDmaPos < 0xA0 ? cart_.rdisabledRam() : ioamhram_);
tima_.loadState(state, TimaInterruptRequester(intreq_));
cart_.loadState(state);
intreq_.loadState(state);
divLastUpdate_ = state.mem.divLastUpdate;
intreq_.setEventTime(state.mem.nextSerialtime > state.cpu.cycleCounter
? state.mem.nextSerialtime
: state.cpu.cycleCounter);
intreq_.setEventTime(state.mem.unhaltTime);
lastOamDmaUpdate_ = state.mem.lastOamDmaUpdate;
dmaSource_ = state.mem.dmaSource;
dmaDestination_ = state.mem.dmaDestination;
oamDmaPos_ = state.mem.oamDmaPos;
serialCnt_ = intreq_.eventTime(intevent_serial) != disabled_time
? serialCntFrom(intreq_.eventTime(intevent_serial) - state.cpu.cycleCounter,
ioamhram_[0x102] & isCgb() * 2)
: 8;
cart_.setVrambank(ioamhram_[0x14F] & isCgb());
cart_.setOamDmaSrc(oam_dma_src_off);
cart_.setWrambank(isCgb() && (ioamhram_[0x170] & 0x07) ? ioamhram_[0x170] & 0x07 : 1);
if (lastOamDmaUpdate_ != disabled_time) {
oamDmaInitSetup();
unsigned oamEventPos = oamDmaPos_ < 0xA0 ? 0xA0 : 0x100;
intreq_.setEventTime(
lastOamDmaUpdate_ + (oamEventPos - oamDmaPos_) * 4);
}
intreq_.setEventTime((ioamhram_[0x140] & lcdc_en)
? lcd_.nextMode1IrqTime()
: state.cpu.cycleCounter);
blanklcd_ = false;
if (!isCgb())
std::memset(cart_.vramdata() + 0x2000, 0, 0x2000);
}
void Memory::setEndtime(unsigned long cc, unsigned long inc) {
if (intreq_.eventTime(intevent_blit) <= cc) {
intreq_.setEventTime(intreq_.eventTime(intevent_blit)
+ (70224 << isDoubleSpeed()));
}
intreq_.setEventTime(cc + (inc << isDoubleSpeed()));
}
void Memory::updateSerial(unsigned long const cc) {
if (intreq_.eventTime(intevent_serial) != disabled_time) {
if (intreq_.eventTime(intevent_serial) <= cc) {
ioamhram_[0x101] = (((ioamhram_[0x101] + 1) << serialCnt_) - 1) & 0xFF;
ioamhram_[0x102] &= 0x7F;
intreq_.setEventTime(disabled_time);
intreq_.flagIrq(8);
} else {
int const targetCnt = serialCntFrom(intreq_.eventTime(intevent_serial) - cc,
ioamhram_[0x102] & isCgb() * 2);
ioamhram_[0x101] = (((ioamhram_[0x101] + 1) << (serialCnt_ - targetCnt)) - 1) & 0xFF;
serialCnt_ = targetCnt;
}
}
}
void Memory::updateTimaIrq(unsigned long cc) {
while (intreq_.eventTime(intevent_tima) <= cc)
tima_.doIrqEvent(TimaInterruptRequester(intreq_));
}
void Memory::updateIrqs(unsigned long cc) {
updateSerial(cc);
updateTimaIrq(cc);
lcd_.update(cc);
}
unsigned long Memory::event(unsigned long cc) {
if (lastOamDmaUpdate_ != disabled_time)
updateOamDma(cc);
switch (intreq_.minEventId()) {
case intevent_unhalt:
intreq_.unhalt();
intreq_.setEventTime(disabled_time);
break;
case intevent_end:
intreq_.setEventTime(disabled_time - 1);
while (cc >= intreq_.minEventTime()
&& intreq_.eventTime(intevent_end) != disabled_time) {
cc = event(cc);
}
intreq_.setEventTime(disabled_time);
break;
case intevent_blit:
{
bool const lcden = ioamhram_[0x140] & lcdc_en;
unsigned long blitTime = intreq_.eventTime(intevent_blit);
if (lcden | blanklcd_) {
lcd_.updateScreen(blanklcd_, cc);
intreq_.setEventTime(disabled_time);
intreq_.setEventTime(disabled_time);
while (cc >= intreq_.minEventTime())
cc = event(cc);
} else
blitTime += 70224 << isDoubleSpeed();
blanklcd_ = lcden ^ 1;
intreq_.setEventTime(blitTime);
}
break;
case intevent_serial:
updateSerial(cc);
break;
case intevent_oam:
intreq_.setEventTime(lastOamDmaUpdate_ == disabled_time
? static_cast(disabled_time)
: intreq_.eventTime(intevent_oam) + 0xA0 * 4);
break;
case intevent_dma:
{
bool const doubleSpeed = isDoubleSpeed();
unsigned dmaSrc = dmaSource_;
unsigned dmaDest = dmaDestination_;
unsigned dmaLength = ((ioamhram_[0x155] & 0x7F) + 0x1) * 0x10;
unsigned length = hdmaReqFlagged(intreq_) ? 0x10 : dmaLength;
ackDmaReq(intreq_);
if ((static_cast(dmaDest) + length) & 0x10000) {
length = 0x10000 - dmaDest;
ioamhram_[0x155] |= 0x80;
}
dmaLength -= length;
if (!(ioamhram_[0x140] & lcdc_en))
dmaLength = 0;
{
unsigned long lOamDmaUpdate = lastOamDmaUpdate_;
lastOamDmaUpdate_ = disabled_time;
while (length--) {
unsigned const src = dmaSrc++ & 0xFFFF;
unsigned const data = (src & 0xE000) == 0x8000 || src > 0xFDFF
? 0xFF
: read(src, cc);
cc += 2 << doubleSpeed;
if (cc - 3 > lOamDmaUpdate) {
oamDmaPos_ = (oamDmaPos_ + 1) & 0xFF;
lOamDmaUpdate += 4;
if (oamDmaPos_ < 0xA0) {
if (oamDmaPos_ == 0)
startOamDma(lOamDmaUpdate - 1);
ioamhram_[src & 0xFF] = data;
} else if (oamDmaPos_ == 0xA0) {
endOamDma(lOamDmaUpdate - 1);
lOamDmaUpdate = disabled_time;
}
}
nontrivial_write(0x8000 | (dmaDest++ & 0x1FFF), data, cc);
}
lastOamDmaUpdate_ = lOamDmaUpdate;
}
cc += 4;
dmaSource_ = dmaSrc;
dmaDestination_ = dmaDest;
ioamhram_[0x155] = ((dmaLength / 0x10 - 0x1) & 0xFF) | (ioamhram_[0x155] & 0x80);
if ((ioamhram_[0x155] & 0x80) && lcd_.hdmaIsEnabled()) {
if (lastOamDmaUpdate_ != disabled_time)
updateOamDma(cc);
lcd_.disableHdma(cc);
}
}
break;
case intevent_tima:
tima_.doIrqEvent(TimaInterruptRequester(intreq_));
break;
case intevent_video:
lcd_.update(cc);
break;
case intevent_interrupts:
if (halted()) {
if (isCgb())
cc += 4;
intreq_.unhalt();
intreq_.setEventTime(disabled_time);
}
if (ime()) {
unsigned const pendingIrqs = intreq_.pendingIrqs();
unsigned const n = pendingIrqs & -pendingIrqs;
unsigned address;
if (n <= 4) {
static unsigned char const lut[] = { 0x40, 0x48, 0x48, 0x50 };
address = lut[n-1];
} else
address = 0x50 + n;
intreq_.ackIrq(n);
cc = interrupter_.interrupt(address, cc, *this);
}
break;
}
return cc;
}
unsigned long Memory::stop(unsigned long cc) {
cc += 4 + 4 * isDoubleSpeed();
if (ioamhram_[0x14D] & isCgb()) {
psg_.generateSamples(cc, isDoubleSpeed());
lcd_.speedChange(cc);
ioamhram_[0x14D] ^= 0x81;
intreq_.setEventTime((ioamhram_[0x140] & lcdc_en)
? lcd_.nextMode1IrqTime()
: cc + (70224 << isDoubleSpeed()));
if (intreq_.eventTime(intevent_end) > cc) {
intreq_.setEventTime(cc
+ ( isDoubleSpeed()
? (intreq_.eventTime(intevent_end) - cc) << 1
: (intreq_.eventTime(intevent_end) - cc) >> 1));
}
}
intreq_.halt();
intreq_.setEventTime(cc + 0x20000 + isDoubleSpeed() * 8);
return cc;
}
static void decCycles(unsigned long &counter, unsigned long dec) {
if (counter != disabled_time)
counter -= dec;
}
void Memory::decEventCycles(IntEventId eventId, unsigned long dec) {
if (intreq_.eventTime(eventId) != disabled_time)
intreq_.setEventTime(eventId, intreq_.eventTime(eventId) - dec);
}
unsigned long Memory::resetCounters(unsigned long cc) {
if (lastOamDmaUpdate_ != disabled_time)
updateOamDma(cc);
updateIrqs(cc);
{
unsigned long divinc = (cc - divLastUpdate_) >> 8;
ioamhram_[0x104] = (ioamhram_[0x104] + divinc) & 0xFF;
divLastUpdate_ += divinc << 8;
}
unsigned long const dec = cc < 0x10000
? 0
: (cc & ~0x7FFFul) - 0x8000;
decCycles(divLastUpdate_, dec);
decCycles(lastOamDmaUpdate_, dec);
decEventCycles(intevent_serial, dec);
decEventCycles(intevent_oam, dec);
decEventCycles(intevent_blit, dec);
decEventCycles(intevent_end, dec);
decEventCycles(intevent_unhalt, dec);
unsigned long const oldCC = cc;
cc -= dec;
intreq_.resetCc(oldCC, cc);
tima_.resetCc(oldCC, cc, TimaInterruptRequester(intreq_));
lcd_.resetCc(oldCC, cc);
psg_.resetCounter(cc, oldCC, isDoubleSpeed());
return cc;
}
void Memory::updateInput() {
unsigned state = 0xF;
if ((ioamhram_[0x100] & 0x30) != 0x30 && getInput_) {
unsigned input = (*getInput_)();
unsigned dpad_state = ~input >> 4;
unsigned button_state = ~input;
if (!(ioamhram_[0x100] & 0x10))
state &= dpad_state;
if (!(ioamhram_[0x100] & 0x20))
state &= button_state;
}
if (state != 0xF && (ioamhram_[0x100] & 0xF) == 0xF)
intreq_.flagIrq(0x10);
ioamhram_[0x100] = (ioamhram_[0x100] & -0x10u) | state;
}
void Memory::updateOamDma(unsigned long const cc) {
unsigned char const *const oamDmaSrc = oamDmaSrcPtr();
unsigned cycles = (cc - lastOamDmaUpdate_) >> 2;
while (cycles--) {
oamDmaPos_ = (oamDmaPos_ + 1) & 0xFF;
lastOamDmaUpdate_ += 4;
if (oamDmaPos_ < 0xA0) {
if (oamDmaPos_ == 0)
startOamDma(lastOamDmaUpdate_ - 1);
ioamhram_[oamDmaPos_] = oamDmaSrc ? oamDmaSrc[oamDmaPos_] : cart_.rtcRead();
} else if (oamDmaPos_ == 0xA0) {
endOamDma(lastOamDmaUpdate_ - 1);
lastOamDmaUpdate_ = disabled_time;
break;
}
}
}
void Memory::oamDmaInitSetup() {
if (ioamhram_[0x146] < 0xA0) {
cart_.setOamDmaSrc(ioamhram_[0x146] < 0x80 ? oam_dma_src_rom : oam_dma_src_vram);
} else if (ioamhram_[0x146] < 0xFE - isCgb() * 0x1E) {
cart_.setOamDmaSrc(ioamhram_[0x146] < 0xC0 ? oam_dma_src_sram : oam_dma_src_wram);
} else
cart_.setOamDmaSrc(oam_dma_src_invalid);
}
static unsigned char const * oamDmaSrcZero() {
static unsigned char zeroMem[0xA0];
return zeroMem;
}
unsigned char const * Memory::oamDmaSrcPtr() const {
switch (cart_.oamDmaSrc()) {
case oam_dma_src_rom:
return cart_.romdata(ioamhram_[0x146] >> 6) + (ioamhram_[0x146] << 8);
case oam_dma_src_sram:
return cart_.rsrambankptr() ? cart_.rsrambankptr() + (ioamhram_[0x146] << 8) : 0;
case oam_dma_src_vram:
return cart_.vrambankptr() + (ioamhram_[0x146] << 8);
case oam_dma_src_wram:
return cart_.wramdata(ioamhram_[0x146] >> 4 & 1) + (ioamhram_[0x146] << 8 & 0xFFF);
case oam_dma_src_invalid:
case oam_dma_src_off:
break;
}
return ioamhram_[0x146] == 0xFF && !isCgb() ? oamDmaSrcZero() : cart_.rdisabledRam();
}
void Memory::startOamDma(unsigned long cc) {
lcd_.oamChange(cart_.rdisabledRam(), cc);
}
void Memory::endOamDma(unsigned long cc) {
oamDmaPos_ = 0xFE;
cart_.setOamDmaSrc(oam_dma_src_off);
lcd_.oamChange(ioamhram_, cc);
}
unsigned Memory::nontrivial_ff_read(unsigned const p, unsigned long const cc) {
if (lastOamDmaUpdate_ != disabled_time)
updateOamDma(cc);
switch (p) {
case 0x00:
updateInput();
break;
case 0x01:
case 0x02:
updateSerial(cc);
break;
case 0x04:
{
unsigned long divcycles = (cc - divLastUpdate_) >> 8;
ioamhram_[0x104] = (ioamhram_[0x104] + divcycles) & 0xFF;
divLastUpdate_ += divcycles << 8;
}
break;
case 0x05:
ioamhram_[0x105] = tima_.tima(cc);
break;
case 0x0F:
updateIrqs(cc);
ioamhram_[0x10F] = intreq_.ifreg();
break;
case 0x26:
if (ioamhram_[0x126] & 0x80) {
psg_.generateSamples(cc, isDoubleSpeed());
ioamhram_[0x126] = 0xF0 | psg_.getStatus();
} else
ioamhram_[0x126] = 0x70;
break;
case 0x30:
case 0x31:
case 0x32:
case 0x33:
case 0x34:
case 0x35:
case 0x36:
case 0x37:
case 0x38:
case 0x39:
case 0x3A:
case 0x3B:
case 0x3C:
case 0x3D:
case 0x3E:
case 0x3F:
psg_.generateSamples(cc, isDoubleSpeed());
return psg_.waveRamRead(p & 0xF);
case 0x41:
return ioamhram_[0x141] | lcd_.getStat(ioamhram_[0x145], cc);
case 0x44:
return lcd_.getLyReg(cc);
case 0x69:
return lcd_.cgbBgColorRead(ioamhram_[0x168] & 0x3F, cc);
case 0x6B:
return lcd_.cgbSpColorRead(ioamhram_[0x16A] & 0x3F, cc);
default:
break;
}
return ioamhram_[p + 0x100];
}
static bool isInOamDmaConflictArea(OamDmaSrc const oamDmaSrc, unsigned const p, bool const cgb) {
struct Area { unsigned short areaUpper, exceptAreaLower, exceptAreaWidth, pad; };
static Area const cgbAreas[] = {
{ 0xC000, 0x8000, 0x2000, 0 },
{ 0xC000, 0x8000, 0x2000, 0 },
{ 0xA000, 0x0000, 0x8000, 0 },
{ 0xFE00, 0x0000, 0xC000, 0 },
{ 0xC000, 0x8000, 0x2000, 0 },
{ 0x0000, 0x0000, 0x0000, 0 }
};
static Area const dmgAreas[] = {
{ 0xFE00, 0x8000, 0x2000, 0 },
{ 0xFE00, 0x8000, 0x2000, 0 },
{ 0xA000, 0x0000, 0x8000, 0 },
{ 0xFE00, 0x8000, 0x2000, 0 },
{ 0xFE00, 0x8000, 0x2000, 0 },
{ 0x0000, 0x0000, 0x0000, 0 }
};
Area const *a = cgb ? cgbAreas : dmgAreas;
return p < a[oamDmaSrc].areaUpper
&& p - a[oamDmaSrc].exceptAreaLower >= a[oamDmaSrc].exceptAreaWidth;
}
unsigned Memory::nontrivial_read(unsigned const p, unsigned long const cc) {
if (p < 0xFF80) {
if (lastOamDmaUpdate_ != disabled_time) {
updateOamDma(cc);
if (isInOamDmaConflictArea(cart_.oamDmaSrc(), p, isCgb()) && oamDmaPos_ < 0xA0)
return ioamhram_[oamDmaPos_];
}
if (p < 0xC000) {
if (p < 0x8000)
return cart_.romdata(p >> 14)[p];
if (p < 0xA000) {
if (!lcd_.vramAccessible(cc))
return 0xFF;
return cart_.vrambankptr()[p];
}
if (cart_.rsrambankptr())
return cart_.rsrambankptr()[p];
return cart_.rtcRead();
}
if (p < 0xFE00)
return cart_.wramdata(p >> 12 & 1)[p & 0xFFF];
long const ffp = long(p) - 0xFF00;
if (ffp >= 0)
return nontrivial_ff_read(ffp, cc);
if (!lcd_.oamReadable(cc) || oamDmaPos_ < 0xA0)
return 0xFF;
}
return ioamhram_[p - 0xFE00];
}
void Memory::nontrivial_ff_write(unsigned const p, unsigned data, unsigned long const cc) {
if (lastOamDmaUpdate_ != disabled_time)
updateOamDma(cc);
switch (p & 0xFF) {
case 0x00:
if ((data ^ ioamhram_[0x100]) & 0x30) {
ioamhram_[0x100] = (ioamhram_[0x100] & ~0x30u) | (data & 0x30);
updateInput();
}
return;
case 0x01:
updateSerial(cc);
break;
case 0x02:
updateSerial(cc);
serialCnt_ = 8;
if ((data & 0x81) == 0x81) {
intreq_.setEventTime((data & isCgb() * 2)
? (cc & ~0x07ul) + 0x010 * 8
: (cc & ~0xFFul) + 0x200 * 8);
} else
intreq_.setEventTime(disabled_time);
data |= 0x7E - isCgb() * 2;
break;
case 0x04:
ioamhram_[0x104] = 0;
divLastUpdate_ = cc;
return;
case 0x05:
tima_.setTima(data, cc, TimaInterruptRequester(intreq_));
break;
case 0x06:
tima_.setTma(data, cc, TimaInterruptRequester(intreq_));
break;
case 0x07:
data |= 0xF8;
tima_.setTac(data, cc, TimaInterruptRequester(intreq_));
break;
case 0x0F:
updateIrqs(cc);
intreq_.setIfreg(0xE0 | data);
return;
case 0x10:
if (!psg_.isEnabled())
return;
psg_.generateSamples(cc, isDoubleSpeed());
psg_.setNr10(data);
data |= 0x80;
break;
case 0x11:
if (!psg_.isEnabled()) {
if (isCgb())
return;
data &= 0x3F;
}
psg_.generateSamples(cc, isDoubleSpeed());
psg_.setNr11(data);
data |= 0x3F;
break;
case 0x12:
if (!psg_.isEnabled())
return;
psg_.generateSamples(cc, isDoubleSpeed());
psg_.setNr12(data);
break;
case 0x13:
if (!psg_.isEnabled())
return;
psg_.generateSamples(cc, isDoubleSpeed());
psg_.setNr13(data);
return;
case 0x14:
if (!psg_.isEnabled())
return;
psg_.generateSamples(cc, isDoubleSpeed());
psg_.setNr14(data);
data |= 0xBF;
break;
case 0x16:
if (!psg_.isEnabled()) {
if (isCgb())
return;
data &= 0x3F;
}
psg_.generateSamples(cc, isDoubleSpeed());
psg_.setNr21(data);
data |= 0x3F;
break;
case 0x17:
if (!psg_.isEnabled())
return;
psg_.generateSamples(cc, isDoubleSpeed());
psg_.setNr22(data);
break;
case 0x18:
if (!psg_.isEnabled())
return;
psg_.generateSamples(cc, isDoubleSpeed());
psg_.setNr23(data);
return;
case 0x19:
if (!psg_.isEnabled())
return;
psg_.generateSamples(cc, isDoubleSpeed());
psg_.setNr24(data);
data |= 0xBF;
break;
case 0x1A:
if (!psg_.isEnabled())
return;
psg_.generateSamples(cc, isDoubleSpeed());
psg_.setNr30(data);
data |= 0x7F;
break;
case 0x1B:
if (!psg_.isEnabled() && isCgb())
return;
psg_.generateSamples(cc, isDoubleSpeed());
psg_.setNr31(data);
return;
case 0x1C:
if (!psg_.isEnabled())
return;
psg_.generateSamples(cc, isDoubleSpeed());
psg_.setNr32(data);
data |= 0x9F;
break;
case 0x1D:
if (!psg_.isEnabled())
return;
psg_.generateSamples(cc, isDoubleSpeed());
psg_.setNr33(data);
return;
case 0x1E:
if (!psg_.isEnabled())
return;
psg_.generateSamples(cc, isDoubleSpeed());
psg_.setNr34(data);
data |= 0xBF;
break;
case 0x20:
if (!psg_.isEnabled() && isCgb())
return;
psg_.generateSamples(cc, isDoubleSpeed());
psg_.setNr41(data);
return;
case 0x21:
if (!psg_.isEnabled())
return;
psg_.generateSamples(cc, isDoubleSpeed());
psg_.setNr42(data);
break;
case 0x22:
if (!psg_.isEnabled())
return;
psg_.generateSamples(cc, isDoubleSpeed());
psg_.setNr43(data);
break;
case 0x23:
if (!psg_.isEnabled())
return;
psg_.generateSamples(cc, isDoubleSpeed());
psg_.setNr44(data);
data |= 0xBF;
break;
case 0x24:
if (!psg_.isEnabled())
return;
psg_.generateSamples(cc, isDoubleSpeed());
psg_.setSoVolume(data);
break;
case 0x25:
if (!psg_.isEnabled())
return;
psg_.generateSamples(cc, isDoubleSpeed());
psg_.mapSo(data);
break;
case 0x26:
if ((ioamhram_[0x126] ^ data) & 0x80) {
psg_.generateSamples(cc, isDoubleSpeed());
if (!(data & 0x80)) {
for (unsigned i = 0x10; i < 0x26; ++i)
ff_write(i, 0, cc);
psg_.setEnabled(false);
} else {
psg_.reset();
psg_.setEnabled(true);
}
}
data = (data & 0x80) | (ioamhram_[0x126] & 0x7F);
break;
case 0x30:
case 0x31:
case 0x32:
case 0x33:
case 0x34:
case 0x35:
case 0x36:
case 0x37:
case 0x38:
case 0x39:
case 0x3A:
case 0x3B:
case 0x3C:
case 0x3D:
case 0x3E:
case 0x3F:
psg_.generateSamples(cc, isDoubleSpeed());
psg_.waveRamWrite(p & 0xF, data);
break;
case 0x40:
if (ioamhram_[0x140] != data) {
if ((ioamhram_[0x140] ^ data) & lcdc_en) {
unsigned const lyc = lcd_.getStat(ioamhram_[0x145], cc)
& lcdstat_lycflag;
bool const hdmaEnabled = lcd_.hdmaIsEnabled();
lcd_.lcdcChange(data, cc);
ioamhram_[0x144] = 0;
ioamhram_[0x141] &= 0xF8;
if (data & lcdc_en) {
intreq_.setEventTime(blanklcd_
? lcd_.nextMode1IrqTime()
: lcd_.nextMode1IrqTime()
+ (70224 << isDoubleSpeed()));
} else {
ioamhram_[0x141] |= lyc;
intreq_.setEventTime(
cc + (456 * 4 << isDoubleSpeed()));
if (hdmaEnabled)
flagHdmaReq(intreq_);
}
} else
lcd_.lcdcChange(data, cc);
ioamhram_[0x140] = data;
}
return;
case 0x41:
lcd_.lcdstatChange(data, cc);
data = (ioamhram_[0x141] & 0x87) | (data & 0x78);
break;
case 0x42:
lcd_.scyChange(data, cc);
break;
case 0x43:
lcd_.scxChange(data, cc);
break;
case 0x45:
lcd_.lycRegChange(data, cc);
break;
case 0x46:
if (lastOamDmaUpdate_ != disabled_time)
endOamDma(cc);
lastOamDmaUpdate_ = cc;
intreq_.setEventTime(cc + 8);
ioamhram_[0x146] = data;
oamDmaInitSetup();
return;
case 0x47:
if (!isCgb())
lcd_.dmgBgPaletteChange(data, cc);
break;
case 0x48:
if (!isCgb())
lcd_.dmgSpPalette1Change(data, cc);
break;
case 0x49:
if (!isCgb())
lcd_.dmgSpPalette2Change(data, cc);
break;
case 0x4A:
lcd_.wyChange(data, cc);
break;
case 0x4B:
lcd_.wxChange(data, cc);
break;
case 0x4D:
if (isCgb())
ioamhram_[0x14D] = (ioamhram_[0x14D] & ~1u) | (data & 1);
return;
case 0x4F:
if (isCgb()) {
cart_.setVrambank(data & 1);
ioamhram_[0x14F] = 0xFE | data;
}
return;
case 0x51:
dmaSource_ = data << 8 | (dmaSource_ & 0xFF);
return;
case 0x52:
dmaSource_ = (dmaSource_ & 0xFF00) | (data & 0xF0);
return;
case 0x53:
dmaDestination_ = data << 8 | (dmaDestination_ & 0xFF);
return;
case 0x54:
dmaDestination_ = (dmaDestination_ & 0xFF00) | (data & 0xF0);
return;
case 0x55:
if (isCgb()) {
ioamhram_[0x155] = data & 0x7F;
if (lcd_.hdmaIsEnabled()) {
if (!(data & 0x80)) {
ioamhram_[0x155] |= 0x80;
lcd_.disableHdma(cc);
}
} else {
if (data & 0x80) {
if (ioamhram_[0x140] & lcdc_en) {
lcd_.enableHdma(cc);
} else
flagHdmaReq(intreq_);
} else
flagGdmaReq(intreq_);
}
}
return;
case 0x56:
if (isCgb())
ioamhram_[0x156] = data | 0x3E;
return;
case 0x68:
if (isCgb())
ioamhram_[0x168] = data | 0x40;
return;
case 0x69:
if (isCgb()) {
unsigned index = ioamhram_[0x168] & 0x3F;
lcd_.cgbBgColorChange(index, data, cc);
ioamhram_[0x168] = (ioamhram_[0x168] & ~0x3F)
| ((index + (ioamhram_[0x168] >> 7)) & 0x3F);
}
return;
case 0x6A:
if (isCgb())
ioamhram_[0x16A] = data | 0x40;
return;
case 0x6B:
if (isCgb()) {
unsigned index = ioamhram_[0x16A] & 0x3F;
lcd_.cgbSpColorChange(index, data, cc);
ioamhram_[0x16A] = (ioamhram_[0x16A] & ~0x3F)
| ((index + (ioamhram_[0x16A] >> 7)) & 0x3F);
}
return;
case 0x6C:
if (isCgb())
ioamhram_[0x16C] = data | 0xFE;
return;
case 0x70:
if (isCgb()) {
cart_.setWrambank((data & 0x07) ? data & 0x07 : 1);
ioamhram_[0x170] = data | 0xF8;
}
return;
case 0x72:
case 0x73:
case 0x74:
if (isCgb())
break;
return;
case 0x75:
if (isCgb())
ioamhram_[0x175] = data | 0x8F;
return;
case 0xFF:
intreq_.setIereg(data);
break;
default:
return;
}
ioamhram_[p + 0x100] = data;
}
void Memory::nontrivial_write(unsigned const p, unsigned const data, unsigned long const cc) {
if (lastOamDmaUpdate_ != disabled_time) {
updateOamDma(cc);
if (isInOamDmaConflictArea(cart_.oamDmaSrc(), p, isCgb()) && oamDmaPos_ < 0xA0) {
ioamhram_[oamDmaPos_] = data;
return;
}
}
if (p < 0xFE00) {
if (p < 0xA000) {
if (p < 0x8000) {
cart_.mbcWrite(p, data);
} else if (lcd_.vramAccessible(cc)) {
lcd_.vramChange(cc);
cart_.vrambankptr()[p] = data;
}
} else if (p < 0xC000) {
if (cart_.wsrambankptr())
cart_.wsrambankptr()[p] = data;
else
cart_.rtcWrite(data);
} else
cart_.wramdata(p >> 12 & 1)[p & 0xFFF] = data;
} else if (p - 0xFF80u >= 0x7Fu) {
long const ffp = long(p) - 0xFF00;
if (ffp < 0) {
if (lcd_.oamWritable(cc) && oamDmaPos_ >= 0xA0 && (p < 0xFEA0 || isCgb())) {
lcd_.oamChange(cc);
ioamhram_[p - 0xFE00] = data;
}
} else
nontrivial_ff_write(ffp, data, cc);
} else
ioamhram_[p - 0xFE00] = data;
}
std::size_t Memory::fillSoundBuffer(unsigned long cc) {
psg_.generateSamples(cc, isDoubleSpeed());
return psg_.fillBuffer();
}
int Memory::loadROM(const void *romdata, unsigned romsize, const bool forceDmg, const bool multicartCompat)
{
if (const int fail = cart_.loadROM(romdata, romsize, forceDmg, multicartCompat))
return fail;
psg_.init(cart_.isCgb());
lcd_.reset(ioamhram_, cart_.vramdata(), cart_.isCgb());
interrupter_.setGameShark(std::string());
return 0;
}
}
libgambatte/Makefile.libretro 000664 001750 001750 00000020245 12720365247 017451 0 ustar 00sergio sergio 000000 000000 DEBUG = 0
ifeq ($(platform),)
platform = unix
ifeq ($(shell uname -a),)
platform = win
else ifneq ($(findstring MINGW,$(shell uname -a)),)
platform = win
else ifneq ($(findstring Darwin,$(shell uname -a)),)
platform = osx
else ifneq ($(findstring win,$(shell uname -a)),)
platform = win
endif
endif
# system platform
system_platform = unix
ifeq ($(shell uname -a),)
EXE_EXT = .exe
system_platform = win
else ifneq ($(findstring Darwin,$(shell uname -a)),)
system_platform = osx
else ifneq ($(findstring MINGW,$(shell uname -a)),)
system_platform = win
endif
TARGET_NAME := gambatte
ifeq ($(ARCHFLAGS),)
ifeq ($(archs),ppc)
ARCHFLAGS = -arch ppc -arch ppc64
else
ARCHFLAGS = -arch i386 -arch x86_64
endif
endif
# Unix
ifeq ($(platform), unix)
TARGET := $(TARGET_NAME)_libretro.so
fpic := -fPIC
SHARED := -shared -Wl,-version-script=libretro/link.T
# OS X
else ifeq ($(platform), osx)
TARGET := $(TARGET_NAME)_libretro.dylib
fpic := -fPIC
SHARED := -dynamiclib
OSXVER = `sw_vers -productVersion | cut -d. -f 2`
OSX_LT_MAVERICKS = `(( $(OSXVER) <= 9)) && echo "YES"`
#fpic += -mmacosx-version-min=10.1
ifndef ($(NOUNIVERSAL))
CFLAGS += $(ARCHFLAGS)
CXXFLAGS += $(ARCHFLAGS)
LDFLAGS += $(ARCHFLAGS)
endif
# iOS
else ifneq (,$(findstring ios,$(platform)))
TARGET := $(TARGET_NAME)_libretro_ios.dylib
fpic := -fPIC
SHARED := -dynamiclib
ifeq ($(IOSSDK),)
IOSSDK := $(shell xcodebuild -version -sdk iphoneos Path)
endif
CC = cc -arch armv7 -isysroot $(IOSSDK)
CXX = c++ -arch armv7 -isysroot $(IOSSDK)
ifeq ($(platform),ios9)
CC += -miphoneos-version-min=8.0
CXX += -miphoneos-version-min=8.0
PLATFORM_DEFINES := -miphoneos-version-min=8.0
else
CC += -miphoneos-version-min=5.0
CXX += -miphoneos-version-min=5.0
PLATFORM_DEFINES := -miphoneos-version-min=5.0
endif
# Theos
else ifeq ($(platform), theos_ios)
DEPLOYMENT_IOSVERSION = 5.0
TARGET = iphone:latest:$(DEPLOYMENT_IOSVERSION)
ARCHS = armv7 armv7s
TARGET_IPHONEOS_DEPLOYMENT_VERSION=$(DEPLOYMENT_IOSVERSION)
THEOS_BUILD_DIR := objs
include $(THEOS)/makefiles/common.mk
LIBRARY_NAME = $(TARGET_NAME)_libretro_ios
# QNX
else ifeq ($(platform), qnx)
TARGET := $(TARGET_NAME)_libretro_qnx.so
fpic := -fPIC
SHARED := -lcpp -lm -shared -Wl,-version-script=libretro/link.T
CC = qcc -Vgcc_ntoarmv7le
CXX = QCC -Vgcc_ntoarmv7le_cpp
AR = QCC -Vgcc_ntoarmv7le
PLATFORM_DEFINES := -D__BLACKBERRY_QNX__ -fexceptions -marm -mcpu=cortex-a9 -mfpu=neon -mfloat-abi=softfp
# PS3
else ifeq ($(platform), ps3)
TARGET := $(TARGET_NAME)_libretro_ps3.a
CC = $(CELL_SDK)/host-win32/ppu/bin/ppu-lv2-gcc.exe
CXX = $(CELL_SDK)/host-win32/ppu/bin/ppu-lv2-g++.exe
AR = $(CELL_SDK)/host-win32/ppu/bin/ppu-lv2-ar.exe
PLATFORM_DEFINES := -D__CELLOS_LV2__
STATIC_LINKING = 1
# sncps3
else ifeq ($(platform), sncps3)
TARGET := $(TARGET_NAME)_libretro_ps3.a
CC = $(CELL_SDK)/host-win32/sn/bin/ps3ppusnc.exe
CXX = $(CELL_SDK)/host-win32/sn/bin/ps3ppusnc.exe
AR = $(CELL_SDK)/host-win32/sn/bin/ps3snarl.exe
PLATFORM_DEFINES := -D__CELLOS_LV2__
STATIC_LINKING = 1
# Lightweight PS3 Homebrew SDK
else ifeq ($(platform), psl1ght)
TARGET := $(TARGET_NAME)_libretro_psl1ght.a
CC = $(PS3DEV)/ppu/bin/ppu-gcc$(EXE_EXT)
CXX = $(PS3DEV)/ppu/bin/ppu-g++$(EXE_EXT)
AR = $(PS3DEV)/ppu/bin/ppu-ar$(EXE_EXT)
PLATFORM_DEFINES := -D__CELLOS_LV2__
STATIC_LINKING = 1
# PSP
else ifeq ($(platform), psp1)
TARGET := $(TARGET_NAME)_libretro_psp1.a
CC = psp-gcc$(EXE_EXT)
CXX = psp-g++$(EXE_EXT)
AR = psp-ar$(EXE_EXT)
PLATFORM_DEFINES := -DPSP -DCC_RESAMPLER
CFLAGS += -G0
CXXFLAGS += -G0
STATIC_LINKING = 1
# Vita
else ifeq ($(platform), vita)
TARGET := $(TARGET_NAME)_libretro_vita.a
CC = arm-vita-eabi-gcc$(EXE_EXT)
CXX = arm-vita-eabi-g++$(EXE_EXT)
AR = arm-vita-eabi-ar$(EXE_EXT)
PLATFORM_DEFINES := -DCC_RESAMPLER
CFLAGS += -DVITA
CXXFLAGS += -DVITA
STATIC_LINKING = 1
# CTR(3DS)
else ifeq ($(platform), ctr)
TARGET := $(TARGET_NAME)_libretro_ctr.a
CC = $(DEVKITARM)/bin/arm-none-eabi-gcc$(EXE_EXT)
CXX = $(DEVKITARM)/bin/arm-none-eabi-g++$(EXE_EXT)
AR = $(DEVKITARM)/bin/arm-none-eabi-ar$(EXE_EXT)
PLATFORM_DEFINES := -DARM11 -D_3DS -DCC_RESAMPLER
CFLAGS += -march=armv6k -mtune=mpcore -mfloat-abi=hard
CFLAGS += -Wall -mword-relocations
CFLAGS += -fomit-frame-pointer -ffast-math
CXXFLAGS += $(CFLAGS)
STATIC_LINKING = 1
# Raspberry Pi 2
else ifeq ($(platform), rpi2)
TARGET := $(TARGET_NAME)_libretro.so
fpic := -fPIC
SHARED := -shared -Wl,-version-script=libretro/link.T
PLATFORM_DEFINES := -DARM
CFLAGS += -marm -mcpu=cortex-a7 -mfpu=neon-vfpv4 -mfloat-abi=hard -funsafe-math-optimizations
CFLAGS += -fomit-frame-pointer -ffast-math
CXXFLAGS += $(CFLAGS)
# Xbox 360
else ifeq ($(platform), xenon)
TARGET := $(TARGET_NAME)_libretro_xenon360.a
CC = xenon-gcc$(EXE_EXT)
CXX = xenon-g++$(EXE_EXT)
AR = xenon-ar$(EXE_EXT)
PLATFORM_DEFINES := -D__LIBXENON__
STATIC_LINKING = 1
# Nintendo Game Cube
else ifeq ($(platform), ngc)
TARGET := $(TARGET_NAME)_libretro_ngc.a
CC = $(DEVKITPPC)/bin/powerpc-eabi-gcc$(EXE_EXT)
CXX = $(DEVKITPPC)/bin/powerpc-eabi-g++$(EXE_EXT)
AR = $(DEVKITPPC)/bin/powerpc-eabi-ar$(EXE_EXT)
PLATFORM_DEFINES += -DGEKKO -DHW_DOL -mrvl -mcpu=750 -meabi -mhard-float
STATIC_LINKING = 1
# Nintendo Wii
else ifeq ($(platform), wii)
TARGET := $(TARGET_NAME)_libretro_wii.a
CC = $(DEVKITPPC)/bin/powerpc-eabi-gcc$(EXE_EXT)
CXX = $(DEVKITPPC)/bin/powerpc-eabi-g++$(EXE_EXT)
AR = $(DEVKITPPC)/bin/powerpc-eabi-ar$(EXE_EXT)
PLATFORM_DEFINES += -DGEKKO -DHW_RVL -mrvl -mcpu=750 -meabi -mhard-float
STATIC_LINKING = 1
# ARM
else ifneq (,$(findstring armv,$(platform)))
TARGET := $(TARGET_NAME)_libretro.so
fpic := -fPIC
SHARED := -shared -Wl,-version-script=libretro/link.T
ifneq (,$(findstring cortexa5,$(platform)))
PLATFORM_DEFINES += -marm -mcpu=cortex-a5
else ifneq (,$(findstring cortexa8,$(platform)))
PLATFORM_DEFINES += -marm -mcpu=cortex-a8
else ifneq (,$(findstring cortexa9,$(platform)))
PLATFORM_DEFINES += -marm -mcpu=cortex-a9
else ifneq (,$(findstring cortexa15a7,$(platform)))
PLATFORM_DEFINES += -marm -mcpu=cortex-a15.cortex-a7
else
PLATFORM_DEFINES += -marm
endif
ifneq (,$(findstring softfloat,$(platform)))
PLATFORM_DEFINES += -mfloat-abi=softfp
else ifneq (,$(findstring hardfloat,$(platform)))
PLATFORM_DEFINES += -mfloat-abi=hard
endif
PLATFORM_DEFINES += -DARM
# emscripten
else ifeq ($(platform), emscripten)
TARGET := $(TARGET_NAME)_libretro_emscripten.bc
# GCW0
else ifeq ($(platform), gcw0)
TARGET := $(TARGET_NAME)_libretro.so
CC = /opt/gcw0-toolchain/usr/bin/mipsel-linux-gcc
CXX = /opt/gcw0-toolchain/usr/bin/mipsel-linux-g++
AR = /opt/gcw0-toolchain/usr/bin/mipsel-linux-ar
fpic := -fPIC
SHARED := -shared -Wl,-version-script=libretro/link.T
PLATFORM_DEFINES := -DCC_RESAMPLER
CFLAGS += -O3 -fomit-frame-pointer -march=mips32 -mtune=mips32r2 -mhard-float
CXXFLAGS += $(CFLAGS)
# Windows
else
TARGET := $(TARGET_NAME)_libretro.dll
CC = gcc
CXX = g++
SHARED := -shared -static-libgcc -static-libstdc++ -Wl,-no-undefined -Wl,-version-script=libretro/link.T
endif
ifeq ($(DEBUG), 1)
CFLAGS += -O0 -g
CXXFLAGS += -O0 -g
else
CFLAGS += -O3
CXXFLAGS += -O3 -fno-exceptions -fno-rtti -DHAVE_STDINT_H
endif
CORE_DIR := src
include Makefile.common
OBJS := $(SOURCES_CXX:.cpp=.o) $(SOURCES_C:.c=.o)
DEFINES := -D__LIBRETRO__ $(PLATFORM_DEFINES) -DHAVE_STDINT_H -DHAVE_INTTYPES_H -DINLINE=inline -DVIDEO_RGB565
CFLAGS += $(CODE_DEFINES) $(fpic) $(DEFINES)
CXXFLAGS += $(fpic) $(DEFINES)
LIBS :=
%.o: %.cpp
$(CXX) -c -o $@ $< $(CXXFLAGS) $(INCFLAGS)
%.o: %.c
$(CC) -c -o $@ $< $(CFLAGS) $(INCFLAGS)
ifeq ($(platform), theos_ios)
COMMON_FLAGS := -DIOS $(COMMON_DEFINES) $(INCFLAGS) -I$(THEOS_INCLUDE_PATH) -Wno-error
$(LIBRARY_NAME)_CFLAGS += $(CFLAGS) $(COMMON_FLAGS)
$(LIBRARY_NAME)_CXXFLAGS += $(CXXFLAGS) $(COMMON_FLAGS)
${LIBRARY_NAME}_FILES = $(SOURCES_CXX) $(SOURCES_C)
include $(THEOS_MAKE_PATH)/library.mk
else
all: $(TARGET)
ifeq ($(platform), osx)
ifndef ($(NOUNIVERSAL))
CFLAGS += $(ARCHFLAGS)
CXXFLAGS += $(ARCHFLAGS)
LFLAGS += $(ARCHFLAGS)
endif
endif
$(TARGET): $(OBJS)
ifeq ($(STATIC_LINKING), 1)
$(AR) rcs $@ $(OBJS)
else
$(CXX) -o $@ $(SHARED) $(OBJS) $(LDFLAGS) $(LIBS)
endif
clean-objs:
rm -f $(OBJS)
clean:
rm -f $(OBJS)
rm -f $(TARGET)
.PHONY: clean clean-objs
endif
libgambatte/src/mem/ 000700 001750 001750 00000000000 12720366137 015515 5 ustar 00sergio sergio 000000 000000 libgambatte/libretro/msvc/msvc-2010/msvc-2010.vcxproj 000664 001750 001750 00000016205 12720365247 023260 0 ustar 00sergio sergio 000000 000000 
DebugWin32ReleaseWin32{A79F81F6-3FEE-48AA-9157-24EB772B624E}Win32Projmsvc-2010DynamicLibraryUnicodeDynamicLibraryUnicodetrue$(OutDir)msvc-2010$(TargetExt)$(SolutionDir)msvc-2010\$(Configuration)\$(OutDir)msvc-2010$(TargetExt)$(SolutionDir)msvc-2010\$(Configuration)\NotUsingLevel3ProgramDatabaseDisabledfalsetruefalse$(OutDir)$(ProjectName).pchMultiThreadedDebug_DEBUG;_WIN32;_LIB;%(PreprocessorDefinitions);HAVE_STDINT_HCallcap..\..\..\include;..\src\;..\src\video;..\src\file;..\src\sound;..\src\mem;..\..\..\..\common;..\libsnes;..\..\..\..\common\resampletruelibretro.defLevel3NotUsingFulltruetrueProgramDatabaseSizefalsefalse$(OutDir)$(ProjectName).pchMultiThreadedNDEBUG;_WIN32;_LIB;%(PreprocessorDefinitions);HAVE_STDINT_H..\..\..\include;..\..\..\src\;..\..\..\src\video;..\..\..\src\file;..\..\..\src\sound;..\..\..\src\mem;..\..\..\..\common;..\libsnes;..\..\..\..\common\resampletruetruetruelibretro.def
libgambatte/libretro/msvc/msvc-2003-xbox1/ 000700 001750 001750 00000000000 12720366137 021333 5 ustar 00sergio sergio 000000 000000 libgambatte/src/interruptrequester.cpp 000664 001750 001750 00000006073 12720365247 021462 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2010 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#include "interruptrequester.h"
#include "savestate.h"
namespace gambatte {
InterruptRequester::InterruptRequester()
: eventTimes_(disabled_time)
, minIntTime_(0)
, ifreg_(0)
, iereg_(0)
{
}
void InterruptRequester::saveState(SaveState &state) const {
state.mem.minIntTime = minIntTime_;
state.mem.IME = ime();
state.mem.halted = halted();
}
void InterruptRequester::loadState(SaveState const &state) {
minIntTime_ = state.mem.minIntTime;
ifreg_ = state.mem.ioamhram.get()[0x10F];
iereg_ = state.mem.ioamhram.get()[0x1FF] & 0x1F;
intFlags_.set(state.mem.IME, state.mem.halted);
eventTimes_.setValue(intFlags_.imeOrHalted() && pendingIrqs()
? minIntTime_
: static_cast(disabled_time));
}
void InterruptRequester::resetCc(unsigned long oldCc, unsigned long newCc) {
minIntTime_ = minIntTime_ < oldCc ? 0 : minIntTime_ - (oldCc - newCc);
if (eventTimes_.value(intevent_interrupts) != disabled_time)
eventTimes_.setValue(minIntTime_);
}
void InterruptRequester::ei(unsigned long cc) {
intFlags_.setIme();
minIntTime_ = cc + 1;
if (pendingIrqs())
eventTimes_.setValue(minIntTime_);
}
void InterruptRequester::di() {
intFlags_.unsetIme();
if (!intFlags_.imeOrHalted())
eventTimes_.setValue(disabled_time);
}
void InterruptRequester::halt() {
intFlags_.setHalted();
if (pendingIrqs())
eventTimes_.setValue(minIntTime_);
}
void InterruptRequester::unhalt() {
intFlags_.unsetHalted();
if (!intFlags_.imeOrHalted())
eventTimes_.setValue(disabled_time);
}
void InterruptRequester::flagIrq(unsigned bit) {
ifreg_ |= bit;
if (intFlags_.imeOrHalted() && pendingIrqs())
eventTimes_.setValue(minIntTime_);
}
void InterruptRequester::ackIrq(unsigned bit) {
ifreg_ ^= bit;
di();
}
void InterruptRequester::setIereg(unsigned iereg) {
iereg_ = iereg & 0x1F;
if (intFlags_.imeOrHalted()) {
eventTimes_.setValue(pendingIrqs()
? minIntTime_
: static_cast(disabled_time));
}
}
void InterruptRequester::setIfreg(unsigned ifreg) {
ifreg_ = ifreg;
if (intFlags_.imeOrHalted()) {
eventTimes_.setValue(pendingIrqs()
? minIntTime_
: static_cast(disabled_time));
}
}
}
libgambatte/include/gambatte.h 000664 001750 001750 00000012704 12720365247 017551 0 ustar 00sergio sergio 000000 000000 /***************************************************************************
* Copyright (C) 2007 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* This program 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 General Public License version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef GAMBATTE_H
#define GAMBATTE_H
#include "inputgetter.h"
#include "gbint.h"
#include
#include
namespace gambatte {
#ifdef VIDEO_RGB565
typedef uint16_t video_pixel_t;
#else
typedef uint_least32_t video_pixel_t;
#endif
enum { BG_PALETTE = 0, SP1_PALETTE = 1, SP2_PALETTE = 2 };
class GB {
public:
GB();
~GB();
enum LoadFlag {
FORCE_DMG = 1, /**< Treat the ROM as not having CGB support regardless of what its header advertises. */
GBA_CGB = 2, /**< Use GBA intial CPU register values when in CGB mode. */
MULTICART_COMPAT = 4 /**< Use heuristics to detect and support some multicart MBCs disguised as MBC1. */
};
int load(const void *romdata, unsigned size, unsigned flags = 0);
/** Emulates until at least 'samples' stereo sound samples are produced in the supplied buffer,
* or until a video frame has been drawn.
*
* There are 35112 stereo sound samples in a video frame.
* May run for uptil 2064 stereo samples too long.
* A stereo sample consists of two native endian 2s complement 16-bit PCM samples,
* with the left sample preceding the right one. Usually casting soundBuf to/from
* short* is OK and recommended. The reason for not using a short* in the interface
* is to avoid implementation-defined behaviour without compromising performance.
*
* Returns early when a new video frame has finished drawing in the video buffer,
* such that the caller may update the video output before the frame is overwritten.
* The return value indicates whether a new video frame has been drawn, and the
* exact time (in number of samples) at which it was drawn.
*
* @param videoBuf 160x144 RGB32 (native endian) video frame buffer or 0
* @param pitch distance in number of pixels (not bytes) from the start of one line to the next in videoBuf.
* @param soundBuf buffer with space >= samples + 2064
* @param samples in: number of stereo samples to produce, out: actual number of samples produced
* @return sample number at which the video frame was produced. -1 means no frame was produced.
*/
long runFor(gambatte::video_pixel_t *videoBuf, int pitch,
gambatte::uint_least32_t *soundBuf, unsigned &samples);
/** Reset to initial state.
* Equivalent to reloading a ROM image, or turning a Game Boy Color off and on again.
*/
void reset();
/** @param palNum 0 <= palNum < 3. One of BG_PALETTE, SP1_PALETTE and SP2_PALETTE.
* @param colorNum 0 <= colorNum < 4
*/
void setDmgPaletteColor(unsigned palNum, unsigned colorNum, unsigned rgb32);
/** Sets the callback used for getting input state. */
void setInputGetter(InputGetter *getInput);
/** Sets the directory used for storing save data. The default is the same directory as the ROM Image file. */
void setSaveDir(const std::string &sdir);
void *savedata_ptr();
unsigned savedata_size();
void *rtcdata_ptr();
unsigned rtcdata_size();
/** Returns true if the currently loaded ROM image is treated as having CGB support. */
bool isCgb() const;
/** Returns true if a ROM image is loaded. */
bool isLoaded() const;
void saveState(void *data);
void loadState(const void *data);
size_t stateSize() const;
void setColorCorrection(bool enable);
video_pixel_t gbcToRgb32(const unsigned bgr15);
/** Set Game Genie codes to apply to currently loaded ROM image. Cleared on ROM load.
* @param codes Game Genie codes in format HHH-HHH-HHH;HHH-HHH-HHH;... where H is [0-9]|[A-F]
*/
void setGameGenie(const std::string &codes);
/** Set Game Shark codes to apply to currently loaded ROM image. Cleared on ROM load.
* @param codes Game Shark codes in format 01HHHHHH;01HHHHHH;... where H is [0-9]|[A-F]
*/
void setGameShark(const std::string &codes);
void clearCheats();
#ifdef __LIBRETRO__
void *vram_ptr() const;
void *rambank0_ptr() const;
void *rambank1_ptr() const;
void *rombank0_ptr() const;
void *rombank1_ptr() const;
#endif
private:
struct Priv;
Priv *const p_;
void loadState(const std::string &filepath, bool osdMessage);
GB(const GB &);
GB & operator=(const GB &);
};
}
#endif
libgambatte/src/sound/duty_unit.h 000664 001750 001750 00000004174 12720365247 020307 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2007 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#ifndef DUTY_UNIT_H
#define DUTY_UNIT_H
#include "sound_unit.h"
#include "master_disabler.h"
#include "../savestate.h"
namespace gambatte {
class DutyUnit : public SoundUnit {
public:
DutyUnit();
virtual void event();
virtual void resetCounters(unsigned long oldCc);
bool isHighState() const { return high_; }
void nr1Change(unsigned newNr1, unsigned long cc);
void nr3Change(unsigned newNr3, unsigned long cc);
void nr4Change(unsigned newNr4, unsigned long cc);
void reset();
void saveState(SaveState::SPU::Duty &dstate, unsigned long cc);
void loadState(SaveState::SPU::Duty const &dstate, unsigned nr1, unsigned nr4, unsigned long cc);
void killCounter();
void reviveCounter(unsigned long cc);
//intended for use by SweepUnit only.
unsigned freq() const { return 2048 - (period_ >> 1); }
void setFreq(unsigned newFreq, unsigned long cc);
private:
unsigned long nextPosUpdate_;
unsigned short period_;
unsigned char pos_;
unsigned char duty_;
unsigned char inc_;
bool high_;
bool enableEvents_;
void setCounter();
void setDuty(unsigned nr1);
void updatePos(unsigned long cc);
};
class DutyMasterDisabler : public MasterDisabler {
public:
DutyMasterDisabler(bool &m, DutyUnit &dutyUnit) : MasterDisabler(m), dutyUnit_(dutyUnit) {}
virtual void operator()() { MasterDisabler::operator()(); dutyUnit_.killCounter(); }
private:
DutyUnit &dutyUnit_;
};
}
#endif
libgambatte/libretro/libretro.h 000664 001750 001750 00000300744 12720365247 020012 0 ustar 00sergio sergio 000000 000000 /* Copyright (C) 2010-2016 The RetroArch team
*
* ---------------------------------------------------------------------------------------
* The following license statement only applies to this libretro API header (libretro.h).
* ---------------------------------------------------------------------------------------
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef LIBRETRO_H__
#define LIBRETRO_H__
#include
#include
#include
#ifdef __cplusplus
extern "C" {
#endif
#ifndef __cplusplus
#if defined(_MSC_VER) && !defined(SN_TARGET_PS3)
/* Hack applied for MSVC when compiling in C89 mode
* as it isn't C99-compliant. */
#define bool unsigned char
#define true 1
#define false 0
#else
#include
#endif
#endif
#ifndef RETRO_CALLCONV
# if defined(__GNUC__) && defined(__i386__) && !defined(__x86_64__)
# define RETRO_CALLCONV __attribute__((cdecl))
# elif defined(_MSC_VER) && defined(_M_X86) && !defined(_M_X64)
# define RETRO_CALLCONV __cdecl
# else
# define RETRO_CALLCONV /* all other platforms only have one calling convention each */
# endif
#endif
#ifndef RETRO_API
# if defined(_WIN32) || defined(__CYGWIN__) || defined(__MINGW32__)
# ifdef RETRO_IMPORT_SYMBOLS
# ifdef __GNUC__
# define RETRO_API RETRO_CALLCONV __attribute__((__dllimport__))
# else
# define RETRO_API RETRO_CALLCONV __declspec(dllimport)
# endif
# else
# ifdef __GNUC__
# define RETRO_API RETRO_CALLCONV __attribute__((__dllexport__))
# else
# define RETRO_API RETRO_CALLCONV __declspec(dllexport)
# endif
# endif
# else
# if defined(__GNUC__) && __GNUC__ >= 4 && !defined(__CELLOS_LV2__)
# define RETRO_API RETRO_CALLCONV __attribute__((__visibility__("default")))
# else
# define RETRO_API RETRO_CALLCONV
# endif
# endif
#endif
/* Used for checking API/ABI mismatches that can break libretro
* implementations.
* It is not incremented for compatible changes to the API.
*/
#define RETRO_API_VERSION 1
/*
* Libretro's fundamental device abstractions.
*
* Libretro's input system consists of some standardized device types,
* such as a joypad (with/without analog), mouse, keyboard, lightgun
* and a pointer.
*
* The functionality of these devices are fixed, and individual cores
* map their own concept of a controller to libretro's abstractions.
* This makes it possible for frontends to map the abstract types to a
* real input device, and not having to worry about binding input
* correctly to arbitrary controller layouts.
*/
#define RETRO_DEVICE_TYPE_SHIFT 8
#define RETRO_DEVICE_MASK ((1 << RETRO_DEVICE_TYPE_SHIFT) - 1)
#define RETRO_DEVICE_SUBCLASS(base, id) (((id + 1) << RETRO_DEVICE_TYPE_SHIFT) | base)
/* Input disabled. */
#define RETRO_DEVICE_NONE 0
/* The JOYPAD is called RetroPad. It is essentially a Super Nintendo
* controller, but with additional L2/R2/L3/R3 buttons, similar to a
* PS1 DualShock. */
#define RETRO_DEVICE_JOYPAD 1
/* The mouse is a simple mouse, similar to Super Nintendo's mouse.
* X and Y coordinates are reported relatively to last poll (poll callback).
* It is up to the libretro implementation to keep track of where the mouse
* pointer is supposed to be on the screen.
* The frontend must make sure not to interfere with its own hardware
* mouse pointer.
*/
#define RETRO_DEVICE_MOUSE 2
/* KEYBOARD device lets one poll for raw key pressed.
* It is poll based, so input callback will return with the current
* pressed state.
* For event/text based keyboard input, see
* RETRO_ENVIRONMENT_SET_KEYBOARD_CALLBACK.
*/
#define RETRO_DEVICE_KEYBOARD 3
/* Lightgun X/Y coordinates are reported relatively to last poll,
* similar to mouse. */
#define RETRO_DEVICE_LIGHTGUN 4
/* The ANALOG device is an extension to JOYPAD (RetroPad).
* Similar to DualShock it adds two analog sticks.
* This is treated as a separate device type as it returns values in the
* full analog range of [-0x8000, 0x7fff]. Positive X axis is right.
* Positive Y axis is down.
* Only use ANALOG type when polling for analog values of the axes.
*/
#define RETRO_DEVICE_ANALOG 5
/* Abstracts the concept of a pointing mechanism, e.g. touch.
* This allows libretro to query in absolute coordinates where on the
* screen a mouse (or something similar) is being placed.
* For a touch centric device, coordinates reported are the coordinates
* of the press.
*
* Coordinates in X and Y are reported as:
* [-0x7fff, 0x7fff]: -0x7fff corresponds to the far left/top of the screen,
* and 0x7fff corresponds to the far right/bottom of the screen.
* The "screen" is here defined as area that is passed to the frontend and
* later displayed on the monitor.
*
* The frontend is free to scale/resize this screen as it sees fit, however,
* (X, Y) = (-0x7fff, -0x7fff) will correspond to the top-left pixel of the
* game image, etc.
*
* To check if the pointer coordinates are valid (e.g. a touch display
* actually being touched), PRESSED returns 1 or 0.
*
* If using a mouse on a desktop, PRESSED will usually correspond to the
* left mouse button, but this is a frontend decision.
* PRESSED will only return 1 if the pointer is inside the game screen.
*
* For multi-touch, the index variable can be used to successively query
* more presses.
* If index = 0 returns true for _PRESSED, coordinates can be extracted
* with _X, _Y for index = 0. One can then query _PRESSED, _X, _Y with
* index = 1, and so on.
* Eventually _PRESSED will return false for an index. No further presses
* are registered at this point. */
#define RETRO_DEVICE_POINTER 6
/* Buttons for the RetroPad (JOYPAD).
* The placement of these is equivalent to placements on the
* Super Nintendo controller.
* L2/R2/L3/R3 buttons correspond to the PS1 DualShock. */
#define RETRO_DEVICE_ID_JOYPAD_B 0
#define RETRO_DEVICE_ID_JOYPAD_Y 1
#define RETRO_DEVICE_ID_JOYPAD_SELECT 2
#define RETRO_DEVICE_ID_JOYPAD_START 3
#define RETRO_DEVICE_ID_JOYPAD_UP 4
#define RETRO_DEVICE_ID_JOYPAD_DOWN 5
#define RETRO_DEVICE_ID_JOYPAD_LEFT 6
#define RETRO_DEVICE_ID_JOYPAD_RIGHT 7
#define RETRO_DEVICE_ID_JOYPAD_A 8
#define RETRO_DEVICE_ID_JOYPAD_X 9
#define RETRO_DEVICE_ID_JOYPAD_L 10
#define RETRO_DEVICE_ID_JOYPAD_R 11
#define RETRO_DEVICE_ID_JOYPAD_L2 12
#define RETRO_DEVICE_ID_JOYPAD_R2 13
#define RETRO_DEVICE_ID_JOYPAD_L3 14
#define RETRO_DEVICE_ID_JOYPAD_R3 15
/* Index / Id values for ANALOG device. */
#define RETRO_DEVICE_INDEX_ANALOG_LEFT 0
#define RETRO_DEVICE_INDEX_ANALOG_RIGHT 1
#define RETRO_DEVICE_ID_ANALOG_X 0
#define RETRO_DEVICE_ID_ANALOG_Y 1
/* Id values for MOUSE. */
#define RETRO_DEVICE_ID_MOUSE_X 0
#define RETRO_DEVICE_ID_MOUSE_Y 1
#define RETRO_DEVICE_ID_MOUSE_LEFT 2
#define RETRO_DEVICE_ID_MOUSE_RIGHT 3
#define RETRO_DEVICE_ID_MOUSE_WHEELUP 4
#define RETRO_DEVICE_ID_MOUSE_WHEELDOWN 5
#define RETRO_DEVICE_ID_MOUSE_MIDDLE 6
#define RETRO_DEVICE_ID_MOUSE_HORIZ_WHEELUP 7
#define RETRO_DEVICE_ID_MOUSE_HORIZ_WHEELDOWN 8
/* Id values for LIGHTGUN types. */
#define RETRO_DEVICE_ID_LIGHTGUN_X 0
#define RETRO_DEVICE_ID_LIGHTGUN_Y 1
#define RETRO_DEVICE_ID_LIGHTGUN_TRIGGER 2
#define RETRO_DEVICE_ID_LIGHTGUN_CURSOR 3
#define RETRO_DEVICE_ID_LIGHTGUN_TURBO 4
#define RETRO_DEVICE_ID_LIGHTGUN_PAUSE 5
#define RETRO_DEVICE_ID_LIGHTGUN_START 6
/* Id values for POINTER. */
#define RETRO_DEVICE_ID_POINTER_X 0
#define RETRO_DEVICE_ID_POINTER_Y 1
#define RETRO_DEVICE_ID_POINTER_PRESSED 2
/* Returned from retro_get_region(). */
#define RETRO_REGION_NTSC 0
#define RETRO_REGION_PAL 1
/* Id values for LANGUAGE */
enum retro_language
{
RETRO_LANGUAGE_ENGLISH = 0,
RETRO_LANGUAGE_JAPANESE = 1,
RETRO_LANGUAGE_FRENCH = 2,
RETRO_LANGUAGE_SPANISH = 3,
RETRO_LANGUAGE_GERMAN = 4,
RETRO_LANGUAGE_ITALIAN = 5,
RETRO_LANGUAGE_DUTCH = 6,
RETRO_LANGUAGE_PORTUGUESE = 7,
RETRO_LANGUAGE_RUSSIAN = 8,
RETRO_LANGUAGE_KOREAN = 9,
RETRO_LANGUAGE_CHINESE_TRADITIONAL = 10,
RETRO_LANGUAGE_CHINESE_SIMPLIFIED = 11,
RETRO_LANGUAGE_ESPERANTO = 12,
RETRO_LANGUAGE_POLISH = 13,
RETRO_LANGUAGE_LAST,
/* Ensure sizeof(enum) == sizeof(int) */
RETRO_LANGUAGE_DUMMY = INT_MAX
};
/* Passed to retro_get_memory_data/size().
* If the memory type doesn't apply to the
* implementation NULL/0 can be returned.
*/
#define RETRO_MEMORY_MASK 0xff
/* Regular save RAM. This RAM is usually found on a game cartridge,
* backed up by a battery.
* If save game data is too complex for a single memory buffer,
* the SAVE_DIRECTORY (preferably) or SYSTEM_DIRECTORY environment
* callback can be used. */
#define RETRO_MEMORY_SAVE_RAM 0
/* Some games have a built-in clock to keep track of time.
* This memory is usually just a couple of bytes to keep track of time.
*/
#define RETRO_MEMORY_RTC 1
/* System ram lets a frontend peek into a game systems main RAM. */
#define RETRO_MEMORY_SYSTEM_RAM 2
/* Video ram lets a frontend peek into a game systems video RAM (VRAM). */
#define RETRO_MEMORY_VIDEO_RAM 3
/* Keysyms used for ID in input state callback when polling RETRO_KEYBOARD. */
enum retro_key
{
RETROK_UNKNOWN = 0,
RETROK_FIRST = 0,
RETROK_BACKSPACE = 8,
RETROK_TAB = 9,
RETROK_CLEAR = 12,
RETROK_RETURN = 13,
RETROK_PAUSE = 19,
RETROK_ESCAPE = 27,
RETROK_SPACE = 32,
RETROK_EXCLAIM = 33,
RETROK_QUOTEDBL = 34,
RETROK_HASH = 35,
RETROK_DOLLAR = 36,
RETROK_AMPERSAND = 38,
RETROK_QUOTE = 39,
RETROK_LEFTPAREN = 40,
RETROK_RIGHTPAREN = 41,
RETROK_ASTERISK = 42,
RETROK_PLUS = 43,
RETROK_COMMA = 44,
RETROK_MINUS = 45,
RETROK_PERIOD = 46,
RETROK_SLASH = 47,
RETROK_0 = 48,
RETROK_1 = 49,
RETROK_2 = 50,
RETROK_3 = 51,
RETROK_4 = 52,
RETROK_5 = 53,
RETROK_6 = 54,
RETROK_7 = 55,
RETROK_8 = 56,
RETROK_9 = 57,
RETROK_COLON = 58,
RETROK_SEMICOLON = 59,
RETROK_LESS = 60,
RETROK_EQUALS = 61,
RETROK_GREATER = 62,
RETROK_QUESTION = 63,
RETROK_AT = 64,
RETROK_LEFTBRACKET = 91,
RETROK_BACKSLASH = 92,
RETROK_RIGHTBRACKET = 93,
RETROK_CARET = 94,
RETROK_UNDERSCORE = 95,
RETROK_BACKQUOTE = 96,
RETROK_a = 97,
RETROK_b = 98,
RETROK_c = 99,
RETROK_d = 100,
RETROK_e = 101,
RETROK_f = 102,
RETROK_g = 103,
RETROK_h = 104,
RETROK_i = 105,
RETROK_j = 106,
RETROK_k = 107,
RETROK_l = 108,
RETROK_m = 109,
RETROK_n = 110,
RETROK_o = 111,
RETROK_p = 112,
RETROK_q = 113,
RETROK_r = 114,
RETROK_s = 115,
RETROK_t = 116,
RETROK_u = 117,
RETROK_v = 118,
RETROK_w = 119,
RETROK_x = 120,
RETROK_y = 121,
RETROK_z = 122,
RETROK_DELETE = 127,
RETROK_KP0 = 256,
RETROK_KP1 = 257,
RETROK_KP2 = 258,
RETROK_KP3 = 259,
RETROK_KP4 = 260,
RETROK_KP5 = 261,
RETROK_KP6 = 262,
RETROK_KP7 = 263,
RETROK_KP8 = 264,
RETROK_KP9 = 265,
RETROK_KP_PERIOD = 266,
RETROK_KP_DIVIDE = 267,
RETROK_KP_MULTIPLY = 268,
RETROK_KP_MINUS = 269,
RETROK_KP_PLUS = 270,
RETROK_KP_ENTER = 271,
RETROK_KP_EQUALS = 272,
RETROK_UP = 273,
RETROK_DOWN = 274,
RETROK_RIGHT = 275,
RETROK_LEFT = 276,
RETROK_INSERT = 277,
RETROK_HOME = 278,
RETROK_END = 279,
RETROK_PAGEUP = 280,
RETROK_PAGEDOWN = 281,
RETROK_F1 = 282,
RETROK_F2 = 283,
RETROK_F3 = 284,
RETROK_F4 = 285,
RETROK_F5 = 286,
RETROK_F6 = 287,
RETROK_F7 = 288,
RETROK_F8 = 289,
RETROK_F9 = 290,
RETROK_F10 = 291,
RETROK_F11 = 292,
RETROK_F12 = 293,
RETROK_F13 = 294,
RETROK_F14 = 295,
RETROK_F15 = 296,
RETROK_NUMLOCK = 300,
RETROK_CAPSLOCK = 301,
RETROK_SCROLLOCK = 302,
RETROK_RSHIFT = 303,
RETROK_LSHIFT = 304,
RETROK_RCTRL = 305,
RETROK_LCTRL = 306,
RETROK_RALT = 307,
RETROK_LALT = 308,
RETROK_RMETA = 309,
RETROK_LMETA = 310,
RETROK_LSUPER = 311,
RETROK_RSUPER = 312,
RETROK_MODE = 313,
RETROK_COMPOSE = 314,
RETROK_HELP = 315,
RETROK_PRINT = 316,
RETROK_SYSREQ = 317,
RETROK_BREAK = 318,
RETROK_MENU = 319,
RETROK_POWER = 320,
RETROK_EURO = 321,
RETROK_UNDO = 322,
RETROK_LAST,
RETROK_DUMMY = INT_MAX /* Ensure sizeof(enum) == sizeof(int) */
};
enum retro_mod
{
RETROKMOD_NONE = 0x0000,
RETROKMOD_SHIFT = 0x01,
RETROKMOD_CTRL = 0x02,
RETROKMOD_ALT = 0x04,
RETROKMOD_META = 0x08,
RETROKMOD_NUMLOCK = 0x10,
RETROKMOD_CAPSLOCK = 0x20,
RETROKMOD_SCROLLOCK = 0x40,
RETROKMOD_DUMMY = INT_MAX /* Ensure sizeof(enum) == sizeof(int) */
};
/* If set, this call is not part of the public libretro API yet. It can
* change or be removed at any time. */
#define RETRO_ENVIRONMENT_EXPERIMENTAL 0x10000
/* Environment callback to be used internally in frontend. */
#define RETRO_ENVIRONMENT_PRIVATE 0x20000
/* Environment commands. */
#define RETRO_ENVIRONMENT_SET_ROTATION 1 /* const unsigned * --
* Sets screen rotation of graphics.
* Is only implemented if rotation can be accelerated by hardware.
* Valid values are 0, 1, 2, 3, which rotates screen by 0, 90, 180,
* 270 degrees counter-clockwise respectively.
*/
#define RETRO_ENVIRONMENT_GET_OVERSCAN 2 /* bool * --
* Boolean value whether or not the implementation should use overscan,
* or crop away overscan.
*/
#define RETRO_ENVIRONMENT_GET_CAN_DUPE 3 /* bool * --
* Boolean value whether or not frontend supports frame duping,
* passing NULL to video frame callback.
*/
/* Environ 4, 5 are no longer supported (GET_VARIABLE / SET_VARIABLES),
* and reserved to avoid possible ABI clash.
*/
#define RETRO_ENVIRONMENT_SET_MESSAGE 6 /* const struct retro_message * --
* Sets a message to be displayed in implementation-specific manner
* for a certain amount of 'frames'.
* Should not be used for trivial messages, which should simply be
* logged via RETRO_ENVIRONMENT_GET_LOG_INTERFACE (or as a
* fallback, stderr).
*/
#define RETRO_ENVIRONMENT_SHUTDOWN 7 /* N/A (NULL) --
* Requests the frontend to shutdown.
* Should only be used if game has a specific
* way to shutdown the game from a menu item or similar.
*/
#define RETRO_ENVIRONMENT_SET_PERFORMANCE_LEVEL 8
/* const unsigned * --
* Gives a hint to the frontend how demanding this implementation
* is on a system. E.g. reporting a level of 2 means
* this implementation should run decently on all frontends
* of level 2 and up.
*
* It can be used by the frontend to potentially warn
* about too demanding implementations.
*
* The levels are "floating".
*
* This function can be called on a per-game basis,
* as certain games an implementation can play might be
* particularly demanding.
* If called, it should be called in retro_load_game().
*/
#define RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY 9
/* const char ** --
* Returns the "system" directory of the frontend.
* This directory can be used to store system specific
* content such as BIOSes, configuration data, etc.
* The returned value can be NULL.
* If so, no such directory is defined,
* and it's up to the implementation to find a suitable directory.
*
* NOTE: Some cores used this folder also for "save" data such as
* memory cards, etc, for lack of a better place to put it.
* This is now discouraged, and if possible, cores should try to
* use the new GET_SAVE_DIRECTORY.
*/
#define RETRO_ENVIRONMENT_SET_PIXEL_FORMAT 10
/* const enum retro_pixel_format * --
* Sets the internal pixel format used by the implementation.
* The default pixel format is RETRO_PIXEL_FORMAT_0RGB1555.
* This pixel format however, is deprecated (see enum retro_pixel_format).
* If the call returns false, the frontend does not support this pixel
* format.
*
* This function should be called inside retro_load_game() or
* retro_get_system_av_info().
*/
#define RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS 11
/* const struct retro_input_descriptor * --
* Sets an array of retro_input_descriptors.
* It is up to the frontend to present this in a usable way.
* The array is terminated by retro_input_descriptor::description
* being set to NULL.
* This function can be called at any time, but it is recommended
* to call it as early as possible.
*/
#define RETRO_ENVIRONMENT_SET_KEYBOARD_CALLBACK 12
/* const struct retro_keyboard_callback * --
* Sets a callback function used to notify core about keyboard events.
*/
#define RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE 13
/* const struct retro_disk_control_callback * --
* Sets an interface which frontend can use to eject and insert
* disk images.
* This is used for games which consist of multiple images and
* must be manually swapped out by the user (e.g. PSX).
*/
#define RETRO_ENVIRONMENT_SET_HW_RENDER 14
/* struct retro_hw_render_callback * --
* Sets an interface to let a libretro core render with
* hardware acceleration.
* Should be called in retro_load_game().
* If successful, libretro cores will be able to render to a
* frontend-provided framebuffer.
* The size of this framebuffer will be at least as large as
* max_width/max_height provided in get_av_info().
* If HW rendering is used, pass only RETRO_HW_FRAME_BUFFER_VALID or
* NULL to retro_video_refresh_t.
*/
#define RETRO_ENVIRONMENT_GET_VARIABLE 15
/* struct retro_variable * --
* Interface to acquire user-defined information from environment
* that cannot feasibly be supported in a multi-system way.
* 'key' should be set to a key which has already been set by
* SET_VARIABLES.
* 'data' will be set to a value or NULL.
*/
#define RETRO_ENVIRONMENT_SET_VARIABLES 16
/* const struct retro_variable * --
* Allows an implementation to signal the environment
* which variables it might want to check for later using
* GET_VARIABLE.
* This allows the frontend to present these variables to
* a user dynamically.
* This should be called as early as possible (ideally in
* retro_set_environment).
*
* 'data' points to an array of retro_variable structs
* terminated by a { NULL, NULL } element.
* retro_variable::key should be namespaced to not collide
* with other implementations' keys. E.g. A core called
* 'foo' should use keys named as 'foo_option'.
* retro_variable::value should contain a human readable
* description of the key as well as a '|' delimited list
* of expected values.
*
* The number of possible options should be very limited,
* i.e. it should be feasible to cycle through options
* without a keyboard.
*
* First entry should be treated as a default.
*
* Example entry:
* { "foo_option", "Speed hack coprocessor X; false|true" }
*
* Text before first ';' is description. This ';' must be
* followed by a space, and followed by a list of possible
* values split up with '|'.
*
* Only strings are operated on. The possible values will
* generally be displayed and stored as-is by the frontend.
*/
#define RETRO_ENVIRONMENT_GET_VARIABLE_UPDATE 17
/* bool * --
* Result is set to true if some variables are updated by
* frontend since last call to RETRO_ENVIRONMENT_GET_VARIABLE.
* Variables should be queried with GET_VARIABLE.
*/
#define RETRO_ENVIRONMENT_SET_SUPPORT_NO_GAME 18
/* const bool * --
* If true, the libretro implementation supports calls to
* retro_load_game() with NULL as argument.
* Used by cores which can run without particular game data.
* This should be called within retro_set_environment() only.
*/
#define RETRO_ENVIRONMENT_GET_LIBRETRO_PATH 19
/* const char ** --
* Retrieves the absolute path from where this libretro
* implementation was loaded.
* NULL is returned if the libretro was loaded statically
* (i.e. linked statically to frontend), or if the path cannot be
* determined.
* Mostly useful in cooperation with SET_SUPPORT_NO_GAME as assets can
* be loaded without ugly hacks.
*/
/* Environment 20 was an obsolete version of SET_AUDIO_CALLBACK.
* It was not used by any known core at the time,
* and was removed from the API. */
#define RETRO_ENVIRONMENT_SET_AUDIO_CALLBACK 22
/* const struct retro_audio_callback * --
* Sets an interface which is used to notify a libretro core about audio
* being available for writing.
* The callback can be called from any thread, so a core using this must
* have a thread safe audio implementation.
* It is intended for games where audio and video are completely
* asynchronous and audio can be generated on the fly.
* This interface is not recommended for use with emulators which have
* highly synchronous audio.
*
* The callback only notifies about writability; the libretro core still
* has to call the normal audio callbacks
* to write audio. The audio callbacks must be called from within the
* notification callback.
* The amount of audio data to write is up to the implementation.
* Generally, the audio callback will be called continously in a loop.
*
* Due to thread safety guarantees and lack of sync between audio and
* video, a frontend can selectively disallow this interface based on
* internal configuration. A core using this interface must also
* implement the "normal" audio interface.
*
* A libretro core using SET_AUDIO_CALLBACK should also make use of
* SET_FRAME_TIME_CALLBACK.
*/
#define RETRO_ENVIRONMENT_SET_FRAME_TIME_CALLBACK 21
/* const struct retro_frame_time_callback * --
* Lets the core know how much time has passed since last
* invocation of retro_run().
* The frontend can tamper with the timing to fake fast-forward,
* slow-motion, frame stepping, etc.
* In this case the delta time will use the reference value
* in frame_time_callback..
*/
#define RETRO_ENVIRONMENT_GET_RUMBLE_INTERFACE 23
/* struct retro_rumble_interface * --
* Gets an interface which is used by a libretro core to set
* state of rumble motors in controllers.
* A strong and weak motor is supported, and they can be
* controlled indepedently.
*/
#define RETRO_ENVIRONMENT_GET_INPUT_DEVICE_CAPABILITIES 24
/* uint64_t * --
* Gets a bitmask telling which device type are expected to be
* handled properly in a call to retro_input_state_t.
* Devices which are not handled or recognized always return
* 0 in retro_input_state_t.
* Example bitmask: caps = (1 << RETRO_DEVICE_JOYPAD) | (1 << RETRO_DEVICE_ANALOG).
* Should only be called in retro_run().
*/
#define RETRO_ENVIRONMENT_GET_SENSOR_INTERFACE (25 | RETRO_ENVIRONMENT_EXPERIMENTAL)
/* struct retro_sensor_interface * --
* Gets access to the sensor interface.
* The purpose of this interface is to allow
* setting state related to sensors such as polling rate,
* enabling/disable it entirely, etc.
* Reading sensor state is done via the normal
* input_state_callback API.
*/
#define RETRO_ENVIRONMENT_GET_CAMERA_INTERFACE (26 | RETRO_ENVIRONMENT_EXPERIMENTAL)
/* struct retro_camera_callback * --
* Gets an interface to a video camera driver.
* A libretro core can use this interface to get access to a
* video camera.
* New video frames are delivered in a callback in same
* thread as retro_run().
*
* GET_CAMERA_INTERFACE should be called in retro_load_game().
*
* Depending on the camera implementation used, camera frames
* will be delivered as a raw framebuffer,
* or as an OpenGL texture directly.
*
* The core has to tell the frontend here which types of
* buffers can be handled properly.
* An OpenGL texture can only be handled when using a
* libretro GL core (SET_HW_RENDER).
* It is recommended to use a libretro GL core when
* using camera interface.
*
* The camera is not started automatically. The retrieved start/stop
* functions must be used to explicitly
* start and stop the camera driver.
*/
#define RETRO_ENVIRONMENT_GET_LOG_INTERFACE 27
/* struct retro_log_callback * --
* Gets an interface for logging. This is useful for
* logging in a cross-platform way
* as certain platforms cannot use use stderr for logging.
* It also allows the frontend to
* show logging information in a more suitable way.
* If this interface is not used, libretro cores should
* log to stderr as desired.
*/
#define RETRO_ENVIRONMENT_GET_PERF_INTERFACE 28
/* struct retro_perf_callback * --
* Gets an interface for performance counters. This is useful
* for performance logging in a cross-platform way and for detecting
* architecture-specific features, such as SIMD support.
*/
#define RETRO_ENVIRONMENT_GET_LOCATION_INTERFACE 29
/* struct retro_location_callback * --
* Gets access to the location interface.
* The purpose of this interface is to be able to retrieve
* location-based information from the host device,
* such as current latitude / longitude.
*/
#define RETRO_ENVIRONMENT_GET_CONTENT_DIRECTORY 30 /* Old name, kept for compatibility. */
#define RETRO_ENVIRONMENT_GET_CORE_ASSETS_DIRECTORY 30
/* const char ** --
* Returns the "core assets" directory of the frontend.
* This directory can be used to store specific assets that the
* core relies upon, such as art assets,
* input data, etc etc.
* The returned value can be NULL.
* If so, no such directory is defined,
* and it's up to the implementation to find a suitable directory.
*/
#define RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY 31
/* const char ** --
* Returns the "save" directory of the frontend.
* This directory can be used to store SRAM, memory cards,
* high scores, etc, if the libretro core
* cannot use the regular memory interface (retro_get_memory_data()).
*
* NOTE: libretro cores used to check GET_SYSTEM_DIRECTORY for
* similar things before.
* They should still check GET_SYSTEM_DIRECTORY if they want to
* be backwards compatible.
* The path here can be NULL. It should only be non-NULL if the
* frontend user has set a specific save path.
*/
#define RETRO_ENVIRONMENT_SET_SYSTEM_AV_INFO 32
/* const struct retro_system_av_info * --
* Sets a new av_info structure. This can only be called from
* within retro_run().
* This should *only* be used if the core is completely altering the
* internal resolutions, aspect ratios, timings, sampling rate, etc.
* Calling this can require a full reinitialization of video/audio
* drivers in the frontend,
*
* so it is important to call it very sparingly, and usually only with
* the users explicit consent.
* An eventual driver reinitialize will happen so that video and
* audio callbacks
* happening after this call within the same retro_run() call will
* target the newly initialized driver.
*
* This callback makes it possible to support configurable resolutions
* in games, which can be useful to
* avoid setting the "worst case" in max_width/max_height.
*
* ***HIGHLY RECOMMENDED*** Do not call this callback every time
* resolution changes in an emulator core if it's
* expected to be a temporary change, for the reasons of possible
* driver reinitialization.
* This call is not a free pass for not trying to provide
* correct values in retro_get_system_av_info(). If you need to change
* things like aspect ratio or nominal width/height,
* use RETRO_ENVIRONMENT_SET_GEOMETRY, which is a softer variant
* of SET_SYSTEM_AV_INFO.
*
* If this returns false, the frontend does not acknowledge a
* changed av_info struct.
*/
#define RETRO_ENVIRONMENT_SET_PROC_ADDRESS_CALLBACK 33
/* const struct retro_get_proc_address_interface * --
* Allows a libretro core to announce support for the
* get_proc_address() interface.
* This interface allows for a standard way to extend libretro where
* use of environment calls are too indirect,
* e.g. for cases where the frontend wants to call directly into the core.
*
* If a core wants to expose this interface, SET_PROC_ADDRESS_CALLBACK
* **MUST** be called from within retro_set_environment().
*/
#define RETRO_ENVIRONMENT_SET_SUBSYSTEM_INFO 34
/* const struct retro_subsystem_info * --
* This environment call introduces the concept of libretro "subsystems".
* A subsystem is a variant of a libretro core which supports
* different kinds of games.
* The purpose of this is to support e.g. emulators which might
* have special needs, e.g. Super Nintendo's Super GameBoy, Sufami Turbo.
* It can also be used to pick among subsystems in an explicit way
* if the libretro implementation is a multi-system emulator itself.
*
* Loading a game via a subsystem is done with retro_load_game_special(),
* and this environment call allows a libretro core to expose which
* subsystems are supported for use with retro_load_game_special().
* A core passes an array of retro_game_special_info which is terminated
* with a zeroed out retro_game_special_info struct.
*
* If a core wants to use this functionality, SET_SUBSYSTEM_INFO
* **MUST** be called from within retro_set_environment().
*/
#define RETRO_ENVIRONMENT_SET_CONTROLLER_INFO 35
/* const struct retro_controller_info * --
* This environment call lets a libretro core tell the frontend
* which controller types are recognized in calls to
* retro_set_controller_port_device().
*
* Some emulators such as Super Nintendo
* support multiple lightgun types which must be specifically
* selected from.
* It is therefore sometimes necessary for a frontend to be able
* to tell the core about a special kind of input device which is
* not covered by the libretro input API.
*
* In order for a frontend to understand the workings of an input device,
* it must be a specialized type
* of the generic device types already defined in the libretro API.
*
* Which devices are supported can vary per input port.
* The core must pass an array of const struct retro_controller_info which
* is terminated with a blanked out struct. Each element of the struct
* corresponds to an ascending port index to
* retro_set_controller_port_device().
* Even if special device types are set in the libretro core,
* libretro should only poll input based on the base input device types.
*/
#define RETRO_ENVIRONMENT_SET_MEMORY_MAPS (36 | RETRO_ENVIRONMENT_EXPERIMENTAL)
/* const struct retro_memory_map * --
* This environment call lets a libretro core tell the frontend
* about the memory maps this core emulates.
* This can be used to implement, for example, cheats in a core-agnostic way.
*
* Should only be used by emulators; it doesn't make much sense for
* anything else.
* It is recommended to expose all relevant pointers through
* retro_get_memory_* as well.
*
* Can be called from retro_init and retro_load_game.
*/
#define RETRO_ENVIRONMENT_SET_GEOMETRY 37
/* const struct retro_game_geometry * --
* This environment call is similar to SET_SYSTEM_AV_INFO for changing
* video parameters, but provides a guarantee that drivers will not be
* reinitialized.
* This can only be called from within retro_run().
*
* The purpose of this call is to allow a core to alter nominal
* width/heights as well as aspect ratios on-the-fly, which can be
* useful for some emulators to change in run-time.
*
* max_width/max_height arguments are ignored and cannot be changed
* with this call as this could potentially require a reinitialization or a
* non-constant time operation.
* If max_width/max_height are to be changed, SET_SYSTEM_AV_INFO is required.
*
* A frontend must guarantee that this environment call completes in
* constant time.
*/
#define RETRO_ENVIRONMENT_GET_USERNAME 38
/* const char **
* Returns the specified username of the frontend, if specified by the user.
* This username can be used as a nickname for a core that has online facilities
* or any other mode where personalization of the user is desirable.
* The returned value can be NULL.
* If this environ callback is used by a core that requires a valid username,
* a default username should be specified by the core.
*/
#define RETRO_ENVIRONMENT_GET_LANGUAGE 39
/* unsigned * --
* Returns the specified language of the frontend, if specified by the user.
* It can be used by the core for localization purposes.
*/
#define RETRO_ENVIRONMENT_GET_CURRENT_SOFTWARE_FRAMEBUFFER (40 | RETRO_ENVIRONMENT_EXPERIMENTAL)
/* struct retro_framebuffer * --
* Returns a preallocated framebuffer which the core can use for rendering
* the frame into when not using SET_HW_RENDER.
* The framebuffer returned from this call must not be used
* after the current call to retro_run() returns.
*
* The goal of this call is to allow zero-copy behavior where a core
* can render directly into video memory, avoiding extra bandwidth cost by copying
* memory from core to video memory.
*
* If this call succeeds and the core renders into it,
* the framebuffer pointer and pitch can be passed to retro_video_refresh_t.
* If the buffer from GET_CURRENT_SOFTWARE_FRAMEBUFFER is to be used,
* the core must pass the exact
* same pointer as returned by GET_CURRENT_SOFTWARE_FRAMEBUFFER;
* i.e. passing a pointer which is offset from the
* buffer is undefined. The width, height and pitch parameters
* must also match exactly to the values obtained from GET_CURRENT_SOFTWARE_FRAMEBUFFER.
*
* It is possible for a frontend to return a different pixel format
* than the one used in SET_PIXEL_FORMAT. This can happen if the frontend
* needs to perform conversion.
*
* It is still valid for a core to render to a different buffer
* even if GET_CURRENT_SOFTWARE_FRAMEBUFFER succeeds.
*
* A frontend must make sure that the pointer obtained from this function is
* writeable (and readable).
*/
enum retro_hw_render_interface_type
{
RETRO_HW_RENDER_INTERFACE_VULKAN = 0,
RETRO_HW_RENDER_INTERFACE_DUMMY = INT_MAX
};
/* Base struct. All retro_hw_render_interface_* types
* contain at least these fields. */
struct retro_hw_render_interface
{
enum retro_hw_render_interface_type interface_type;
unsigned interface_version;
};
#define RETRO_ENVIRONMENT_GET_HW_RENDER_INTERFACE (41 | RETRO_ENVIRONMENT_EXPERIMENTAL)
/* const struct retro_hw_render_interface ** --
* Returns an API specific rendering interface for accessing API specific data.
* Not all HW rendering APIs support or need this.
* The contents of the returned pointer is specific to the rendering API
* being used. See the various headers like libretro_vulkan.h, etc.
*
* GET_HW_RENDER_INTERFACE cannot be called before context_reset has been called.
* Similarly, after context_destroyed callback returns,
* the contents of the HW_RENDER_INTERFACE are invalidated.
*/
#define RETRO_ENVIRONMENT_SET_SUPPORT_ACHIEVEMENTS (42 | RETRO_ENVIRONMENT_EXPERIMENTAL)
/* const bool * --
* If true, the libretro implementation supports achievements
* either via memory descriptors set with RETRO_ENVIRONMENT_SET_MEMORY_MAPS
* or via retro_get_memory_data/retro_get_memory_size.
*
* This must be called before the first call to retro_run.
*/
#define RETRO_MEMDESC_CONST (1 << 0) /* The frontend will never change this memory area once retro_load_game has returned. */
#define RETRO_MEMDESC_BIGENDIAN (1 << 1) /* The memory area contains big endian data. Default is little endian. */
#define RETRO_MEMDESC_ALIGN_2 (1 << 16) /* All memory access in this area is aligned to their own size, or 2, whichever is smaller. */
#define RETRO_MEMDESC_ALIGN_4 (2 << 16)
#define RETRO_MEMDESC_ALIGN_8 (3 << 16)
#define RETRO_MEMDESC_MINSIZE_2 (1 << 24) /* All memory in this region is accessed at least 2 bytes at the time. */
#define RETRO_MEMDESC_MINSIZE_4 (2 << 24)
#define RETRO_MEMDESC_MINSIZE_8 (3 << 24)
struct retro_memory_descriptor
{
uint64_t flags;
/* Pointer to the start of the relevant ROM or RAM chip.
* It's strongly recommended to use 'offset' if possible, rather than
* doing math on the pointer.
*
* If the same byte is mapped my multiple descriptors, their descriptors
* must have the same pointer.
* If 'start' does not point to the first byte in the pointer, put the
* difference in 'offset' instead.
*
* May be NULL if there's nothing usable here (e.g. hardware registers and
* open bus). No flags should be set if the pointer is NULL.
* It's recommended to minimize the number of descriptors if possible,
* but not mandatory. */
void *ptr;
size_t offset;
/* This is the location in the emulated address space
* where the mapping starts. */
size_t start;
/* Which bits must be same as in 'start' for this mapping to apply.
* The first memory descriptor to claim a certain byte is the one
* that applies.
* A bit which is set in 'start' must also be set in this.
* Can be zero, in which case each byte is assumed mapped exactly once.
* In this case, 'len' must be a power of two. */
size_t select;
/* If this is nonzero, the set bits are assumed not connected to the
* memory chip's address pins. */
size_t disconnect;
/* This one tells the size of the current memory area.
* If, after start+disconnect are applied, the address is higher than
* this, the highest bit of the address is cleared.
*
* If the address is still too high, the next highest bit is cleared.
* Can be zero, in which case it's assumed to be infinite (as limited
* by 'select' and 'disconnect'). */
size_t len;
/* To go from emulated address to physical address, the following
* order applies:
* Subtract 'start', pick off 'disconnect', apply 'len', add 'offset'.
*
* The address space name must consist of only a-zA-Z0-9_-,
* should be as short as feasible (maximum length is 8 plus the NUL),
* and may not be any other address space plus one or more 0-9A-F
* at the end.
* However, multiple memory descriptors for the same address space is
* allowed, and the address space name can be empty. NULL is treated
* as empty.
*
* Address space names are case sensitive, but avoid lowercase if possible.
* The same pointer may exist in multiple address spaces.
*
* Examples:
* blank+blank - valid (multiple things may be mapped in the same namespace)
* 'Sp'+'Sp' - valid (multiple things may be mapped in the same namespace)
* 'A'+'B' - valid (neither is a prefix of each other)
* 'S'+blank - valid ('S' is not in 0-9A-F)
* 'a'+blank - valid ('a' is not in 0-9A-F)
* 'a'+'A' - valid (neither is a prefix of each other)
* 'AR'+blank - valid ('R' is not in 0-9A-F)
* 'ARB'+blank - valid (the B can't be part of the address either, because
* there is no namespace 'AR')
* blank+'B' - not valid, because it's ambigous which address space B1234
* would refer to.
* The length can't be used for that purpose; the frontend may want
* to append arbitrary data to an address, without a separator. */
const char *addrspace;
};
/* The frontend may use the largest value of 'start'+'select' in a
* certain namespace to infer the size of the address space.
*
* If the address space is larger than that, a mapping with .ptr=NULL
* should be at the end of the array, with .select set to all ones for
* as long as the address space is big.
*
* Sample descriptors (minus .ptr, and RETRO_MEMFLAG_ on the flags):
* SNES WRAM:
* .start=0x7E0000, .len=0x20000
* (Note that this must be mapped before the ROM in most cases; some of the
* ROM mappers
* try to claim $7E0000, or at least $7E8000.)
* SNES SPC700 RAM:
* .addrspace="S", .len=0x10000
* SNES WRAM mirrors:
* .flags=MIRROR, .start=0x000000, .select=0xC0E000, .len=0x2000
* .flags=MIRROR, .start=0x800000, .select=0xC0E000, .len=0x2000
* SNES WRAM mirrors, alternate equivalent descriptor:
* .flags=MIRROR, .select=0x40E000, .disconnect=~0x1FFF
* (Various similar constructions can be created by combining parts of
* the above two.)
* SNES LoROM (512KB, mirrored a couple of times):
* .flags=CONST, .start=0x008000, .select=0x408000, .disconnect=0x8000, .len=512*1024
* .flags=CONST, .start=0x400000, .select=0x400000, .disconnect=0x8000, .len=512*1024
* SNES HiROM (4MB):
* .flags=CONST, .start=0x400000, .select=0x400000, .len=4*1024*1024
* .flags=CONST, .offset=0x8000, .start=0x008000, .select=0x408000, .len=4*1024*1024
* SNES ExHiROM (8MB):
* .flags=CONST, .offset=0, .start=0xC00000, .select=0xC00000, .len=4*1024*1024
* .flags=CONST, .offset=4*1024*1024, .start=0x400000, .select=0xC00000, .len=4*1024*1024
* .flags=CONST, .offset=0x8000, .start=0x808000, .select=0xC08000, .len=4*1024*1024
* .flags=CONST, .offset=4*1024*1024+0x8000, .start=0x008000, .select=0xC08000, .len=4*1024*1024
* Clarify the size of the address space:
* .ptr=NULL, .select=0xFFFFFF
* .len can be implied by .select in many of them, but was included for clarity.
*/
struct retro_memory_map
{
const struct retro_memory_descriptor *descriptors;
unsigned num_descriptors;
};
struct retro_controller_description
{
/* Human-readable description of the controller. Even if using a generic
* input device type, this can be set to the particular device type the
* core uses. */
const char *desc;
/* Device type passed to retro_set_controller_port_device(). If the device
* type is a sub-class of a generic input device type, use the
* RETRO_DEVICE_SUBCLASS macro to create an ID.
*
* E.g. RETRO_DEVICE_SUBCLASS(RETRO_DEVICE_JOYPAD, 1). */
unsigned id;
};
struct retro_controller_info
{
const struct retro_controller_description *types;
unsigned num_types;
};
struct retro_subsystem_memory_info
{
/* The extension associated with a memory type, e.g. "psram". */
const char *extension;
/* The memory type for retro_get_memory(). This should be at
* least 0x100 to avoid conflict with standardized
* libretro memory types. */
unsigned type;
};
struct retro_subsystem_rom_info
{
/* Describes what the content is (SGB BIOS, GB ROM, etc). */
const char *desc;
/* Same definition as retro_get_system_info(). */
const char *valid_extensions;
/* Same definition as retro_get_system_info(). */
bool need_fullpath;
/* Same definition as retro_get_system_info(). */
bool block_extract;
/* This is set if the content is required to load a game.
* If this is set to false, a zeroed-out retro_game_info can be passed. */
bool required;
/* Content can have multiple associated persistent
* memory types (retro_get_memory()). */
const struct retro_subsystem_memory_info *memory;
unsigned num_memory;
};
struct retro_subsystem_info
{
/* Human-readable string of the subsystem type, e.g. "Super GameBoy" */
const char *desc;
/* A computer friendly short string identifier for the subsystem type.
* This name must be [a-z].
* E.g. if desc is "Super GameBoy", this can be "sgb".
* This identifier can be used for command-line interfaces, etc.
*/
const char *ident;
/* Infos for each content file. The first entry is assumed to be the
* "most significant" content for frontend purposes.
* E.g. with Super GameBoy, the first content should be the GameBoy ROM,
* as it is the most "significant" content to a user.
* If a frontend creates new file paths based on the content used
* (e.g. savestates), it should use the path for the first ROM to do so. */
const struct retro_subsystem_rom_info *roms;
/* Number of content files associated with a subsystem. */
unsigned num_roms;
/* The type passed to retro_load_game_special(). */
unsigned id;
};
typedef void (*retro_proc_address_t)(void);
/* libretro API extension functions:
* (None here so far).
*
* Get a symbol from a libretro core.
* Cores should only return symbols which are actual
* extensions to the libretro API.
*
* Frontends should not use this to obtain symbols to standard
* libretro entry points (static linking or dlsym).
*
* The symbol name must be equal to the function name,
* e.g. if void retro_foo(void); exists, the symbol must be called "retro_foo".
* The returned function pointer must be cast to the corresponding type.
*/
typedef retro_proc_address_t (*retro_get_proc_address_t)(const char *sym);
struct retro_get_proc_address_interface
{
retro_get_proc_address_t get_proc_address;
};
enum retro_log_level
{
RETRO_LOG_DEBUG = 0,
RETRO_LOG_INFO,
RETRO_LOG_WARN,
RETRO_LOG_ERROR,
RETRO_LOG_DUMMY = INT_MAX
};
/* Logging function. Takes log level argument as well. */
typedef void (*retro_log_printf_t)(enum retro_log_level level,
const char *fmt, ...);
struct retro_log_callback
{
retro_log_printf_t log;
};
/* Performance related functions */
/* ID values for SIMD CPU features */
#define RETRO_SIMD_SSE (1 << 0)
#define RETRO_SIMD_SSE2 (1 << 1)
#define RETRO_SIMD_VMX (1 << 2)
#define RETRO_SIMD_VMX128 (1 << 3)
#define RETRO_SIMD_AVX (1 << 4)
#define RETRO_SIMD_NEON (1 << 5)
#define RETRO_SIMD_SSE3 (1 << 6)
#define RETRO_SIMD_SSSE3 (1 << 7)
#define RETRO_SIMD_MMX (1 << 8)
#define RETRO_SIMD_MMXEXT (1 << 9)
#define RETRO_SIMD_SSE4 (1 << 10)
#define RETRO_SIMD_SSE42 (1 << 11)
#define RETRO_SIMD_AVX2 (1 << 12)
#define RETRO_SIMD_VFPU (1 << 13)
#define RETRO_SIMD_PS (1 << 14)
#define RETRO_SIMD_AES (1 << 15)
#define RETRO_SIMD_VFPV3 (1 << 16)
#define RETRO_SIMD_VFPV4 (1 << 17)
#define RETRO_SIMD_POPCNT (1 << 18)
#define RETRO_SIMD_MOVBE (1 << 19)
typedef uint64_t retro_perf_tick_t;
typedef int64_t retro_time_t;
struct retro_perf_counter
{
const char *ident;
retro_perf_tick_t start;
retro_perf_tick_t total;
retro_perf_tick_t call_cnt;
bool registered;
};
/* Returns current time in microseconds.
* Tries to use the most accurate timer available.
*/
typedef retro_time_t (*retro_perf_get_time_usec_t)(void);
/* A simple counter. Usually nanoseconds, but can also be CPU cycles.
* Can be used directly if desired (when creating a more sophisticated
* performance counter system).
* */
typedef retro_perf_tick_t (*retro_perf_get_counter_t)(void);
/* Returns a bit-mask of detected CPU features (RETRO_SIMD_*). */
typedef uint64_t (*retro_get_cpu_features_t)(void);
/* Asks frontend to log and/or display the state of performance counters.
* Performance counters can always be poked into manually as well.
*/
typedef void (*retro_perf_log_t)(void);
/* Register a performance counter.
* ident field must be set with a discrete value and other values in
* retro_perf_counter must be 0.
* Registering can be called multiple times. To avoid calling to
* frontend redundantly, you can check registered field first. */
typedef void (*retro_perf_register_t)(struct retro_perf_counter *counter);
/* Starts a registered counter. */
typedef void (*retro_perf_start_t)(struct retro_perf_counter *counter);
/* Stops a registered counter. */
typedef void (*retro_perf_stop_t)(struct retro_perf_counter *counter);
/* For convenience it can be useful to wrap register, start and stop in macros.
* E.g.:
* #ifdef LOG_PERFORMANCE
* #define RETRO_PERFORMANCE_INIT(perf_cb, name) static struct retro_perf_counter name = {#name}; if (!name.registered) perf_cb.perf_register(&(name))
* #define RETRO_PERFORMANCE_START(perf_cb, name) perf_cb.perf_start(&(name))
* #define RETRO_PERFORMANCE_STOP(perf_cb, name) perf_cb.perf_stop(&(name))
* #else
* ... Blank macros ...
* #endif
*
* These can then be used mid-functions around code snippets.
*
* extern struct retro_perf_callback perf_cb; * Somewhere in the core.
*
* void do_some_heavy_work(void)
* {
* RETRO_PERFORMANCE_INIT(cb, work_1;
* RETRO_PERFORMANCE_START(cb, work_1);
* heavy_work_1();
* RETRO_PERFORMANCE_STOP(cb, work_1);
*
* RETRO_PERFORMANCE_INIT(cb, work_2);
* RETRO_PERFORMANCE_START(cb, work_2);
* heavy_work_2();
* RETRO_PERFORMANCE_STOP(cb, work_2);
* }
*
* void retro_deinit(void)
* {
* perf_cb.perf_log(); * Log all perf counters here for example.
* }
*/
struct retro_perf_callback
{
retro_perf_get_time_usec_t get_time_usec;
retro_get_cpu_features_t get_cpu_features;
retro_perf_get_counter_t get_perf_counter;
retro_perf_register_t perf_register;
retro_perf_start_t perf_start;
retro_perf_stop_t perf_stop;
retro_perf_log_t perf_log;
};
/* FIXME: Document the sensor API and work out behavior.
* It will be marked as experimental until then.
*/
enum retro_sensor_action
{
RETRO_SENSOR_ACCELEROMETER_ENABLE = 0,
RETRO_SENSOR_ACCELEROMETER_DISABLE,
RETRO_SENSOR_DUMMY = INT_MAX
};
/* Id values for SENSOR types. */
#define RETRO_SENSOR_ACCELEROMETER_X 0
#define RETRO_SENSOR_ACCELEROMETER_Y 1
#define RETRO_SENSOR_ACCELEROMETER_Z 2
typedef bool (*retro_set_sensor_state_t)(unsigned port,
enum retro_sensor_action action, unsigned rate);
typedef float (*retro_sensor_get_input_t)(unsigned port, unsigned id);
struct retro_sensor_interface
{
retro_set_sensor_state_t set_sensor_state;
retro_sensor_get_input_t get_sensor_input;
};
enum retro_camera_buffer
{
RETRO_CAMERA_BUFFER_OPENGL_TEXTURE = 0,
RETRO_CAMERA_BUFFER_RAW_FRAMEBUFFER,
RETRO_CAMERA_BUFFER_DUMMY = INT_MAX
};
/* Starts the camera driver. Can only be called in retro_run(). */
typedef bool (*retro_camera_start_t)(void);
/* Stops the camera driver. Can only be called in retro_run(). */
typedef void (*retro_camera_stop_t)(void);
/* Callback which signals when the camera driver is initialized
* and/or deinitialized.
* retro_camera_start_t can be called in initialized callback.
*/
typedef void (*retro_camera_lifetime_status_t)(void);
/* A callback for raw framebuffer data. buffer points to an XRGB8888 buffer.
* Width, height and pitch are similar to retro_video_refresh_t.
* First pixel is top-left origin.
*/
typedef void (*retro_camera_frame_raw_framebuffer_t)(const uint32_t *buffer,
unsigned width, unsigned height, size_t pitch);
/* A callback for when OpenGL textures are used.
*
* texture_id is a texture owned by camera driver.
* Its state or content should be considered immutable, except for things like
* texture filtering and clamping.
*
* texture_target is the texture target for the GL texture.
* These can include e.g. GL_TEXTURE_2D, GL_TEXTURE_RECTANGLE, and possibly
* more depending on extensions.
*
* affine points to a packed 3x3 column-major matrix used to apply an affine
* transform to texture coordinates. (affine_matrix * vec3(coord_x, coord_y, 1.0))
* After transform, normalized texture coord (0, 0) should be bottom-left
* and (1, 1) should be top-right (or (width, height) for RECTANGLE).
*
* GL-specific typedefs are avoided here to avoid relying on gl.h in
* the API definition.
*/
typedef void (*retro_camera_frame_opengl_texture_t)(unsigned texture_id,
unsigned texture_target, const float *affine);
struct retro_camera_callback
{
/* Set by libretro core.
* Example bitmask: caps = (1 << RETRO_CAMERA_BUFFER_OPENGL_TEXTURE) | (1 << RETRO_CAMERA_BUFFER_RAW_FRAMEBUFFER).
*/
uint64_t caps;
/* Desired resolution for camera. Is only used as a hint. */
unsigned width;
unsigned height;
/* Set by frontend. */
retro_camera_start_t start;
retro_camera_stop_t stop;
/* Set by libretro core if raw framebuffer callbacks will be used. */
retro_camera_frame_raw_framebuffer_t frame_raw_framebuffer;
/* Set by libretro core if OpenGL texture callbacks will be used. */
retro_camera_frame_opengl_texture_t frame_opengl_texture;
/* Set by libretro core. Called after camera driver is initialized and
* ready to be started.
* Can be NULL, in which this callback is not called.
*/
retro_camera_lifetime_status_t initialized;
/* Set by libretro core. Called right before camera driver is
* deinitialized.
* Can be NULL, in which this callback is not called.
*/
retro_camera_lifetime_status_t deinitialized;
};
/* Sets the interval of time and/or distance at which to update/poll
* location-based data.
*
* To ensure compatibility with all location-based implementations,
* values for both interval_ms and interval_distance should be provided.
*
* interval_ms is the interval expressed in milliseconds.
* interval_distance is the distance interval expressed in meters.
*/
typedef void (*retro_location_set_interval_t)(unsigned interval_ms,
unsigned interval_distance);
/* Start location services. The device will start listening for changes to the
* current location at regular intervals (which are defined with
* retro_location_set_interval_t). */
typedef bool (*retro_location_start_t)(void);
/* Stop location services. The device will stop listening for changes
* to the current location. */
typedef void (*retro_location_stop_t)(void);
/* Get the position of the current location. Will set parameters to
* 0 if no new location update has happened since the last time. */
typedef bool (*retro_location_get_position_t)(double *lat, double *lon,
double *horiz_accuracy, double *vert_accuracy);
/* Callback which signals when the location driver is initialized
* and/or deinitialized.
* retro_location_start_t can be called in initialized callback.
*/
typedef void (*retro_location_lifetime_status_t)(void);
struct retro_location_callback
{
retro_location_start_t start;
retro_location_stop_t stop;
retro_location_get_position_t get_position;
retro_location_set_interval_t set_interval;
retro_location_lifetime_status_t initialized;
retro_location_lifetime_status_t deinitialized;
};
enum retro_rumble_effect
{
RETRO_RUMBLE_STRONG = 0,
RETRO_RUMBLE_WEAK = 1,
RETRO_RUMBLE_DUMMY = INT_MAX
};
/* Sets rumble state for joypad plugged in port 'port'.
* Rumble effects are controlled independently,
* and setting e.g. strong rumble does not override weak rumble.
* Strength has a range of [0, 0xffff].
*
* Returns true if rumble state request was honored.
* Calling this before first retro_run() is likely to return false. */
typedef bool (*retro_set_rumble_state_t)(unsigned port,
enum retro_rumble_effect effect, uint16_t strength);
struct retro_rumble_interface
{
retro_set_rumble_state_t set_rumble_state;
};
/* Notifies libretro that audio data should be written. */
typedef void (*retro_audio_callback_t)(void);
/* True: Audio driver in frontend is active, and callback is
* expected to be called regularily.
* False: Audio driver in frontend is paused or inactive.
* Audio callback will not be called until set_state has been
* called with true.
* Initial state is false (inactive).
*/
typedef void (*retro_audio_set_state_callback_t)(bool enabled);
struct retro_audio_callback
{
retro_audio_callback_t callback;
retro_audio_set_state_callback_t set_state;
};
/* Notifies a libretro core of time spent since last invocation
* of retro_run() in microseconds.
*
* It will be called right before retro_run() every frame.
* The frontend can tamper with timing to support cases like
* fast-forward, slow-motion and framestepping.
*
* In those scenarios the reference frame time value will be used. */
typedef int64_t retro_usec_t;
typedef void (*retro_frame_time_callback_t)(retro_usec_t usec);
struct retro_frame_time_callback
{
retro_frame_time_callback_t callback;
/* Represents the time of one frame. It is computed as
* 1000000 / fps, but the implementation will resolve the
* rounding to ensure that framestepping, etc is exact. */
retro_usec_t reference;
};
/* Pass this to retro_video_refresh_t if rendering to hardware.
* Passing NULL to retro_video_refresh_t is still a frame dupe as normal.
* */
#define RETRO_HW_FRAME_BUFFER_VALID ((void*)-1)
/* Invalidates the current HW context.
* Any GL state is lost, and must not be deinitialized explicitly.
* If explicit deinitialization is desired by the libretro core,
* it should implement context_destroy callback.
* If called, all GPU resources must be reinitialized.
* Usually called when frontend reinits video driver.
* Also called first time video driver is initialized,
* allowing libretro core to initialize resources.
*/
typedef void (*retro_hw_context_reset_t)(void);
/* Gets current framebuffer which is to be rendered to.
* Could change every frame potentially.
*/
typedef uintptr_t (*retro_hw_get_current_framebuffer_t)(void);
/* Get a symbol from HW context. */
typedef retro_proc_address_t (*retro_hw_get_proc_address_t)(const char *sym);
enum retro_hw_context_type
{
RETRO_HW_CONTEXT_NONE = 0,
/* OpenGL 2.x. Driver can choose to use latest compatibility context. */
RETRO_HW_CONTEXT_OPENGL = 1,
/* OpenGL ES 2.0. */
RETRO_HW_CONTEXT_OPENGLES2 = 2,
/* Modern desktop core GL context. Use version_major/
* version_minor fields to set GL version. */
RETRO_HW_CONTEXT_OPENGL_CORE = 3,
/* OpenGL ES 3.0 */
RETRO_HW_CONTEXT_OPENGLES3 = 4,
/* OpenGL ES 3.1+. Set version_major/version_minor. For GLES2 and GLES3,
* use the corresponding enums directly. */
RETRO_HW_CONTEXT_OPENGLES_VERSION = 5,
/* Vulkan, see RETRO_ENVIRONMENT_GET_HW_RENDER_INTERFACE. */
RETRO_HW_CONTEXT_VULKAN = 6,
RETRO_HW_CONTEXT_DUMMY = INT_MAX
};
struct retro_hw_render_callback
{
/* Which API to use. Set by libretro core. */
enum retro_hw_context_type context_type;
/* Called when a context has been created or when it has been reset.
* An OpenGL context is only valid after context_reset() has been called.
*
* When context_reset is called, OpenGL resources in the libretro
* implementation are guaranteed to be invalid.
*
* It is possible that context_reset is called multiple times during an
* application lifecycle.
* If context_reset is called without any notification (context_destroy),
* the OpenGL context was lost and resources should just be recreated
* without any attempt to "free" old resources.
*/
retro_hw_context_reset_t context_reset;
/* Set by frontend.
* TODO: This is rather obsolete. The frontend should not
* be providing preallocated framebuffers. */
retro_hw_get_current_framebuffer_t get_current_framebuffer;
/* Set by frontend. */
retro_hw_get_proc_address_t get_proc_address;
/* Set if render buffers should have depth component attached.
* TODO: Obsolete. */
bool depth;
/* Set if stencil buffers should be attached.
* TODO: Obsolete. */
bool stencil;
/* If depth and stencil are true, a packed 24/8 buffer will be added.
* Only attaching stencil is invalid and will be ignored. */
/* Use conventional bottom-left origin convention. If false,
* standard libretro top-left origin semantics are used.
* TODO: Move to GL specific interface. */
bool bottom_left_origin;
/* Major version number for core GL context or GLES 3.1+. */
unsigned version_major;
/* Minor version number for core GL context or GLES 3.1+. */
unsigned version_minor;
/* If this is true, the frontend will go very far to avoid
* resetting context in scenarios like toggling fullscreen, etc.
* TODO: Obsolete? Maybe frontend should just always assume this ...
*/
bool cache_context;
/* The reset callback might still be called in extreme situations
* such as if the context is lost beyond recovery.
*
* For optimal stability, set this to false, and allow context to be
* reset at any time.
*/
/* A callback to be called before the context is destroyed in a
* controlled way by the frontend. */
retro_hw_context_reset_t context_destroy;
/* OpenGL resources can be deinitialized cleanly at this step.
* context_destroy can be set to NULL, in which resources will
* just be destroyed without any notification.
*
* Even when context_destroy is non-NULL, it is possible that
* context_reset is called without any destroy notification.
* This happens if context is lost by external factors (such as
* notified by GL_ARB_robustness).
*
* In this case, the context is assumed to be already dead,
* and the libretro implementation must not try to free any OpenGL
* resources in the subsequent context_reset.
*/
/* Creates a debug context. */
bool debug_context;
};
/* Callback type passed in RETRO_ENVIRONMENT_SET_KEYBOARD_CALLBACK.
* Called by the frontend in response to keyboard events.
* down is set if the key is being pressed, or false if it is being released.
* keycode is the RETROK value of the char.
* character is the text character of the pressed key. (UTF-32).
* key_modifiers is a set of RETROKMOD values or'ed together.
*
* The pressed/keycode state can be indepedent of the character.
* It is also possible that multiple characters are generated from a
* single keypress.
* Keycode events should be treated separately from character events.
* However, when possible, the frontend should try to synchronize these.
* If only a character is posted, keycode should be RETROK_UNKNOWN.
*
* Similarily if only a keycode event is generated with no corresponding
* character, character should be 0.
*/
typedef void (*retro_keyboard_event_t)(bool down, unsigned keycode,
uint32_t character, uint16_t key_modifiers);
struct retro_keyboard_callback
{
retro_keyboard_event_t callback;
};
/* Callbacks for RETRO_ENVIRONMENT_SET_DISK_CONTROL_INTERFACE.
* Should be set for implementations which can swap out multiple disk
* images in runtime.
*
* If the implementation can do this automatically, it should strive to do so.
* However, there are cases where the user must manually do so.
*
* Overview: To swap a disk image, eject the disk image with
* set_eject_state(true).
* Set the disk index with set_image_index(index). Insert the disk again
* with set_eject_state(false).
*/
/* If ejected is true, "ejects" the virtual disk tray.
* When ejected, the disk image index can be set.
*/
typedef bool (*retro_set_eject_state_t)(bool ejected);
/* Gets current eject state. The initial state is 'not ejected'. */
typedef bool (*retro_get_eject_state_t)(void);
/* Gets current disk index. First disk is index 0.
* If return value is >= get_num_images(), no disk is currently inserted.
*/
typedef unsigned (*retro_get_image_index_t)(void);
/* Sets image index. Can only be called when disk is ejected.
* The implementation supports setting "no disk" by using an
* index >= get_num_images().
*/
typedef bool (*retro_set_image_index_t)(unsigned index);
/* Gets total number of images which are available to use. */
typedef unsigned (*retro_get_num_images_t)(void);
struct retro_game_info;
/* Replaces the disk image associated with index.
* Arguments to pass in info have same requirements as retro_load_game().
* Virtual disk tray must be ejected when calling this.
*
* Replacing a disk image with info = NULL will remove the disk image
* from the internal list.
* As a result, calls to get_image_index() can change.
*
* E.g. replace_image_index(1, NULL), and previous get_image_index()
* returned 4 before.
* Index 1 will be removed, and the new index is 3.
*/
typedef bool (*retro_replace_image_index_t)(unsigned index,
const struct retro_game_info *info);
/* Adds a new valid index (get_num_images()) to the internal disk list.
* This will increment subsequent return values from get_num_images() by 1.
* This image index cannot be used until a disk image has been set
* with replace_image_index. */
typedef bool (*retro_add_image_index_t)(void);
struct retro_disk_control_callback
{
retro_set_eject_state_t set_eject_state;
retro_get_eject_state_t get_eject_state;
retro_get_image_index_t get_image_index;
retro_set_image_index_t set_image_index;
retro_get_num_images_t get_num_images;
retro_replace_image_index_t replace_image_index;
retro_add_image_index_t add_image_index;
};
enum retro_pixel_format
{
/* 0RGB1555, native endian.
* 0 bit must be set to 0.
* This pixel format is default for compatibility concerns only.
* If a 15/16-bit pixel format is desired, consider using RGB565. */
RETRO_PIXEL_FORMAT_0RGB1555 = 0,
/* XRGB8888, native endian.
* X bits are ignored. */
RETRO_PIXEL_FORMAT_XRGB8888 = 1,
/* RGB565, native endian.
* This pixel format is the recommended format to use if a 15/16-bit
* format is desired as it is the pixel format that is typically
* available on a wide range of low-power devices.
*
* It is also natively supported in APIs like OpenGL ES. */
RETRO_PIXEL_FORMAT_RGB565 = 2,
/* Ensure sizeof() == sizeof(int). */
RETRO_PIXEL_FORMAT_UNKNOWN = INT_MAX
};
struct retro_message
{
const char *msg; /* Message to be displayed. */
unsigned frames; /* Duration in frames of message. */
};
/* Describes how the libretro implementation maps a libretro input bind
* to its internal input system through a human readable string.
* This string can be used to better let a user configure input. */
struct retro_input_descriptor
{
/* Associates given parameters with a description. */
unsigned port;
unsigned device;
unsigned index;
unsigned id;
/* Human readable description for parameters.
* The pointer must remain valid until
* retro_unload_game() is called. */
const char *description;
};
struct retro_system_info
{
/* All pointers are owned by libretro implementation, and pointers must
* remain valid until retro_deinit() is called. */
const char *library_name; /* Descriptive name of library. Should not
* contain any version numbers, etc. */
const char *library_version; /* Descriptive version of core. */
const char *valid_extensions; /* A string listing probably content
* extensions the core will be able to
* load, separated with pipe.
* I.e. "bin|rom|iso".
* Typically used for a GUI to filter
* out extensions. */
/* If true, retro_load_game() is guaranteed to provide a valid pathname
* in retro_game_info::path.
* ::data and ::size are both invalid.
*
* If false, ::data and ::size are guaranteed to be valid, but ::path
* might not be valid.
*
* This is typically set to true for libretro implementations that must
* load from file.
* Implementations should strive for setting this to false, as it allows
* the frontend to perform patching, etc. */
bool need_fullpath;
/* If true, the frontend is not allowed to extract any archives before
* loading the real content.
* Necessary for certain libretro implementations that load games
* from zipped archives. */
bool block_extract;
};
struct retro_game_geometry
{
unsigned base_width; /* Nominal video width of game. */
unsigned base_height; /* Nominal video height of game. */
unsigned max_width; /* Maximum possible width of game. */
unsigned max_height; /* Maximum possible height of game. */
float aspect_ratio; /* Nominal aspect ratio of game. If
* aspect_ratio is <= 0.0, an aspect ratio
* of base_width / base_height is assumed.
* A frontend could override this setting,
* if desired. */
};
struct retro_system_timing
{
double fps; /* FPS of video content. */
double sample_rate; /* Sampling rate of audio. */
};
struct retro_system_av_info
{
struct retro_game_geometry geometry;
struct retro_system_timing timing;
};
struct retro_variable
{
/* Variable to query in RETRO_ENVIRONMENT_GET_VARIABLE.
* If NULL, obtains the complete environment string if more
* complex parsing is necessary.
* The environment string is formatted as key-value pairs
* delimited by semicolons as so:
* "key1=value1;key2=value2;..."
*/
const char *key;
/* Value to be obtained. If key does not exist, it is set to NULL. */
const char *value;
};
struct retro_game_info
{
const char *path; /* Path to game, UTF-8 encoded.
* Usually used as a reference.
* May be NULL if rom was loaded from stdin
* or similar.
* retro_system_info::need_fullpath guaranteed
* that this path is valid. */
const void *data; /* Memory buffer of loaded game. Will be NULL
* if need_fullpath was set. */
size_t size; /* Size of memory buffer. */
const char *meta; /* String of implementation specific meta-data. */
};
#define RETRO_MEMORY_ACCESS_WRITE (1 << 0)
/* The core will write to the buffer provided by retro_framebuffer::data. */
#define RETRO_MEMORY_ACCESS_READ (1 << 1)
/* The core will read from retro_framebuffer::data. */
#define RETRO_MEMORY_TYPE_CACHED (1 << 0)
/* The memory in data is cached.
* If not cached, random writes and/or reading from the buffer is expected to be very slow. */
struct retro_framebuffer
{
void *data; /* The framebuffer which the core can render into.
Set by frontend in GET_CURRENT_SOFTWARE_FRAMEBUFFER.
The initial contents of data are unspecified. */
unsigned width; /* The framebuffer width used by the core. Set by core. */
unsigned height; /* The framebuffer height used by the core. Set by core. */
size_t pitch; /* The number of bytes between the beginning of a scanline,
and beginning of the next scanline.
Set by frontend in GET_CURRENT_SOFTWARE_FRAMEBUFFER. */
enum retro_pixel_format format; /* The pixel format the core must use to render into data.
This format could differ from the format used in
SET_PIXEL_FORMAT.
Set by frontend in GET_CURRENT_SOFTWARE_FRAMEBUFFER. */
unsigned access_flags; /* How the core will access the memory in the framebuffer.
RETRO_MEMORY_ACCESS_* flags.
Set by core. */
unsigned memory_flags; /* Flags telling core how the memory has been mapped.
RETRO_MEMORY_TYPE_* flags.
Set by frontend in GET_CURRENT_SOFTWARE_FRAMEBUFFER. */
};
/* Callbacks */
/* Environment callback. Gives implementations a way of performing
* uncommon tasks. Extensible. */
typedef bool (*retro_environment_t)(unsigned cmd, void *data);
/* Render a frame. Pixel format is 15-bit 0RGB1555 native endian
* unless changed (see RETRO_ENVIRONMENT_SET_PIXEL_FORMAT).
*
* Width and height specify dimensions of buffer.
* Pitch specifices length in bytes between two lines in buffer.
*
* For performance reasons, it is highly recommended to have a frame
* that is packed in memory, i.e. pitch == width * byte_per_pixel.
* Certain graphic APIs, such as OpenGL ES, do not like textures
* that are not packed in memory.
*/
typedef void (*retro_video_refresh_t)(const void *data, unsigned width,
unsigned height, size_t pitch);
/* Renders a single audio frame. Should only be used if implementation
* generates a single sample at a time.
* Format is signed 16-bit native endian.
*/
typedef void (*retro_audio_sample_t)(int16_t left, int16_t right);
/* Renders multiple audio frames in one go.
*
* One frame is defined as a sample of left and right channels, interleaved.
* I.e. int16_t buf[4] = { l, r, l, r }; would be 2 frames.
* Only one of the audio callbacks must ever be used.
*/
typedef size_t (*retro_audio_sample_batch_t)(const int16_t *data,
size_t frames);
/* Polls input. */
typedef void (*retro_input_poll_t)(void);
/* Queries for input for player 'port'. device will be masked with
* RETRO_DEVICE_MASK.
*
* Specialization of devices such as RETRO_DEVICE_JOYPAD_MULTITAP that
* have been set with retro_set_controller_port_device()
* will still use the higher level RETRO_DEVICE_JOYPAD to request input.
*/
typedef int16_t (*retro_input_state_t)(unsigned port, unsigned device,
unsigned index, unsigned id);
/* Sets callbacks. retro_set_environment() is guaranteed to be called
* before retro_init().
*
* The rest of the set_* functions are guaranteed to have been called
* before the first call to retro_run() is made. */
RETRO_API void retro_set_environment(retro_environment_t);
RETRO_API void retro_set_video_refresh(retro_video_refresh_t);
RETRO_API void retro_set_audio_sample(retro_audio_sample_t);
RETRO_API void retro_set_audio_sample_batch(retro_audio_sample_batch_t);
RETRO_API void retro_set_input_poll(retro_input_poll_t);
RETRO_API void retro_set_input_state(retro_input_state_t);
/* Library global initialization/deinitialization. */
RETRO_API void retro_init(void);
RETRO_API void retro_deinit(void);
/* Must return RETRO_API_VERSION. Used to validate ABI compatibility
* when the API is revised. */
RETRO_API unsigned retro_api_version(void);
/* Gets statically known system info. Pointers provided in *info
* must be statically allocated.
* Can be called at any time, even before retro_init(). */
RETRO_API void retro_get_system_info(struct retro_system_info *info);
/* Gets information about system audio/video timings and geometry.
* Can be called only after retro_load_game() has successfully completed.
* NOTE: The implementation of this function might not initialize every
* variable if needed.
* E.g. geom.aspect_ratio might not be initialized if core doesn't
* desire a particular aspect ratio. */
RETRO_API void retro_get_system_av_info(struct retro_system_av_info *info);
/* Sets device to be used for player 'port'.
* By default, RETRO_DEVICE_JOYPAD is assumed to be plugged into all
* available ports.
* Setting a particular device type is not a guarantee that libretro cores
* will only poll input based on that particular device type. It is only a
* hint to the libretro core when a core cannot automatically detect the
* appropriate input device type on its own. It is also relevant when a
* core can change its behavior depending on device type. */
RETRO_API void retro_set_controller_port_device(unsigned port, unsigned device);
/* Resets the current game. */
RETRO_API void retro_reset(void);
/* Runs the game for one video frame.
* During retro_run(), input_poll callback must be called at least once.
*
* If a frame is not rendered for reasons where a game "dropped" a frame,
* this still counts as a frame, and retro_run() should explicitly dupe
* a frame if GET_CAN_DUPE returns true.
* In this case, the video callback can take a NULL argument for data.
*/
RETRO_API void retro_run(void);
/* Returns the amount of data the implementation requires to serialize
* internal state (save states).
* Between calls to retro_load_game() and retro_unload_game(), the
* returned size is never allowed to be larger than a previous returned
* value, to ensure that the frontend can allocate a save state buffer once.
*/
RETRO_API size_t retro_serialize_size(void);
/* Serializes internal state. If failed, or size is lower than
* retro_serialize_size(), it should return false, true otherwise. */
RETRO_API bool retro_serialize(void *data, size_t size);
RETRO_API bool retro_unserialize(const void *data, size_t size);
RETRO_API void retro_cheat_reset(void);
RETRO_API void retro_cheat_set(unsigned index, bool enabled, const char *code);
/* Loads a game. */
RETRO_API bool retro_load_game(const struct retro_game_info *game);
/* Loads a "special" kind of game. Should not be used,
* except in extreme cases. */
RETRO_API bool retro_load_game_special(
unsigned game_type,
const struct retro_game_info *info, size_t num_info
);
/* Unloads a currently loaded game. */
RETRO_API void retro_unload_game(void);
/* Gets region of game. */
RETRO_API unsigned retro_get_region(void);
/* Gets region of memory. */
RETRO_API void *retro_get_memory_data(unsigned id);
RETRO_API size_t retro_get_memory_size(unsigned id);
#ifdef __cplusplus
}
#endif
#endif
libgambatte/src/video/ly_counter.h 000664 001750 001750 00000003203 12720365247 020414 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2007 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#ifndef LY_COUNTER_H
#define LY_COUNTER_H
namespace gambatte {
struct SaveState;
class LyCounter {
public:
LyCounter();
void doEvent();
bool isDoubleSpeed() const { return ds_; }
unsigned long frameCycles(unsigned long cc) const {
return ly_ * 456ul + lineCycles(cc);
}
unsigned lineCycles(unsigned long cc) const {
return 456u - ((time_ - cc) >> isDoubleSpeed());
}
unsigned lineTime() const { return lineTime_; }
unsigned ly() const { return ly_; }
unsigned long nextLineCycle(unsigned lineCycle, unsigned long cycleCounter) const;
unsigned long nextFrameCycle(unsigned long frameCycle, unsigned long cycleCounter) const;
void reset(unsigned long videoCycles, unsigned long lastUpdate);
void setDoubleSpeed(bool ds);
unsigned long time() const { return time_; }
private:
unsigned long time_;
unsigned short lineTime_;
unsigned char ly_;
bool ds_;
};
}
#endif
libgambatte/src/tima.h 000664 001750 001750 00000004112 12720365247 016055 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2007 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#ifndef TIMA_H
#define TIMA_H
#include "interruptrequester.h"
namespace gambatte {
class TimaInterruptRequester {
public:
explicit TimaInterruptRequester(InterruptRequester &intreq) : intreq_(intreq) {}
void flagIrq() const { intreq_.flagIrq(4); }
unsigned long nextIrqEventTime() const { return intreq_.eventTime(intevent_tima); }
void setNextIrqEventTime(unsigned long time) const { intreq_.setEventTime(time); }
private:
InterruptRequester &intreq_;
};
class Tima {
public:
Tima();
void saveState(SaveState &) const;
void loadState(const SaveState &, TimaInterruptRequester timaIrq);
void resetCc(unsigned long oldCc, unsigned long newCc, TimaInterruptRequester timaIrq);
void setTima(unsigned tima, unsigned long cc, TimaInterruptRequester timaIrq);
void setTma(unsigned tma, unsigned long cc, TimaInterruptRequester timaIrq);
void setTac(unsigned tac, unsigned long cc, TimaInterruptRequester timaIrq);
unsigned tima(unsigned long cc);
void doIrqEvent(TimaInterruptRequester timaIrq);
private:
unsigned long lastUpdate_;
unsigned long tmatime_;
unsigned char tima_;
unsigned char tma_;
unsigned char tac_;
void updateIrq(unsigned long const cc, TimaInterruptRequester timaIrq) {
while (cc >= timaIrq.nextIrqEventTime())
doIrqEvent(timaIrq);
}
void updateTima(unsigned long cc);
};
}
#endif
libgambatte/src/mem/cartridge.cpp 000664 001750 001750 00000052633 12720365247 020213 0 ustar 00sergio sergio 000000 000000 /***************************************************************************
* Copyright (C) 2007-2010 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* This program 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 General Public License version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "cartridge.h"
#include "../savestate.h"
#include
#include
#include
#include
namespace gambatte
{
static unsigned toMulti64Rombank(const unsigned rombank)
{
return (rombank >> 1 & 0x30) | (rombank & 0xF);
}
static inline unsigned rambanks(MemPtrs const &memptrs)
{
return (memptrs.rambankdataend() - memptrs.rambankdata()) / 0x2000;
}
static inline unsigned rombanks(MemPtrs const &memptrs)
{
return (memptrs.romdataend() - memptrs.romdata() ) / 0x4000;
}
class DefaultMbc : public Mbc {
public:
virtual bool isAddressWithinAreaRombankCanBeMappedTo(unsigned addr, unsigned bank) const {
return (addr< 0x4000) == (bank == 0);
}
};
class Mbc0 : public DefaultMbc {
MemPtrs &memptrs;
bool enableRam;
public:
explicit Mbc0(MemPtrs &memptrs)
: memptrs(memptrs),
enableRam(false)
{
}
virtual void romWrite(const unsigned P, const unsigned data) {
if (P < 0x2000) {
enableRam = (data & 0xF) == 0xA;
memptrs.setRambank(enableRam ? MemPtrs::READ_EN | MemPtrs::WRITE_EN : 0, 0);
}
}
virtual void saveState(SaveState::Mem &ss) const {
ss.enableRam = enableRam;
}
virtual void loadState(const SaveState::Mem &ss) {
enableRam = ss.enableRam;
memptrs.setRambank(enableRam ? MemPtrs::READ_EN | MemPtrs::WRITE_EN : 0, 0);
}
};
class Mbc1 : public DefaultMbc {
MemPtrs &memptrs;
unsigned char rombank;
unsigned char rambank;
bool enableRam;
bool rambankMode;
static unsigned adjustedRombank(unsigned bank) { return (bank & 0x1F) ? bank : bank | 1; }
void setRambank() const { memptrs.setRambank(enableRam ? MemPtrs::READ_EN | MemPtrs::WRITE_EN : 0, rambank & (rambanks(memptrs) - 1)); }
void setRombank() const { memptrs.setRombank(adjustedRombank(rombank) & (rombanks(memptrs) - 1)); }
public:
explicit Mbc1(MemPtrs &memptrs)
: memptrs(memptrs),
rombank(1),
rambank(0),
enableRam(false),
rambankMode(false)
{
}
virtual void romWrite(const unsigned P, const unsigned data) {
switch (P >> 13 & 3) {
case 0:
enableRam = (data & 0xF) == 0xA;
setRambank();
break;
case 1:
rombank = rambankMode ? data & 0x1F : (rombank & 0x60) | (data & 0x1F);
setRombank();
break;
case 2:
if (rambankMode) {
rambank = data & 3;
setRambank();
} else {
rombank = (data << 5 & 0x60) | (rombank & 0x1F);
setRombank();
}
break;
case 3:
// Pretty sure this should take effect immediately, but I have a policy not to change old behavior
// unless I have something (eg. a verified test or a game) that justifies it.
rambankMode = data & 1;
break;
}
}
virtual void saveState(SaveState::Mem &ss) const {
ss.rombank = rombank;
ss.rambank = rambank;
ss.enableRam = enableRam;
ss.rambankMode = rambankMode;
}
virtual void loadState(const SaveState::Mem &ss) {
rombank = ss.rombank;
rambank = ss.rambank;
enableRam = ss.enableRam;
rambankMode = ss.rambankMode;
setRambank();
setRombank();
}
};
class Mbc1Multi64 : public Mbc {
MemPtrs &memptrs;
unsigned char rombank;
bool enableRam;
bool rombank0Mode;
static unsigned adjustedRombank(unsigned bank) { return (bank & 0x1F) ? bank : bank | 1; }
void setRombank() const {
if (rombank0Mode) {
const unsigned rb = toMulti64Rombank(rombank);
memptrs.setRombank0(rb & 0x30);
memptrs.setRombank(adjustedRombank(rb));
} else {
memptrs.setRombank0(0);
memptrs.setRombank(adjustedRombank(rombank) & (rombanks(memptrs) - 1));
}
}
public:
explicit Mbc1Multi64(MemPtrs &memptrs)
: memptrs(memptrs),
rombank(1),
enableRam(false),
rombank0Mode(false)
{
}
virtual void romWrite(const unsigned P, const unsigned data) {
switch (P >> 13 & 3) {
case 0:
enableRam = (data & 0xF) == 0xA;
memptrs.setRambank(enableRam ? MemPtrs::READ_EN | MemPtrs::WRITE_EN : 0, 0);
break;
case 1:
rombank = (rombank & 0x60) | (data & 0x1F);
memptrs.setRombank(rombank0Mode
? adjustedRombank(toMulti64Rombank(rombank))
: adjustedRombank(rombank) & (rombanks(memptrs) - 1));
break;
case 2:
rombank = (data << 5 & 0x60) | (rombank & 0x1F);
setRombank();
break;
case 3:
rombank0Mode = data & 1;
setRombank();
break;
}
}
virtual void saveState(SaveState::Mem &ss) const {
ss.rombank = rombank;
ss.enableRam = enableRam;
ss.rambankMode = rombank0Mode;
}
virtual void loadState(const SaveState::Mem &ss) {
rombank = ss.rombank;
enableRam = ss.enableRam;
rombank0Mode = ss.rambankMode;
memptrs.setRambank(enableRam ? MemPtrs::READ_EN | MemPtrs::WRITE_EN : 0, 0);
setRombank();
}
virtual bool isAddressWithinAreaRombankCanBeMappedTo(unsigned addr, unsigned bank) const {
return (addr < 0x4000) == ((bank & 0xF) == 0);
}
};
class Mbc2 : public DefaultMbc {
MemPtrs &memptrs;
unsigned char rombank;
bool enableRam;
public:
explicit Mbc2(MemPtrs &memptrs)
: memptrs(memptrs),
rombank(1),
enableRam(false)
{
}
virtual void romWrite(const unsigned P, const unsigned data) {
switch (P & 0x6100) {
case 0x0000:
enableRam = (data & 0xF) == 0xA;
memptrs.setRambank(enableRam ? MemPtrs::READ_EN | MemPtrs::WRITE_EN : 0, 0);
break;
case 0x2100:
rombank = data & 0xF;
memptrs.setRombank(rombank & (rombanks(memptrs) - 1));
break;
}
}
virtual void saveState(SaveState::Mem &ss) const {
ss.rombank = rombank;
ss.enableRam = enableRam;
}
virtual void loadState(const SaveState::Mem &ss) {
rombank = ss.rombank;
enableRam = ss.enableRam;
memptrs.setRambank(enableRam ? MemPtrs::READ_EN | MemPtrs::WRITE_EN : 0, 0);
memptrs.setRombank(rombank & (rombanks(memptrs) - 1));
}
};
class Mbc3 : public DefaultMbc {
MemPtrs &memptrs;
Rtc *const rtc;
unsigned char rombank;
unsigned char rambank;
bool enableRam;
void setRambank() const {
unsigned flags = enableRam ? MemPtrs::READ_EN | MemPtrs::WRITE_EN : 0;
if (rtc) {
rtc->set(enableRam, rambank);
if (rtc->getActive())
flags |= MemPtrs::RTC_EN;
}
memptrs.setRambank(flags, rambank & (rambanks(memptrs) - 1));
}
public:
Mbc3(MemPtrs &memptrs, Rtc *const rtc)
: memptrs(memptrs),
rtc(rtc),
rombank(1),
rambank(0),
enableRam(false)
{
}
virtual void romWrite(const unsigned P, const unsigned data) {
switch (P >> 13 & 3) {
case 0:
enableRam = (data & 0xF) == 0xA;
setRambank();
break;
case 1:
rombank = data & 0x7F;
setRombank();
break;
case 2:
rambank = data;
setRambank();
break;
case 3:
if (rtc)
rtc->latch(data);
break;
}
}
virtual void saveState(SaveState::Mem &ss) const {
ss.rombank = rombank;
ss.rambank = rambank;
ss.enableRam = enableRam;
}
virtual void loadState(const SaveState::Mem &ss) {
rombank = ss.rombank;
rambank = ss.rambank;
enableRam = ss.enableRam;
setRambank();
setRombank();
}
void setRombank() const {
memptrs.setRombank(std::max(rombank & (rombanks(memptrs) - 1), 1u));
}
};
class HuC1 : public DefaultMbc {
MemPtrs &memptrs;
unsigned char rombank;
unsigned char rambank;
bool enableRam;
bool rambankMode;
void setRambank() const {
memptrs.setRambank(enableRam ? MemPtrs::READ_EN | MemPtrs::WRITE_EN : MemPtrs::READ_EN,
rambankMode ? rambank & (rambanks(memptrs) - 1) : 0);
}
void setRombank() const { memptrs.setRombank((rambankMode ? rombank : rambank << 6 | rombank) & (rombanks(memptrs) - 1)); }
public:
explicit HuC1(MemPtrs &memptrs)
: memptrs(memptrs),
rombank(1),
rambank(0),
enableRam(false),
rambankMode(false)
{
}
virtual void romWrite(const unsigned P, const unsigned data) {
switch (P >> 13 & 3) {
case 0:
enableRam = (data & 0xF) == 0xA;
setRambank();
break;
case 1:
rombank = data & 0x3F;
setRombank();
break;
case 2:
rambank = data & 3;
rambankMode ? setRambank() : setRombank();
break;
case 3:
rambankMode = data & 1;
setRambank();
setRombank();
break;
}
}
virtual void saveState(SaveState::Mem &ss) const {
ss.rombank = rombank;
ss.rambank = rambank;
ss.enableRam = enableRam;
ss.rambankMode = rambankMode;
}
virtual void loadState(const SaveState::Mem &ss) {
rombank = ss.rombank;
rambank = ss.rambank;
enableRam = ss.enableRam;
rambankMode = ss.rambankMode;
setRambank();
setRombank();
}
};
class Mbc5 : public DefaultMbc {
MemPtrs &memptrs;
unsigned short rombank;
unsigned char rambank;
bool enableRam;
static unsigned adjustedRombank(const unsigned bank) { return bank; }
void setRambank() const {
memptrs.setRambank(enableRam ? MemPtrs::READ_EN | MemPtrs::WRITE_EN : 0,
rambank & (rambanks(memptrs) - 1));
}
void setRombank() const { memptrs.setRombank(adjustedRombank(rombank) & (rombanks(memptrs) - 1));}
public:
explicit Mbc5(MemPtrs &memptrs)
: memptrs(memptrs),
rombank(1),
rambank(0),
enableRam(false)
{
}
virtual void romWrite(const unsigned P, const unsigned data) {
switch (P >> 13 & 3) {
case 0:
enableRam = (data & 0xF) == 0xA;
setRambank();
break;
case 1:
rombank = P < 0x3000 ? (rombank & 0x100) | data
: (data << 8 & 0x100) | (rombank & 0xFF);
setRombank();
break;
case 2:
rambank = data & 0xF;
setRambank();
break;
case 3:
break;
}
}
virtual void saveState(SaveState::Mem &ss) const {
ss.rombank = rombank;
ss.rambank = rambank;
ss.enableRam = enableRam;
}
virtual void loadState(const SaveState::Mem &ss) {
rombank = ss.rombank;
rambank = ss.rambank;
enableRam = ss.enableRam;
setRambank();
setRombank();
}
};
static bool hasRtc(unsigned headerByte0x147)
{
switch (headerByte0x147)
{
case 0x0F:
case 0x10:
return true;
default:
return false;
}
}
void Cartridge::setStatePtrs(SaveState &state)
{
state.mem.vram.set(memptrs_.vramdata(), memptrs_.vramdataend() - memptrs_.vramdata());
state.mem.sram.set(memptrs_.rambankdata(), memptrs_.rambankdataend() - memptrs_.rambankdata());
state.mem.wram.set(memptrs_.wramdata(0), memptrs_.wramdataend() - memptrs_.wramdata(0));
}
void Cartridge::saveState(SaveState &state) const
{
mbc->saveState(state.mem);
rtc_.saveState(state);
}
void Cartridge::loadState(const SaveState &state)
{
rtc_.loadState(state);
mbc->loadState(state.mem);
}
static void enforce8bit(unsigned char *data, unsigned long sz)
{
if (static_cast(0x100))
while (sz--)
*data++ &= 0xFF;
}
static unsigned pow2ceil(unsigned n)
{
--n;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
++n;
return n;
}
int Cartridge::loadROM(const void *data, unsigned romsize, const bool forceDmg, const bool multiCartCompat)
{
uint8_t *romdata = (uint8_t*)data;
if (romsize < 0x4000 || !romdata)
return -1;
unsigned rambanks = 1;
unsigned rombanks = 2;
bool cgb = false;
enum Cartridgetype { PLAIN, MBC1, MBC2, MBC3, MBC5, HUC1 } type = PLAIN;
{
unsigned i;
unsigned char header[0x150];
for (i = 0; i < 0x150; i++)
header[i] = romdata[i];
switch (header[0x0147])
{
case 0x00: printf("Plain ROM loaded.\n"); type = PLAIN; break;
case 0x01: printf("MBC1 ROM loaded.\n"); type = MBC1; break;
case 0x02: printf("MBC1 ROM+RAM loaded.\n"); type = MBC1; break;
case 0x03: printf("MBC1 ROM+RAM+BATTERY loaded.\n"); type = MBC1; break;
case 0x05: printf("MBC2 ROM loaded.\n"); type = MBC2; break;
case 0x06: printf("MBC2 ROM+BATTERY loaded.\n"); type = MBC2; break;
case 0x08: printf("Plain ROM with additional RAM loaded.\n"); type = MBC2; break;
case 0x09: printf("Plain ROM with additional RAM and Battery loaded.\n"); type = MBC2;break;
case 0x0B: printf("MM01 ROM not supported.\n"); return -1;
case 0x0C: printf("MM01 ROM not supported.\n"); return -1;
case 0x0D: printf("MM01 ROM not supported.\n"); return -1;
case 0x0F: printf("MBC3 ROM+TIMER+BATTERY loaded.\n"); type = MBC3; break;
case 0x10: printf("MBC3 ROM+TIMER+RAM+BATTERY loaded.\n"); type = MBC3; break;
case 0x11: printf("MBC3 ROM loaded.\n"); type = MBC3; break;
case 0x12: printf("MBC3 ROM+RAM loaded.\n"); type = MBC3; break;
case 0x13: printf("MBC3 ROM+RAM+BATTERY loaded.\n"); type = MBC3; break;
case 0x15: printf("MBC4 ROM not supported.\n"); return -1;
case 0x16: printf("MBC4 ROM not supported.\n"); return -1;
case 0x17: printf("MBC4 ROM not supported.\n"); return -1;
case 0x19: printf("MBC5 ROM loaded.\n"); type = MBC5; break;
case 0x1A: printf("MBC5 ROM+RAM loaded.\n"); type = MBC5; break;
case 0x1B: printf("MBC5 ROM+RAM+BATTERY loaded.\n"); type = MBC5; break;
case 0x1C: printf("MBC5+RUMBLE ROM not supported.\n"); type = MBC5; break;
case 0x1D: printf("MBC5+RUMBLE+RAM ROM not suported.\n"); type = MBC5; break;
case 0x1E: printf("MBC5+RUMBLE+RAM+BATTERY ROM not supported.\n"); type = MBC5; break;
case 0x20: printf("MBC6 ROM not supported.\n"); return -1;
case 0x22: printf("MBC7 ROM not supported.\n"); return -1;
case 0xFC: printf("Pocket Camera ROM not supported.\n"); return -1;
case 0xFD: printf("Bandai TAMA5 ROM not supported.\n"); return -1;
case 0xFE: printf("HuC3 ROM+RAM+BATTERY loaded.\n"); return -1;
case 0xFF: printf("HuC1 ROM+BATTERY loaded.\n"); type = HUC1; break;
default: printf("Wrong data-format, corrupt or unsupported ROM.\n"); return -1;
}
switch (header[0x0149])
{
case 0x00: /*std::puts("No RAM");*/ rambanks = type == MBC2; break;
case 0x01: /*std::puts("2kB RAM");*/ /*rambankrom=1; break;*/
case 0x02: /*std::puts("8kB RAM");*/
rambanks = 1;
break;
case 0x03: /*std::puts("32kB RAM");*/
rambanks = 4;
break;
case 0x04: /*std::puts("128kB RAM");*/
rambanks = 16;
break;
case 0x05: /*std::puts("undocumented kB RAM");*/
rambanks = 16;
break;
default: /*std::puts("Wrong data-format, corrupt or unsupported ROM loaded.");*/
rambanks = 16;
break;
}
cgb = header[0x0143] >> 7 & (1 ^ forceDmg);
printf("cgb: %d\n", cgb);
}
printf("rambanks: %u\n", rambanks);
rombanks = pow2ceil(romsize / 0x4000);
printf("rombanks: %u\n", static_cast(romsize / 0x4000));
ggUndoList_.clear();
mbc.reset();
memptrs_.reset(rombanks, rambanks, cgb ? 8 : 2);
rtc_.set(false, 0);
memcpy(memptrs_.romdata(), romdata, ((romsize / 0x4000) * 0x4000ul) * sizeof(unsigned char));
std::memset(memptrs_.romdata() + (romsize / 0x4000) * 0x4000ul, 0xFF, (rombanks - romsize / 0x4000) * 0x4000ul);
enforce8bit(memptrs_.romdata(), rombanks * 0x4000ul);
switch (type)
{
case PLAIN: mbc.reset(new Mbc0(memptrs_)); break;
case MBC1:
if (!rambanks && rombanks == 64 && multiCartCompat) {
std::puts("Multi-ROM \"MBC1\" presumed");
mbc.reset(new Mbc1Multi64(memptrs_));
} else
mbc.reset(new Mbc1(memptrs_));
break;
case MBC2: mbc.reset(new Mbc2(memptrs_)); break;
case MBC3: mbc.reset(new Mbc3(memptrs_, hasRtc(memptrs_.romdata()[0x147]) ? &rtc_ : 0)); break;
case MBC5: mbc.reset(new Mbc5(memptrs_)); break;
case HUC1: mbc.reset(new HuC1(memptrs_)); break;
}
return 0;
}
static int asHex(const char c)
{
return c >= 'A' ? c - 'A' + 0xA : c - '0';
}
void Cartridge::applyGameGenie(const std::string &code)
{
if (6 < code.length())
{
const unsigned val = (asHex(code[0]) << 4 | asHex(code[1])) & 0xFF;
const unsigned addr = (asHex(code[2]) << 8 | asHex(code[4]) << 4 | asHex(code[5]) | (asHex(code[6]) ^ 0xF) << 12) & 0x7FFF;
unsigned cmp = 0xFFFF;
if (10 < code.length())
{
cmp = (asHex(code[8]) << 4 | asHex(code[10])) ^ 0xFF;
cmp = ((cmp >> 2 | cmp << 6) ^ 0x45) & 0xFF;
}
for (unsigned bank = 0; bank < static_cast(memptrs_.romdataend() - memptrs_.romdata()) / 0x4000; ++bank)
{
if (mbc->isAddressWithinAreaRombankCanBeMappedTo(addr, bank)
&& (cmp > 0xFF || memptrs_.romdata()[bank * 0x4000ul + (addr & 0x3FFF)] == cmp))
{
ggUndoList_.push_back(AddrData(bank * 0x4000ul + (addr & 0x3FFF), memptrs_.romdata()[bank * 0x4000ul + (addr & 0x3FFF)]));
memptrs_.romdata()[bank * 0x4000ul + (addr & 0x3FFF)] = val;
}
}
}
}
void Cartridge::setGameGenie(const std::string &codes)
{
#if 0
if (loaded())
#endif
{
for (std::vector::reverse_iterator it = ggUndoList_.rbegin(), end = ggUndoList_.rend(); it != end; ++it)
{
if (memptrs_.romdata() + it->addr < memptrs_.romdataend())
memptrs_.romdata()[it->addr] = it->data;
}
ggUndoList_.clear();
std::string code;
for (std::size_t pos = 0; pos < codes.length()
&& (code = codes.substr(pos, codes.find(';', pos) - pos), true); pos += code.length() + 1)
applyGameGenie(code);
}
}
}
libgambatte/src/initstate.h 000664 001750 001750 00000002774 12720365247 017143 0 ustar 00sergio sergio 000000 000000 /***************************************************************************
* Copyright (C) 2008 by Sindre Aam�s *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* This program 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 General Public License version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef INITSTATE_H
#define INITSTATE_H
namespace gambatte {
void setInitState(struct SaveState &state, bool cgb, bool gbaCgbMode);
}
#endif
libgambatte/src/sound/sound_unit.h 000664 001750 001750 00000002354 12720365247 020450 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2007 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#ifndef SOUND_UNIT_H
#define SOUND_UNIT_H
namespace gambatte {
class SoundUnit {
public:
enum { counter_max = 0x80000000u, counter_disabled = 0xFFFFFFFFu };
virtual ~SoundUnit() {}
virtual void event() = 0;
virtual void resetCounters(unsigned long /*oldCc*/) {
if (counter_ != counter_disabled)
counter_ -= counter_max;
}
unsigned long counter() const { return counter_; }
protected:
SoundUnit() : counter_(counter_disabled) {}
unsigned long counter_;
};
}
#endif
libgambatte/src/statesaver.cpp 000664 001750 001750 00000046277 12720365247 017661 0 ustar 00sergio sergio 000000 000000 /***************************************************************************
* Copyright (C) 2008 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* This program 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 General Public License version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "statesaver.h"
#include "savestate.h"
#include "gambatte-array.h"
#include
#include
#include
#include
class omemstream
{
public:
omemstream(void *data) : wr_ptr(static_cast(data)), has_written(0) {}
void put(uint8_t data)
{
if (wr_ptr)
*wr_ptr++ = data;
has_written++;
}
void write(const void *data, size_t size)
{
if (wr_ptr)
{
std::memcpy(wr_ptr, data, size);
wr_ptr += size;
}
has_written += size;
}
size_t size() const { return has_written; }
bool fail() const { return false; }
bool good() const { return true; }
private:
uint8_t *wr_ptr;
size_t has_written;
};
class imemstream
{
public:
imemstream(const void *data) : rd_ptr(static_cast(data)), has_read(0) {}
uint8_t get()
{
uint8_t ret = *rd_ptr++;
has_read++;
return ret;
}
void read(void *data, size_t size)
{
std::memcpy(data, rd_ptr, size);
rd_ptr += size;
}
void ignore(size_t len = 1)
{
rd_ptr += len;
has_read += len;
}
void getline(char *data, size_t size, char delim = '\n')
{
size_t count = 0;
while ((count < size - 1) && (*rd_ptr != delim))
{
*data++ = *rd_ptr++;
has_read++;
}
rd_ptr++;
has_read++;
*data = '\0';
}
bool fail() const { return false; }
bool good() const { return true; }
private:
const uint8_t *rd_ptr;
size_t has_read;
};
namespace {
using namespace gambatte;
enum AsciiChar {
NUL, SOH, STX, ETX, EOT, ENQ, ACK, BEL, BS, TAB, LF, VT, FF, CR, SO, SI,
DLE, DC1, DC2, DC3, DC4, NAK, SYN, ETB, CAN, EM, SUB, ESC, FS, GS, RS, US,
SP, XCL, QOT, HSH, DLR, PRC, AMP, APO, LPA, RPA, AST, PLU, COM, HYP, STP, DIV,
NO0, NO1, NO2, NO3, NO4, NO5, NO6, NO7, NO8, NO9, CLN, SCL, LT, EQL, GT, QTN,
AT, 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, LBX, BSL, RBX, CAT, UND,
ACN, 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, LBR, BAR, RBR, TLD, DEL
};
struct Saver {
const char *label;
void (*save)(omemstream &file, const SaveState &state);
void (*load)(imemstream &file, SaveState &state);
unsigned char labelsize;
};
static inline bool operator<(const Saver &l, const Saver &r) {
return std::strcmp(l.label, r.label) < 0;
}
static void put24(omemstream &file, const unsigned long data) {
file.put(data >> 16 & 0xFF);
file.put(data >> 8 & 0xFF);
file.put(data & 0xFF);
}
static void put32(omemstream &file, const unsigned long data) {
file.put(data >> 24 & 0xFF);
file.put(data >> 16 & 0xFF);
file.put(data >> 8 & 0xFF);
file.put(data & 0xFF);
}
static void write(omemstream &file, const unsigned char data) {
static const char inf[] = { 0x00, 0x00, 0x01 };
file.write(inf, sizeof(inf));
file.put(data & 0xFF);
}
static void write(omemstream &file, const unsigned short data) {
static const char inf[] = { 0x00, 0x00, 0x02 };
file.write(inf, sizeof(inf));
file.put(data >> 8 & 0xFF);
file.put(data & 0xFF);
}
static void write(omemstream &file, const unsigned long data) {
static const char inf[] = { 0x00, 0x00, 0x04 };
file.write(inf, sizeof(inf));
put32(file, data);
}
static inline void write(omemstream &file, const bool data) {
write(file, static_cast(data));
}
static void write(omemstream &file, const unsigned char *data, const unsigned long sz) {
put24(file, sz);
file.write(reinterpret_cast(data), sz);
}
static void write(omemstream &file, const bool *data, const unsigned long sz) {
put24(file, sz);
for (unsigned long i = 0; i < sz; ++i)
file.put(data[i]);
}
static unsigned long get24(imemstream &file) {
unsigned long tmp = file.get() & 0xFF;
tmp = tmp << 8 | (file.get() & 0xFF);
return tmp << 8 | (file.get() & 0xFF);
}
static unsigned long read(imemstream &file) {
unsigned long size = get24(file);
if (size > 4) {
file.ignore(size - 4);
size = 4;
}
unsigned long out = 0;
switch (size) {
case 4: out = (out | (file.get() & 0xFF)) << 8;
case 3: out = (out | (file.get() & 0xFF)) << 8;
case 2: out = (out | (file.get() & 0xFF)) << 8;
case 1: out = out | (file.get() & 0xFF);
}
return out;
}
static inline void read(imemstream &file, unsigned char &data) {
data = read(file) & 0xFF;
}
static inline void read(imemstream &file, unsigned short &data) {
data = read(file) & 0xFFFF;
}
static inline void read(imemstream &file, unsigned long &data) {
data = read(file);
}
static inline void read(imemstream &file, bool &data) {
data = read(file);
}
static void read(imemstream &file, unsigned char *data, unsigned long sz) {
const unsigned long size = get24(file);
if (size < sz)
sz = size;
file.read(reinterpret_cast(data), sz);
file.ignore(size - sz);
if (static_cast(0x100)) {
for (unsigned long i = 0; i < sz; ++i)
data[i] &= 0xFF;
}
}
static void read(imemstream &file, bool *data, unsigned long sz) {
const unsigned long size = get24(file);
if (size < sz)
sz = size;
for (unsigned long i = 0; i < sz; ++i)
data[i] = file.get();
file.ignore(size - sz);
}
} // anon namespace
namespace gambatte {
class SaverList {
public:
typedef std::vector list_t;
typedef list_t::const_iterator const_iterator;
private:
list_t list;
unsigned char maxLabelsize_;
public:
SaverList();
const_iterator begin() const { return list.begin(); }
const_iterator end() const { return list.end(); }
unsigned maxLabelsize() const { return maxLabelsize_; }
};
static void pushSaver(SaverList::list_t &list, const char *label,
void (*save)(omemstream &file, const SaveState &state),
void (*load)(imemstream &file, SaveState &state), unsigned labelsize) {
const Saver saver = { label, save, load, labelsize };
list.push_back(saver);
}
SaverList::SaverList() {
#define ADD(arg) do { \
struct Func { \
static void save(omemstream &file, const SaveState &state) { write(file, state.arg); } \
static void load(imemstream &file, SaveState &state) { read(file, state.arg); } \
}; \
\
pushSaver(list, label, Func::save, Func::load, sizeof label); \
} while (0)
#define ADDPTR(arg) do { \
struct Func { \
static void save(omemstream &file, const SaveState &state) { write(file, state.arg.get(), state.arg.size()); } \
static void load(imemstream &file, SaveState &state) { read(file, state.arg.ptr, state.arg.size()); } \
}; \
\
pushSaver(list, label, Func::save, Func::load, sizeof label); \
} while (0)
#define ADDARRAY(arg) do { \
struct Func { \
static void save(omemstream &file, const SaveState &state) { write(file, state.arg, sizeof(state.arg)); } \
static void load(imemstream &file, SaveState &state) { read(file, state.arg, sizeof(state.arg)); } \
}; \
\
pushSaver(list, label, Func::save, Func::load, sizeof label); \
} while (0)
{ static const char label[] = { c,c, NUL }; ADD(cpu.cycleCounter); }
{ static const char label[] = { p,c, NUL }; ADD(cpu.pc); }
{ static const char label[] = { s,p, NUL }; ADD(cpu.sp); }
{ static const char label[] = { a, NUL }; ADD(cpu.a); }
{ static const char label[] = { b, NUL }; ADD(cpu.b); }
{ static const char label[] = { c, NUL }; ADD(cpu.c); }
{ static const char label[] = { d, NUL }; ADD(cpu.d); }
{ static const char label[] = { e, NUL }; ADD(cpu.e); }
{ static const char label[] = { f, NUL }; ADD(cpu.f); }
{ static const char label[] = { h, NUL }; ADD(cpu.h); }
{ static const char label[] = { l, NUL }; ADD(cpu.l); }
{ static const char label[] = { s,k,i,p, NUL }; ADD(cpu.skip); }
{ static const char label[] = { h,a,l,t, NUL }; ADD(mem.halted); }
{ static const char label[] = { v,r,a,m, NUL }; ADDPTR(mem.vram); }
{ static const char label[] = { s,r,a,m, NUL }; ADDPTR(mem.sram); }
{ static const char label[] = { w,r,a,m, NUL }; ADDPTR(mem.wram); }
{ static const char label[] = { h,r,a,m, NUL }; ADDPTR(mem.ioamhram); }
{ static const char label[] = { l,d,i,v,u,p, NUL }; ADD(mem.divLastUpdate); }
{ static const char label[] = { l,t,i,m,a,u,p, NUL }; ADD(mem.timaLastUpdate); }
{ static const char label[] = { t,m,a,t,i,m,e, NUL }; ADD(mem.tmatime); }
{ static const char label[] = { s,e,r,i,a,l,t, NUL }; ADD(mem.nextSerialtime); }
{ static const char label[] = { l,o,d,m,a,u,p, NUL }; ADD(mem.lastOamDmaUpdate); }
{ static const char label[] = { m,i,n,i,n,t,t, NUL }; ADD(mem.minIntTime); }
{ static const char label[] = { u,n,h,a,l,t,t, NUL }; ADD(mem.unhaltTime); }
{ static const char label[] = { r,o,m,b,a,n,k, NUL }; ADD(mem.rombank); }
{ static const char label[] = { d,m,a,s,r,c, NUL }; ADD(mem.dmaSource); }
{ static const char label[] = { d,m,a,d,s,t, NUL }; ADD(mem.dmaDestination); }
{ static const char label[] = { r,a,m,b,a,n,k, NUL }; ADD(mem.rambank); }
{ static const char label[] = { o,d,m,a,p,o,s, NUL }; ADD(mem.oamDmaPos); }
{ static const char label[] = { i,m,e, NUL }; ADD(mem.IME); }
{ static const char label[] = { s,r,a,m,o,n, NUL }; ADD(mem.enableRam); }
{ static const char label[] = { r,a,m,b,m,o,d, NUL }; ADD(mem.rambankMode); }
{ static const char label[] = { h,d,m,a, NUL }; ADD(mem.hdmaTransfer); }
{ static const char label[] = { b,g,p, NUL }; ADDPTR(ppu.bgpData); }
{ static const char label[] = { o,b,j,p, NUL }; ADDPTR(ppu.objpData); }
{ static const char label[] = { s,p,o,s,b,u,f, NUL }; ADDPTR(ppu.oamReaderBuf); }
{ static const char label[] = { s,p,s,z,b,u,f, NUL }; ADDPTR(ppu.oamReaderSzbuf); }
{ static const char label[] = { s,p,a,t,t,r, NUL }; ADDARRAY(ppu.spAttribList); }
{ static const char label[] = { s,p,b,y,t,e,NO0, NUL }; ADDARRAY(ppu.spByte0List); }
{ static const char label[] = { s,p,b,y,t,e,NO1, NUL }; ADDARRAY(ppu.spByte1List); }
{ static const char label[] = { v,c,y,c,l,e,s, NUL }; ADD(ppu.videoCycles); }
{ static const char label[] = { e,d,M,NO0,t,i,m, NUL }; ADD(ppu.enableDisplayM0Time); }
{ static const char label[] = { m,NO0,t,i,m,e, NUL }; ADD(ppu.lastM0Time); }
{ static const char label[] = { n,m,NO0,i,r,q, NUL }; ADD(ppu.nextM0Irq); }
{ static const char label[] = { b,g,t,w, NUL }; ADD(ppu.tileword); }
{ static const char label[] = { b,g,n,t,w, NUL }; ADD(ppu.ntileword); }
{ static const char label[] = { w,i,n,y,p,o,s, NUL }; ADD(ppu.winYPos); }
{ static const char label[] = { x,p,o,s, NUL }; ADD(ppu.xpos); }
{ static const char label[] = { e,n,d,x, NUL }; ADD(ppu.endx); }
{ static const char label[] = { p,p,u,r,NO0, NUL }; ADD(ppu.reg0); }
{ static const char label[] = { p,p,u,r,NO1, NUL }; ADD(ppu.reg1); }
{ static const char label[] = { b,g,a,t,r,b, NUL }; ADD(ppu.attrib); }
{ static const char label[] = { b,g,n,a,t,r,b, NUL }; ADD(ppu.nattrib); }
{ static const char label[] = { p,p,u,s,t,a,t, NUL }; ADD(ppu.state); }
{ static const char label[] = { n,s,p,r,i,t,e, NUL }; ADD(ppu.nextSprite); }
{ static const char label[] = { c,s,p,r,i,t,e, NUL }; ADD(ppu.currentSprite); }
{ static const char label[] = { l,y,c, NUL }; ADD(ppu.lyc); }
{ static const char label[] = { m,NO0,l,y,c, NUL }; ADD(ppu.m0lyc); }
{ static const char label[] = { o,l,d,w,y, NUL }; ADD(ppu.oldWy); }
{ static const char label[] = { w,i,n,d,r,a,w, NUL }; ADD(ppu.winDrawState); }
{ static const char label[] = { w,s,c,x, NUL }; ADD(ppu.wscx); }
{ static const char label[] = { w,e,m,a,s,t,r, NUL }; ADD(ppu.weMaster); }
{ static const char label[] = { l,c,d,s,i,r,q, NUL }; ADD(ppu.pendingLcdstatIrq); }
{ static const char label[] = { s,p,u,c,n,t,r, NUL }; ADD(spu.cycleCounter); }
{ static const char label[] = { s,w,p,c,n,t,r, NUL }; ADD(spu.ch1.sweep.counter); }
{ static const char label[] = { s,w,p,s,h,d,w, NUL }; ADD(spu.ch1.sweep.shadow); }
{ static const char label[] = { s,w,p,n,e,g, NUL }; ADD(spu.ch1.sweep.negging); }
{ static const char label[] = { d,u,t,NO1,c,t,r, NUL }; ADD(spu.ch1.duty.nextPosUpdate); }
{ static const char label[] = { d,u,t,NO1,p,o,s, NUL }; ADD(spu.ch1.duty.pos); }
{ static const char label[] = { e,n,v,NO1,c,t,r, NUL }; ADD(spu.ch1.env.counter); }
{ static const char label[] = { e,n,v,NO1,v,o,l, NUL }; ADD(spu.ch1.env.volume); }
{ static const char label[] = { l,e,n,NO1,c,t,r, NUL }; ADD(spu.ch1.lcounter.counter); }
{ static const char label[] = { l,e,n,NO1,v,a,l, NUL }; ADD(spu.ch1.lcounter.lengthCounter); }
{ static const char label[] = { n,r,NO1,NO0, NUL }; ADD(spu.ch1.sweep.nr0); }
{ static const char label[] = { n,r,NO1,NO3, NUL }; ADD(spu.ch1.duty.nr3); }
{ static const char label[] = { n,r,NO1,NO4, NUL }; ADD(spu.ch1.nr4); }
{ static const char label[] = { c,NO1,m,a,s,t,r, NUL }; ADD(spu.ch1.master); }
{ static const char label[] = { d,u,t,NO2,c,t,r, NUL }; ADD(spu.ch2.duty.nextPosUpdate); }
{ static const char label[] = { d,u,t,NO2,p,o,s, NUL }; ADD(spu.ch2.duty.pos); }
{ static const char label[] = { e,n,v,NO2,c,t,r, NUL }; ADD(spu.ch2.env.counter); }
{ static const char label[] = { e,n,v,NO2,v,o,l, NUL }; ADD(spu.ch2.env.volume); }
{ static const char label[] = { l,e,n,NO2,c,t,r, NUL }; ADD(spu.ch2.lcounter.counter); }
{ static const char label[] = { l,e,n,NO2,v,a,l, NUL }; ADD(spu.ch2.lcounter.lengthCounter); }
{ static const char label[] = { n,r,NO2,NO3, NUL }; ADD(spu.ch2.duty.nr3); }
{ static const char label[] = { n,r,NO2,NO4, NUL }; ADD(spu.ch2.nr4); }
{ static const char label[] = { c,NO2,m,a,s,t,r, NUL }; ADD(spu.ch2.master); }
{ static const char label[] = { w,a,v,e,r,a,m, NUL }; ADDPTR(spu.ch3.waveRam); }
{ static const char label[] = { l,e,n,NO3,c,t,r, NUL }; ADD(spu.ch3.lcounter.counter); }
{ static const char label[] = { l,e,n,NO3,v,a,l, NUL }; ADD(spu.ch3.lcounter.lengthCounter); }
{ static const char label[] = { w,a,v,e,c,t,r, NUL }; ADD(spu.ch3.waveCounter); }
{ static const char label[] = { l,w,a,v,r,d,t, NUL }; ADD(spu.ch3.lastReadTime); }
{ static const char label[] = { w,a,v,e,p,o,s, NUL }; ADD(spu.ch3.wavePos); }
{ static const char label[] = { w,a,v,s,m,p,l, NUL }; ADD(spu.ch3.sampleBuf); }
{ static const char label[] = { n,r,NO3,NO3, NUL }; ADD(spu.ch3.nr3); }
{ static const char label[] = { n,r,NO3,NO4, NUL }; ADD(spu.ch3.nr4); }
{ static const char label[] = { c,NO3,m,a,s,t,r, NUL }; ADD(spu.ch3.master); }
{ static const char label[] = { l,f,s,r,c,t,r, NUL }; ADD(spu.ch4.lfsr.counter); }
{ static const char label[] = { l,f,s,r,r,e,g, NUL }; ADD(spu.ch4.lfsr.reg); }
{ static const char label[] = { e,n,v,NO4,c,t,r, NUL }; ADD(spu.ch4.env.counter); }
{ static const char label[] = { e,n,v,NO4,v,o,l, NUL }; ADD(spu.ch4.env.volume); }
{ static const char label[] = { l,e,n,NO4,c,t,r, NUL }; ADD(spu.ch4.lcounter.counter); }
{ static const char label[] = { l,e,n,NO4,v,a,l, NUL }; ADD(spu.ch4.lcounter.lengthCounter); }
{ static const char label[] = { n,r,NO4,NO4, NUL }; ADD(spu.ch4.nr4); }
{ static const char label[] = { c,NO4,m,a,s,t,r, NUL }; ADD(spu.ch4.master); }
{ static const char label[] = { r,t,c,b,a,s,e, NUL }; ADD(rtc.baseTime); }
{ static const char label[] = { r,t,c,h,a,l,t, NUL }; ADD(rtc.haltTime); }
{ static const char label[] = { r,t,c,d,h, NUL }; ADD(rtc.dataDh); }
{ static const char label[] = { r,t,c,d,l, NUL }; ADD(rtc.dataDl); }
{ static const char label[] = { r,t,c,h, NUL }; ADD(rtc.dataH); }
{ static const char label[] = { r,t,c,m, NUL }; ADD(rtc.dataM); }
{ static const char label[] = { r,t,c,s, NUL }; ADD(rtc.dataS); }
{ static const char label[] = { r,t,c,l,l,d, NUL }; ADD(rtc.lastLatchData); }
#undef ADD
#undef ADDPTR
#undef ADDARRAY
list.resize(list.size());
std::sort(list.begin(), list.end());
maxLabelsize_ = 0;
for (std::size_t i = 0; i < list.size(); ++i) {
if (list[i].labelsize > maxLabelsize_)
maxLabelsize_ = list[i].labelsize;
}
}
}
namespace {
static void writeSnapShot(omemstream &file) {
put24(file, 0);
}
static SaverList list;
} // anon namespace
namespace gambatte {
void StateSaver::saveState(const SaveState &state, void *data) {
omemstream file(data);
if (file.fail())
return;
{ static const char ver[] = { 0, 1 }; file.write(ver, sizeof(ver)); }
writeSnapShot(file);
for (SaverList::const_iterator it = list.begin(); it != list.end(); ++it) {
file.write(it->label, it->labelsize);
(*it->save)(file, state);
}
}
bool StateSaver::loadState(SaveState &state, const void *data) {
imemstream file(data);
if (file.fail() || file.get() != 0)
return false;
file.ignore();
file.ignore(get24(file));
const Array labelbuf(list.maxLabelsize());
const Saver labelbufSaver = { labelbuf, 0, 0, list.maxLabelsize() };
SaverList::const_iterator done = list.begin();
while (file.good() && done != list.end()) {
file.getline(labelbuf, list.maxLabelsize(), NUL);
SaverList::const_iterator it = done;
if (std::strcmp(labelbuf, it->label)) {
it = std::lower_bound(it + 1, list.end(), labelbufSaver);
if (it == list.end() || std::strcmp(labelbuf, it->label)) {
file.ignore(get24(file));
continue;
}
} else
++done;
(*it->load)(file, state);
}
state.cpu.cycleCounter &= 0x7FFFFFFF;
state.spu.cycleCounter &= 0x7FFFFFFF;
return true;
}
size_t StateSaver::stateSize(const SaveState &state) {
omemstream file(0);
if (file.fail())
return 0;
{ static const char ver[] = { 0, 1 }; file.write(ver, sizeof(ver)); }
writeSnapShot(file);
for (SaverList::const_iterator it = list.begin(); it != list.end(); ++it) {
file.write(it->label, it->labelsize);
(*it->save)(file, state);
}
return file.size();
}
}
libgambatte/include/gbint.h 000664 001750 001750 00000004033 12720365247 017064 0 ustar 00sergio sergio 000000 000000 /***************************************************************************
* Copyright (C) 2007 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* This program 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 General Public License version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef GAMBATTE_INT_H
#define GAMBATTE_INT_H
#ifdef HAVE_CSTDINT
#include
namespace gambatte {
using std::uint_least32_t;
using std::uint_least16_t;
}
#elif defined(HAVE_STDINT_H)
#include
namespace gambatte {
using ::uint_least32_t;
using ::uint_least16_t;
}
#else
namespace gambatte {
#ifdef CHAR_LEAST_32
typedef unsigned char uint_least32_t;
#elif defined(SHORT_LEAST_32)
typedef unsigned short uint_least32_t;
#elif defined(INT_LEAST_32)
typedef unsigned uint_least32_t;
#else
typedef unsigned long uint_least32_t;
#endif
#ifdef CHAR_LEAST_16
typedef unsigned char uint_least16_t;
#else
typedef unsigned short uint_least16_t;
#endif
}
#endif
#endif
libgambatte/src/savestate.h 000664 001750 001750 00000010233 12720365247 017123 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2008 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#ifndef SAVESTATE_H
#define SAVESTATE_H
#include
#include
namespace gambatte {
class SaverList;
struct SaveState {
template
class Ptr {
public:
Ptr() : ptr(0), size_(0) {}
T const * get() const { return ptr; }
std::size_t size() const { return size_; }
void set(T *p, std::size_t size) { ptr = p; size_ = size; }
friend class SaverList;
friend void setInitState(SaveState &, bool, bool);
private:
T *ptr;
std::size_t size_;
};
struct CPU {
unsigned long cycleCounter;
unsigned short pc;
unsigned short sp;
unsigned char a;
unsigned char b;
unsigned char c;
unsigned char d;
unsigned char e;
unsigned char f;
unsigned char h;
unsigned char l;
bool skip;
} cpu;
struct Mem {
Ptr vram;
Ptr sram;
Ptr wram;
Ptr ioamhram;
unsigned long divLastUpdate;
unsigned long timaLastUpdate;
unsigned long tmatime;
unsigned long nextSerialtime;
unsigned long lastOamDmaUpdate;
unsigned long minIntTime;
unsigned long unhaltTime;
unsigned short rombank;
unsigned short dmaSource;
unsigned short dmaDestination;
unsigned char rambank;
unsigned char oamDmaPos;
bool IME;
bool halted;
bool enableRam;
bool rambankMode;
bool hdmaTransfer;
} mem;
struct PPU {
Ptr bgpData;
Ptr objpData;
//SpriteMapper::OamReader
Ptr oamReaderBuf;
Ptr oamReaderSzbuf;
unsigned long videoCycles;
unsigned long enableDisplayM0Time;
unsigned short lastM0Time;
unsigned short nextM0Irq;
unsigned short tileword;
unsigned short ntileword;
unsigned char spAttribList[10];
unsigned char spByte0List[10];
unsigned char spByte1List[10];
unsigned char winYPos;
unsigned char xpos;
unsigned char endx;
unsigned char reg0;
unsigned char reg1;
unsigned char attrib;
unsigned char nattrib;
unsigned char state;
unsigned char nextSprite;
unsigned char currentSprite;
unsigned char lyc;
unsigned char m0lyc;
unsigned char oldWy;
unsigned char winDrawState;
unsigned char wscx;
bool weMaster;
bool pendingLcdstatIrq;
} ppu;
struct SPU {
struct Duty {
unsigned long nextPosUpdate;
unsigned char nr3;
unsigned char pos;
bool high;
};
struct Env {
unsigned long counter;
unsigned char volume;
};
struct LCounter {
unsigned long counter;
unsigned short lengthCounter;
};
struct {
struct {
unsigned long counter;
unsigned short shadow;
unsigned char nr0;
bool negging;
} sweep;
Duty duty;
Env env;
LCounter lcounter;
unsigned char nr4;
bool master;
} ch1;
struct {
Duty duty;
Env env;
LCounter lcounter;
unsigned char nr4;
bool master;
} ch2;
struct {
Ptr waveRam;
LCounter lcounter;
unsigned long waveCounter;
unsigned long lastReadTime;
unsigned char nr3;
unsigned char nr4;
unsigned char wavePos;
unsigned char sampleBuf;
bool master;
} ch3;
struct {
struct {
unsigned long counter;
unsigned short reg;
} lfsr;
Env env;
LCounter lcounter;
unsigned char nr4;
bool master;
} ch4;
unsigned long cycleCounter;
} spu;
struct RTC {
unsigned long baseTime;
unsigned long haltTime;
unsigned char dataDh;
unsigned char dataDl;
unsigned char dataH;
unsigned char dataM;
unsigned char dataS;
bool lastLatchData;
} rtc;
};
}
#endif
libgambatte/ 000700 001750 001750 00000000000 12720366137 014150 5 ustar 00sergio sergio 000000 000000 libgambatte/src/sound/channel3.h 000664 001750 001750 00000005165 12720365247 017757 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2007 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#ifndef SOUND_CHANNEL3_H
#define SOUND_CHANNEL3_H
#include "gbint.h"
#include "length_counter.h"
#include "master_disabler.h"
namespace gambatte {
struct SaveState;
class Channel3 {
public:
Channel3();
bool isActive() const { return master_; }
void reset();
void init(bool cgb);
void setStatePtrs(SaveState &state);
void saveState(SaveState &state) const;
void loadState(const SaveState &state);
void setNr0(unsigned data);
void setNr1(unsigned data) { lengthCounter_.nr1Change(data, nr4_, cycleCounter_); }
void setNr2(unsigned data);
void setNr3(unsigned data) { nr3_ = data; }
void setNr4(unsigned data);
void setSo(unsigned long soMask);
void update(uint_least32_t *buf, unsigned long soBaseVol, unsigned long cycles);
unsigned waveRamRead(unsigned index) const {
if (master_) {
if (!cgb_ && cycleCounter_ != lastReadTime_)
return 0xFF;
index = wavePos_ >> 1;
}
return waveRam_[index];
}
void waveRamWrite(unsigned index, unsigned data) {
if (master_) {
if (!cgb_ && cycleCounter_ != lastReadTime_)
return;
index = wavePos_ >> 1;
}
waveRam_[index] = data;
}
private:
class Ch3MasterDisabler : public MasterDisabler {
public:
Ch3MasterDisabler(bool &m, unsigned long &wC) : MasterDisabler(m), waveCounter_(wC) {}
virtual void operator()() {
MasterDisabler::operator()();
waveCounter_ = SoundUnit::counter_disabled;
}
private:
unsigned long &waveCounter_;
};
unsigned char waveRam_[0x10];
Ch3MasterDisabler disableMaster_;
LengthCounter lengthCounter_;
unsigned long cycleCounter_;
unsigned long soMask_;
unsigned long prevOut_;
unsigned long waveCounter_;
unsigned long lastReadTime_;
unsigned char nr0_;
unsigned char nr3_;
unsigned char nr4_;
unsigned char wavePos_;
unsigned char rshift_;
unsigned char sampleBuf_;
bool master_;
bool cgb_;
void updateWaveCounter(unsigned long cc);
};
}
#endif
libgambatte/libretro/msvc/msvc-2003-xbox1.sln 000664 001750 001750 00000002716 12720365247 022074 0 ustar 00sergio sergio 000000 000000 Microsoft Visual Studio Solution File, Format Version 8.00
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "msvc-2003-xbox1", "msvc-2003-xbox1/msvc-2003-xbox1.vcproj", "{FAB7B0EE-4915-4CBA-A673-DDEF9B89F168}"
ProjectSection(ProjectDependencies) = postProject
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
Debug = Debug
Profile = Profile
Profile_FastCap = Profile_FastCap
Release = Release
Release_LTCG = Release_LTCG
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{FAB7B0EE-4915-4CBA-A673-DDEF9B89F168}.Debug.ActiveCfg = Debug|Xbox
{FAB7B0EE-4915-4CBA-A673-DDEF9B89F168}.Debug.Build.0 = Debug|Xbox
{FAB7B0EE-4915-4CBA-A673-DDEF9B89F168}.Profile.ActiveCfg = Profile|Xbox
{FAB7B0EE-4915-4CBA-A673-DDEF9B89F168}.Profile.Build.0 = Profile|Xbox
{FAB7B0EE-4915-4CBA-A673-DDEF9B89F168}.Profile_FastCap.ActiveCfg = Profile_FastCap|Xbox
{FAB7B0EE-4915-4CBA-A673-DDEF9B89F168}.Profile_FastCap.Build.0 = Profile_FastCap|Xbox
{FAB7B0EE-4915-4CBA-A673-DDEF9B89F168}.Release.ActiveCfg = Release|Xbox
{FAB7B0EE-4915-4CBA-A673-DDEF9B89F168}.Release.Build.0 = Release|Xbox
{FAB7B0EE-4915-4CBA-A673-DDEF9B89F168}.Release_LTCG.ActiveCfg = Release_LTCG|Xbox
{FAB7B0EE-4915-4CBA-A673-DDEF9B89F168}.Release_LTCG.Build.0 = Release_LTCG|Xbox
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal
libgambatte/src/sound/length_counter.h 000664 001750 001750 00000002647 12720365247 021306 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2007 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#ifndef LENGTH_COUNTER_H
#define LENGTH_COUNTER_H
#include "sound_unit.h"
#include "../savestate.h"
namespace gambatte {
class MasterDisabler;
class LengthCounter : public SoundUnit {
public:
LengthCounter(MasterDisabler &disabler, unsigned lengthMask);
virtual void event();
void nr1Change(unsigned newNr1, unsigned nr4, unsigned long cc);
void nr4Change(unsigned oldNr4, unsigned newNr4, unsigned long cc);
void saveState(SaveState::SPU::LCounter &lstate) const;
void loadState(SaveState::SPU::LCounter const &lstate, unsigned long cc);
private:
MasterDisabler &disableMaster_;
unsigned short lengthCounter_;
unsigned char const lengthMask_;
};
}
#endif
common/uncopyable.h 000664 001750 001750 00000003031 12720365247 015511 0 ustar 00sergio sergio 000000 000000 /***************************************************************************
* Copyright (C) 2009 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* This program 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 General Public License version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef UNCOPYABLE_H
#define UNCOPYABLE_H
class Uncopyable {
Uncopyable(const Uncopyable&);
Uncopyable& operator=(const Uncopyable&);
public:
Uncopyable() {}
};
#endif
libgambatte/src/video.cpp 000664 001750 001750 00000056571 12720365247 016604 0 ustar 00sergio sergio 000000 000000 /***************************************************************************
* Copyright (C) 2007 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* This program 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 General Public License version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "video.h"
#include "savestate.h"
#include
#include
namespace gambatte
{
void LCD::reset(const unsigned char *const oamram, unsigned char const *vram, const bool cgb)
{
ppu_.reset(oamram, vram, cgb);
lycIrq_.setCgb(cgb);
refreshPalettes();
}
static unsigned long mode2IrqSchedule(const unsigned statReg, const LyCounter &lyCounter, const unsigned long cycleCounter)
{
if (!(statReg & 0x20))
return disabled_time;
unsigned next = lyCounter.time() - cycleCounter;
if (lyCounter.ly() >= 143 || (lyCounter.ly() == 142 && next <= 4) || (statReg & 0x08))
next += (153u - lyCounter.ly()) * lyCounter.lineTime();
else
{
if (next <= 4)
next += lyCounter.lineTime();
next -= 4;
}
return cycleCounter + next;
}
static inline unsigned long m0IrqTimeFromXpos166Time(
const unsigned long xpos166Time, const bool cgb, const bool ds)
{
return xpos166Time + cgb - ds;
}
static inline unsigned long hdmaTimeFromM0Time(
const unsigned long m0Time, const bool ds)
{
return m0Time + 1 - ds;
}
static unsigned long nextHdmaTime(const unsigned long lastM0Time,
const unsigned long nextM0Time, const unsigned long cycleCounter, const bool ds)
{
return cycleCounter < hdmaTimeFromM0Time(lastM0Time, ds)
? hdmaTimeFromM0Time(lastM0Time, ds)
: hdmaTimeFromM0Time(nextM0Time, ds);
}
void LCD::setStatePtrs(SaveState &state)
{
state.ppu.bgpData.set( bgpData_, sizeof bgpData_);
state.ppu.objpData.set(objpData_, sizeof objpData_);
ppu_.setStatePtrs(state);
}
void LCD::saveState(SaveState &state) const
{
state.mem.hdmaTransfer = hdmaIsEnabled();
state.ppu.nextM0Irq = eventTimes_(MODE0_IRQ) - ppu_.now();
state.ppu.pendingLcdstatIrq = eventTimes_(ONESHOT_LCDSTATIRQ) != disabled_time;
lycIrq_.saveState(state);
m0Irq_.saveState(state);
ppu_.saveState(state);
}
void LCD::loadState(const SaveState &state, const unsigned char *const oamram)
{
statReg_ = state.mem.ioamhram.get()[0x141];
m2IrqStatReg_ = statReg_;
m1IrqStatReg_ = statReg_;
ppu_.loadState(state, oamram);
lycIrq_.loadState(state);
m0Irq_.loadState(state);
if (ppu_.lcdc() & 0x80)
{
nextM0Time_.predictNextM0Time(ppu_);
lycIrq_.reschedule(ppu_.lyCounter(), ppu_.now());
eventTimes_.setm(state.ppu.pendingLcdstatIrq
? ppu_.now() + 1 : static_cast(disabled_time));
eventTimes_.setm(state.ppu.oldWy != state.mem.ioamhram.get()[0x14A]
? ppu_.now() + 1 : static_cast(disabled_time));
eventTimes_.set(ppu_.lyCounter().time());
eventTimes_.setm(SpriteMapper::schedule(ppu_.lyCounter(), ppu_.now()));
eventTimes_.setm(lycIrq_.time());
eventTimes_.setm(ppu_.lyCounter().nextFrameCycle(144 * 456, ppu_.now()));
eventTimes_.setm(mode2IrqSchedule(statReg_, ppu_.lyCounter(), ppu_.now()));
eventTimes_.setm((statReg_ & 0x08) ? ppu_.now() + state.ppu.nextM0Irq : static_cast(disabled_time));
eventTimes_.setm(state.mem.hdmaTransfer
? nextHdmaTime(ppu_.lastM0Time(), nextM0Time_.predictedNextM0Time(), ppu_.now(), isDoubleSpeed())
: static_cast(disabled_time));
}
else
{
for (int i = 0; i < NUM_MEM_EVENTS; ++i)
eventTimes_.set(static_cast(i), disabled_time);
}
refreshPalettes();
}
void LCD::refreshPalettes()
{
if (ppu_.cgb())
{
for (unsigned i = 0; i < 8 * 8; i += 2)
{
ppu_.bgPalette()[i >> 1] = gbcToRgb32( bgpData_[i] | bgpData_[i + 1] << 8);
ppu_.spPalette()[i >> 1] = gbcToRgb32(objpData_[i] | objpData_[i + 1] << 8);
}
}
else
{
setDmgPalette(ppu_.bgPalette() , dmgColorsRgb32_ , bgpData_[0]);
setDmgPalette(ppu_.spPalette() , dmgColorsRgb32_ + 4, objpData_[0]);
setDmgPalette(ppu_.spPalette() + 4, dmgColorsRgb32_ + 8, objpData_[1]);
}
}
void LCD::resetCc(const unsigned long oldCc, const unsigned long newCc)
{
update(oldCc);
ppu_.resetCc(oldCc, newCc);
if (ppu_.lcdc() & 0x80)
{
const unsigned long dec = oldCc - newCc;
nextM0Time_.invalidatePredictedNextM0Time();
lycIrq_.reschedule(ppu_.lyCounter(), newCc);
for (int i = 0; i < NUM_MEM_EVENTS; ++i)
{
if (eventTimes_(static_cast(i)) != disabled_time)
eventTimes_.set(static_cast(i), eventTimes_(static_cast(i)) - dec);
}
eventTimes_.set(ppu_.lyCounter().time());
}
}
void LCD::speedChange(const unsigned long cycleCounter)
{
update(cycleCounter);
ppu_.speedChange(cycleCounter);
if (ppu_.lcdc() & 0x80)
{
nextM0Time_.predictNextM0Time(ppu_);
lycIrq_.reschedule(ppu_.lyCounter(), cycleCounter);
eventTimes_.set(ppu_.lyCounter().time());
eventTimes_.setm(SpriteMapper::schedule(ppu_.lyCounter(), cycleCounter));
eventTimes_.setm(lycIrq_.time());
eventTimes_.setm(ppu_.lyCounter().nextFrameCycle(144 * 456, cycleCounter));
eventTimes_.setm(mode2IrqSchedule(statReg_, ppu_.lyCounter(), cycleCounter));
if (eventTimes_(MODE0_IRQ) != disabled_time && eventTimes_(MODE0_IRQ) - cycleCounter > 1)
eventTimes_.setm(m0IrqTimeFromXpos166Time(ppu_.predictedNextXposTime(166), ppu_.cgb(), isDoubleSpeed()));
if (hdmaIsEnabled() && eventTimes_(HDMA_REQ) - cycleCounter > 1)
{
eventTimes_.setm(nextHdmaTime(ppu_.lastM0Time(),
nextM0Time_.predictedNextM0Time(), cycleCounter, isDoubleSpeed()));
}
}
}
static inline unsigned long m0TimeOfCurrentLine(const unsigned long nextLyTime,
const unsigned long lastM0Time, const unsigned long nextM0Time)
{
return nextM0Time < nextLyTime ? nextM0Time : lastM0Time;
}
unsigned long LCD::m0TimeOfCurrentLine(const unsigned long cc)
{
if (cc >= nextM0Time_.predictedNextM0Time())
{
update(cc);
nextM0Time_.predictNextM0Time(ppu_);
}
return gambatte::m0TimeOfCurrentLine(ppu_.lyCounter().time(), ppu_.lastM0Time(), nextM0Time_.predictedNextM0Time());
}
static bool isHdmaPeriod(const LyCounter &lyCounter,
const unsigned long m0TimeOfCurrentLy, const unsigned long cycleCounter)
{
const unsigned timeToNextLy = lyCounter.time() - cycleCounter;
return /*(ppu_.lcdc & 0x80) && */lyCounter.ly() < 144 && timeToNextLy > 4
&& cycleCounter >= hdmaTimeFromM0Time(m0TimeOfCurrentLy, lyCounter.isDoubleSpeed());
}
void LCD::enableHdma(const unsigned long cycleCounter)
{
if (cycleCounter >= nextM0Time_.predictedNextM0Time())
{
update(cycleCounter);
nextM0Time_.predictNextM0Time(ppu_);
}
else if (cycleCounter >= eventTimes_.nextEventTime())
update(cycleCounter);
if (isHdmaPeriod(ppu_.lyCounter(),
gambatte::m0TimeOfCurrentLine(ppu_.lyCounter().time(),
ppu_.lastM0Time(), nextM0Time_.predictedNextM0Time()), cycleCounter))
eventTimes_.flagHdmaReq();
eventTimes_.setm(nextHdmaTime(ppu_.lastM0Time(), nextM0Time_.predictedNextM0Time(), cycleCounter, isDoubleSpeed()));
}
void LCD::disableHdma(const unsigned long cycleCounter)
{
if (cycleCounter >= eventTimes_.nextEventTime())
update(cycleCounter);
eventTimes_.setm(disabled_time);
}
bool LCD::vramAccessible(const unsigned long cc)
{
if (cc >= eventTimes_.nextEventTime())
update(cc);
return !(ppu_.lcdc() & 0x80) || ppu_.lyCounter().ly() >= 144
|| ppu_.lyCounter().lineCycles(cc) < 80U
|| cc + isDoubleSpeed() - ppu_.cgb() + 2 >= m0TimeOfCurrentLine(cc);
}
bool LCD::cgbpAccessible(const unsigned long cc)
{
if (cc >= eventTimes_.nextEventTime())
update(cc);
return !(ppu_.lcdc() & 0x80) || ppu_.lyCounter().ly() >= 144
|| ppu_.lyCounter().lineCycles(cc) < 80U + isDoubleSpeed()
|| cc >= m0TimeOfCurrentLine(cc) + 3 - isDoubleSpeed();
}
void LCD::doCgbBgColorChange(unsigned index, const unsigned data, const unsigned long cc)
{
if (cgbpAccessible(cc))
{
update(cc);
doCgbColorChange(bgpData_, ppu_.bgPalette(), index, data);
}
}
void LCD::doCgbSpColorChange(unsigned index, const unsigned data, const unsigned long cc)
{
if (cgbpAccessible(cc))
{
update(cc);
doCgbColorChange(objpData_, ppu_.spPalette(), index, data);
}
}
bool LCD::oamReadable(const unsigned long cc)
{
if (!(ppu_.lcdc() & 0x80) || ppu_.inactivePeriodAfterDisplayEnable(cc))
return true;
if (cc >= eventTimes_.nextEventTime())
update(cc);
if (ppu_.lyCounter().lineCycles(cc) + 4 - ppu_.lyCounter().isDoubleSpeed() * 3u >= 456)
return ppu_.lyCounter().ly() >= 144-1 && ppu_.lyCounter().ly() != 153;
return ppu_.lyCounter().ly() >= 144 || cc + isDoubleSpeed() - ppu_.cgb() + 2 >= m0TimeOfCurrentLine(cc);
}
bool LCD::oamWritable(const unsigned long cc)
{
if (!(ppu_.lcdc() & 0x80) || ppu_.inactivePeriodAfterDisplayEnable(cc))
return true;
if (cc >= eventTimes_.nextEventTime())
update(cc);
if (ppu_.lyCounter().lineCycles(cc) + 3 + ppu_.cgb() - ppu_.lyCounter().isDoubleSpeed() * 2u >= 456)
return ppu_.lyCounter().ly() >= 144-1 && ppu_.lyCounter().ly() != 153;
return ppu_.lyCounter().ly() >= 144 || cc + isDoubleSpeed() - ppu_.cgb() + 2 >= m0TimeOfCurrentLine(cc);
}
void LCD::mode3CyclesChange()
{
nextM0Time_.invalidatePredictedNextM0Time();
if (eventTimes_(MODE0_IRQ) != disabled_time
&& eventTimes_(MODE0_IRQ) > m0IrqTimeFromXpos166Time(ppu_.now(), ppu_.cgb(), isDoubleSpeed())) {
eventTimes_.setm(m0IrqTimeFromXpos166Time(ppu_.predictedNextXposTime(166), ppu_.cgb(), isDoubleSpeed()));
}
if (eventTimes_(HDMA_REQ) != disabled_time
&& eventTimes_(HDMA_REQ) > hdmaTimeFromM0Time(ppu_.lastM0Time(), isDoubleSpeed())) {
nextM0Time_.predictNextM0Time(ppu_);
eventTimes_.setm(hdmaTimeFromM0Time(nextM0Time_.predictedNextM0Time(), isDoubleSpeed()));
}
}
void LCD::wxChange(const unsigned newValue, const unsigned long cycleCounter)
{
update(cycleCounter + isDoubleSpeed() + 1);
ppu_.setWx(newValue);
mode3CyclesChange();
}
void LCD::wyChange(const unsigned newValue, const unsigned long cc)
{
update(cc + 1);
ppu_.setWy(newValue);
// mode3CyclesChange(); // should be safe to wait until after wy2 delay, because no mode3 events are close to when wy1 is read.
// wy2 is a delayed version of wy. really just slowness of ly == wy comparison.
if (ppu_.cgb() && (ppu_.lcdc() & 0x80)) {
eventTimes_.setm(cc + 5);
} else {
update(cc + 2);
ppu_.updateWy2();
mode3CyclesChange();
}
}
void LCD::scxChange(const unsigned newScx, const unsigned long cycleCounter) {
update(cycleCounter + ppu_.cgb() + isDoubleSpeed());
ppu_.setScx(newScx);
mode3CyclesChange();
}
void LCD::scyChange(const unsigned newValue, const unsigned long cycleCounter) {
update(cycleCounter + ppu_.cgb() + isDoubleSpeed());
ppu_.setScy(newValue);
}
void LCD::oamChange(const unsigned long cc) {
if (ppu_.lcdc() & 0x80) {
update(cc);
ppu_.oamChange(cc);
eventTimes_.setm(SpriteMapper::schedule(ppu_.lyCounter(), cc));
}
}
void LCD::oamChange(const unsigned char *const oamram, const unsigned long cc) {
update(cc);
ppu_.oamChange(oamram, cc);
if (ppu_.lcdc() & 0x80)
eventTimes_.setm(SpriteMapper::schedule(ppu_.lyCounter(), cc));
}
void LCD::lcdcChange(const unsigned data, const unsigned long cc) {
const unsigned oldLcdc = ppu_.lcdc();
update(cc);
if ((oldLcdc ^ data) & 0x80)
{
ppu_.setLcdc(data, cc);
if (data & 0x80) {
lycIrq_.lcdReset();
m0Irq_.lcdReset(statReg_, lycIrq_.lycReg());
if (lycIrq_.lycReg() == 0 && (statReg_ & 0x40))
eventTimes_.flagIrq(2);
nextM0Time_.predictNextM0Time(ppu_);
lycIrq_.reschedule(ppu_.lyCounter(), cc);
eventTimes_.set(ppu_.lyCounter().time());
eventTimes_.setm(SpriteMapper::schedule(ppu_.lyCounter(), cc));
eventTimes_.setm(lycIrq_.time());
eventTimes_.setm(ppu_.lyCounter().nextFrameCycle(144 * 456, cc));
eventTimes_.setm(mode2IrqSchedule(statReg_, ppu_.lyCounter(), cc));
if (statReg_ & 0x08)
eventTimes_.setm(m0IrqTimeFromXpos166Time(ppu_.predictedNextXposTime(166), ppu_.cgb(), isDoubleSpeed()));
if (hdmaIsEnabled())
eventTimes_.setm(nextHdmaTime(ppu_.lastM0Time(),
nextM0Time_.predictedNextM0Time(), cc, isDoubleSpeed()));
}
else
{
for (int i = 0; i < NUM_MEM_EVENTS; ++i)
eventTimes_.set(static_cast(i), disabled_time);
}
}
else if (data & 0x80)
{
if (ppu_.cgb())
{
ppu_.setLcdc((oldLcdc & ~0x14) | (data & 0x14), cc);
if ((oldLcdc ^ data) & 0x04)
eventTimes_.setm(SpriteMapper::schedule(ppu_.lyCounter(), cc));
update(cc + isDoubleSpeed() + 1);
ppu_.setLcdc(data, cc + isDoubleSpeed() + 1);
if ((oldLcdc ^ data) & 0x20)
mode3CyclesChange();
}
else
{
ppu_.setLcdc(data, cc);
if ((oldLcdc ^ data) & 0x04)
eventTimes_.setm(SpriteMapper::schedule(ppu_.lyCounter(), cc));
if ((oldLcdc ^ data) & 0x22)
mode3CyclesChange();
}
}
else
ppu_.setLcdc(data, cc);
}
void LCD::lcdstatChange(const unsigned data, const unsigned long cc)
{
if (cc >= eventTimes_.nextEventTime())
update(cc);
const unsigned old = statReg_;
statReg_ = data;
lycIrq_.statRegChange(data, ppu_.lyCounter(), cc);
if (ppu_.lcdc() & 0x80)
{
if (!ppu_.cgb())
{
const unsigned timeToNextLy = ppu_.lyCounter().time() - cc;
const unsigned lycCmpLy = ppu_.lyCounter().ly() == 153 && timeToNextLy <= 444U + 8 ? 0 : ppu_.lyCounter().ly();
if (lycCmpLy == lycIrq_.lycReg())
{
if (!(old & 0x40) && (ppu_.lyCounter().ly() < 144 || !(old & 0x10)))
eventTimes_.flagIrq(2);
}
else if (ppu_.lyCounter().ly() >= 144)
{
if (!(old & 0x10))
eventTimes_.flagIrq(2);
}
else if (cc + 1 >= m0TimeOfCurrentLine(cc))
{
if (!(old & 0x08))
eventTimes_.flagIrq(2);
}
}
else
{
const unsigned timeToNextLy = ppu_.lyCounter().time() - cc;
const unsigned lycCmpLy = ppu_.lyCounter().ly() == 153 && timeToNextLy <= (444U << isDoubleSpeed()) + 8
? 0 : ppu_.lyCounter().ly();
const bool lycperiod = lycCmpLy == lycIrq_.lycReg() && timeToNextLy > 4U - isDoubleSpeed() * 4U;
const bool lycperiodActive = lycperiod && (old & 0x40);
if (lycperiod && (data & 0x40) - (old & 0x40) == 0x40 && (ppu_.lyCounter().ly() < 144 || !(old & 0x10)))
eventTimes_.flagIrq(2);
else if (ppu_.lyCounter().ly() >= 144 && (data & 0x10) - (old & 0x10) == 0x10 &&
(ppu_.lyCounter().ly() < 153 || timeToNextLy > 4U - isDoubleSpeed() * 4U) && !lycperiodActive)
eventTimes_.flagIrq(2);
else if ((data & 0x08) - (old & 0x08) == 0x08 && ppu_.lyCounter().ly() < 144 && !lycperiodActive &&
timeToNextLy > 4 && cc + isDoubleSpeed() * 2 >= m0TimeOfCurrentLine(cc))
eventTimes_.flagIrq(2);
else if ((data & 0x28) == 0x20 && !(old & 0x20)
&& ((timeToNextLy <= 4 && ppu_.lyCounter().ly() < 143)
|| (timeToNextLy == 456*2 && ppu_.lyCounter().ly() < 144)))
eventTimes_.flagIrq(2);
}
if ((data & 0x08) && eventTimes_(MODE0_IRQ) == disabled_time)
{
update(cc);
eventTimes_.setm(m0IrqTimeFromXpos166Time(ppu_.predictedNextXposTime(166), ppu_.cgb(), isDoubleSpeed()));
}
eventTimes_.setm(mode2IrqSchedule(data, ppu_.lyCounter(), cc));
eventTimes_.setm(lycIrq_.time());
}
m2IrqStatReg_ = eventTimes_(MODE2_IRQ) - cc > (ppu_.cgb() - isDoubleSpeed()) * 4U
? data : (m2IrqStatReg_ & 0x10) | (statReg_ & ~0x10);
m1IrqStatReg_ = eventTimes_(MODE1_IRQ) - cc > (ppu_.cgb() - isDoubleSpeed()) * 4U
? data : (m1IrqStatReg_ & 0x08) | (statReg_ & ~0x08);
m0Irq_.statRegChange(data, eventTimes_(MODE0_IRQ), cc, ppu_.cgb());
}
void LCD::lycRegChange(const unsigned data, const unsigned long cc)
{
if (data == lycIrq_.lycReg())
return;
if (cc >= eventTimes_.nextEventTime())
update(cc);
m0Irq_.lycRegChange(data, eventTimes_(MODE0_IRQ), cc, isDoubleSpeed(), ppu_.cgb());
lycIrq_.lycRegChange(data, ppu_.lyCounter(), cc);
if (!(ppu_.lcdc() & 0x80))
return;
eventTimes_.setm(lycIrq_.time());
const unsigned timeToNextLy = ppu_.lyCounter().time() - cc;
if ((statReg_ & 0x40) && data < 154 &&
(ppu_.lyCounter().ly() < 144 || !(statReg_ & 0x10) || (ppu_.lyCounter().ly() == 153 && timeToNextLy <= 4U)))
{
unsigned lycCmpLy = ppu_.lyCounter().ly();
if (ppu_.cgb())
{
if (timeToNextLy <= 4U >> isDoubleSpeed())
lycCmpLy = lycCmpLy < 153 ? lycCmpLy + 1 : 0;
else if (timeToNextLy <= 8)
lycCmpLy = 0xFF;
else if (lycCmpLy == 153 && timeToNextLy <= (448U << isDoubleSpeed()) + 8)
lycCmpLy = 0;
}
else
{
if (timeToNextLy <= 4)
lycCmpLy = 0xFF;
else if (lycCmpLy == 153 && timeToNextLy <= 444U + 8)
lycCmpLy = 0;
}
if (data == lycCmpLy)
{
if (ppu_.cgb() && !isDoubleSpeed())
eventTimes_.setm(cc + 5);
else
eventTimes_.flagIrq(2);
}
}
}
unsigned LCD::getStat(const unsigned lycReg, const unsigned long cc)
{
unsigned stat = 0;
if (ppu_.lcdc() & 0x80)
{
if (cc >= eventTimes_.nextEventTime())
update(cc);
const unsigned timeToNextLy = ppu_.lyCounter().time() - cc;
if (ppu_.lyCounter().ly() > 143)
{
if (ppu_.lyCounter().ly() < 153 || timeToNextLy > 4 - isDoubleSpeed() * 4U)
stat = 1;
}
else
{
const unsigned lineCycles = 456 - (timeToNextLy >> isDoubleSpeed());
if (lineCycles < 80)
{
if (!ppu_.inactivePeriodAfterDisplayEnable(cc))
stat = 2;
}
else if (cc + isDoubleSpeed() - ppu_.cgb() + 2 < m0TimeOfCurrentLine(cc))
stat = 3;
}
if ((ppu_.lyCounter().ly() == lycReg && timeToNextLy > 4 - isDoubleSpeed() * 4U) ||
(lycReg == 0 && ppu_.lyCounter().ly() == 153 && timeToNextLy >> isDoubleSpeed() <= 456 - 8))
stat |= 4;
}
return stat;
}
inline void LCD::doMode2IrqEvent()
{
const unsigned ly = eventTimes_(LY_COUNT) - eventTimes_(MODE2_IRQ) < 8
? (ppu_.lyCounter().ly() == 153 ? 0 : ppu_.lyCounter().ly() + 1)
: ppu_.lyCounter().ly();
if ((ly != 0 || !(m2IrqStatReg_ & 0x10)) &&
(!(m2IrqStatReg_ & 0x40) || (lycIrq_.lycReg() != 0 ? ly != (lycIrq_.lycReg() + 1U) : ly > 1)))
eventTimes_.flagIrq(2);
m2IrqStatReg_ = statReg_;
if (!(statReg_ & 0x08))
{
unsigned long nextTime = eventTimes_(MODE2_IRQ) + ppu_.lyCounter().lineTime();
if (ly == 0)
nextTime -= 4;
else if (ly == 143)
nextTime += ppu_.lyCounter().lineTime() * 10 + 4;
eventTimes_.setm(nextTime);
}
else
eventTimes_.setm(eventTimes_(MODE2_IRQ) + (70224 << isDoubleSpeed()));
}
inline void LCD::event()
{
switch (eventTimes_.nextEvent())
{
case MEM_EVENT:
switch (eventTimes_.nextMemEvent())
{
case MODE1_IRQ:
eventTimes_.flagIrq((m1IrqStatReg_ & 0x18) == 0x10 ? 3 : 1);
m1IrqStatReg_ = statReg_;
eventTimes_.setm(eventTimes_(MODE1_IRQ) + (70224 << isDoubleSpeed()));
break;
case LYC_IRQ:
{
unsigned char ifreg = 0;
lycIrq_.doEvent(&ifreg, ppu_.lyCounter());
eventTimes_.flagIrq(ifreg);
eventTimes_.setm(lycIrq_.time());
}
break;
case SPRITE_MAP:
eventTimes_.setm(ppu_.doSpriteMapEvent(eventTimes_(SPRITE_MAP)));
mode3CyclesChange();
break;
case HDMA_REQ:
eventTimes_.flagHdmaReq();
nextM0Time_.predictNextM0Time(ppu_);
eventTimes_.setm(hdmaTimeFromM0Time(nextM0Time_.predictedNextM0Time(), isDoubleSpeed()));
break;
case MODE2_IRQ:
doMode2IrqEvent();
break;
case MODE0_IRQ:
{
unsigned char ifreg = 0;
m0Irq_.doEvent(&ifreg, ppu_.lyCounter().ly(), statReg_, lycIrq_.lycReg());
eventTimes_.flagIrq(ifreg);
}
eventTimes_.setm((statReg_ & 0x08)
? m0IrqTimeFromXpos166Time(ppu_.predictedNextXposTime(166), ppu_.cgb(), isDoubleSpeed())
: static_cast(disabled_time));
break;
case ONESHOT_LCDSTATIRQ:
eventTimes_.flagIrq(2);
eventTimes_.setm(disabled_time);
break;
case ONESHOT_UPDATEWY2:
ppu_.updateWy2();
mode3CyclesChange();
eventTimes_.setm(disabled_time);
break;
}
break;
case LY_COUNT:
ppu_.doLyCountEvent();
eventTimes_.set(ppu_.lyCounter().time());
break;
}
}
void LCD::update(const unsigned long cycleCounter)
{
if (!(ppu_.lcdc() & 0x80))
return;
while (cycleCounter >= eventTimes_.nextEventTime())
{
ppu_.update(eventTimes_.nextEventTime());
event();
}
ppu_.update(cycleCounter);
}
}
libgambatte/libretro/msvc/msvc-2010-360.sln 000664 001750 001750 00000003516 12720365247 021340 0 ustar 00sergio sergio 000000 000000 
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "msvc-2010-360", "msvc-2010-360/msvc-2010-360.vcxproj", "{A79F81F6-3FEE-48AA-9157-24EB772B624E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
CodeAnalysis|Xbox 360 = CodeAnalysis|Xbox 360
Debug|Xbox 360 = Debug|Xbox 360
Profile_FastCap|Xbox 360 = Profile_FastCap|Xbox 360
Profile|Xbox 360 = Profile|Xbox 360
Release_LTCG|Xbox 360 = Release_LTCG|Xbox 360
Release|Xbox 360 = Release|Xbox 360
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A79F81F6-3FEE-48AA-9157-24EB772B624E}.CodeAnalysis|Xbox 360.ActiveCfg = CodeAnalysis|Xbox 360
{A79F81F6-3FEE-48AA-9157-24EB772B624E}.CodeAnalysis|Xbox 360.Build.0 = CodeAnalysis|Xbox 360
{A79F81F6-3FEE-48AA-9157-24EB772B624E}.Debug|Xbox 360.ActiveCfg = Debug|Xbox 360
{A79F81F6-3FEE-48AA-9157-24EB772B624E}.Debug|Xbox 360.Build.0 = Debug|Xbox 360
{A79F81F6-3FEE-48AA-9157-24EB772B624E}.Profile_FastCap|Xbox 360.ActiveCfg = Profile_FastCap|Xbox 360
{A79F81F6-3FEE-48AA-9157-24EB772B624E}.Profile_FastCap|Xbox 360.Build.0 = Profile_FastCap|Xbox 360
{A79F81F6-3FEE-48AA-9157-24EB772B624E}.Profile|Xbox 360.ActiveCfg = Profile|Xbox 360
{A79F81F6-3FEE-48AA-9157-24EB772B624E}.Profile|Xbox 360.Build.0 = Profile|Xbox 360
{A79F81F6-3FEE-48AA-9157-24EB772B624E}.Release_LTCG|Xbox 360.ActiveCfg = Release_LTCG|Xbox 360
{A79F81F6-3FEE-48AA-9157-24EB772B624E}.Release_LTCG|Xbox 360.Build.0 = Release_LTCG|Xbox 360
{A79F81F6-3FEE-48AA-9157-24EB772B624E}.Release|Xbox 360.ActiveCfg = Release|Xbox 360
{A79F81F6-3FEE-48AA-9157-24EB772B624E}.Release|Xbox 360.Build.0 = Release|Xbox 360
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
libgambatte/src/minkeeper.h 000664 001750 001750 00000012604 12720365247 017107 0 ustar 00sergio sergio 000000 000000 /***************************************************************************
* Copyright (C) 2009 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* This program 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 General Public License version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef MINKEEPER_H
#define MINKEEPER_H
#include
namespace MinKeeperUtil
{
template struct CeiledLog2 { enum { RESULT = 1 + CeiledLog2<(n + 1) / 2>::RESULT }; };
template<> struct CeiledLog2<1> { enum { RESULT = 0 }; };
template struct RoundedDiv2n { enum { RESULT = RoundedDiv2n<(v + 1) / 2, n - 1>::RESULT }; };
template struct RoundedDiv2n { enum { RESULT = v }; };
template class T, int n> struct Sum { enum { RESULT = T::RESULT + Sum::RESULT }; };
template class T> struct Sum { enum { RESULT = 0 }; };
}
// Keeps track of minimum value identified by id as values change.
// Higher ids prioritized (as min value) if values are equal. Can easily be reversed by swapping < for <=.
// Higher ids can be faster to change when the number of ids isn't a power of 2.
// Thus the ones that change more frequently should have higher ids if priority allows it.
template
class MinKeeper
{
enum { LEVELS = MinKeeperUtil::CeiledLog2::RESULT };
template struct Num { enum { RESULT = MinKeeperUtil::RoundedDiv2n::RESULT }; };
template struct Sum { enum { RESULT = MinKeeperUtil::Sum::RESULT }; };
template
struct UpdateValue {
enum { P = Sum::RESULT + id };
enum { C0 = Sum::RESULT + id * 2 };
static void updateValue(MinKeeper *const s)
{
// GCC 4.3 generates better code with the ternary operator on i386.
s->a[P] = (id * 2 + 1 == Num::RESULT || s->values[s->a[C0]] < s->values[s->a[C0 + 1]]) ? s->a[C0] : s->a[C0 + 1];
UpdateValue::updateValue(s);
}
};
template
struct UpdateValue
{
static void updateValue(MinKeeper *const s)
{
s->minValue_ = s->values[s->a[0]];
}
};
template struct FillLut {
static void fillLut(MinKeeper *const s)
{
s->updateValueLut[id] = updateValue;
FillLut::fillLut(s);
}
};
template struct FillLut<-1,dummy> {
static void fillLut(MinKeeper *const)
{
}
};
unsigned long values[ids];
unsigned long minValue_;
void (*updateValueLut[Num::RESULT])(MinKeeper*const);
int a[Sum::RESULT];
template static void updateValue(MinKeeper *const s);
public:
MinKeeper(unsigned long initValue = 0xFFFFFFFF);
int min() const { return a[0]; }
unsigned long minValue() const { return minValue_; }
template
void setValue(const unsigned long cnt)
{
values[id] = cnt;
updateValue(this);
}
void setValue(const int id, const unsigned long cnt)
{
values[id] = cnt;
updateValueLut[id >> 1](this);
}
unsigned long value(const int id) const { return values[id]; }
};
template
MinKeeper::MinKeeper(const unsigned long initValue)
{
std::fill(values, values + ids, initValue);
for (int i = 0; i < Num::RESULT; ++i)
{
a[Sum::RESULT + i] = (i * 2 + 1 == ids || values[i * 2] < values[i * 2 + 1]) ? i * 2 : i * 2 + 1;
}
int n = Num::RESULT;
int off = Sum::RESULT;
while (off)
{
const int pn = (n + 1) >> 1;
const int poff = off - pn;
for (int i = 0; i < pn; ++i)
{
a[poff + i] = (i * 2 + 1 == n ||
values[a[off + i * 2]] < values[a[off + i * 2 + 1]]) ?
a[off + i * 2] : a[off + i * 2 + 1];
}
off = poff;
n = pn;
}
minValue_ = values[a[0]];
FillLut::RESULT-1,0>::fillLut(this);
}
template
template
void MinKeeper::updateValue(MinKeeper *const s)
{
s->a[Sum::RESULT + id] = (id * 2 + 1 == ids || s->values[id * 2] < s->values[id * 2 + 1]) ? id * 2 : id * 2 + 1;
UpdateValue::updateValue(s);
}
#endif
README 000664 001750 001750 00000011411 12720365247 012570 0 ustar 00sergio sergio 000000 000000 --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
Copyright (C) 2007 by Sindre Aamås
aamas@stud.ntnu.no
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program 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 General Public License version 2 for more details.
You should have received a copy of the GNU General Public License
version 2 along with this program; if not, write to the
Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
About
--------------------------------------------------------------------------------
Gambatte is an accuracy-focused, open-source, cross-platform
Game Boy Color emulator written in C++. It is based on hundreds of
corner case hardware tests, as well as previous documentation and reverse
engineering efforts.
The core emulation code is contained in a separate library back-end
(libgambatte) written in platform-independent C++. There is currently a GUI
front-end (gambatte_qt) using Trolltech's Qt4 toolkit, and a simple command-line
SDL front-end (gambatte_sdl).
The GUI front-end contains platform-specific extensions for video, sound and
timers. It should work on MS Windows, Linux/BSD/UNIX-like OSes, and Mac OS X.
The SDL front-end should be usable on all platforms with a working SDL port. It
should also be quite trivial to create new (simple) front-ends (note that the
library API should in no way be considered stable).
Usage
--------------------------------------------------------------------------------
You will have to supply Gambatte with a ROM image file of the GB/GBC
program/game you'd like to run/play, either as a command-line argument to
gambatte_sdl, or through the File->Open... menu in gambatte_qt.
gambatte_sdl keyboard commands:
TAB - fast-forward
Ctrl-f - toggle full screen
Ctrl-r - reset
F5 - save state
F6 - previous state slot
F7 - next state slot
F8 - load state
0 to 9 - select state slot 0 to 9
Default key mapping:
Up: Up
Down: Down
Left: Left
Right: Right
A: D
B: C
Start: Return
Select: Shift
Compiling
--------------------------------------------------------------------------------
Building Gambatte from source code can be done by executing the
build_.sh scripts for the qt/sdl front-ends respectively, or by issueing
the correct build command (either 'scons' or 'qmake && make') in the top-level
subdirectories (libgambatte will have to be built first). The clean.sh script
can be executed to remove all generated files after a compile (including
binaries).
Requirements for building libgambatte:
- A decent C++ compiler (like g++ in the GNU Compiler Collection).
- SCons.
- optionally zlib
Requirements for building gambatte_sdl:
- A decent C++ compiler (like g++ in the GNU Compiler Collection).
- SDL headers and library.
- SCons.
(- libgambatte.)
Requirements for building gambatte_qt:
- A decent C++ compiler (like g++ in the GNU Compiler Collection).
- Qt4 (Core, GUI, OpenGL) headers and library.
- Qmake and make (GNU Make should work).
- Platform-specific requirements:
* MS Windows:
- Win32 API headers and libraries.
- DirectSound and DirectDraw7 headers and libraries.
- Direct3D9 headers
* Linux/BSD/UNIX-like OSes:
- POSIX/UNIX headers (unistd.h, fcntl.h, sys/ioctl.h, sys/time.h, sys/shm.h).
- Open Sound System header (sys/soundcard.h).
- X11 Xlib, XVideo, XRandR and XShm headers and libraries.
- Alsa headers and library (Linux only).
* Max OS X:
- Recent Mac OS X SDK (Panther Xcode/SDK should work)
(- libgambatte.)
Installing after a compile simply amounts to copying the generated binary
(either gambatte_qt/bin/gambatte_qt<.exe> or gambatte_sdl/gambatte_sdl<.exe>)
to wherever you'd like to keep it.
Thanks
--------------------------------------------------------------------------------
Derek Liauw Kie Fa (Kreed)
Gilles Vollant
Jeff Frohwein
Jonathan Gevaryahu (Lord Nightmare)
kOOPa
Marat Fayzullin
Martin Korth (nocash)
Maxim Stepin (MaxSt)
Nach
Pan of Anthrox
Pascal Felber
Paul Robson
SDL
Shay Green (blargg)
The OpenGL Extension Wrangler Library
--------------------------------------------------------------------------------
Game Boy and Game Boy Color are registered trademarks of
Nintendo of America Inc.
Gambatte is not affiliated with or endorsed by any of the companies mentioned.
libgambatte/src/video/next_m0_time.h 000664 001750 001750 00000000575 12720365247 020632 0 ustar 00sergio sergio 000000 000000 #ifndef NEXT_M0_TIME_H_
#define NEXT_M0_TIME_H_
namespace gambatte {
class NextM0Time {
public:
NextM0Time() : predictedNextM0Time_(0) {}
void predictNextM0Time(class PPU const &v);
void invalidatePredictedNextM0Time() { predictedNextM0Time_ = 0; }
unsigned predictedNextM0Time() const { return predictedNextM0Time_; }
private:
unsigned predictedNextM0Time_;
};
}
#endif
libgambatte/src/sound/channel1.cpp 000664 001750 001750 00000015174 12720365247 020311 0 ustar 00sergio sergio 000000 000000 //
// Copyright (C) 2007 by sinamas
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program 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 General Public License version 2 for more details.
//
// You should have received a copy of the GNU General Public License
// version 2 along with this program; if not, write to the
// Free Software Foundation, Inc.,
// 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#include "channel1.h"
#include "../savestate.h"
#include
namespace gambatte {
Channel1::SweepUnit::SweepUnit(MasterDisabler &disabler, DutyUnit &dutyUnit)
: disableMaster_(disabler)
, dutyUnit_(dutyUnit)
, shadow_(0)
, nr0_(0)
, negging_(false)
, cgb_(false)
{
}
unsigned Channel1::SweepUnit::calcFreq() {
unsigned freq = shadow_ >> (nr0_ & 0x07);
if (nr0_ & 0x08) {
freq = shadow_ - freq;
negging_ = true;
} else
freq = shadow_ + freq;
if (freq & 2048)
disableMaster_();
return freq;
}
void Channel1::SweepUnit::event() {
unsigned long const period = nr0_ >> 4 & 0x07;
if (period) {
unsigned const freq = calcFreq();
if (!(freq & 2048) && (nr0_ & 0x07)) {
shadow_ = freq;
dutyUnit_.setFreq(freq, counter_);
calcFreq();
}
counter_ += period << 14;
} else
counter_ += 8ul << 14;
}
void Channel1::SweepUnit::nr0Change(unsigned newNr0) {
if (negging_ && !(newNr0 & 0x08))
disableMaster_();
nr0_ = newNr0;
}
void Channel1::SweepUnit::nr4Init(unsigned long const cc) {
negging_ = false;
shadow_ = dutyUnit_.freq();
unsigned const period = nr0_ >> 4 & 0x07;
unsigned const shift = nr0_ & 0x07;
if (period | shift)
counter_ = ((((cc + 2 + cgb_ * 2) >> 14) + (period ? period : 8)) << 14) + 2;
else
counter_ = counter_disabled;
if (shift)
calcFreq();
}
void Channel1::SweepUnit::reset() {
counter_ = counter_disabled;
}
void Channel1::SweepUnit::saveState(SaveState &state) const {
state.spu.ch1.sweep.counter = counter_;
state.spu.ch1.sweep.shadow = shadow_;
state.spu.ch1.sweep.nr0 = nr0_;
state.spu.ch1.sweep.negging = negging_;
}
void Channel1::SweepUnit::loadState(SaveState const &state) {
counter_ = std::max(state.spu.ch1.sweep.counter, state.spu.cycleCounter);
shadow_ = state.spu.ch1.sweep.shadow;
nr0_ = state.spu.ch1.sweep.nr0;
negging_ = state.spu.ch1.sweep.negging;
}
Channel1::Channel1()
: staticOutputTest_(*this, dutyUnit_)
, disableMaster_(master_, dutyUnit_)
, lengthCounter_(disableMaster_, 0x3F)
, envelopeUnit_(staticOutputTest_)
, sweepUnit_(disableMaster_, dutyUnit_)
, nextEventUnit_(0)
, cycleCounter_(0)
, soMask_(0)
, prevOut_(0)
, nr4_(0)
, master_(false)
{
setEvent();
}
void Channel1::setEvent() {
nextEventUnit_ = &sweepUnit_;
if (envelopeUnit_.counter() < nextEventUnit_->counter())
nextEventUnit_ = &envelopeUnit_;
if (lengthCounter_.counter() < nextEventUnit_->counter())
nextEventUnit_ = &lengthCounter_;
}
void Channel1::setNr0(unsigned data) {
sweepUnit_.nr0Change(data);
setEvent();
}
void Channel1::setNr1(unsigned data) {
lengthCounter_.nr1Change(data, nr4_, cycleCounter_);
dutyUnit_.nr1Change(data, cycleCounter_);
setEvent();
}
void Channel1::setNr2(unsigned data) {
if (envelopeUnit_.nr2Change(data))
disableMaster_();
else
staticOutputTest_(cycleCounter_);
setEvent();
}
void Channel1::setNr3(unsigned data) {
dutyUnit_.nr3Change(data, cycleCounter_);
setEvent();
}
void Channel1::setNr4(unsigned const data) {
lengthCounter_.nr4Change(nr4_, data, cycleCounter_);
nr4_ = data;
dutyUnit_.nr4Change(data, cycleCounter_);
if (data & 0x80) { // init-bit
nr4_ &= 0x7F;
master_ = !envelopeUnit_.nr4Init(cycleCounter_);
sweepUnit_.nr4Init(cycleCounter_);
staticOutputTest_(cycleCounter_);
}
setEvent();
}
void Channel1::setSo(unsigned long soMask) {
soMask_ = soMask;
staticOutputTest_(cycleCounter_);
setEvent();
}
void Channel1::reset() {
// cycleCounter >> 12 & 7 represents the frame sequencer position.
cycleCounter_ &= 0xFFF;
cycleCounter_ += ~(cycleCounter_ + 2) << 1 & 0x1000;
dutyUnit_.reset();
envelopeUnit_.reset();
sweepUnit_.reset();
setEvent();
}
void Channel1::init(bool cgb) {
sweepUnit_.init(cgb);
}
void Channel1::saveState(SaveState &state) {
sweepUnit_.saveState(state);
dutyUnit_.saveState(state.spu.ch1.duty, cycleCounter_);
envelopeUnit_.saveState(state.spu.ch1.env);
lengthCounter_.saveState(state.spu.ch1.lcounter);
state.spu.cycleCounter = cycleCounter_;
state.spu.ch1.nr4 = nr4_;
state.spu.ch1.master = master_;
}
void Channel1::loadState(SaveState const &state) {
sweepUnit_.loadState(state);
dutyUnit_.loadState(state.spu.ch1.duty, state.mem.ioamhram.get()[0x111],
state.spu.ch1.nr4, state.spu.cycleCounter);
envelopeUnit_.loadState(state.spu.ch1.env, state.mem.ioamhram.get()[0x112],
state.spu.cycleCounter);
lengthCounter_.loadState(state.spu.ch1.lcounter, state.spu.cycleCounter);
cycleCounter_ = state.spu.cycleCounter;
nr4_ = state.spu.ch1.nr4;
master_ = state.spu.ch1.master;
}
void Channel1::update(uint_least32_t *buf, unsigned long const soBaseVol, unsigned long cycles) {
unsigned long const outBase = envelopeUnit_.dacIsOn() ? soBaseVol & soMask_ : 0;
unsigned long const outLow = outBase * (0 - 15ul);
unsigned long const endCycles = cycleCounter_ + cycles;
for (;;) {
unsigned long const outHigh = master_
? outBase * (envelopeUnit_.getVolume() * 2 - 15ul)
: outLow;
unsigned long const nextMajorEvent = std::min(nextEventUnit_->counter(), endCycles);
unsigned long out = dutyUnit_.isHighState() ? outHigh : outLow;
while (dutyUnit_.counter() <= nextMajorEvent) {
*buf = out - prevOut_;
prevOut_ = out;
buf += dutyUnit_.counter() - cycleCounter_;
cycleCounter_ = dutyUnit_.counter();
dutyUnit_.event();
out = dutyUnit_.isHighState() ? outHigh : outLow;
}
if (cycleCounter_ < nextMajorEvent) {
*buf = out - prevOut_;
prevOut_ = out;
buf += nextMajorEvent - cycleCounter_;
cycleCounter_ = nextMajorEvent;
}
if (nextEventUnit_->counter() == nextMajorEvent) {
nextEventUnit_->event();
setEvent();
} else
break;
}
if (cycleCounter_ >= SoundUnit::counter_max) {
dutyUnit_.resetCounters(cycleCounter_);
lengthCounter_.resetCounters(cycleCounter_);
envelopeUnit_.resetCounters(cycleCounter_);
sweepUnit_.resetCounters(cycleCounter_);
cycleCounter_ -= SoundUnit::counter_max;
}
}
}
libgambatte/src/insertion_sort.h 000664 001750 001750 00000003656 12720365247 020220 0 ustar 00sergio sergio 000000 000000 /***************************************************************************
* Copyright (C) 2007 by Sindre Aamås *
* aamas@stud.ntnu.no *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License version 2 as *
* published by the Free Software Foundation. *
* *
* This program 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 General Public License version 2 for more details. *
* *
* You should have received a copy of the GNU General Public License *
* version 2 along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef INSERTION_SORT_H
#define INSERTION_SORT_H
#include
template
void insertionSort(T *const start, T *const end, Less less) {
if (start >= end)
return;
T *a = start;
while (++a < end) {
const T e = *a;
T *b = a;
while (b != start && less(e, *(b - 1))) {
*b = *(b - 1);
b = b - 1;
}
*b = e;
}
}
template
inline void insertionSort(T *const start, T *const end) {
insertionSort(start, end, std::less());
}
#endif /*INSERTION_SORT_H*/
libgambatte/libretro/msvc/msvc-2010.bat 000664 001750 001750 00000007745 12720365247 021014 0 ustar 00sergio sergio 000000 000000 @echo off
@echo Setting environment for using Microsoft Visual Studio 2010 x86 tools.
@call :GetVSCommonToolsDir
@if "%VS100COMNTOOLS%"=="" goto error_no_VS100COMNTOOLSDIR
@call "%VS100COMNTOOLS%VCVarsQueryRegistry.bat" 32bit No64bit
@if "%VSINSTALLDIR%"=="" goto error_no_VSINSTALLDIR
@if "%FrameworkDir32%"=="" goto error_no_FrameworkDIR32
@if "%FrameworkVersion32%"=="" goto error_no_FrameworkVer32
@if "%Framework35Version%"=="" goto error_no_Framework35Version
@set FrameworkDir=%FrameworkDir32%
@set FrameworkVersion=%FrameworkVersion32%
@if not "%WindowsSdkDir%" == "" (
@set "PATH=%WindowsSdkDir%bin\NETFX 4.0 Tools;%WindowsSdkDir%bin;%PATH%"
@set "INCLUDE=%WindowsSdkDir%include;%INCLUDE%"
@set "LIB=%WindowsSdkDir%lib;%LIB%"
)
@rem
@rem Root of Visual Studio IDE installed files.
@rem
@set DevEnvDir=%VSINSTALLDIR%Common7\IDE\
@rem PATH
@rem ----
@if exist "%VSINSTALLDIR%Team Tools\Performance Tools" (
@set "PATH=%VSINSTALLDIR%Team Tools\Performance Tools;%PATH%"
)
@if exist "%ProgramFiles%\HTML Help Workshop" set PATH=%ProgramFiles%\HTML Help Workshop;%PATH%
@if exist "%ProgramFiles(x86)%\HTML Help Workshop" set PATH=%ProgramFiles(x86)%\HTML Help Workshop;%PATH%
@if exist "%VCINSTALLDIR%VCPackages" set PATH=%VCINSTALLDIR%VCPackages;%PATH%
@set PATH=%FrameworkDir%%Framework35Version%;%PATH%
@set PATH=%FrameworkDir%%FrameworkVersion%;%PATH%
@set PATH=%VSINSTALLDIR%Common7\Tools;%PATH%
@if exist "%VCINSTALLDIR%BIN" set PATH=%VCINSTALLDIR%BIN;%PATH%
@set PATH=%DevEnvDir%;%PATH%
@if exist "%VSINSTALLDIR%VSTSDB\Deploy" (
@set "PATH=%VSINSTALLDIR%VSTSDB\Deploy;%PATH%"
)
@if not "%FSHARPINSTALLDIR%" == "" (
@set "PATH=%FSHARPINSTALLDIR%;%PATH%"
)
@rem INCLUDE
@rem -------
@if exist "%VCINSTALLDIR%ATLMFC\INCLUDE" set INCLUDE=%VCINSTALLDIR%ATLMFC\INCLUDE;%INCLUDE%
@if exist "%VCINSTALLDIR%INCLUDE" set INCLUDE=%VCINSTALLDIR%INCLUDE;%INCLUDE%
@rem LIB
@rem ---
@if exist "%VCINSTALLDIR%ATLMFC\LIB" set LIB=%VCINSTALLDIR%ATLMFC\LIB;%LIB%
@if exist "%VCINSTALLDIR%LIB" set LIB=%VCINSTALLDIR%LIB;%LIB%
@rem LIBPATH
@rem -------
@if exist "%VCINSTALLDIR%ATLMFC\LIB" set LIBPATH=%VCINSTALLDIR%ATLMFC\LIB;%LIBPATH%
@if exist "%VCINSTALLDIR%LIB" set LIBPATH=%VCINSTALLDIR%LIB;%LIBPATH%
@set LIBPATH=%FrameworkDir%%Framework35Version%;%LIBPATH%
@set LIBPATH=%FrameworkDir%%FrameworkVersion%;%LIBPATH%
@goto end
@REM -----------------------------------------------------------------------
:GetVSCommonToolsDir
@set VS100COMNTOOLS=
@call :GetVSCommonToolsDirHelper32 HKLM > nul 2>&1
@if errorlevel 1 call :GetVSCommonToolsDirHelper32 HKCU > nul 2>&1
@if errorlevel 1 call :GetVSCommonToolsDirHelper64 HKLM > nul 2>&1
@if errorlevel 1 call :GetVSCommonToolsDirHelper64 HKCU > nul 2>&1
@exit /B 0
:GetVSCommonToolsDirHelper32
@for /F "tokens=1,2*" %%i in ('reg query "%1\SOFTWARE\Microsoft\VisualStudio\SxS\VS7" /v "10.0"') DO (
@if "%%i"=="10.0" (
@SET "VS100COMNTOOLS=%%k"
)
)
@if "%VS100COMNTOOLS%"=="" exit /B 1
@SET "VS100COMNTOOLS=%VS100COMNTOOLS%Common7\Tools\"
@exit /B 0
:GetVSCommonToolsDirHelper64
@for /F "tokens=1,2*" %%i in ('reg query "%1\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\SxS\VS7" /v "10.0"') DO (
@if "%%i"=="10.0" (
@SET "VS100COMNTOOLS=%%k"
)
)
@if "%VS100COMNTOOLS%"=="" exit /B 1
@SET "VS100COMNTOOLS=%VS100COMNTOOLS%Common7\Tools\"
@exit /B 0
@REM -----------------------------------------------------------------------
:error_no_VS100COMNTOOLSDIR
@echo ERROR: Cannot determine the location of the VS Common Tools folder.
@goto end
:error_no_VSINSTALLDIR
@echo ERROR: Cannot determine the location of the VS installation.
@goto end
:error_no_FrameworkDIR32
@echo ERROR: Cannot determine the location of the .NET Framework 32bit installation.
@goto end
:error_no_FrameworkVer32
@echo ERROR: Cannot determine the version of the .NET Framework 32bit installation.
@goto end
:error_no_Framework35Version
@echo ERROR: Cannot determine the .NET Framework 3.5 version.
@goto end
:end
msbuild msvc-2010.sln /p:Configuration=Release /target:clean
msbuild msvc-2010.sln /p:Configuration=Release
exit
libgambatte/libretro/msvc/msvc-2010/msvc-2010.vcxproj.filters 000664 001750 001750 00000013133 12720365247 024724 0 ustar 00sergio sergio 000000 000000