Gets to title screen, input works

This commit is contained in:
Varun Patil 2018-04-30 22:49:27 +05:30
parent 5b3c1d2b13
commit 9ba124d991
18 changed files with 4524 additions and 2511 deletions

View File

@ -49,6 +49,10 @@
#include "binding-types.h"
#include "mrb-ext/marshal.h"
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
static void mrbBindingExecute();
static void mrbBindingTerminate();
static void mrbBindingReset();
@ -114,8 +118,17 @@ static void mrbBindingInit(mrb_state *mrb)
/* Load RPG module */
mrb_load_irep(mrb, mrbModuleRPG);
/* Load global constants */
mrb_define_global_const(mrb, "MKXP", mrb_true_value());
// mrb_value debug = mrb_bool_value(shState->config().editor.debug);
// if (rgssVer == 1)
//mrb_define_global_const(mrb, "DEBUG", debug);
// else if (rgssVer >= 2)
//mrb_define_global_const(mrb, "TEST", debug);
//mrb_define_global_const(mrb, "BTEST", mrb_bool_value(shState->config().editor.battleTest));
mrb_gc_arena_restore(mrb, arena);
}
@ -164,7 +177,8 @@ showExcMessageBox(mrb_state *mrb, mrb_value exc)
snprintf(msgBoxText, sizeof(msgBoxText), "Script '%s' line %d: %s occured.\n\n%s",
mrbValueString(file), mrb_fixnum(line), excClass, mrbValueString(mesg));
shState->eThread().showMessageBox(msgBoxText, SDL_MESSAGEBOX_ERROR);
printf("Show msg %s\n", msgBoxText);
// shState->eThread().showMessageBox(msgBoxText, SDL_MESSAGEBOX_ERROR);
}
static void
@ -248,6 +262,7 @@ runMrbFile(mrb_state *mrb, const char *filename)
static void
runRMXPScripts(mrb_state *mrb, mrbc_context *ctx)
{
printf("Inside runrmxpscriptes\n");
const std::string &scriptPack = shState->rtData().config.game.scripts;
if (scriptPack.empty())
@ -261,7 +276,7 @@ runRMXPScripts(mrb_state *mrb, mrbc_context *ctx)
showError(std::string("Unable to open '") + scriptPack + "'");
return;
}
printf("afterrxdataread\n");
/* We use a secondary util state to unmarshal the scripts */
mrb_state *scriptMrb = mrb_open();
SDL_RWops ops;
@ -289,13 +304,17 @@ runRMXPScripts(mrb_state *mrb, mrbc_context *ctx)
return;
}
int scriptCount = mrb_ary_len(scriptMrb, scriptArray);
int scriptCount = RARRAY_LEN(scriptArray);
std::string decodeBuffer;
decodeBuffer.resize(0x1000);
for (int i = 0; i < scriptCount; ++i)
{
#ifdef __EMSCRIPTEN
printf("EMS SLEEP IN runRMXPScripts\n");
emscripten_sleep(10);
#endif
mrb_value script = mrb_ary_entry(scriptArray, i);
mrb_value scriptChksum = mrb_ary_entry(script, 0);
@ -357,6 +376,7 @@ runRMXPScripts(mrb_state *mrb, mrbc_context *ctx)
static void mrbBindingExecute()
{
printf("STARTBINDING EXECUTE\n");
mrb_state *mrb = mrb_open();
shState->setBindingData(mrb);
@ -371,12 +391,12 @@ static void mrbBindingExecute()
mrbc_context *ctx = mrbc_context_new(mrb);
ctx->capture_errors = 1;
printf("CONFIG\n");
const Config &conf = shState->rtData().config;
const std::string &customScript = conf.customScript;
// const std::string &mrbFile = conf.mrbFile;
(void) runMrbFile; // FIXME mrbFile support on ice for now
printf("before runrmxpscripts\n");
if (!customScript.empty())
runCustomScript(mrb, ctx, customScript.c_str());
// else if (!mrbFile.empty())

View File

@ -0,0 +1,407 @@
/*
** binding-mruby.cpp
**
** This file is part of mkxp.
**
** Copyright (C) 2013 Jonas Kulla <Nyocurio@gmail.com>
**
** mkxp 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.
**
** mkxp 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 mkxp. If not, see <http://www.gnu.org/licenses/>.
*/
#include "binding.h"
#include <mruby.h>
#include <mruby/string.h>
#include <mruby/array.h>
#include <mruby/class.h>
#include <mruby/irep.h>
#include <mruby/compile.h>
#include <mruby/proc.h>
#include <mruby/dump.h>
#include <stdio.h>
#include <zlib.h>
#include <string>
#include <SDL_messagebox.h>
#include <SDL_rwops.h>
#include <SDL_timer.h>
#include "sharedstate.h"
#include "texpool.h"
#include "eventthread.h"
#include "filesystem.h"
#include "exception.h"
#include "binding-util.h"
#include "binding-types.h"
#include "mrb-ext/marshal.h"
static void mrbBindingExecute();
static void mrbBindingTerminate();
static void mrbBindingReset();
ScriptBinding scriptBindingImpl =
{
mrbBindingExecute,
mrbBindingTerminate,
mrbBindingReset
};
ScriptBinding *scriptBinding = &scriptBindingImpl;
void fileBindingInit(mrb_state *);
void timeBindingInit(mrb_state *);
void marshalBindingInit(mrb_state *);
void kernelBindingInit(mrb_state *);
void tableBindingInit(mrb_state *);
void etcBindingInit(mrb_state *);
void fontBindingInit(mrb_state *);
void bitmapBindingInit(mrb_state *);
void spriteBindingInit(mrb_state *);
void planeBindingInit(mrb_state *);
void viewportBindingInit(mrb_state *);
void windowBindingInit(mrb_state *);
void tilemapBindingInit(mrb_state *);
void inputBindingInit(mrb_state *);
void audioBindingInit(mrb_state *);
void graphicsBindingInit(mrb_state *);
/* From module_rpg.c */
extern const uint8_t mrbModuleRPG[];
static void mrbBindingInit(mrb_state *mrb)
{
int arena = mrb_gc_arena_save(mrb);
/* Init standard classes */
fileBindingInit(mrb);
timeBindingInit(mrb);
marshalBindingInit(mrb);
kernelBindingInit(mrb);
/* Init RGSS classes */
tableBindingInit(mrb);
etcBindingInit(mrb);
fontBindingInit(mrb);
bitmapBindingInit(mrb);
spriteBindingInit(mrb);
planeBindingInit(mrb);
viewportBindingInit(mrb);
windowBindingInit(mrb);
tilemapBindingInit(mrb);
/* Init RGSS modules */
inputBindingInit(mrb);
audioBindingInit(mrb);
graphicsBindingInit(mrb);
/* Load RPG module */
mrb_load_irep(mrb, mrbModuleRPG);
mrb_define_global_const(mrb, "MKXP", mrb_true_value());
mrb_gc_arena_restore(mrb, arena);
}
static mrb_value
mkxpTimeOp(mrb_state *mrb, mrb_value)
{
mrb_int iterations = 1;
const char *opName = "";
mrb_value block;
mrb_get_args(mrb, "|iz&", &iterations, &opName, &block);
Uint64 start = SDL_GetPerformanceCounter();
for (int i = 0; i < iterations; ++i)
mrb_yield(mrb, block, mrb_nil_value());
Uint64 diff = SDL_GetPerformanceCounter() - start;
double avg = (double) diff / iterations;
double sec = avg / SDL_GetPerformanceFrequency();
float ms = sec * 1000;
printf("<%s> [%f ms]\n", opName, ms);
fflush(stdout);
return mrb_float_value(mrb, ms);
}
static const char *
mrbValueString(mrb_value value)
{
return mrb_string_p(value) ? RSTRING_PTR(value) : 0;
}
static void
showExcMessageBox(mrb_state *mrb, mrb_value exc)
{
/* Display actual exception in a message box */
mrb_value mesg = mrb_funcall(mrb, exc, "message", 0);
mrb_value line = mrb_attr_get(mrb, exc, mrb_intern_lit(mrb, "line"));
mrb_value file = mrb_attr_get(mrb, exc, mrb_intern_lit(mrb, "file"));
const char *excClass = mrb_class_name(mrb, mrb_class(mrb, exc));
char msgBoxText[512];
snprintf(msgBoxText, sizeof(msgBoxText), "Script '%s' line %d: %s occured.\n\n%s",
mrbValueString(file), mrb_fixnum(line), excClass, mrbValueString(mesg));
shState->eThread().showMessageBox(msgBoxText, SDL_MESSAGEBOX_ERROR);
}
static void
checkException(mrb_state *mrb)
{
if (!mrb->exc)
return;
mrb_value exc = mrb_obj_value(mrb->exc);
MrbData &mrbData = *getMrbData(mrb);
/* Check if an actual exception occured, or just a shutdown was called */
if (mrb_obj_class(mrb, exc) != mrbData.exc[Shutdown])
showExcMessageBox(mrb, exc);
}
static void
showError(const std::string &msg)
{
shState->eThread().showMessageBox(msg.c_str());
}
static void
runCustomScript(mrb_state *mrb, mrbc_context *ctx, const char *filename)
{
/* Execute custom script */
FILE *f = fopen(filename, "rb");
if (!f)
{
static char buffer[256];
snprintf(buffer, sizeof(buffer), "Unable to open script '%s'", filename);
showError(buffer);
return;
}
ctx->filename = strdup(filename);
ctx->lineno = 1;
/* Run code */
mrb_load_file_cxt(mrb, f, ctx);
free(ctx->filename);
fclose(f);
}
static void
runMrbFile(mrb_state *mrb, const char *filename)
{
/* Execute compiled script */
FILE *f = fopen(filename, "rb");
if (!f)
{
static char buffer[256];
snprintf(buffer, sizeof(buffer), "Unable to open compiled script '%s'", filename);
showError(buffer);
return;
}
mrb_irep *irep = mrb_read_irep_file(mrb, f);
if (!irep)
{
static char buffer[256];
snprintf(buffer, sizeof(buffer), "Unable to read compiled script '%s'", filename);
showError(buffer);
return;
}
RProc *proc = mrb_proc_new(mrb, irep);
mrb_run(mrb, proc, mrb_top_self(mrb));
fclose(f);
}
static void
runRMXPScripts(mrb_state *mrb, mrbc_context *ctx)
{
const std::string &scriptPack = shState->rtData().config.game.scripts;
if (scriptPack.empty())
{
showError("No game scripts specified (missing Game.ini?)");
return;
}
if (!shState->fileSystem().exists(scriptPack.c_str()))
{
showError(std::string("Unable to open '") + scriptPack + "'");
return;
}
/* We use a secondary util state to unmarshal the scripts */
mrb_state *scriptMrb = mrb_open();
SDL_RWops ops;
shState->fileSystem().openReadRaw(ops, scriptPack.c_str());
mrb_value scriptArray = mrb_nil_value();
std::string readError;
try
{
scriptArray = marshalLoadInt(scriptMrb, &ops);
}
catch (const Exception &e)
{
readError = std::string(": ") + e.msg;
}
SDL_RWclose(&ops);
if (!mrb_array_p(scriptArray))
{
showError(std::string("Failed to read script data") + readError);
mrb_close(scriptMrb);
return;
}
int scriptCount = mrb_ary_len(scriptMrb, scriptArray);
std::string decodeBuffer;
decodeBuffer.resize(0x1000);
for (int i = 0; i < scriptCount; ++i)
{
mrb_value script = mrb_ary_entry(scriptArray, i);
mrb_value scriptChksum = mrb_ary_entry(script, 0);
mrb_value scriptName = mrb_ary_entry(script, 1);
mrb_value scriptString = mrb_ary_entry(script, 2);
(void) scriptChksum;
int result = Z_OK;
unsigned long bufferLen;
while (true)
{
unsigned char *bufferPtr =
reinterpret_cast<unsigned char*>(const_cast<char*>(decodeBuffer.c_str()));
unsigned char *sourcePtr =
reinterpret_cast<unsigned char*>(RSTRING_PTR(scriptString));
bufferLen = decodeBuffer.length();
result = uncompress(bufferPtr, &bufferLen,
sourcePtr, RSTRING_LEN(scriptString));
bufferPtr[bufferLen] = '\0';
if (result != Z_BUF_ERROR)
break;
decodeBuffer.resize(decodeBuffer.size()*2);
}
if (result != Z_OK)
{
static char buffer[256];
snprintf(buffer, sizeof(buffer), "Error decoding script %d: '%s'",
i, RSTRING_PTR(scriptName));
showError(buffer);
break;
}
ctx->filename = RSTRING_PTR(scriptName);
ctx->lineno = 1;
int ai = mrb_gc_arena_save(mrb);
/* Execute code */
mrb_load_nstring_cxt(mrb, decodeBuffer.c_str(), bufferLen, ctx);
mrb_gc_arena_restore(mrb, ai);
if (mrb->exc)
break;
}
mrb_close(scriptMrb);
}
static void mrbBindingExecute()
{
mrb_state *mrb = mrb_open();
shState->setBindingData(mrb);
MrbData mrbData(mrb);
mrb->ud = &mrbData;
mrb_define_module_function(mrb, mrb->kernel_module, "time_op",
mkxpTimeOp, MRB_ARGS_OPT(2) | MRB_ARGS_BLOCK());
mrbBindingInit(mrb);
mrbc_context *ctx = mrbc_context_new(mrb);
ctx->capture_errors = 1;
const Config &conf = shState->rtData().config;
const std::string &customScript = conf.customScript;
// const std::string &mrbFile = conf.mrbFile;
(void) runMrbFile; // FIXME mrbFile support on ice for now
if (!customScript.empty())
runCustomScript(mrb, ctx, customScript.c_str());
// else if (!mrbFile.empty())
// runMrbFile(mrb, mrbFile.c_str());
else
runRMXPScripts(mrb, ctx);
checkException(mrb);
shState->rtData().rqTermAck.set();
shState->texPool().disable();
mrbc_context_free(mrb, ctx);
mrb_close(mrb);
}
static void mrbBindingTerminate()
{
mrb_state *mrb = static_cast<mrb_state*>(shState->bindingData());
MrbData *data = static_cast<MrbData*>(mrb->ud);
mrb_raise(mrb, data->exc[Shutdown], "");
}
static void mrbBindingReset()
{
// No idea how to do this with mruby yet
}

View File

@ -0,0 +1,11 @@
--- binding-mruby/binding-mruby.cpp
+++ binding-mruby/binding-mruby.cpp
@@ -117,7 +117,7 @@ static void mrbBindingInit(mrb_state *mrb)
/* Load global constants */
mrb_define_global_const(mrb, "MKXP", mrb_true_value());
- mrb_value debug = rb_bool_new(shState->config().editor.debug);
+ mrb_value debug = mrb_bool_value(shState->config().editor.debug);
if (rgssVer == 1)
mrb_define_global_const(mrb, "DEBUG", debug);
else if (rgssVer >= 2)

View File

@ -72,7 +72,7 @@ static const MrbExcData excData[] =
{ PHYSFS, "PHYSFSError" },
{ SDL, "SDLError" },
{ MKXP, "MKXPError" },
{ IO, "IOError" }
{ IO, "IOError2" }
};
static elementsN(excData);

View File

@ -28,6 +28,7 @@
#include <mruby/data.h>
#include <mruby/variable.h>
#include <mruby/class.h>
#include <mruby/string.h>
#include <stdio.h>
@ -352,11 +353,13 @@ inline mrb_value
objectLoad(mrb_state *mrb, mrb_value self, const mrb_data_type &type)
{
RClass *klass = mrb_class_ptr(self);
char *data;
int data_len;
mrb_get_args(mrb, "s", &data, &data_len);
C *c = C::deserialize(data, data_len);
mrb_value data;
mrb_get_args(mrb, "S", &data);
int data_len = mrb_string_value_len(mrb, data);
C *c = C::deserialize(RSTRING_PTR(data), data_len);
RData *obj = mrb_data_object_alloc(mrb, klass, c, &type);
mrb_value obj_value = mrb_obj_value(obj);

View File

@ -49,7 +49,12 @@ MRB_METHOD(fontInitialize)
mrb_get_args(mrb, "|zi", &name, &size);
Font *f = new Font(name, size);
Font *f;
std::vector<std::string> names;
names.push_back(name);
f = new Font(&names, size);
setPrivateData(self, f, FontType);
@ -86,9 +91,7 @@ MRB_METHOD(fontInitializeCopy)
MRB_METHOD(FontGetName)
{
Font *f = getPrivateData<Font>(mrb, self);
return mrb_str_new_cstr(mrb, f->getName());
return mrb_iv_get(mrb, self, mrb_intern_cstr(mrb, "name"));
}
MRB_METHOD(FontSetName)
@ -98,7 +101,11 @@ MRB_METHOD(FontSetName)
mrb_value name;
mrb_get_args(mrb, "S", &name);
f->setName(RSTRING_PTR(name));
std::vector<std::string> names;
names.push_back(RSTRING_PTR(name));
f->setName(names);
mrb_iv_set(mrb, self, mrb_intern_cstr(mrb, "name"), name);
return name;
}
@ -135,17 +142,21 @@ DEF_KLASS_PROP(Font, mrb_bool, DefaultItalic, "b", bool)
DEF_KLASS_PROP(Font, mrb_bool, DefaultOutline, "b", bool)
DEF_KLASS_PROP(Font, mrb_bool, DefaultShadow, "b", bool)
MRB_FUNCTION(FontGetDefaultName)
MRB_METHOD(FontGetDefaultName)
{
return mrb_str_new_cstr(mrb, Font::getDefaultName());
return mrb_iv_get(mrb, self, mrb_intern_cstr(mrb, "default_name"));
}
MRB_FUNCTION(FontSetDefaultName)
MRB_METHOD(FontSetDefaultName)
{
mrb_value nameObj;
mrb_get_args(mrb, "S", &nameObj);
Font::setDefaultName(RSTRING_PTR(nameObj));
std::vector<std::string> names;
names.push_back(RSTRING_PTR(nameObj));
Font::setDefaultName(names, shState->fontState());
mrb_iv_set(mrb, self, mrb_intern_cstr(mrb, "default_name"), nameObj);
return nameObj;
}

View File

@ -24,6 +24,7 @@
#include "exception.h"
#include "binding-util.h"
#include "util.h"
#include "eventthread.h"
#include <mruby/hash.h>
#include <string.h>
@ -33,6 +34,7 @@ MRB_FUNCTION(inputUpdate)
MRB_FUN_UNUSED_PARAM;
shState->input().update();
shState->eThread().process(shState->rtData());
return mrb_nil_value();
}

File diff suppressed because it is too large Load Diff

3275
binding-mruby/module_rpg.xxd Normal file

File diff suppressed because it is too large Load Diff

View File

@ -596,7 +596,7 @@ fileBindingInit(mrb_state *mrb)
mrb_define_method(mrb, klass, "path", fileGetPath, MRB_ARGS_NONE());
/* FileTest */
RClass *module = mrb_define_module(mrb, "FileTest");
RClass *module = mrb_define_module(mrb, "MKXPFileTest");
mrb_define_module_function(mrb, module, "exist?", fileTestDoesExist, MRB_ARGS_REQ(1));
mrb_define_module_function(mrb, module, "directory?", fileTestIsDirectory, MRB_ARGS_REQ(1));
mrb_define_module_function(mrb, module, "file?", fileTestIsFile, MRB_ARGS_REQ(1));

View File

@ -172,7 +172,7 @@ MRB_FUNCTION(kernelLoadData)
mrb_get_args(mrb, "z", &filename);
SDL_RWops ops;
GUARD_EXC( shState->fileSystem().openRead(ops, filename); )
GUARD_EXC( shState->fileSystem().openReadRaw(ops, filename); )
mrb_value obj;
try { obj = marshalLoadInt(mrb, &ops); }

View File

@ -473,8 +473,8 @@ read_value(MarshalContext *ctx)
mrb_state *mrb = ctx->mrb;
int8_t type = ctx->readByte();
mrb_value value;
if (mrb->arena_idx > maxArena)
maxArena = mrb->arena_idx;
if (mrb->gc.arena_idx > maxArena)
maxArena = mrb->gc.arena_idx;
int arena = mrb_gc_arena_save(mrb);
@ -676,7 +676,7 @@ static void
write_array(MarshalContext *ctx, mrb_value array)
{
mrb_state *mrb = ctx->mrb;
int len = mrb_ary_len(mrb, array);
int len = RARRAY_LEN(array);
write_fixnum(ctx, len);
int i;
@ -687,8 +687,6 @@ write_array(MarshalContext *ctx, mrb_value array)
}
}
KHASH_DECLARE(ht, mrb_value, mrb_value, 1)
static void
write_hash(MarshalContext *ctx, mrb_value hash)
{
@ -707,7 +705,7 @@ write_hash(MarshalContext *ctx, mrb_value hash)
continue;
write_value(ctx, kh_key(h, k));
write_value(ctx, kh_val(h, k));
write_value(ctx, kh_val(h, k).v);
}
}
@ -732,7 +730,7 @@ write_object(MarshalContext *ctx, mrb_value object)
write_value(ctx, mrb_str_intern(mrb, path));
mrb_value iv_ary = mrb_obj_instance_variables(mrb, object);
int iv_count = mrb_ary_len(mrb, iv_ary);
int iv_count = RARRAY_LEN(iv_ary);
write_fixnum(ctx, iv_count);
int i;

View File

@ -21,9 +21,10 @@
#ifndef BOOSTHASH_H
#define BOOSTHASH_H
#include <string>
#include <map>
#include <set>
#include <boost/unordered/unordered_map.hpp>
#include <boost/unordered/unordered_set.hpp>
#include <utility>
/* Wrappers around the boost unordered template classes,
@ -33,7 +34,7 @@ template<typename K, typename V>
class BoostHash
{
private:
typedef std::map<K, V> BoostType;
typedef boost::unordered_map<K, V> BoostType;
typedef std::pair<K, V> PairType;
BoostType p;
@ -97,7 +98,7 @@ template<typename K>
class BoostSet
{
private:
typedef std::set<K> BoostType;
typedef boost::unordered_set<K> BoostType;
BoostType p;
public:

View File

@ -446,7 +446,8 @@ private:
SDL_Delay(ticks / tickFreqMS);
#endif
#endif
#ifdef __EMSCRIPTEN
#ifdef __EMSCRIPTEN__
printf("EMSCRIPTEN SLEEP IN GRAPHICS\n");
emscripten_sleep(ticks /tickFreqMS);
#endif
}

View File

@ -46,6 +46,11 @@
#include "icon.png.xxd"
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
static void
rgssThreadError(RGSSThreadData *rtData, const std::string &msg)
{
@ -141,10 +146,10 @@ int rgssThreadFun(void *userdata)
return 0;
}
printf("BEFORE SCRIPT EXECUTE\n");
/* Start script execution */
scriptBinding->execute();
printf("AFTER SCRIPT\n");
threadData->rqTermAck.set();
threadData->ethread->requestTerminate();
@ -335,6 +340,11 @@ int main(int argc, char *argv[])
/* Wait for RGSS thread response */
for (int i = 0; i < 1000; ++i)
{
#ifdef __EMSCRIPTEN
printf("EMSCRIPTEN_SLEEP in main.cpp\n");
emscripten_sleep(10);
#endif
/* We can stop waiting when the request was ack'd */
if (rtData.rqTermAck)
{

View File

@ -297,6 +297,8 @@ processDirectories(RGSS_archiveData *data, BoostSet<std::string> &topLevel,
if (slash)
nameBuf[i] = '/';
break;
}
/* Check for more entries */
@ -331,14 +333,16 @@ verifyHeader(PHYSFS_Io *io, char version)
}
static void*
RGSS_openArchive(PHYSFS_Io *io, const char *, int forWrite)
RGSS_openArchive(PHYSFS_Io *io, const char *, int forWrite, int *claimed)
{
if (forWrite)
return 0;
return NULL;
/* Version 1 */
if (!verifyHeader(io, 1))
return 0;
return NULL;
else
*claimed = 1;
RGSS_archiveData *data = new RGSS_archiveData;
data->archiveIo = io;
@ -389,9 +393,9 @@ RGSS_openArchive(PHYSFS_Io *io, const char *, int forWrite)
return data;
}
static void
static PHYSFS_EnumerateCallbackResult
RGSS_enumerateFiles(void *opaque, const char *dirname,
PHYSFS_EnumFilesCallback cb,
PHYSFS_EnumerateCallback cb,
const char *origdir, void *callbackdata)
{
RGSS_archiveData *data = static_cast<RGSS_archiveData*>(opaque);
@ -399,13 +403,15 @@ RGSS_enumerateFiles(void *opaque, const char *dirname,
std::string _dirname(dirname);
if (!data->dirHash.contains(_dirname))
return;
return PHYSFS_ENUM_STOP;
const BoostSet<std::string> &entries = data->dirHash[_dirname];
BoostSet<std::string>::const_iterator iter;
for (iter = entries.cbegin(); iter != entries.cend(); ++iter)
cb(callbackdata, origdir, iter->c_str());
return PHYSFS_ENUM_OK;
}
static PHYSFS_Io*
@ -536,19 +542,21 @@ readUint32AndXor(PHYSFS_Io *io, uint32_t &result, uint32_t key)
}
static void*
RGSS3_openArchive(PHYSFS_Io *io, const char *, int forWrite)
RGSS3_openArchive(PHYSFS_Io *io, const char *, int forWrite, int *claimed)
{
if (forWrite)
return 0;
return NULL;
/* Version 3 */
if (!verifyHeader(io, 3))
return 0;
return NULL;
else
*claimed = 1;
uint32_t baseMagic;
if (!readUint32(io, baseMagic))
return 0;
return NULL;
baseMagic = (baseMagic * 9) + 3;
@ -605,7 +613,7 @@ RGSS3_openArchive(PHYSFS_Io *io, const char *, int forWrite)
error:
delete data;
return 0;
return NULL;
}
return data;

633
src/rgssad.cpp.orig Normal file
View File

@ -0,0 +1,633 @@
/*
** rgssad.cpp
**
** This file is part of mkxp.
**
** Copyright (C) 2014 Jonas Kulla <Nyocurio@gmail.com>
**
** mkxp 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.
**
** mkxp 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 mkxp. If not, see <http://www.gnu.org/licenses/>.
*/
#include "rgssad.h"
#include "boost-hash.h"
#include <stdint.h>
#include <string.h>
struct RGSS_entryData
{
int64_t offset;
uint64_t size;
uint32_t startMagic;
};
struct RGSS_entryHandle
{
const RGSS_entryData data;
uint32_t currentMagic;
uint64_t currentOffset;
PHYSFS_Io *io;
RGSS_entryHandle(const RGSS_entryData &data, PHYSFS_Io *archIo)
: data(data),
currentMagic(data.startMagic),
currentOffset(0)
{
io = archIo->duplicate(archIo);
}
~RGSS_entryHandle()
{
io->destroy(io);
}
};
struct RGSS_archiveData
{
PHYSFS_Io *archiveIo;
/* Maps: file path
* to: entry data */
BoostHash<std::string, RGSS_entryData> entryHash;
/* Maps: directory path,
* to: list of contained entries */
BoostHash<std::string, BoostSet<std::string> > dirHash;
};
static bool
readUint32(PHYSFS_Io *io, uint32_t &result)
{
char buff[4];
PHYSFS_sint64 count = io->read(io, buff, 4);
result = ((buff[0] << 0x00) & 0x000000FF) |
((buff[1] << 0x08) & 0x0000FF00) |
((buff[2] << 0x10) & 0x00FF0000) |
((buff[3] << 0x18) & 0xFF000000) ;
return (count == 4);
}
#define RGSS_HEADER "RGSSAD"
#define RGSS_MAGIC 0xDEADCAFE
#define PHYSFS_ALLOC(type) \
static_cast<type*>(PHYSFS_getAllocator()->Malloc(sizeof(type)))
#define IO_READ(io, dest, size) (io->read(io, dest, size) == size)
static inline uint32_t
advanceMagic(uint32_t &magic)
{
uint32_t old = magic;
magic = magic * 7 + 3;
return old;
}
static PHYSFS_sint64
RGSS_ioRead(PHYSFS_Io *self, void *buffer, PHYSFS_uint64 len)
{
RGSS_entryHandle *entry = static_cast<RGSS_entryHandle*>(self->opaque);
PHYSFS_Io *io = entry->io;
uint64_t toRead = std::min<uint64_t>(entry->data.size - entry->currentOffset, len);
uint64_t offs = entry->currentOffset;
io->seek(io, entry->data.offset + offs);
/* We divide up the bytes to be read in 3 categories:
*
* preAlign: If the current read address is not dword
* aligned, this is the number of bytes to read til
* we reach alignment again (therefore can only be
* 3 or less).
*
* align: The number of aligned dwords we can read
* times 4 (= number of bytes).
*
* postAlign: The number of bytes to read after the
* last aligned dword. Always 3 or less.
*
* Treating the pre- and post aligned reads specially,
* we can read all aligned dwords in one syscall directly
* into the write buffer and then run the xor chain on
* it afterwards. */
uint8_t preAlign = 4 - (offs % 4);
if (preAlign == 4)
preAlign = 0;
else
preAlign = std::min<uint64_t>(preAlign, len);
uint8_t postAlign = (len > preAlign) ? (offs + len) % 4 : 0;
uint64_t align = len - (preAlign + postAlign);
/* Byte buffer pointer */
uint8_t *bBufferP = static_cast<uint8_t*>(buffer);
if (preAlign > 0)
{
uint32_t dword;
io->read(io, &dword, preAlign);
/* Need to align the bytes with the
* magic before xoring */
dword <<= 8 * (offs % 4);
dword ^= entry->currentMagic;
/* Shift them back to normal */
dword >>= 8 * (offs % 4);
memcpy(bBufferP, &dword, preAlign);
bBufferP += preAlign;
/* Only advance the magic if we actually
* reached the next alignment */
if ((offs+preAlign) % 4 == 0)
advanceMagic(entry->currentMagic);
}
if (align > 0)
{
/* Double word buffer pointer */
uint32_t *dwBufferP = reinterpret_cast<uint32_t*>(bBufferP);
/* Read aligned dwords in one go */
io->read(io, bBufferP, align);
/* Then xor them */
for (uint64_t i = 0; i < (align / 4); ++i)
dwBufferP[i] ^= advanceMagic(entry->currentMagic);
bBufferP += align;
}
if (postAlign > 0)
{
uint32_t dword;
io->read(io, &dword, postAlign);
/* Bytes are already aligned with magic */
dword ^= entry->currentMagic;
memcpy(bBufferP, &dword, postAlign);
}
entry->currentOffset += toRead;
return toRead;
}
static int
RGSS_ioSeek(PHYSFS_Io *self, PHYSFS_uint64 offset)
{
RGSS_entryHandle *entry = static_cast<RGSS_entryHandle*>(self->opaque);
if (offset == entry->currentOffset)
return 1;
if (offset > entry->data.size-1)
return 0;
/* If rewinding, we need to rewind to begining */
if (offset < entry->currentOffset)
{
entry->currentOffset = 0;
entry->currentMagic = entry->data.startMagic;
}
/* For each overstepped alignment, advance magic */
uint64_t currentDword = entry->currentOffset / 4;
uint64_t targetDword = offset / 4;
uint64_t dwordsSought = targetDword - currentDword;
for (uint64_t i = 0; i < dwordsSought; ++i)
advanceMagic(entry->currentMagic);
entry->currentOffset = offset;
entry->io->seek(entry->io, entry->data.offset + entry->currentOffset);
return 1;
}
static PHYSFS_sint64
RGSS_ioTell(PHYSFS_Io *self)
{
const RGSS_entryHandle *entry = static_cast<RGSS_entryHandle*>(self->opaque);
return entry->currentOffset;
}
static PHYSFS_sint64
RGSS_ioLength(PHYSFS_Io *self)
{
const RGSS_entryHandle *entry = static_cast<RGSS_entryHandle*>(self->opaque);
return entry->data.size;
}
static PHYSFS_Io*
RGSS_ioDuplicate(PHYSFS_Io *self)
{
const RGSS_entryHandle *entry = static_cast<RGSS_entryHandle*>(self->opaque);
RGSS_entryHandle *entryDup = new RGSS_entryHandle(*entry);
PHYSFS_Io *dup = PHYSFS_ALLOC(PHYSFS_Io);
*dup = *self;
dup->opaque = entryDup;
return dup;
}
static void
RGSS_ioDestroy(PHYSFS_Io *self)
{
RGSS_entryHandle *entry = static_cast<RGSS_entryHandle*>(self->opaque);
delete entry;
PHYSFS_getAllocator()->Free(self);
}
static const PHYSFS_Io RGSS_IoTemplate =
{
0, /* version */
0, /* opaque */
RGSS_ioRead,
0, /* write */
RGSS_ioSeek,
RGSS_ioTell,
RGSS_ioLength,
RGSS_ioDuplicate,
0, /* flush */
RGSS_ioDestroy
};
static void
processDirectories(RGSS_archiveData *data, BoostSet<std::string> &topLevel,
char *nameBuf, uint32_t nameLen)
{
/* Check for top level entries */
for (uint32_t i = 0; i < nameLen; ++i)
{
bool slash = nameBuf[i] == '/';
if (!slash && i+1 < nameLen)
continue;
if (slash)
nameBuf[i] = '\0';
topLevel.insert(nameBuf);
if (slash)
nameBuf[i] = '/';
}
/* Check for more entries */
for (uint32_t i = nameLen; i > 0; i--)
if (nameBuf[i] == '/')
{
nameBuf[i] = '\0';
const char *dir = nameBuf;
const char *entry = &nameBuf[i+1];
BoostSet<std::string> &entryList = data->dirHash[dir];
entryList.insert(entry);
}
}
static bool
verifyHeader(PHYSFS_Io *io, char version)
{
char header[8];
if (!IO_READ(io, header, sizeof(header)))
return false;
if (strcmp(header, RGSS_HEADER))
return false;
if (header[7] != version)
return false;
return true;
}
static void*
RGSS_openArchive(PHYSFS_Io *io, const char *, int forWrite)
{
if (forWrite)
return 0;
/* Version 1 */
if (!verifyHeader(io, 1))
return 0;
RGSS_archiveData *data = new RGSS_archiveData;
data->archiveIo = io;
uint32_t magic = RGSS_MAGIC;
/* Top level entry list */
BoostSet<std::string> &topLevel = data->dirHash[""];
while (true)
{
/* Read filename length,
* if nothing was read, no files remain */
uint32_t nameLen;
if (!readUint32(io, nameLen))
break;
nameLen ^= advanceMagic(magic);
static char nameBuf[512];
for (uint32_t i = 0; i < nameLen; ++i)
{
char c;
io->read(io, &c, 1);
nameBuf[i] = c ^ (advanceMagic(magic) & 0xFF);
if (nameBuf[i] == '\\')
nameBuf[i] = '/';
}
nameBuf[nameLen] = '\0';
uint32_t entrySize;
readUint32(io, entrySize);
entrySize ^= advanceMagic(magic);
RGSS_entryData entry;
entry.offset = io->tell(io);
entry.size = entrySize;
entry.startMagic = magic;
data->entryHash.insert(nameBuf, entry);
processDirectories(data, topLevel, nameBuf, nameLen);
io->seek(io, entry.offset + entry.size);
}
return data;
}
static void
RGSS_enumerateFiles(void *opaque, const char *dirname,
PHYSFS_EnumFilesCallback cb,
const char *origdir, void *callbackdata)
{
RGSS_archiveData *data = static_cast<RGSS_archiveData*>(opaque);
std::string _dirname(dirname);
if (!data->dirHash.contains(_dirname))
return;
const BoostSet<std::string> &entries = data->dirHash[_dirname];
BoostSet<std::string>::const_iterator iter;
for (iter = entries.cbegin(); iter != entries.cend(); ++iter)
cb(callbackdata, origdir, iter->c_str());
}
static PHYSFS_Io*
RGSS_openRead(void *opaque, const char *filename)
{
RGSS_archiveData *data = static_cast<RGSS_archiveData*>(opaque);
if (!data->entryHash.contains(filename))
return 0;
RGSS_entryHandle *entry =
new RGSS_entryHandle(data->entryHash[filename], data->archiveIo);
PHYSFS_Io *io = PHYSFS_ALLOC(PHYSFS_Io);
*io = RGSS_IoTemplate;
io->opaque = entry;
return io;
}
static int
RGSS_stat(void *opaque, const char *filename, PHYSFS_Stat *stat)
{
RGSS_archiveData *data = static_cast<RGSS_archiveData*>(opaque);
bool hasFile = data->entryHash.contains(filename);
bool hasDir = data->dirHash.contains(filename);
if (!hasFile && !hasDir)
{
PHYSFS_setErrorCode(PHYSFS_ERR_NOT_FOUND);
return 0;
}
stat->modtime =
stat->createtime =
stat->accesstime = 0;
stat->readonly = 1;
if (hasFile)
{
const RGSS_entryData &entry = data->entryHash[filename];
stat->filesize = entry.size;
stat->filetype = PHYSFS_FILETYPE_REGULAR;
}
else
{
stat->filesize = 0;
stat->filetype = PHYSFS_FILETYPE_DIRECTORY;
}
return 1;
}
static void
RGSS_closeArchive(void *opaque)
{
RGSS_archiveData *data = static_cast<RGSS_archiveData*>(opaque);
delete data;
}
static PHYSFS_Io*
RGSS_noop1(void*, const char*)
{
return 0;
}
static int
RGSS_noop2(void*, const char*)
{
return 0;
}
const PHYSFS_Archiver RGSS1_Archiver =
{
0,
{
"RGSSAD",
"RGSS encrypted archive format",
"", /* Author */
"", /* Website */
0 /* symlinks not supported */
},
RGSS_openArchive,
RGSS_enumerateFiles,
RGSS_openRead,
RGSS_noop1, /* openWrite */
RGSS_noop1, /* openAppend */
RGSS_noop2, /* remove */
RGSS_noop2, /* mkdir */
RGSS_stat,
RGSS_closeArchive
};
const PHYSFS_Archiver RGSS2_Archiver =
{
0,
{
"RGSS2A",
"RGSS2 encrypted archive format",
"", /* Author */
"", /* Website */
0 /* symlinks not supported */
},
RGSS_openArchive,
RGSS_enumerateFiles,
RGSS_openRead,
RGSS_noop1, /* openWrite */
RGSS_noop1, /* openAppend */
RGSS_noop2, /* remove */
RGSS_noop2, /* mkdir */
RGSS_stat,
RGSS_closeArchive
};
static bool
readUint32AndXor(PHYSFS_Io *io, uint32_t &result, uint32_t key)
{
if (!readUint32(io, result))
return false;
result ^= key;
return true;
}
static void*
RGSS3_openArchive(PHYSFS_Io *io, const char *, int forWrite)
{
if (forWrite)
return 0;
/* Version 3 */
if (!verifyHeader(io, 3))
return 0;
uint32_t baseMagic;
if (!readUint32(io, baseMagic))
return 0;
baseMagic = (baseMagic * 9) + 3;
RGSS_archiveData *data = new RGSS_archiveData;
data->archiveIo = io;
/* Top level entry list */
BoostSet<std::string> &topLevel = data->dirHash[""];
while (true)
{
uint32_t offset, size, magic, nameLen;
if (!readUint32AndXor(io, offset, baseMagic))
goto error;
/* Zero offset means entry list has ended */
if (offset == 0)
break;
if (!readUint32AndXor(io, size, baseMagic))
goto error;
if (!readUint32AndXor(io, magic, baseMagic))
goto error;
if (!readUint32AndXor(io, nameLen, baseMagic))
goto error;
char nameBuf[512];
if (!IO_READ(io, nameBuf, nameLen))
goto error;
for (uint32_t i = 0; i < nameLen; ++i)
{
nameBuf[i] ^= ((baseMagic >> 8*(i%4)) & 0xFF);
if (nameBuf[i] == '\\')
nameBuf[i] = '/';
}
nameBuf[nameLen] = '\0';
RGSS_entryData entry;
entry.offset = offset;
entry.size = size;
entry.startMagic = magic;
data->entryHash.insert(nameBuf, entry);
processDirectories(data, topLevel, nameBuf, nameLen);
continue;
error:
delete data;
return 0;
}
return data;
}
const PHYSFS_Archiver RGSS3_Archiver =
{
0,
{
"RGSS3A",
"RGSS3 encrypted archive format",
"", /* Author */
"", /* Website */
0 /* symlinks not supported */
},
RGSS3_openArchive,
RGSS_enumerateFiles,
RGSS_openRead,
RGSS_noop1, /* openWrite */
RGSS_noop1, /* openAppend */
RGSS_noop2, /* remove */
RGSS_noop2, /* mkdir */
RGSS_stat,
RGSS_closeArchive
};

95
src/rgssad.cpp.rej Normal file
View File

@ -0,0 +1,95 @@
--- src/rgssad.cpp
+++ src/rgssad.cpp
@@ -297,8 +297,6 @@ processDirectories(RGSS_archiveData *data, BoostSet<std::string> &topLevel,
if (slash)
nameBuf[i] = '/';
-
- break;
}
/* Check for more entries */
@@ -333,16 +331,14 @@ verifyHeader(PHYSFS_Io *io, char version)
}
static void*
-RGSS_openArchive(PHYSFS_Io *io, const char *, int forWrite, int *claimed)
+RGSS_openArchive(PHYSFS_Io *io, const char *, int forWrite)
{
if (forWrite)
- return NULL;
+ return 0;
/* Version 1 */
if (!verifyHeader(io, 1))
- return NULL;
- else
- *claimed = 1;
+ return 0;
RGSS_archiveData *data = new RGSS_archiveData;
data->archiveIo = io;
@@ -393,9 +389,9 @@ RGSS_openArchive(PHYSFS_Io *io, const char *, int forWrite, int *claimed)
return data;
}
-static PHYSFS_EnumerateCallbackResult
+static void
RGSS_enumerateFiles(void *opaque, const char *dirname,
- PHYSFS_EnumerateCallback cb,
+ PHYSFS_EnumFilesCallback cb,
const char *origdir, void *callbackdata)
{
RGSS_archiveData *data = static_cast<RGSS_archiveData*>(opaque);
@@ -403,15 +399,13 @@ RGSS_enumerateFiles(void *opaque, const char *dirname,
std::string _dirname(dirname);
if (!data->dirHash.contains(_dirname))
- return PHYSFS_ENUM_STOP;
+ return;
const BoostSet<std::string> &entries = data->dirHash[_dirname];
BoostSet<std::string>::const_iterator iter;
for (iter = entries.cbegin(); iter != entries.cend(); ++iter)
cb(callbackdata, origdir, iter->c_str());
-
- return PHYSFS_ENUM_OK;
}
static PHYSFS_Io*
@@ -542,21 +536,19 @@ readUint32AndXor(PHYSFS_Io *io, uint32_t &result, uint32_t key)
}
static void*
-RGSS3_openArchive(PHYSFS_Io *io, const char *, int forWrite, int *claimed)
+RGSS3_openArchive(PHYSFS_Io *io, const char *, int forWrite)
{
if (forWrite)
- return NULL;
+ return 0;
/* Version 3 */
if (!verifyHeader(io, 3))
- return NULL;
- else
- *claimed = 1;
+ return 0;
uint32_t baseMagic;
if (!readUint32(io, baseMagic))
- return NULL;
+ return 0;
baseMagic = (baseMagic * 9) + 3;
@@ -613,7 +605,7 @@ RGSS3_openArchive(PHYSFS_Io *io, const char *, int forWrite, int *claimed)
error:
delete data;
- return NULL;
+ return 0;
}
return data;