diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..3502ba45 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,30 @@ + +*.txt text eol=lf +Makefile text eol=lf +README text eol=lf +COPYING text eol=lf +CONTRIBUTING text eol=lf +COMPILING text eol=lf +*.s text eol=lf +*.c text eol=lf +*.h text eol=lf +*.pl text eol=lf +*.py text eol=lf +*.sh text eol=lf + +*.s linguist-language=Assembly +*.c linguist-language=C +*.h linguist-language=C +include/**/*.h linguist-language=C++ +meta/**/*.h linguist-language=C++ +source/**/*.h linguist-language=C++ +tools/**/*.h linguist-language=C++ + +*.pl linguist-vendored +*.py linguist-vendored +*.sh linguist-vendored +Makefile linguist-vendored +doc/** linguist-vendored +etc/** linguist-vendored +data/** linguist-vendored +util/** linguist-vendored diff --git a/.github/workflows/cmake-multi-platform.yml b/.github/workflows/cmake-multi-platform.yml index bc55f166..bb098c9a 100644 --- a/.github/workflows/cmake-multi-platform.yml +++ b/.github/workflows/cmake-multi-platform.yml @@ -2,7 +2,7 @@ name: CMake (Linux and Windows) on: push: - branches: [ "master", "dev", "workflow-test" ] + branches: [ "master", "dev", "dev-no-makeheaders", "workflow-test" ] pull_request: branches: [ "master", "dev" ] diff --git a/.gitignore b/.gitignore index 9634f5d4..003e5726 100644 --- a/.gitignore +++ b/.gitignore @@ -20,8 +20,6 @@ HatchGameEngine.exe *-Debug.exe *-Release.exe -makeheaders.bin -include/* # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs @@ -38,6 +36,7 @@ mono_crash.* [Aa][Rr][Mm]/ [Aa][Rr][Mm]64/ bld/ +builds/ [Bb]in/ [Oo]bj/ [Ll]og/ diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json new file mode 100644 index 00000000..d80ebc6d --- /dev/null +++ b/.vscode/c_cpp_properties.json @@ -0,0 +1,56 @@ +{ + "configurations": [ + { + "name": "Mac", + "includePath": [ + "${workspaceFolder}/include", + "${workspaceFolder}/source", + "/opt/homebrew/opt/llvm/include", + "/opt/homebrew/include", + "/usr/local/include" + ], + "defines": [ + "MACOSX", + "TARGET_NAME=\"HatchGameEngine\"", + "USING_OPENGL", + "USING_LIBPNG", + "USING_LIBPNG_HEADER=", + "DEBUG", + "USING_VM_DISPATCH_TABLE", + "_THREAD_SAFE", + "__VSCODE_INTELLISENSE__" + ], + "cStandard": "c89", + "cppStandard": "c++11", + "macFrameworkPath": [ + "/System/Library/Frameworks", + "/Library/Frameworks" + ], + "compilerPath": "/opt/homebrew/opt/llvm/bin/clang", + "intelliSenseMode": "clang-arm64" + }, { + "name": "Linux", + "includePath": [ + "${workspaceFolder}/include", + "${workspaceFolder}/source", + "/usr/local/include", + "/usr/include" + ], + "defines": [ + "LINUX", + "TARGET_NAME=HatchGameEngine", + "USING_LIBPNG", + "USING_LIBPNG_HEADER=", + "DEBUG", + "USING_VM_DISPATCH_TABLE", + "_THREAD_SAFE", + "__VSCODE_INTELLISENSE__" + ], + "cStandard": "c89", + "cppStandard": "c++11", + "compilerPath": "/usr/bin/gcc", + "intelliSenseMode": "gcc-x64" + } + ], + "version": 4 +} diff --git a/CMakeLists.txt b/CMakeLists.txt index b26b0eb2..0051b96a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -87,18 +87,6 @@ endif() add_definitions(-DMINIZ_NO_ARCHIVE_APIS -DMINIZ_NO_ARCHIVE_WRITING_APIS -DMINIZ_NO_TIME ) -if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") - set(MAKEHEADERS_BINARY makeheaders.exe) -else() - set(MAKEHEADERS_BINARY makeheaders) -endif() - -add_custom_target(makeheaders ALL - COMMAND ${CMAKE_SOURCE_DIR}/tools/${MAKEHEADERS_BINARY} source/ - WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} - BYPRODUCTS "${CMAKE_SOURCE_DIR}/include/makeheaders.bin" "${CMAKE_SOURCE_DIR}/include/Engine" - COMMENT "Generating header files") - find_file(REPO_DIR NAMES .git PATHS ${CMAKE_SOURCE_DIR} NO_DEFAULT_PATH) if (REPO_DIR) @@ -112,7 +100,6 @@ if (REPO_DIR) endif() add_executable(${PROJECT_NAME} ${HATCH_SOURCES}) -add_dependencies(${PROJECT_NAME} makeheaders) set(OUT_EXEC_NAME ${PROJECT_NAME}) diff --git a/Makefile b/Makefile index 3daef30d..9a5bcebd 100644 --- a/Makefile +++ b/Makefile @@ -37,17 +37,15 @@ ifeq ($(PLATFORM),$(PLATFORM_WINDOWS)) PROGRAM_SUFFIX := .exe endif -ifeq ($(PLATFORM),$(PLATFORM_LINUX)) -MAKEHEADERS := ./tools/makeheaders -else -MAKEHEADERS := ./tools/makeheaders$(PROGRAM_SUFFIX) -endif - USING_LIBAV = 0 USING_CURL = 0 USING_LIBPNG = 1 USING_ASSIMP = 1 +ifeq ($(PLATFORM),$(PLATFORM_MACOS)) +USING_ASSIMP = 0 +endif + TARGET = HatchGameEngine TARGETDIR = builds/$(OUT_FOLDER)/$(TARGET) OBJS = main.o @@ -63,10 +61,10 @@ ifeq ($(PLATFORM),$(PLATFORM_MACOS)) OBJ_DIRS += $(addprefix out/$(OUT_FOLDER)/, $(dir $(SRC_M:source/%.m=%.o))) endif -OBJS := $(addprefix out/$(OUT_FOLDER)/, $(SRC_C:source/%.c=%.o)) \ +OBJS := $(addprefix out/$(OUT_FOLDER)/, $(SRC_C:source/%.c=%.o)) \ $(addprefix out/$(OUT_FOLDER)/, $(SRC_CPP:source/%.cpp=%.o)) ifeq ($(PLATFORM),$(PLATFORM_MACOS)) -OBJ_DIRS += $(addprefix out/$(OUT_FOLDER)/, $(SRC_M:source/%.m=%.o)) +OBJS += $(addprefix out/$(OUT_FOLDER)/, $(SRC_M:source/%.m=%.o)) endif INCLUDES = -Wall -Wno-deprecated -Wno-unused-variable \ @@ -90,13 +88,10 @@ ifneq ($(MSYS_VERSION),0) DEFINES += -DMSYS endif endif -ifeq ($(PLATOFRM),$(PLATFORM_MACOS)) -INCLUDES += -F/Library/Frameworks/ \ - -F/System/Library/Frameworks/ \ - -Fmeta/mac/ \ - -I/Library/Frameworks/SDL2.framework/Headers/ \ - -I/System/Library/Frameworks/OpenGL.framework/Headers/ -DEFINES += -DMACOSX -DUSING_FRAMEWORK +ifeq ($(PLATFORM),$(PLATFORM_MACOS)) +INCLUDES += -I/opt/homebrew/include +LIBS += -lobjc +DEFINES += -DMACOSX -DUSING_OPENGL endif ifeq ($(PLATFORM),$(PLATFORM_LINUX)) DEFINES += -DLINUX @@ -132,25 +127,23 @@ LIBS += -logg -lvorbis -lvorbisfile LIBS += -lz ifeq ($(PLATFORM),$(PLATFORM_MACOS)) -LINKER = -framework SDL2 \ - -framework OpenGL \ - -framework CoreFoundation \ - -framework CoreServices \ - -framework Foundation - # \ - -framework Cocoa +LINKER = -framework IOKit \ + -framework OpenGL \ + -framework CoreFoundation \ + -framework CoreServices \ + -framework Foundation \ + -framework Cocoa endif all: mkdir -p $(OBJ_DIRS) - $(MAKEHEADERS) source $(MAKE) build clean: rm -rf $(OBJS) build: $(OBJS) - $(CXX) $^ $(INCLUDES) $(LIBS) $(LINKER) -o "$(TARGETDIR)" -std=c++11 + $(CXX) $^ $(INCLUDES) $(LIBS) $(LINKER) -o "$(TARGETDIR)" -std=c++17 $(OBJ_DIRS): mkdir -p $@ @@ -164,7 +157,6 @@ package: @mkdir -p "$(TARGETDIR).app/Contents/Resources" @# @rm -rf $(OBJS) @mkdir -p $(OBJ_DIRS) - @./tools/makeheaders source @make build @chmod +x "$(TARGETDIR)" @cp "$(TARGETDIR)" "$(TARGETDIR).app/Contents/MacOS/$(TARGET)" @@ -226,7 +218,7 @@ package: @install_name_tool -change /usr/local/Cellar/libvorbis/1.3.6/lib/libvorbis.0.dylib @executable_path/../Frameworks/_libvorbis.0.dylib "$(TARGETDIR).app/Contents/Frameworks/_libvorbisfile.3.dylib" out/$(OUT_FOLDER)/%.o: source/%.cpp - $(CXX) -c -g $(INCLUDES) $(DEFINES) -o "$@" "$<" -std=c++11 + $(CXX) -c -g $(INCLUDES) $(DEFINES) -o "$@" "$<" -std=c++17 out/$(OUT_FOLDER)/%.o: source/%.c $(CC) -c -g $(INCLUDES) $(DEFINES) -o "$@" "$<" -std=c11 diff --git a/VisualC/HatchGameEngine.vcxproj b/VisualC/HatchGameEngine.vcxproj index 044eca69..76a10fef 100644 --- a/VisualC/HatchGameEngine.vcxproj +++ b/VisualC/HatchGameEngine.vcxproj @@ -94,11 +94,6 @@ Console Ws2_32.lib;Wldap32.lib;Advapi32.lib;Crypt32.lib;Normaliz.lib;legacy_stdio_definitions.lib;glew32s.lib;opengl32.lib;freetype.lib;SDL2.lib;SDL2main.lib;%(AdditionalDependencies) - - CD "..\tools" -"makeheaders.exe" ../source -CD .. - copy "$(TargetPath)" "$(SolutionDir)..\builds\win\$(TargetName)-Debug.exe" @@ -118,11 +113,6 @@ CD .. true Ws2_32.lib;Wldap32.lib;Advapi32.lib;Crypt32.lib;Normaliz.lib;legacy_stdio_definitions.lib;glew32s.lib;opengl32.lib;freetype.lib;SDL2.lib;SDL2main.lib;%(AdditionalDependencies) - - CD "..\tools" -"makeheaders.exe" ../source -CD .. - copy "$(TargetPath)" "$(SolutionDir)..\builds\win\$(TargetName)-Release.exe" @@ -131,11 +121,6 @@ CD .. stdcpp17 - - CD "..\tools" -"makeheaders.exe" ../source -CD .. - copy "$(TargetPath)" "$(SolutionDir)..\builds\win\$(TargetName)-Debug.exe" @@ -144,11 +129,6 @@ CD .. stdcpp17 - - CD "..\tools" -"makeheaders.exe" ../source -CD .. - copy "$(TargetPath)" "$(SolutionDir)..\builds\win\$(TargetName)-Release.exe" @@ -263,10 +243,6 @@ CD .. - - - - diff --git a/VisualC/HatchGameEngine.vcxproj.filters b/VisualC/HatchGameEngine.vcxproj.filters index a16cbcd1..d8c447fa 100644 --- a/VisualC/HatchGameEngine.vcxproj.filters +++ b/VisualC/HatchGameEngine.vcxproj.filters @@ -339,18 +339,6 @@ Source Files - - Source Files - - - Source Files - - - Source Files - - - Source Files - Source Files diff --git a/include/Engine/Application.h b/include/Engine/Application.h new file mode 100644 index 00000000..80ff1496 --- /dev/null +++ b/include/Engine/Application.h @@ -0,0 +1,90 @@ +#ifndef ENGINE_APPLICATION_H +#define ENGINE_APPLICATION_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class Application { +private: + static void MakeEngineVersion(); + static void Restart(); + static void LoadAudioSettings(); + static void LoadKeyBinds(); + static void LoadDevSettings(); + static void PollEvents(); + static void RunFrame(void* p); + static void DelayFrame(); + static void LoadGameConfig(); + static void DisposeGameConfig(); + static string ParseGameVersion(XMLNode* versionNode); + static void LoadGameInfo(); + static int HandleAppEvents(void* data, SDL_Event* event); + +public: + static vector CmdLineArgs; + static INI* Settings; + static char SettingsFile[4096]; + static XMLNode* GameConfig; + static int TargetFPS; + static float CurrentFPS; + static bool Running; + static bool GameStart; + static SDL_Window* Window; + static char WindowTitle[256]; + static int WindowWidth; + static int WindowHeight; + static int DefaultMonitor; + static Platforms Platform; + static char EngineVersion[256]; + static char GameTitle[256]; + static char GameTitleShort[256]; + static char GameVersion[256]; + static char GameDescription[256]; + static int UpdatesPerFrame; + static bool Stepper; + static bool Step; + static int MasterVolume; + static int MusicVolume; + static int SoundVolume; + static int StartSceneNum; + static bool DevMenuActivated; + + static void Init(int argc, char* args[]); + static void SetTargetFrameRate(int targetFPS); + static bool IsPC(); + static bool IsMobile(); + static void GetPerformanceSnapshot(); + static void SetWindowTitle(const char* title); + static void UpdateWindowTitle(); + static void SetMasterVolume(int volume); + static void SetMusicVolume(int volume); + static void SetSoundVolume(int volume); + static bool IsWindowResizeable(); + static void SetWindowSize(int window_w, int window_h); + static bool GetWindowFullscreen(); + static void SetWindowFullscreen(bool isFullscreen); + static void SetWindowBorderless(bool isBorderless); + static int GetKeyBind(int bind); + static void SetKeyBind(int bind, int key); + static void Run(int argc, char* args[]); + static void Cleanup(); + static void LoadSceneInfo(); + static void InitPlayerControls(); + static bool LoadSettings(const char* filename); + static void ReadSettings(); + static void ReloadSettings(); + static void ReloadSettings(const char* filename); + static void InitSettings(const char* filename); + static void SaveSettings(); + static void SaveSettings(const char* filename); + static void SetSettingsFilename(const char* filename); +}; + +#endif /* ENGINE_APPLICATION_H */ diff --git a/include/Engine/Audio/AudioManager.h b/include/Engine/Audio/AudioManager.h new file mode 100644 index 00000000..3579fb6a --- /dev/null +++ b/include/Engine/Audio/AudioManager.h @@ -0,0 +1,81 @@ +#ifndef ENGINE_AUDIO_AUDIOMANAGER_H +#define ENGINE_AUDIO_AUDIOMANAGER_H + +#include +#include +#include +#include +#include + +class AudioManager { +private: + static void UpdateChannelPlayer(AudioPlayback* playback, ISound* sound); + static bool HandleFading(AudioChannel* audio); + +public: + static SDL_AudioDeviceID Device; + static SDL_AudioSpec DeviceFormat; + static bool AudioEnabled; + static Uint8 BytesPerSample; + static Uint8* MixBuffer; + static size_t MixBufferSize; + static deque MusicStack; + static AudioChannel* SoundArray; + static int SoundArrayLength; + static float MasterVolume; + static float MusicVolume; + static float SoundVolume; + static float LowPassFilter; + static Uint8* AudioQueue; + static size_t AudioQueueSize; + static size_t AudioQueueMaxSize; + enum { + REQUEST_EOF = 0, + REQUEST_ERROR = -1, + REQUEST_CONVERTING = -2, + }; + + static void CalculateCoeffs(); + static Sint16 ProcessSample(Sint16 inSample, int channel); + static float ProcessSampleFloat(float inSample, int channel); + static void Init(); + static void ClampParams(float& pan, float& speed, float& volume); + static void SetSound(int channel, ISound* music); + static void SetSound(int channel, ISound* sound, bool loop, int loopPoint, float pan, float speed, float volume, void* origin); + static int PlaySound(ISound* music); + static int PlaySound(ISound* music, bool loop, int loopPoint, float pan, float speed, float volume, void* origin); + static void PushMusic(ISound* music, bool loop, Uint32 lp, float pan, float speed, float volume, double fadeInAfterFinished); + static void PushMusicAt(ISound* music, double at, bool loop, Uint32 lp, float pan, float speed, float volume, double fadeInAfterFinished); + static void RemoveMusic(ISound* music); + static bool IsPlayingMusic(); + static bool IsPlayingMusic(ISound* music); + static void ClearMusic(); + static void ClearSounds(); + static void FadeOutMusic(double seconds); + static void AlterMusic(float pan, float speed, float volume); + static double GetMusicPosition(ISound* music); + static void Lock(); + static void Unlock(); + static int GetFreeChannel(); + static void AlterChannel(int channel, float pan, float speed, float volume); + static bool AudioIsPlaying(int channel); + static bool AudioIsPlaying(ISound* audio); + static void AudioUnpause(int channel); + static void AudioUnpause(ISound* audio); + static void AudioPause(int channel); + static void AudioPause(ISound* audio); + static void AudioStop(int channel); + static void AudioStop(ISound* audio); + static void AudioUnpauseAll(); + static void AudioPauseAll(); + static void AudioStopAll(); + static bool IsOriginPlaying(void* origin, ISound* audio); + static void StopOriginSound(void* origin, ISound* audio); + static void StopAllOriginSounds(void* origin); + static void MixAudioLR(Uint8* dest, Uint8* src, size_t len, float volumeL, float volumeR); + static bool AudioPlayMix(AudioChannel* audio, Uint8* stream, int len, float volume); + static void AudioCallback(void* data, Uint8* stream, int len); + static void Dispose(); +}; + +#endif /* ENGINE_AUDIO_AUDIOMANAGER_H */ diff --git a/include/Engine/Audio/AudioPlayback.h b/include/Engine/Audio/AudioPlayback.h new file mode 100644 index 00000000..91c8038c --- /dev/null +++ b/include/Engine/Audio/AudioPlayback.h @@ -0,0 +1,33 @@ +#ifndef ENGINE_AUDIO_AUDIOPLAYBACK_H +#define ENGINE_AUDIO_AUDIOPLAYBACK_H + +#include +#include +#include + +class AudioPlayback { +private: + void CreateConversionStream(SDL_AudioSpec format); + +public: + Uint8* Buffer = NULL; + Uint8* UnconvertedSampleBuffer = NULL; + Uint32 BufferedSamples = 0; + SDL_AudioSpec Format; + size_t BytesPerSample = 0; + size_t RequiredSamples = 0; + size_t DeviceBytesPerSample = 0; + SDL_AudioStream* ConversionStream = NULL; + SoundFormat* SoundData = NULL; + bool OwnsSoundData = false; + Sint32 LoopIndex = -1; + + AudioPlayback(SDL_AudioSpec format, size_t requiredSamples, size_t audioBytesPerSample, size_t deviceBytesPerSample); + void Change(SDL_AudioSpec format, size_t requiredSamples, size_t audioBytesPerSample, size_t deviceBytesPerSample); + void Dispose(); + int RequestSamples(int samples, bool loop, int sample_to_loop_to); + void Seek(int samples); + ~AudioPlayback(); +}; + +#endif /* ENGINE_AUDIO_AUDIOPLAYBACK_H */ diff --git a/include/Engine/Bytecode/Bytecode.h b/include/Engine/Bytecode/Bytecode.h new file mode 100644 index 00000000..b1a7004d --- /dev/null +++ b/include/Engine/Bytecode/Bytecode.h @@ -0,0 +1,23 @@ +#ifndef ENGINE_BYTECODE_BYTECODE_H +#define ENGINE_BYTECODE_BYTECODE_H + +#include +#include + +class Bytecode { +public: + static const char* Magic; + static Uint32 LatestVersion; + static vector FunctionNames; + vector Functions; + Uint8 Version; + bool HasDebugInfo = false; + const char* SourceFilename = nullptr; + + Bytecode(); + ~Bytecode(); + bool Read(BytecodeContainer bytecode, HashMap* tokens); + void Write(Stream* stream, const char* sourceFilename, HashMap* tokenMap); +}; + +#endif /* ENGINE_BYTECODE_BYTECODE_H */ diff --git a/include/Engine/Bytecode/Compiler.h b/include/Engine/Bytecode/Compiler.h new file mode 100644 index 00000000..a8722156 --- /dev/null +++ b/include/Engine/Bytecode/Compiler.h @@ -0,0 +1,213 @@ +#ifndef ENGINE_BYTECODE_COMPILER_H +#define ENGINE_BYTECODE_COMPILER_H + +#include +#include + +class Compiler { +private: + void WarnVariablesUnused(); + void WriteBytecode(Stream* stream, const char* filename); + +public: + static Parser parser; + static Scanner scanner; + static ParseRule* Rules; + static vector Functions; + static vector ModuleLocals; + static HashMap* TokenMap; + static bool ShowWarnings; + static bool WriteDebugInfo; + static bool WriteSourceFilename; + Compiler* Enclosing = nullptr; + ObjFunction* Function = nullptr; + int Type = 0; + string ClassName; + Local Locals[0x100]; + int LocalCount = 0; + int ScopeDepth = 0; + vector ClassHashList; + vector ClassExtendedList; + vector* UnusedVariables = nullptr; + + Token MakeToken(int type); + Token MakeTokenRaw(int type, const char* message); + Token ErrorToken(const char* message); + bool IsEOF(); + bool IsDigit(char c); + bool IsHexDigit(char c); + bool IsAlpha(char c); + bool IsIdentifierStart(char c); + bool IsIdentifierBody(char c); + bool MatchChar(char expected); + char AdvanceChar(); + char PrevChar(); + char PeekChar(); + char PeekNextChar(); + virtual void SkipWhitespace(); + int CheckKeyword(int start, int length, const char* rest, int type); + virtual int GetKeywordType(); + Token StringToken(); + Token NumberToken(); + Token IdentifierToken(); + virtual Token ScanToken(); + void AdvanceToken(); + Token NextToken(); + Token PeekToken(); + Token PeekNextToken(); + Token PrevToken(); + bool MatchToken(int expectedType); + bool MatchAssignmentToken(); + bool CheckToken(int expectedType); + void ConsumeToken(int type, const char* message); + void SynchronizeToken(); + bool ReportError(int line, bool fatal, const char* string, ...); + bool ReportErrorPos(int line, int pos, bool fatal, const char* string, ...); + void ErrorAt(Token* token, const char* message, bool fatal); + void Error(const char* message); + void ErrorAtCurrent(const char* message); + void Warning(const char* message); + void WarningInFunction(const char* format, ...); + void ParseVariable(const char* errorMessage); + bool IdentifiersEqual(Token* a, Token* b); + void MarkInitialized(); + void DefineVariableToken(Token global); + void DeclareVariable(Token* name); + int ParseModuleVariable(const char* errorMessage); + void DefineModuleVariable(int local); + int DeclareModuleVariable(Token* name); + void EmitSetOperation(Uint8 setOp, int arg, Token name); + void EmitGetOperation(Uint8 getOp, int arg, Token name); + void EmitAssignmentToken(Token assignmentToken); + void EmitCopy(Uint8 count); + void EmitCall(const char *name, int argCount, bool isSuper); + void EmitCall(Token name, int argCount, bool isSuper); + void NamedVariable(Token name, bool canAssign); + void ScopeBegin(); + void ScopeEnd(); + void ClearToScope(int depth); + void PopToScope(int depth); + void PopMultiple(int count); + int AddLocal(Token name); + int AddLocal(const char* name, size_t len); + int AddHiddenLocal(const char* name, size_t len); + void RenameLocal(Local* local, const char* name, size_t len); + void RenameLocal(Local* local, const char* name); + void RenameLocal(Local* local, Token name); + int ResolveLocal(Token* name); + int AddModuleLocal(Token name); + int ResolveModuleLocal(Token* name); + Uint8 GetArgumentList(); + void GetThis(bool canAssign); + void GetSuper(bool canAssign); + void GetDot(bool canAssign); + void GetElement(bool canAssign); + void GetGrouping(bool canAssign); + void GetLiteral(bool canAssign); + void GetInteger(bool canAssign); + void GetDecimal(bool canAssign); + ObjString* MakeString(Token token); + void GetString(bool canAssign); + void GetArray(bool canAssign); + void GetMap(bool canAssign); + bool IsConstant(); + void GetConstant(bool canAssign); + int GetConstantValue(); + void GetVariable(bool canAssign); + void GetLogicalAND(bool canAssign); + void GetLogicalOR(bool canAssign); + void GetConditional(bool canAssign); + void GetUnary(bool canAssign); + void GetNew(bool canAssign); + void GetBinary(bool canAssign); + void GetHas(bool canAssign); + void GetSuffix(bool canAssign); + void GetCall(bool canAssign); + void GetExpression(); + void GetPrintStatement(); + void GetExpressionStatement(); + void GetContinueStatement(); + void GetDoWhileStatement(); + void GetReturnStatement(); + void GetRepeatStatement(); + void GetSwitchStatement(); + void GetCaseStatement(); + void GetDefaultStatement(); + void GetWhileStatement(); + void GetBreakStatement(); + void GetBlockStatement(); + void GetWithStatement(); + void GetForStatement(); + void GetForEachStatement(); + void GetIfStatement(); + void GetStatement(); + int GetFunction(int type, string className); + int GetFunction(int type); + void GetMethod(Token className); + void GetVariableDeclaration(); + void GetModuleVariableDeclaration(); + void GetPropertyDeclaration(Token propertyName); + void GetClassDeclaration(); + void GetEnumDeclaration(); + void GetImportDeclaration(); + void GetUsingDeclaration(); + void GetEventDeclaration(); + void GetDeclaration(); + static void MakeRules(); + ParseRule* GetRule(int type); + void ParsePrecedence(Precedence precedence); + Uint32 GetHash(char* string); + Uint32 GetHash(Token token); + Chunk* CurrentChunk(); + int CodePointer(); + void EmitByte(Uint8 byte); + void EmitBytes(Uint8 byte1, Uint8 byte2); + void EmitUint16(Uint16 value); + void EmitUint32(Uint32 value); + int GetConstantIndex(VMValue value); + int EmitConstant(VMValue value); + void EmitLoop(int loopStart); + int GetJump(int offset); + int GetPosition(); + int EmitJump(Uint8 instruction); + int EmitJump(Uint8 instruction, int jump); + void PatchJump(int offset, int jump); + void PatchJump(int offset); + void EmitStringHash(const char* string); + void EmitStringHash(Token token); + void EmitReturn(); + void StartBreakJumpList(); + void EndBreakJumpList(); + void StartContinueJumpList(); + void EndContinueJumpList(); + void StartSwitchJumpList(); + void EndSwitchJumpList(); + int FindConstant(VMValue value); + int MakeConstant(VMValue value); + bool HasThis(); + void SetReceiverName(const char *name); + void SetReceiverName(Token name); + static int HashInstruction(const char* name, Chunk* chunk, int offset); + static int ConstantInstruction(const char* name, Chunk* chunk, int offset); + static int SimpleInstruction(const char* name, int offset); + static int ByteInstruction(const char* name, Chunk* chunk, int offset); + static int LocalInstruction(const char* name, Chunk* chunk, int offset); + static int MethodInstruction(const char* name, Chunk* chunk, int offset); + static int InvokeInstruction(const char* name, Chunk* chunk, int offset); + static int JumpInstruction(const char* name, int sign, Chunk* chunk, int offset); + static int ClassInstruction(const char* name, Chunk* chunk, int offset); + static int EnumInstruction(const char* name, Chunk* chunk, int offset); + static int WithInstruction(const char* name, Chunk* chunk, int offset); + static int DebugInstruction(Chunk* chunk, int offset); + static void DebugChunk(Chunk* chunk, const char* name, int minArity, int maxArity); + static void Init(); + static void PrepareCompiling(); + void Initialize(Compiler* enclosing, int scope, int type); + bool Compile(const char* filename, const char* source, const char* output); + void Finish(); + virtual ~Compiler(); + static void FinishCompiling(); + static void Dispose(); +}; + +#endif /* ENGINE_BYTECODE_COMPILER_H */ diff --git a/include/Engine/Bytecode/GarbageCollector.h b/include/Engine/Bytecode/GarbageCollector.h new file mode 100644 index 00000000..d28d2b6e --- /dev/null +++ b/include/Engine/Bytecode/GarbageCollector.h @@ -0,0 +1,30 @@ +#ifndef ENGINE_BYTECODE_GARBAGECOLLECTOR_H +#define ENGINE_BYTECODE_GARBAGECOLLECTOR_H + +#include +#include + +class GarbageCollector { +private: + static void FreeValue(VMValue value); + static void GrayValue(VMValue value); + static void GrayObject(void* obj); + static void GrayHashMapItem(Uint32, VMValue value); + static void GrayHashMap(void* pointer); + static void BlackenObject(Obj* object); + +public: + static vector GrayList; + static Obj* RootObject; + static size_t NextGC; + static size_t GarbageSize; + static double MaxTimeAlotted; + static bool Print; + static bool FilterSweepEnabled; + static int FilterSweepType; + + static void Init(); + static void Collect(); +}; + +#endif /* ENGINE_BYTECODE_GARBAGECOLLECTOR_H */ diff --git a/include/Engine/Bytecode/ScriptEntity.h b/include/Engine/Bytecode/ScriptEntity.h new file mode 100644 index 00000000..ec4d02dc --- /dev/null +++ b/include/Engine/Bytecode/ScriptEntity.h @@ -0,0 +1,73 @@ +#ifndef ENGINE_BYTECODE_SCRIPTENTITY_H +#define ENGINE_BYTECODE_SCRIPTENTITY_H + +#include +#include + +class ScriptEntity : public Entity { +private: + bool GetCallableValue(Uint32 hash, VMValue& value); + ObjFunction* GetCallableFunction(Uint32 hash); + +public: + static bool DisableAutoAnimate; + ObjInstance* Instance = NULL; + HashMap* Properties; + + void Link(ObjInstance* instance); + void LinkFields(); + bool RunFunction(Uint32 hash); + bool RunCreateFunction(VMValue flag); + bool RunInitializer(); + bool ChangeClass(const char* className); + void Copy(ScriptEntity* other, bool copyClass); + void CopyFields(ScriptEntity* other); + void CopyVMFields(ScriptEntity* other); + void Initialize(); + void Create(VMValue flag); + void Create(); + void PostCreate(); + void UpdateEarly(); + void Update(); + void UpdateLate(); + void RenderEarly(); + void Render(int CamX, int CamY); + void RenderLate(); + void OnAnimationFinish(); + void OnSceneLoad(); + void OnSceneRestart(); + void GameStart(); + void Remove(); + void Dispose(); + static bool VM_Getter(Obj* object, Uint32 hash, VMValue* result, Uint32 threadID); + static bool VM_Setter(Obj* object, Uint32 hash, VMValue value, Uint32 threadID); + static VMValue VM_SetAnimation(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_ResetAnimation(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_Animate(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_GetIDWithinClass(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_AddToRegistry(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_IsInRegistry(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_RemoveFromRegistry(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_ApplyMotion(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_InView(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_CollidedWithObject(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_GetHitboxFromSprite(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_ReturnHitboxFromSprite(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_CollideWithObject(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_SolidCollideWithObject(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_TopSolidCollideWithObject(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_ApplyPhysics(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_PropertyExists(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_PropertyGet(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_SetViewVisibility(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_SetViewOverride(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_AddToDrawGroup(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_IsInDrawGroup(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_RemoveFromDrawGroup(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_PlaySound(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_LoopSound(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_StopSound(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_StopAllSounds(int argCount, VMValue* args, Uint32 threadID); +}; + +#endif /* ENGINE_BYTECODE_SCRIPTENTITY_H */ diff --git a/include/Engine/Bytecode/ScriptManager.h b/include/Engine/Bytecode/ScriptManager.h new file mode 100644 index 00000000..10a622ab --- /dev/null +++ b/include/Engine/Bytecode/ScriptManager.h @@ -0,0 +1,89 @@ +#ifndef ENGINE_BYTECODE_SCRIPTMANAGER_H +#define ENGINE_BYTECODE_SCRIPTMANAGER_H +class ScriptEntity; + +#include +#include +#include +#include +#include +#include +#include +#include + +class ScriptManager { +private: + static Uint32 GetBranchLimit(); + static void RemoveNonGlobalableValue(Uint32 hash, VMValue value); + static void FreeNativeValue(Uint32 hash, VMValue value); + static void FreeFunction(ObjFunction* function); + static void FreeModule(ObjModule* module); + static void FreeClass(ObjClass* klass); + static void FreeEnumeration(ObjEnum* enumeration); + static void FreeNamespace(ObjNamespace* ns); + static void FreeModules(); + +public: + static bool LoadAllClasses; + static HashMap* Globals; + static HashMap* Constants; + static std::set FreedGlobals; + static VMThread Threads[8]; + static Uint32 ThreadCount; + static vector ModuleList; + static HashMap* Sources; + static HashMap* Classes; + static HashMap* Tokens; + static vector AllNamespaces; + static vector ClassImplList; + static SDL_mutex* GlobalLock; + + static void RequestGarbageCollection(); + static void ForceGarbageCollection(); + static void ResetStack(); + static void Init(); + static void DisposeGlobalValueTable(HashMap* globals); + static void Dispose(); + static void FreeString(ObjString* string); + static void FreeGlobalValue(Uint32 hash, VMValue value); + static VMValue CastValueAsString(VMValue v, bool prettyPrint); + static VMValue CastValueAsString(VMValue v); + static VMValue CastValueAsInteger(VMValue v); + static VMValue CastValueAsDecimal(VMValue v); + static VMValue Concatenate(VMValue va, VMValue vb); + static bool ValuesSortaEqual(VMValue a, VMValue b); + static bool ValuesEqual(VMValue a, VMValue b); + static bool ValueFalsey(VMValue a); + static VMValue DelinkValue(VMValue val); + static bool DoIntegerConversion(VMValue& value, Uint32 threadID); + static bool DoDecimalConversion(VMValue& value, Uint32 threadID); + static void FreeValue(VMValue value); + static bool Lock(); + static void Unlock(); + static void DefineMethod(VMThread* thread, ObjFunction* function, Uint32 hash); + static void DefineNative(ObjClass* klass, const char* name, NativeFn function); + static void GlobalLinkInteger(ObjClass* klass, const char* name, int* value); + static void GlobalLinkDecimal(ObjClass* klass, const char* name, float* value); + static void GlobalConstInteger(ObjClass* klass, const char* name, int value); + static void GlobalConstDecimal(ObjClass* klass, const char* name, float value); + static ObjClass* GetClassParent(ObjClass* klass); + static VMValue GetClassMethod(ObjClass* klass, Uint32 hash); + static void LinkStandardLibrary(); + static void LinkExtensions(); + static bool RunBytecode(BytecodeContainer bytecodeContainer, Uint32 filenameHash); + static bool CallFunction(char* functionName); + static Entity* SpawnObject(const char* objectName); + static Uint32 MakeFilenameHash(char *filename); + static BytecodeContainer GetBytecodeFromFilenameHash(Uint32 filenameHash); + static bool ClassExists(const char* objectName); + static bool LoadScript(char* filename); + static bool LoadScript(const char* filename); + static bool LoadScript(Uint32 hash); + static bool LoadObjectClass(const char* objectName, bool addNativeFunctions); + static void AddNativeObjectFunctions(ObjClass* klass); + static ObjClass* GetObjectClass(const char* className); + static Entity* ObjectSpawnFunction(ObjectList* list); + static void LoadClasses(); +}; + +#endif /* ENGINE_BYTECODE_SCRIPTMANAGER_H */ diff --git a/include/Engine/Bytecode/SourceFileMap.h b/include/Engine/Bytecode/SourceFileMap.h new file mode 100644 index 00000000..b14bc343 --- /dev/null +++ b/include/Engine/Bytecode/SourceFileMap.h @@ -0,0 +1,21 @@ +#ifndef ENGINE_BYTECODE_SOURCEFILEMAP_H +#define ENGINE_BYTECODE_SOURCEFILEMAP_H + +#include +#include + +class SourceFileMap { +public: + static bool Initialized; + static HashMap* Checksums; + static HashMap*>* ClassMap; + static Uint32 DirectoryChecksum; + static Uint32 Magic; + static bool DoLogging; + + static void CheckInit(); + static void CheckForUpdate(); + static void Dispose(); +}; + +#endif /* ENGINE_BYTECODE_SOURCEFILEMAP_H */ diff --git a/include/Engine/Bytecode/StandardLibrary.h b/include/Engine/Bytecode/StandardLibrary.h new file mode 100644 index 00000000..03c69093 --- /dev/null +++ b/include/Engine/Bytecode/StandardLibrary.h @@ -0,0 +1,26 @@ +#ifndef ENGINE_BYTECODE_STANDARDLIBRARY_H +#define ENGINE_BYTECODE_STANDARDLIBRARY_H + +#include +#include +#include + +class StandardLibrary { +public: + static int GetInteger(VMValue* args, int index, Uint32 threadID); + static float GetDecimal(VMValue* args, int index, Uint32 threadID); + static char* GetString(VMValue* args, int index, Uint32 threadID); + static ObjString* GetVMString(VMValue* args, int index, Uint32 threadID); + static ObjArray* GetArray(VMValue* args, int index, Uint32 threadID); + static ObjMap* GetMap(VMValue* args, int index, Uint32 threadID); + static ISprite* GetSprite(VMValue* args, int index, Uint32 threadID); + static ISound* GetSound(VMValue* args, int index, Uint32 threadID); + static ObjInstance* GetInstance(VMValue* args, int index, Uint32 threadID); + static ObjFunction* GetFunction(VMValue* args, int index, Uint32 threadID); + static void CheckArgCount(int argCount, int expects); + static void CheckAtLeastArgCount(int argCount, int expects); + static void Link(); + static void Dispose(); +}; + +#endif /* ENGINE_BYTECODE_STANDARDLIBRARY_H */ diff --git a/include/Engine/Bytecode/TypeImpl/ArrayImpl.h b/include/Engine/Bytecode/TypeImpl/ArrayImpl.h new file mode 100644 index 00000000..f557be34 --- /dev/null +++ b/include/Engine/Bytecode/TypeImpl/ArrayImpl.h @@ -0,0 +1,16 @@ +#ifndef ENGINE_BYTECODE_TYPEIMPL_ARRAYIMPL_H +#define ENGINE_BYTECODE_TYPEIMPL_ARRAYIMPL_H + +#include +#include + +class ArrayImpl { +public: + static ObjClass *Class; + + static void Init(); + static VMValue VM_Iterate(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_IteratorValue(int argCount, VMValue* args, Uint32 threadID); +}; + +#endif /* ENGINE_BYTECODE_TYPEIMPL_ARRAYIMPL_H */ diff --git a/include/Engine/Bytecode/TypeImpl/FunctionImpl.h b/include/Engine/Bytecode/TypeImpl/FunctionImpl.h new file mode 100644 index 00000000..4c1fedb2 --- /dev/null +++ b/include/Engine/Bytecode/TypeImpl/FunctionImpl.h @@ -0,0 +1,15 @@ +#ifndef ENGINE_BYTECODE_TYPEIMPL_FUNCTIONIMPL_H +#define ENGINE_BYTECODE_TYPEIMPL_FUNCTIONIMPL_H + +#include +#include + +class FunctionImpl { +public: + static ObjClass *Class; + + static void Init(); + static VMValue VM_Bind(int argCount, VMValue* args, Uint32 threadID); +}; + +#endif /* ENGINE_BYTECODE_TYPEIMPL_FUNCTIONIMPL_H */ diff --git a/include/Engine/Bytecode/TypeImpl/MapImpl.h b/include/Engine/Bytecode/TypeImpl/MapImpl.h new file mode 100644 index 00000000..d86228a6 --- /dev/null +++ b/include/Engine/Bytecode/TypeImpl/MapImpl.h @@ -0,0 +1,17 @@ +#ifndef ENGINE_BYTECODE_TYPEIMPL_MAPIMPL_H +#define ENGINE_BYTECODE_TYPEIMPL_MAPIMPL_H + +#include +#include + +class MapImpl { +public: + static ObjClass *Class; + + static void Init(); + static VMValue VM_GetKeys(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_Iterate(int argCount, VMValue* args, Uint32 threadID); + static VMValue VM_IteratorValue(int argCount, VMValue* args, Uint32 threadID); +}; + +#endif /* ENGINE_BYTECODE_TYPEIMPL_MAPIMPL_H */ diff --git a/include/Engine/Bytecode/TypeImpl/StringImpl.h b/include/Engine/Bytecode/TypeImpl/StringImpl.h new file mode 100644 index 00000000..34a9ad81 --- /dev/null +++ b/include/Engine/Bytecode/TypeImpl/StringImpl.h @@ -0,0 +1,16 @@ +#ifndef ENGINE_BYTECODE_TYPEIMPL_STRINGIMPL_H +#define ENGINE_BYTECODE_TYPEIMPL_STRINGIMPL_H + +#include +#include + +class StringImpl { +public: + static ObjClass *Class; + + static void Init(); + static bool VM_ElementGet(Obj* object, VMValue at, VMValue* result, Uint32 threadID); + static bool VM_ElementSet(Obj* object, VMValue at, VMValue value, Uint32 threadID); +}; + +#endif /* ENGINE_BYTECODE_TYPEIMPL_STRINGIMPL_H */ diff --git a/include/Engine/Bytecode/VMThread.h b/include/Engine/Bytecode/VMThread.h new file mode 100644 index 00000000..1834a735 --- /dev/null +++ b/include/Engine/Bytecode/VMThread.h @@ -0,0 +1,106 @@ +#ifndef ENGINE_BYTECODE_VMTHREAD_H +#define ENGINE_BYTECODE_VMTHREAD_H + +#include +#include +#include + +class VMThread { +private: + string GetFunctionName(ObjFunction* function); + void PrintStackTrace(PrintBuffer* buffer, const char* errorString); + bool CheckBranchLimit(CallFrame* frame); + bool DoJump(CallFrame* frame, int offset); + bool DoJumpBack(CallFrame* frame, int offset); + bool GetProperty(Obj* object, ObjClass* klass, Uint32 hash, bool checkFields, ValueGetFn getter); + bool GetProperty(Obj* object, ObjClass* klass, Uint32 hash, bool checkFields); + bool GetProperty(Obj* object, ObjClass* klass, Uint32 hash); + bool HasProperty(Obj* object, ObjClass* klass, Uint32 hash, bool checkFields, ValueGetFn getter); + bool HasProperty(Obj* object, ObjClass* klass, Uint32 hash, bool checkFields); + bool HasProperty(Obj* object, ObjClass* klass, Uint32 hash); + bool SetProperty(Table* fields, Uint32 hash, VMValue field, VMValue value); + bool BindMethod(VMValue receiver, VMValue method); + bool CallBoundMethod(ObjBoundMethod* bound, int argCount); + bool CallValue(VMValue callee, int argCount); + bool CallForObject(VMValue callee, int argCount); + bool InstantiateClass(VMValue callee, int argCount); + bool DoClassExtension(VMValue value, VMValue originalValue, bool clearSrc); + +public: + VMValue Stack[STACK_SIZE_MAX]; + VMValue* StackTop = Stack; + VMValue RegisterValue; + CallFrame Frames[FRAMES_MAX]; + Uint32 FrameCount; + Uint32 ReturnFrame; + VMValue FunctionToInvoke; + VMValue InterpretResult; + enum ThreadState { + CREATED = 0, + RUNNING = 1, + WAITING = 2, + CLOSED = 3, + }; + char Name[THREAD_NAME_MAX]; + Uint32 ID; + bool DebugInfo; + Uint32 BranchLimit; + static bool InstructionIgnoreMap[0x100]; + static std::jmp_buf JumpBuffer; + + static char* GetToken(Uint32 hash); + static char* GetVariableOrMethodName(Uint32 hash); + void MakeErrorMessage(PrintBuffer* buffer, const char* errorString); + int ThrowRuntimeError(bool fatal, const char* errorMessage, ...); + void PrintStack(); + void ReturnFromNative() throw(); + void Push(VMValue value); + VMValue Pop(); + void Pop(unsigned amount); + VMValue Peek(int offset); + Uint32 StackSize(); + void ResetStack(); + Uint8 ReadByte(CallFrame* frame); + Uint16 ReadUInt16(CallFrame* frame); + Uint32 ReadUInt32(CallFrame* frame); + Sint16 ReadSInt16(CallFrame* frame); + Sint32 ReadSInt32(CallFrame* frame); + VMValue ReadConstant(CallFrame* frame); + bool ShowBranchLimitMessage(const char* errorMessage, ...); + int RunInstruction(); + void RunInstructionSet(); + void RunValue(VMValue value, int argCount); + void RunFunction(ObjFunction* func, int argCount); + void InvokeForEntity(VMValue value, int argCount); + VMValue RunEntityFunction(ObjFunction* function, int argCount); + void CallInitializer(VMValue value); + bool Call(ObjFunction* function, int argCount); + bool InvokeFromClass(ObjClass* klass, Uint32 hash, int argCount); + bool InvokeForInstance(Uint32 hash, int argCount, bool isSuper); + bool Import(VMValue value); + bool ImportModule(VMValue value); + VMValue Values_Multiply(); + VMValue Values_Division(); + VMValue Values_Modulo(); + VMValue Values_Plus(); + VMValue Values_Minus(); + VMValue Values_BitwiseLeft(); + VMValue Values_BitwiseRight(); + VMValue Values_BitwiseAnd(); + VMValue Values_BitwiseXor(); + VMValue Values_BitwiseOr(); + VMValue Values_LogicalAND(); + VMValue Values_LogicalOR(); + VMValue Values_LessThan(); + VMValue Values_GreaterThan(); + VMValue Values_LessThanOrEqual(); + VMValue Values_GreaterThanOrEqual(); + VMValue Values_Increment(); + VMValue Values_Decrement(); + VMValue Values_Negate(); + VMValue Values_LogicalNOT(); + VMValue Values_BitwiseNOT(); + VMValue Value_TypeOf(); +}; + +#endif /* ENGINE_BYTECODE_VMTHREAD_H */ diff --git a/include/Engine/Bytecode/Values.h b/include/Engine/Bytecode/Values.h new file mode 100644 index 00000000..af283f71 --- /dev/null +++ b/include/Engine/Bytecode/Values.h @@ -0,0 +1,17 @@ +#ifndef ENGINE_BYTECODE_VALUES_H +#define ENGINE_BYTECODE_VALUES_H + +#include +#include +#include + +class Values { +public: + static void PrintValue(VMValue value); + static void PrintValue(PrintBuffer* buffer, VMValue value); + static void PrintValue(PrintBuffer* buffer, VMValue value, bool prettyPrint); + static void PrintValue(PrintBuffer* buffer, VMValue value, int indent, bool prettyPrint); + static void PrintObject(PrintBuffer* buffer, VMValue value, int indent, bool prettyPrint); +}; + +#endif /* ENGINE_BYTECODE_VALUES_H */ diff --git a/include/Engine/Diagnostics/Clock.h b/include/Engine/Diagnostics/Clock.h new file mode 100644 index 00000000..25e2406b --- /dev/null +++ b/include/Engine/Diagnostics/Clock.h @@ -0,0 +1,15 @@ +#ifndef ENGINE_DIAGNOSTICS_CLOCK_H +#define ENGINE_DIAGNOSTICS_CLOCK_H + +#include + +class Clock { +public: + static void Init(); + static void Start(); + static double GetTicks(); + static double End(); + static void Delay(double milliseconds); +}; + +#endif /* ENGINE_DIAGNOSTICS_CLOCK_H */ diff --git a/include/Engine/Diagnostics/Log.h b/include/Engine/Diagnostics/Log.h new file mode 100644 index 00000000..df094ddd --- /dev/null +++ b/include/Engine/Diagnostics/Log.h @@ -0,0 +1,23 @@ +#ifndef ENGINE_DIAGNOSTICS_LOG_H +#define ENGINE_DIAGNOSTICS_LOG_H + + +class Log { +public: + enum LogLevels { + LOG_VERBOSE = -1, + LOG_INFO = 0, + LOG_WARN = 1, + LOG_ERROR = 2, + LOG_IMPORTANT = 3, + }; + static int LogLevel; + static const char* LogFilename; + static bool WriteToFile; + + static void Init(); + static void SetLogLevel(int sev); + static void Print(int sev, const char* format, ...); +}; + +#endif /* ENGINE_DIAGNOSTICS_LOG_H */ diff --git a/include/Engine/Diagnostics/Memory.h b/include/Engine/Diagnostics/Memory.h new file mode 100644 index 00000000..2bb312a0 --- /dev/null +++ b/include/Engine/Diagnostics/Memory.h @@ -0,0 +1,34 @@ +#ifndef ENGINE_DIAGNOSTICS_MEMORY_H +#define ENGINE_DIAGNOSTICS_MEMORY_H + +#include + +class Memory { +private: + static vector TrackedMemory; + static vector TrackedSizes; + static vector TrackedMemoryNames; + + +public: + static size_t MemoryUsage; + static bool IsTracking; + + static void Memset4(void* dst, Uint32 val, size_t dwords); + static void* Malloc(size_t size); + static void* Calloc(size_t count, size_t size); + static void* Realloc(void* pointer, size_t size); + static void* TrackedMalloc(const char* identifier, size_t size); + static void* TrackedCalloc(const char* identifier, size_t count, size_t size); + static void Track(void* pointer, const char* identifier); + static void Track(void* pointer, size_t size, const char* identifier); + static void TrackLast(const char* identifier); + static void Free(void* pointer); + static void Remove(void* pointer); + static const char* GetName(void* pointer); + static void ClearTrackedMemory(); + static size_t CheckLeak(); + static void PrintLeak(); +}; + +#endif /* ENGINE_DIAGNOSTICS_MEMORY_H */ diff --git a/include/Engine/Diagnostics/PerformanceMeasure.h b/include/Engine/Diagnostics/PerformanceMeasure.h new file mode 100644 index 00000000..0eb926a1 --- /dev/null +++ b/include/Engine/Diagnostics/PerformanceMeasure.h @@ -0,0 +1,15 @@ +#ifndef ENGINE_DIAGNOSTICS_PERFORMANCEMEASURE_H +#define ENGINE_DIAGNOSTICS_PERFORMANCEMEASURE_H + +#include +#include + +class PerformanceMeasure { +public: + static bool Initialized; + static Perf_ViewRender PERF_ViewRender[MAX_SCENE_VIEWS]; + + static void Init(); +}; + +#endif /* ENGINE_DIAGNOSTICS_PERFORMANCEMEASURE_H */ diff --git a/include/Engine/Diagnostics/RemoteDebug.h b/include/Engine/Diagnostics/RemoteDebug.h new file mode 100644 index 00000000..ab312599 --- /dev/null +++ b/include/Engine/Diagnostics/RemoteDebug.h @@ -0,0 +1,14 @@ +#ifndef ENGINE_DIAGNOSTICS_REMOTEDEBUG_H +#define ENGINE_DIAGNOSTICS_REMOTEDEBUG_H + + +class RemoteDebug { +public: + static bool Initialized; + static bool UsingRemoteDebug; + + static void Init(); + static bool AwaitResponse(); +}; + +#endif /* ENGINE_DIAGNOSTICS_REMOTEDEBUG_H */ diff --git a/include/Engine/Extensions/Discord.h b/include/Engine/Extensions/Discord.h new file mode 100644 index 00000000..20e26929 --- /dev/null +++ b/include/Engine/Extensions/Discord.h @@ -0,0 +1,20 @@ +#ifndef ENGINE_EXTENSIONS_DISCORD_H +#define ENGINE_EXTENSIONS_DISCORD_H + +#include + +class Discord { +public: + static bool Initialized; + + static void Init(const char* application_id, const char* steam_id); + static void UpdatePresence(char* details); + static void UpdatePresence(char* details, char* state); + static void UpdatePresence(char* details, char* state, char* image_key); + static void UpdatePresence(char* details, char* state, char* image_key, time_t start_time); + static void UpdatePresence(char* details, char* state, char* image_key, int party_size, int party_max); + static void UpdatePresence(char* details, char* state, char* image_key, int party_size, int party_max, time_t start_time); + static void Dispose(); +}; + +#endif /* ENGINE_EXTENSIONS_DISCORD_H */ diff --git a/include/Engine/Filesystem/Directory.h b/include/Engine/Filesystem/Directory.h new file mode 100644 index 00000000..15080199 --- /dev/null +++ b/include/Engine/Filesystem/Directory.h @@ -0,0 +1,17 @@ +#ifndef ENGINE_FILESYSTEM_DIRECTORY_H +#define ENGINE_FILESYSTEM_DIRECTORY_H + +#include + +class Directory { +public: + static bool Exists(const char* path); + static bool Create(const char* path); + static bool GetCurrentWorkingDirectory(char* out, size_t sz); + static void GetFiles(vector* files, const char* path, const char* searchPattern, bool allDirs); + static vector GetFiles(const char* path, const char* searchPattern, bool allDirs); + static void GetDirectories(vector* files, const char* path, const char* searchPattern, bool allDirs); + static vector GetDirectories(const char* path, const char* searchPattern, bool allDirs); +}; + +#endif /* ENGINE_FILESYSTEM_DIRECTORY_H */ diff --git a/include/Engine/Filesystem/File.h b/include/Engine/Filesystem/File.h new file mode 100644 index 00000000..2a6fe55b --- /dev/null +++ b/include/Engine/Filesystem/File.h @@ -0,0 +1,13 @@ +#ifndef ENGINE_FILESYSTEM_FILE_H +#define ENGINE_FILESYSTEM_FILE_H + +#include + +class File { +public: + static bool Exists(const char* path); + static size_t ReadAllBytes(const char* path, char** out); + static bool WriteAllBytes(const char* path, const char* bytes, size_t len); +}; + +#endif /* ENGINE_FILESYSTEM_FILE_H */ diff --git a/include/Engine/FontFace.h b/include/Engine/FontFace.h new file mode 100644 index 00000000..621ff6ca --- /dev/null +++ b/include/Engine/FontFace.h @@ -0,0 +1,15 @@ +#ifndef ENGINE_FONTFACE_H +#define ENGINE_FONTFACE_H + +#include +#include +#include +#include +#include + +class FontFace { +public: + static ISprite* SpriteFromFont(Stream* stream, int pixelSize, char* filename); +}; + +#endif /* ENGINE_FONTFACE_H */ diff --git a/include/Engine/Graphics.h b/include/Engine/Graphics.h new file mode 100644 index 00000000..4e25359b --- /dev/null +++ b/include/Engine/Graphics.h @@ -0,0 +1,190 @@ +#ifndef ENGINE_GRAPHICS_H +#define ENGINE_GRAPHICS_H +class ISprite; +class IModel; + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class Graphics { +public: + static HashMap* TextureMap; + static map SpriteSheetTextureMap; + static bool VsyncEnabled; + static int MultisamplingEnabled; + static int FontDPI; + static bool SupportsBatching; + static bool TextureBlend; + static bool TextureInterpolate; + static Uint32 PreferredPixelFormat; + static Uint32 MaxTextureWidth; + static Uint32 MaxTextureHeight; + static Texture* TextureHead; + static vector VertexBuffers; + static Scene3D Scene3Ds[MAX_3D_SCENES]; + static stack StateStack; + static stack MatrixStack; + static Matrix4x4* ModelViewMatrix; + static Viewport CurrentViewport; + static Viewport BackupViewport; + static ClipArea CurrentClip; + static ClipArea BackupClip; + static View* CurrentView; + static float BlendColors[4]; + static float TintColors[4]; + static int BlendMode; + static int TintMode; + static int StencilTest; + static int StencilOpPass; + static int StencilOpFail; + static void* FramebufferPixels; + static size_t FramebufferSize; + static Uint32 PaletteColors[MAX_PALETTE_COUNT][0x100]; + static Uint8 PaletteIndexLines[MAX_FRAMEBUFFER_HEIGHT]; + static bool PaletteUpdated; + static Texture* PaletteTexture; + static Texture* CurrentRenderTarget; + static Sint32 CurrentScene3D; + static Sint32 CurrentVertexBuffer; + static void* CurrentShader; + static bool SmoothFill; + static bool SmoothStroke; + static float PixelOffset; + static bool NoInternalTextures; + static bool UsePalettes; + static bool UsePaletteIndexLines; + static bool UseTinting; + static bool UseDepthTesting; + static bool UseSoftwareRenderer; + static unsigned CurrentFrame; + // Rendering functions + static GraphicsFunctions Internal; + static GraphicsFunctions* GfxFunctions; + static const char* Renderer; + + static void Init(); + static void ChooseBackend(); + static Uint32 GetWindowFlags(); + static void SetVSync(bool enabled); + static void Reset(); + static void Dispose(); + static Point ProjectToScreen(float x, float y, float z); + static Texture* CreateTexture(Uint32 format, Uint32 access, Uint32 width, Uint32 height); + static Texture* CreateTextureFromPixels(Uint32 width, Uint32 height, void* pixels, int pitch); + static Texture* CreateTextureFromSurface(SDL_Surface* surface); + static int LockTexture(Texture* texture, void** pixels, int* pitch); + static int UpdateTexture(Texture* texture, SDL_Rect* src, void* pixels, int pitch); + static int UpdateYUVTexture(Texture* texture, SDL_Rect* src, Uint8* pixelsY, int pitchY, Uint8* pixelsU, int pitchU, Uint8* pixelsV, int pitchV); + static int SetTexturePalette(Texture* texture, void* palette, unsigned numPaletteColors); + static int ConvertTextureToRGBA(Texture* texture); + static int ConvertTextureToPalette(Texture* texture, unsigned paletteNumber); + static void UnlockTexture(Texture* texture); + static void DisposeTexture(Texture* texture); + static TextureReference* GetSpriteSheet(string sheetPath); + static TextureReference* AddSpriteSheet(string sheetPath, Texture* texture); + static void DisposeSpriteSheet(string sheetPath); + static void DeleteSpriteSheetMap(); + static Uint32 CreateVertexBuffer(Uint32 maxVertices, int unloadPolicy); + static void DeleteVertexBuffer(Uint32 vertexBufferIndex); + static void UseShader(void* shader); + static void SetTextureInterpolation(bool interpolate); + static void Clear(); + static void Present(); + static void SoftwareStart(); + static void SoftwareEnd(); + static void UpdateGlobalPalette(); + static void UnloadSceneData(); + static void SetRenderTarget(Texture* texture); + static void CopyScreen(int source_x, int source_y, int source_w, int source_h, int dest_x, int dest_y, int dest_w, int dest_h, Texture* texture); + static void UpdateOrtho(float width, float height); + static void UpdateOrthoFlipped(float width, float height); + static void UpdatePerspective(float fovy, float aspect, float nearv, float farv); + static void UpdateProjectionMatrix(); + static void MakePerspectiveMatrix(Matrix4x4* out, float fov, float near, float far, float aspect); + static void CalculateMVPMatrix(Matrix4x4* output, Matrix4x4* modelMatrix, Matrix4x4* viewMatrix, Matrix4x4* projMatrix); + static void SetViewport(float x, float y, float w, float h); + static void ResetViewport(); + static void Resize(int width, int height); + static void SetClip(int x, int y, int width, int height); + static void ClearClip(); + static void Save(); + static void Translate(float x, float y, float z); + static void Rotate(float x, float y, float z); + static void Scale(float x, float y, float z); + static void Restore(); + static BlendState GetBlendState(); + static void PushState(); + static void PopState(); + static void SetBlendColor(float r, float g, float b, float a); + static void SetBlendMode(int blendMode); + static void SetBlendMode(int srcC, int dstC, int srcA, int dstA); + static void SetTintColor(float r, float g, float b, float a); + static void SetTintMode(int mode); + static void SetTintEnabled(bool enabled); + static void SetLineWidth(float n); + static void StrokeLine(float x1, float y1, float x2, float y2); + static void StrokeCircle(float x, float y, float rad, float thickness); + static void StrokeEllipse(float x, float y, float w, float h); + static void StrokeTriangle(float x1, float y1, float x2, float y2, float x3, float y3); + static void StrokeRectangle(float x, float y, float w, float h); + static void FillCircle(float x, float y, float rad); + static void FillEllipse(float x, float y, float w, float h); + static void FillTriangle(float x1, float y1, float x2, float y2, float x3, float y3); + static void FillRectangle(float x, float y, float w, float h); + static void DrawTexture(Texture* texture, float sx, float sy, float sw, float sh, float x, float y, float w, float h); + static void DrawSprite(ISprite* sprite, int animation, int frame, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID); + static void DrawSpritePart(ISprite* sprite, int animation, int frame, int sx, int sy, int sw, int sh, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID); + static void DrawSprite(ISprite* sprite, int animation, int frame, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation); + static void DrawSpritePart(ISprite* sprite, int animation, int frame, int sx, int sy, int sw, int sh, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation); + static void DrawTile(int tile, int x, int y, bool flipX, bool flipY); + static void DrawSceneLayer_HorizontalParallax(SceneLayer* layer, View* currentView); + static void DrawSceneLayer_VerticalParallax(SceneLayer* layer, View* currentView); + static void DrawSceneLayer(SceneLayer* layer, View* currentView, int layerIndex, bool useCustomFunction); + static void RunCustomSceneLayerFunction(ObjFunction* func, int layerIndex); + static void DrawPolygon3D(void* data, int vertexCount, int vertexFlag, Texture* texture, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static void DrawSceneLayer3D(void* layer, int sx, int sy, int sw, int sh, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static void DrawModel(void* model, Uint16 animation, Uint32 frame, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static void DrawModelSkinned(void* model, Uint16 armature, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static void DrawVertexBuffer(Uint32 vertexBufferIndex, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static void BindVertexBuffer(Uint32 vertexBufferIndex); + static void UnbindVertexBuffer(); + static void BindScene3D(Uint32 sceneIndex); + static void ClearScene3D(Uint32 sceneIndex); + static void DrawScene3D(Uint32 sceneIndex, Uint32 drawMode); + static Uint32 CreateScene3D(int unloadPolicy); + static void DeleteScene3D(Uint32 sceneIndex); + static void InitScene3D(Uint32 sceneIndex, Uint32 numVertices); + static void MakeSpritePolygon(VertexAttribute data[4], float x, float y, float z, int flipX, int flipY, float scaleX, float scaleY, Texture* texture, int frameX, int frameY, int frameW, int frameH); + static void MakeSpritePolygonUVs(VertexAttribute data[4], int flipX, int flipY, Texture* texture, int frameX, int frameY, int frameW, int frameH); + static void MakeFrameBufferID(ISprite* sprite, AnimFrame* frame); + static void DeleteFrameBufferID(AnimFrame* frame); + static void SetDepthTesting(bool enabled); + static bool SpriteRangeCheck(ISprite* sprite, int animation, int frame); + static void ConvertFromARGBtoNative(Uint32* argb, int count); + static void ConvertFromNativeToARGB(Uint32* argb, int count); + static void SetStencilEnabled(bool enabled); + static bool GetStencilEnabled(); + static void SetStencilTestFunc(int stencilTest); + static void SetStencilPassFunc(int stencilOp); + static void SetStencilFailFunc(int stencilOp); + static void SetStencilValue(int value); + static void SetStencilMask(int mask); + static void ClearStencil(); +}; + +#endif /* ENGINE_GRAPHICS_H */ diff --git a/include/Engine/Hashing/CRC32.h b/include/Engine/Hashing/CRC32.h new file mode 100644 index 00000000..e852c68f --- /dev/null +++ b/include/Engine/Hashing/CRC32.h @@ -0,0 +1,14 @@ +#ifndef ENGINE_HASHING_CRC32_H +#define ENGINE_HASHING_CRC32_H + +#include + +class CRC32 { +public: + static Uint32 EncryptString(char* data); + static Uint32 EncryptString(const char* message); + static Uint32 EncryptData(const void* data, size_t size); + static Uint32 EncryptData(const void* data, size_t size, Uint32 crc); +}; + +#endif /* ENGINE_HASHING_CRC32_H */ diff --git a/include/Engine/Hashing/CombinedHash.h b/include/Engine/Hashing/CombinedHash.h new file mode 100644 index 00000000..70e73d02 --- /dev/null +++ b/include/Engine/Hashing/CombinedHash.h @@ -0,0 +1,13 @@ +#ifndef ENGINE_HASHING_COMBINEDHASH_H +#define ENGINE_HASHING_COMBINEDHASH_H + +#include + +class CombinedHash { +public: + static Uint32 EncryptString(char* data); + static Uint32 EncryptString(const char* message); + static Uint32 EncryptData(const void* message, size_t len); +}; + +#endif /* ENGINE_HASHING_COMBINEDHASH_H */ diff --git a/include/Engine/Hashing/FNV1A.h b/include/Engine/Hashing/FNV1A.h new file mode 100644 index 00000000..3ebb594c --- /dev/null +++ b/include/Engine/Hashing/FNV1A.h @@ -0,0 +1,14 @@ +#ifndef ENGINE_HASHING_FNV1A_H +#define ENGINE_HASHING_FNV1A_H + +#include + +class FNV1A { +public: + static Uint32 EncryptString(char* message); + static Uint32 EncryptString(const char* message); + static Uint32 EncryptData(const void* data, size_t size); + static Uint32 EncryptData(const void* data, size_t size, Uint32 hash); +}; + +#endif /* ENGINE_HASHING_FNV1A_H */ diff --git a/include/Engine/Hashing/MD5.h b/include/Engine/Hashing/MD5.h new file mode 100644 index 00000000..61b23314 --- /dev/null +++ b/include/Engine/Hashing/MD5.h @@ -0,0 +1,16 @@ +#ifndef ENGINE_HASHING_MD5_H +#define ENGINE_HASHING_MD5_H + +#include + +class MD5 { +private: + static void* Body(Uint32* pa, Uint32* pb, Uint32* pc, Uint32* pd, void *data, unsigned long size); + +public: + static Uint8* EncryptString(Uint8* dest, char* message); + static Uint8* EncryptString(Uint8* dest, const char* message); + static Uint8* EncryptData(Uint8* dest, void* data, size_t size); +}; + +#endif /* ENGINE_HASHING_MD5_H */ diff --git a/include/Engine/Hashing/Murmur.h b/include/Engine/Hashing/Murmur.h new file mode 100644 index 00000000..5cd300eb --- /dev/null +++ b/include/Engine/Hashing/Murmur.h @@ -0,0 +1,14 @@ +#ifndef ENGINE_HASHING_MURMUR_H +#define ENGINE_HASHING_MURMUR_H + +#include + +class Murmur { +public: + static Uint32 EncryptString(char* message); + static Uint32 EncryptString(const char* message); + static Uint32 EncryptData(const void* data, size_t size); + static Uint32 EncryptData(const void* key, size_t size, Uint32 hash); +}; + +#endif /* ENGINE_HASHING_MURMUR_H */ diff --git a/include/Engine/IO/Compression/Huffman.h b/include/Engine/IO/Compression/Huffman.h new file mode 100644 index 00000000..6a99fee6 --- /dev/null +++ b/include/Engine/IO/Compression/Huffman.h @@ -0,0 +1,11 @@ +#ifndef ENGINE_IO_COMPRESSION_HUFFMAN_H +#define ENGINE_IO_COMPRESSION_HUFFMAN_H + +#include + +class Huffman { +public: + static bool Decompress(uint8_t* in, size_t in_sz, uint8_t* out, size_t out_sz); +}; + +#endif /* ENGINE_IO_COMPRESSION_HUFFMAN_H */ diff --git a/include/Engine/IO/Compression/LZ11.h b/include/Engine/IO/Compression/LZ11.h new file mode 100644 index 00000000..710cc951 --- /dev/null +++ b/include/Engine/IO/Compression/LZ11.h @@ -0,0 +1,11 @@ +#ifndef ENGINE_IO_COMPRESSION_LZ11_H +#define ENGINE_IO_COMPRESSION_LZ11_H + +#include + +class LZ11 { +public: + static bool Decompress(uint8_t* in, size_t in_sz, uint8_t* out, size_t out_sz); +}; + +#endif /* ENGINE_IO_COMPRESSION_LZ11_H */ diff --git a/include/Engine/IO/Compression/LZSS.h b/include/Engine/IO/Compression/LZSS.h new file mode 100644 index 00000000..9a291795 --- /dev/null +++ b/include/Engine/IO/Compression/LZSS.h @@ -0,0 +1,11 @@ +#ifndef ENGINE_IO_COMPRESSION_LZSS_H +#define ENGINE_IO_COMPRESSION_LZSS_H + +#include + +class LZSS { +public: + static bool Decompress(uint8_t* in, size_t in_sz, uint8_t* out, size_t out_sz); +}; + +#endif /* ENGINE_IO_COMPRESSION_LZSS_H */ diff --git a/include/Engine/IO/Compression/RunLength.h b/include/Engine/IO/Compression/RunLength.h new file mode 100644 index 00000000..cac6e61c --- /dev/null +++ b/include/Engine/IO/Compression/RunLength.h @@ -0,0 +1,11 @@ +#ifndef ENGINE_IO_COMPRESSION_RUNLENGTH_H +#define ENGINE_IO_COMPRESSION_RUNLENGTH_H + +#include + +class RunLength { +public: + static bool Decompress(uint8_t* in, size_t in_sz, uint8_t* out, size_t out_sz); +}; + +#endif /* ENGINE_IO_COMPRESSION_RUNLENGTH_H */ diff --git a/include/Engine/IO/Compression/ZLibStream.h b/include/Engine/IO/Compression/ZLibStream.h new file mode 100644 index 00000000..d43d9bd6 --- /dev/null +++ b/include/Engine/IO/Compression/ZLibStream.h @@ -0,0 +1,29 @@ +#ifndef ENGINE_IO_COMPRESSION_ZLIBSTREAM_H +#define ENGINE_IO_COMPRESSION_ZLIBSTREAM_H + +#include +#include + +class ZLibStream : public Stream { +private: + void Decompress(void* in, size_t inLen); + +public: + Stream* other_stream = NULL; + uint32_t mode = 0; + void* memory = NULL; + size_t memory_size = 0; + + static ZLibStream* New(Stream* other_stream, uint32_t mode); + void Close(); + void Seek(Sint64 offset); + void SeekEnd(Sint64 offset); + void Skip(Sint64 offset); + size_t Position(); + size_t Length(); + size_t ReadBytes(void* data, size_t n); + size_t WriteBytes(void* data, size_t n); + static void Decompress(void* dst, size_t dstLen, void* src, size_t srcLen); +}; + +#endif /* ENGINE_IO_COMPRESSION_ZLIBSTREAM_H */ diff --git a/include/Engine/IO/FileStream.h b/include/Engine/IO/FileStream.h new file mode 100644 index 00000000..d85b5da1 --- /dev/null +++ b/include/Engine/IO/FileStream.h @@ -0,0 +1,30 @@ +#ifndef ENGINE_IO_FILESTREAM_H +#define ENGINE_IO_FILESTREAM_H + +#include +#include + +class FileStream : public Stream { +public: + FILE* f; + size_t size; + enum { + READ_ACCESS = 0, + WRITE_ACCESS = 1, + APPEND_ACCESS = 2, + SAVEGAME_ACCESS = 16, + PREFERENCES_ACCESS = 32, + }; + + static FileStream* New(const char* filename, Uint32 access); + void Close(); + void Seek(Sint64 offset); + void SeekEnd(Sint64 offset); + void Skip(Sint64 offset); + size_t Position(); + size_t Length(); + size_t ReadBytes(void* data, size_t n); + size_t WriteBytes(void* data, size_t n); +}; + +#endif /* ENGINE_IO_FILESTREAM_H */ diff --git a/include/Engine/IO/MemoryStream.h b/include/Engine/IO/MemoryStream.h new file mode 100644 index 00000000..763e0be7 --- /dev/null +++ b/include/Engine/IO/MemoryStream.h @@ -0,0 +1,29 @@ +#ifndef ENGINE_IO_MEMORYSTREAM_H +#define ENGINE_IO_MEMORYSTREAM_H + +#include +#include + +class MemoryStream : public Stream { +public: + Uint8* pointer = NULL; + Uint8* pointer_start = NULL; + size_t size = 0; + bool owns_memory = false; + + static MemoryStream* New(size_t size); + static MemoryStream* New(Stream* other); + static MemoryStream* New(void* data, size_t size); + void Close(); + void Seek(Sint64 offset); + void SeekEnd(Sint64 offset); + void Skip(Sint64 offset); + size_t Position(); + size_t Length(); + size_t ReadBytes(void* data, size_t n); + Uint32 ReadCompressed(void* out); + Uint32 ReadCompressed(void* out, size_t outSz); + size_t WriteBytes(void* data, size_t n); +}; + +#endif /* ENGINE_IO_MEMORYSTREAM_H */ diff --git a/include/Engine/IO/NetworkStream.h b/include/Engine/IO/NetworkStream.h new file mode 100644 index 00000000..cbbfe218 --- /dev/null +++ b/include/Engine/IO/NetworkStream.h @@ -0,0 +1,27 @@ +#ifndef ENGINE_IO_NETWORKSTREAM_H +#define ENGINE_IO_NETWORKSTREAM_H + +#include +#include + +class NetworkStream : public Stream { +public: + FILE* f; + size_t size; + enum { + SERVER_SOCKET = 0, + CLIENT_SOCKET = 1, + }; + + static NetworkStream* New(const char* filename, Uint32 access); + void Close(); + void Seek(Sint64 offset); + void SeekEnd(Sint64 offset); + void Skip(Sint64 offset); + size_t Position(); + size_t Length(); + size_t ReadBytes(void* data, size_t n); + size_t WriteBytes(void* data, size_t n); +}; + +#endif /* ENGINE_IO_NETWORKSTREAM_H */ diff --git a/include/Engine/IO/ResourceStream.h b/include/Engine/IO/ResourceStream.h new file mode 100644 index 00000000..a7bda2a7 --- /dev/null +++ b/include/Engine/IO/ResourceStream.h @@ -0,0 +1,24 @@ +#ifndef ENGINE_IO_RESOURCESTREAM_H +#define ENGINE_IO_RESOURCESTREAM_H + +#include +#include + +class ResourceStream : public Stream { +public: + Uint8* pointer = NULL; + Uint8* pointer_start = NULL; + size_t size = 0; + + static ResourceStream* New(const char* filename); + void Close(); + void Seek(Sint64 offset); + void SeekEnd(Sint64 offset); + void Skip(Sint64 offset); + size_t Position(); + size_t Length(); + size_t ReadBytes(void* data, size_t n); + size_t WriteBytes(void* data, size_t n); +}; + +#endif /* ENGINE_IO_RESOURCESTREAM_H */ diff --git a/include/Engine/IO/SDLStream.h b/include/Engine/IO/SDLStream.h new file mode 100644 index 00000000..21be5238 --- /dev/null +++ b/include/Engine/IO/SDLStream.h @@ -0,0 +1,28 @@ +#ifndef ENGINE_IO_SDLSTREAM_H +#define ENGINE_IO_SDLSTREAM_H + +#include +#include +#include + +class SDLStream : public Stream { +public: + SDL_RWops* f; + enum { + READ_ACCESS = 0, + WRITE_ACCESS = 1, + APPEND_ACCESS = 2, + }; + + static SDLStream* New(const char* filename, Uint32 access); + void Close(); + void Seek(Sint64 offset); + void SeekEnd(Sint64 offset); + void Skip(Sint64 offset); + size_t Position(); + size_t Length(); + size_t ReadBytes(void* data, size_t n); + size_t WriteBytes(void* data, size_t n); +}; + +#endif /* ENGINE_IO_SDLSTREAM_H */ diff --git a/include/Engine/IO/Serializer.h b/include/Engine/IO/Serializer.h new file mode 100644 index 00000000..ce008562 --- /dev/null +++ b/include/Engine/IO/Serializer.h @@ -0,0 +1,72 @@ +#ifndef ENGINE_IO_SERIALIZER_H +#define ENGINE_IO_SERIALIZER_H + +#include +#include + +class Serializer { +private: + void WriteValue(VMValue val); + void WriteObject(Obj* obj); + void WriteObjectsChunk(); + void WriteTextChunk(); + Uint32 GetUniqueObjectID(Obj* obj); + void BeginChunk(Uint32 type); + void FinishChunk(); + void AddChunkToList(); + void WriteObjectPreamble(Uint8 type); + void PatchObjectSize(); + void AddUniqueString(char* chars, size_t length); + Uint32 GetUniqueStringID(char* chars, size_t length); + void AddUniqueObject(Obj* obj); + void GetObject(); + void ReadObject(Obj* obj); + VMValue ReadValue(); + +public: + std::map ObjToID; + std::vector ObjList; + Stream* StreamPtr; + size_t StoredStreamPos; + size_t StoredChunkPos; + Uint32 CurrentChunkType; + struct Chunk { + Uint32 Type; + size_t Offset; + size_t Size; + }; + std::vector ChunkList; + Serializer::Chunk LastChunk; + struct String { + Uint32 Length; + char* Chars; + }; + std::vector StringList; + enum { + CHUNK_OBJS = MakeFourCC("OBJS"), + CHUNK_TEXT = MakeFourCC("TEXT") + }; + enum { + VAL_TYPE_NULL, + VAL_TYPE_INTEGER, + VAL_TYPE_DECIMAL, + VAL_TYPE_OBJECT, + END = 0xFF + }; + enum { + OBJ_TYPE_UNIMPLEMENTED, + OBJ_TYPE_STRING, + OBJ_TYPE_ARRAY, + OBJ_TYPE_MAP + }; + static Uint32 Magic; + static Uint32 Version; + + Serializer(Stream* stream); + void Store(VMValue val); + bool ReadObjectsChunk(); + bool ReadTextChunk(); + VMValue Retrieve(); +}; + +#endif /* ENGINE_IO_SERIALIZER_H */ diff --git a/include/Engine/IO/Stream.h b/include/Engine/IO/Stream.h new file mode 100644 index 00000000..b0a92b0a --- /dev/null +++ b/include/Engine/IO/Stream.h @@ -0,0 +1,54 @@ +#ifndef ENGINE_IO_STREAM_H +#define ENGINE_IO_STREAM_H + +#include +#include + +class Stream { +public: + virtual void Close(); + virtual void Seek(Sint64 offset); + virtual void SeekEnd(Sint64 offset); + virtual void Skip(Sint64 offset); + virtual size_t Position(); + virtual size_t Length(); + virtual size_t ReadBytes(void* data, size_t n); + Uint8 ReadByte(); + Uint16 ReadUInt16(); + Uint16 ReadUInt16BE(); + Uint32 ReadUInt32(); + Uint32 ReadUInt32BE(); + Uint64 ReadUInt64(); + Sint16 ReadInt16(); + Sint16 ReadInt16BE(); + Sint32 ReadInt32(); + Sint32 ReadInt32BE(); + Sint64 ReadInt64(); + float ReadFloat(); + char* ReadLine(); + char* ReadString(); + void SkipString(); + Uint16* ReadUnicodeString(); + char* ReadHeaderedString(); + virtual Uint32 ReadCompressed(void* out); + virtual Uint32 ReadCompressed(void* out, size_t outSz); + virtual size_t WriteBytes(void* data, size_t n); + void WriteByte(Uint8 data); + void WriteUInt16(Uint16 data); + void WriteUInt16BE(Uint16 data); + void WriteUInt32(Uint32 data); + void WriteUInt32BE(Uint32 data); + void WriteUInt64(Uint64 data); + void WriteInt16(Sint16 data); + void WriteInt16BE(Sint16 data); + void WriteInt32(Sint32 data); + void WriteInt32BE(Sint32 data); + void WriteInt64(Sint64 data); + void WriteFloat(float data); + void WriteString(const char* string); + void WriteHeaderedString(const char* string); + void CopyTo(Stream* dest); + virtual ~Stream(); +}; + +#endif /* ENGINE_IO_STREAM_H */ diff --git a/include/Engine/Input/Controller.h b/include/Engine/Input/Controller.h new file mode 100644 index 00000000..0f16b1a6 --- /dev/null +++ b/include/Engine/Input/Controller.h @@ -0,0 +1,44 @@ +#ifndef ENGINE_INPUT_CONTROLLER_H +#define ENGINE_INPUT_CONTROLLER_H + +#include +#include +#include +#include + +class Controller { +private: + static ControllerType DetermineType(void* gamecontroller); + +public: + ControllerType Type; + bool Connected; + bool* ButtonsPressed; + bool* ButtonsHeld; + float* AxisValues; + ControllerRumble* Rumble; + SDL_GameController* Device; + SDL_Joystick* JoystickDevice; + SDL_JoystickID JoystickID; + + Controller(int index); + ~Controller(); + bool Open(int index); + void Close(); + void Reset(); + char* GetName(); + void SetPlayerIndex(int index); + bool GetButton(int button); + bool IsButtonHeld(int button); + bool IsButtonPressed(int button); + float GetAxis(int axis); + void Update(); + bool IsXbox(); + bool IsPlayStation(); + bool IsJoyCon(); + bool HasShareButton(); + bool HasMicrophoneButton(); + bool HasPaddles(); +}; + +#endif /* ENGINE_INPUT_CONTROLLER_H */ diff --git a/include/Engine/Input/InputAction.h b/include/Engine/Input/InputAction.h new file mode 100644 index 00000000..24195521 --- /dev/null +++ b/include/Engine/Input/InputAction.h @@ -0,0 +1,16 @@ +#ifndef ENGINE_INPUT_INPUTACTION_H +#define ENGINE_INPUT_INPUTACTION_H + +#include +#include + +class InputAction { +public: + unsigned ID; + string Name; + + InputAction(const char* name, unsigned id); + ~InputAction(); +}; + +#endif /* ENGINE_INPUT_INPUTACTION_H */ diff --git a/include/Engine/Input/InputPlayer.h b/include/Engine/Input/InputPlayer.h new file mode 100644 index 00000000..ef9bddd2 --- /dev/null +++ b/include/Engine/Input/InputPlayer.h @@ -0,0 +1,78 @@ +#ifndef ENGINE_INPUT_INPUTPLAYER_H +#define ENGINE_INPUT_INPUTPLAYER_H + +#include +#include +#include + +class InputPlayer { +private: + size_t PushBindToList(PlayerInputConfig& config, InputBind* def); + bool ReplaceBindInList(PlayerInputConfig& config, InputBind* def, unsigned index); + bool RemoveBindFromList(PlayerInputConfig& config, unsigned index); + InputBind* GetBindAtIndex(PlayerInputConfig& config, unsigned index); + size_t GetBindCount(PlayerInputConfig& config); + void CopyDefaultBinds(InputPlayer& src, bool filter, int filterType); + void ResetBindList(PlayerInputConfig &dest, PlayerInputConfig &src); + bool CheckInputBindState(InputBind* bind, bool held); + bool CheckIfInputHeld(unsigned actionID, unsigned device); + bool CheckIfInputPressed(unsigned actionID, unsigned device); + bool IsControllerBindHeld(unsigned num); + bool IsControllerBindPressed(unsigned num); + void UpdateControllerBind(unsigned num); + bool GetAnalogControllerBind(unsigned num, float& result); + +public: + int ID; + vector Binds; + vector DefaultBinds; + PlayerInputStatus Status[InputDevice_MAX]; + PlayerInputStatus AllStatus; + vector NumHeld; + vector NumPressed; + vector NumReleased; + bool AnyHeld; + bool AnyPressed; + bool AnyReleased; + vector ControllerState; + bool IsUsingDevice[InputDevice_MAX]; + int ControllerIndex = -1; + const char* ConfigFilename = nullptr; + + InputPlayer(int id); + void SetNumActions(size_t num); + void ClearBinds(); + void ResetBinds(); + void Update(); + int AddBind(unsigned num, InputBind* bind); + bool ReplaceBind(unsigned num, InputBind* bind, unsigned index); + bool RemoveBind(unsigned num, unsigned index); + InputBind* GetBind(unsigned num, unsigned index); + size_t GetBindCount(unsigned num); + int AddDefaultBind(unsigned num, InputBind* bind); + void CopyDefaultBinds(InputPlayer& src); + void CopyDefaultBinds(InputPlayer& src, int filterType); + bool ReplaceDefaultBind(unsigned num, InputBind* bind, unsigned index); + bool RemoveDefaultBind(unsigned num, unsigned index); + InputBind* GetDefaultBind(unsigned num, unsigned index); + size_t GetDefaultBindCount(unsigned num); + bool IsBindIndexValid(unsigned num, unsigned index); + void ClearBinds(unsigned num); + void ClearDefaultBinds(unsigned num); + void ResetBind(unsigned num); + bool IsInputHeld(unsigned actionID, unsigned device); + bool IsInputPressed(unsigned actionID, unsigned device); + bool IsInputReleased(unsigned actionID, unsigned device); + bool IsAnyInputHeld(unsigned device); + bool IsAnyInputPressed(unsigned device); + bool IsAnyInputReleased(unsigned device); + bool IsInputHeld(unsigned actionID); + bool IsInputPressed(unsigned actionID); + bool IsInputReleased(unsigned actionID); + bool IsAnyInputHeld(); + bool IsAnyInputPressed(); + bool IsAnyInputReleased(); + float GetAnalogActionInput(unsigned actionID); +}; + +#endif /* ENGINE_INPUT_INPUTPLAYER_H */ diff --git a/include/Engine/InputManager.h b/include/Engine/InputManager.h new file mode 100644 index 00000000..2de33b66 --- /dev/null +++ b/include/Engine/InputManager.h @@ -0,0 +1,120 @@ +#ifndef ENGINE_INPUTMANAGER_H +#define ENGINE_INPUTMANAGER_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class InputManager { +private: + static void InitStringLookup(); + static int FindController(int joystickID); + static void ParsePlayerControls(InputPlayer& player, XMLNode* node); + static Uint16 ParseKeyModifiers(string& str, string& actionName); + static void ParseDefaultInputBinds(InputPlayer& player, int actionID, string& actionName, XMLNode* node); + +public: + static float MouseX; + static float MouseY; + static int MouseDown; + static int MousePressed; + static int MouseReleased; + static Uint8 KeyboardState[0x120]; + static Uint8 KeyboardStateLast[0x120]; + static Uint16 KeymodState; + static SDL_Scancode KeyToSDLScancode[NUM_KEYBOARD_KEYS]; + static int NumControllers; + static vector Controllers; + static SDL_TouchID TouchDevice; + static void* TouchStates; + static vector Players; + static vector Actions; + + static void Init(); + static char* GetKeyName(int key); + static char* GetButtonName(int button); + static char* GetAxisName(int axis); + static int ParseKeyName(const char* key); + static int ParseButtonName(const char* button); + static int ParseAxisName(const char* axis); + static Controller* OpenController(int index); + static void InitControllers(); + static bool AddController(int index); + static void RemoveController(int joystickID); + static void Poll(); + static Uint16 CheckKeyModifiers(Uint16 modifiers); + static bool IsKeyDown(int key); + static bool IsKeyPressed(int key); + static bool IsKeyReleased(int key); + static Controller* GetController(int index); + static bool ControllerIsConnected(int index); + static bool ControllerIsXbox(int index); + static bool ControllerIsPlayStation(int index); + static bool ControllerIsJoyCon(int index); + static bool ControllerHasShareButton(int index); + static bool ControllerHasMicrophoneButton(int index); + static bool ControllerHasPaddles(int index); + static bool ControllerIsButtonHeld(int index, int button); + static bool ControllerIsButtonPressed(int index, int button); + static float ControllerGetAxis(int index, int axis); + static int ControllerGetType(int index); + static char* ControllerGetName(int index); + static void ControllerSetPlayerIndex(int index, int player_index); + static bool ControllerHasRumble(int index); + static bool ControllerIsRumbleActive(int index); + static bool ControllerRumble(int index, float large_frequency, float small_frequency, int duration); + static bool ControllerRumble(int index, float strength, int duration); + static void ControllerStopRumble(int index); + static void ControllerStopRumble(); + static bool ControllerIsRumblePaused(int index); + static void ControllerSetRumblePaused(int index, bool paused); + static bool ControllerSetLargeMotorFrequency(int index, float frequency); + static bool ControllerSetSmallMotorFrequency(int index, float frequency); + static float TouchGetX(int touch_index); + static float TouchGetY(int touch_index); + static bool TouchIsDown(int touch_index); + static bool TouchIsPressed(int touch_index); + static bool TouchIsReleased(int touch_index); + static int AddPlayer(); + static int GetPlayerCount(); + static void SetPlayerControllerIndex(unsigned playerID, int index); + static int GetPlayerControllerIndex(unsigned playerID); + static bool IsActionHeld(unsigned playerID, unsigned actionID); + static bool IsActionPressed(unsigned playerID, unsigned actionID); + static bool IsActionReleased(unsigned playerID, unsigned actionID); + static bool IsAnyActionHeld(unsigned playerID); + static bool IsAnyActionPressed(unsigned playerID); + static bool IsAnyActionReleased(unsigned playerID); + static bool IsActionHeld(unsigned playerID, unsigned actionID, unsigned device); + static bool IsActionPressed(unsigned playerID, unsigned actionID, unsigned device); + static bool IsActionReleased(unsigned playerID, unsigned actionID, unsigned device); + static bool IsAnyActionHeld(unsigned playerID, unsigned device); + static bool IsAnyActionPressed(unsigned playerID, unsigned device); + static bool IsAnyActionReleased(unsigned playerID, unsigned device); + static bool IsPlayerUsingDevice(unsigned playerID, unsigned device); + static float GetAnalogActionInput(unsigned playerID, unsigned actionID); + static InputBind* GetPlayerInputBind(unsigned playerID, unsigned actionID, unsigned index, bool isDefault); + static bool SetPlayerInputBind(unsigned playerID, unsigned actionID, InputBind* bind, unsigned index, bool isDefault); + static int AddPlayerInputBind(unsigned playerID, unsigned actionID, InputBind* bind, bool isDefault); + static bool RemovePlayerInputBind(unsigned playerID, unsigned actionID, unsigned index, bool isDefault); + static int GetPlayerInputBindCount(unsigned playerID, unsigned actionID, bool isDefault); + static void ClearPlayerBinds(unsigned playerID, unsigned actionID, bool isDefault); + static bool IsBindIndexValid(unsigned playerID, unsigned actionID, unsigned index); + static void ResetPlayerBinds(unsigned playerID); + static void ClearPlayers(); + static int RegisterAction(const char* name); + static int GetActionID(const char* name); + static void ClearInputs(); + static void InitPlayerControls(); + static void Dispose(); +}; + +#endif /* ENGINE_INPUTMANAGER_H */ diff --git a/include/Engine/Math/Clipper.h b/include/Engine/Math/Clipper.h new file mode 100644 index 00000000..b6e4e886 --- /dev/null +++ b/include/Engine/Math/Clipper.h @@ -0,0 +1,17 @@ +#ifndef ENGINE_MATH_CLIPPER_H +#define ENGINE_MATH_CLIPPER_H + +#include +#include + +class Clipper { +private: + static void AddPoint(VertexAttribute* buf, VertexAttribute* v1, VertexAttribute* v2, Vector4 p1, Vector4 p2, Sint64 t); + static bool ClipEdge(Frustum frustum, VertexAttribute* v1, VertexAttribute* v2, PolygonClipBuffer* output); + static int ClipPolygon(Frustum frustum, PolygonClipBuffer* output, VertexAttribute* input, int vertexCount); + +public: + static int FrustumClip(PolygonClipBuffer* output, Frustum* frustum, int num, VertexAttribute* input, int vertexCount); +}; + +#endif /* ENGINE_MATH_CLIPPER_H */ diff --git a/include/Engine/Math/Ease.h b/include/Engine/Math/Ease.h new file mode 100644 index 00000000..a926750b --- /dev/null +++ b/include/Engine/Math/Ease.h @@ -0,0 +1,41 @@ +#ifndef ENGINE_MATH_EASE_H +#define ENGINE_MATH_EASE_H + +#include + +class Ease { +public: + static float InSine(float t); + static float OutSine(float t); + static float InOutSine(float t); + static float InQuad(float t); + static float OutQuad(float t); + static float InOutQuad(float t); + static float InCubic(float t); + static float OutCubic(float t); + static float InOutCubic(float t); + static float InQuart(float t); + static float OutQuart(float t); + static float InOutQuart(float t); + static float InQuint(float t); + static float OutQuint(float t); + static float InOutQuint(float t); + static float InExpo(float t); + static float OutExpo(float t); + static float InOutExpo(float t); + static float InCirc(float t); + static float OutCirc(float t); + static float InOutCirc(float t); + static float InBack(float t); + static float OutBack(float t); + static float InOutBack(float t); + static float InElastic(float t); + static float OutElastic(float t); + static float InOutElastic(float t); + static float InBounce(float t); + static float OutBounce(float t); + static float InOutBounce(float t); + static float Triangle(float t); +}; + +#endif /* ENGINE_MATH_EASE_H */ diff --git a/include/Engine/Math/Geometry.h b/include/Engine/Math/Geometry.h new file mode 100644 index 00000000..7ab3db53 --- /dev/null +++ b/include/Engine/Math/Geometry.h @@ -0,0 +1,17 @@ +#ifndef ENGINE_MATH_GEOMETRY_H +#define ENGINE_MATH_GEOMETRY_H + +#include +#include + +class Geometry { +private: + static bool CheckEar(vector& input, unsigned count, unsigned prev, unsigned curr, unsigned next); + static int GetPointForTriangulation(int point, unsigned count); + +public: + static vector* Triangulate(Polygon2D& input, vector holes); + static vector* Intersect(unsigned clipType, unsigned fillRule, vector inputSubjects, vector inputClips); +}; + +#endif /* ENGINE_MATH_GEOMETRY_H */ diff --git a/include/Engine/Math/Math.h b/include/Engine/Math/Math.h new file mode 100644 index 00000000..7a950aae --- /dev/null +++ b/include/Engine/Math/Math.h @@ -0,0 +1,49 @@ +#ifndef ENGINE_MATH_MATH_H +#define ENGINE_MATH_MATH_H + +#include + +class Math { +public: + static void Init(); + static float Cos(float n); + static float Sin(float n); + static float Tan(float n); + static float Asin(float x); + static float Acos(float x); + static float Atan(float x, float y); + static float Distance(float x1, float y1, float x2, float y2); + static float Hypot(float a, float b, float c); + static void ClearTrigLookupTables(); + static void CalculateTrigAngles(); + static int Sin1024(int angle); + static int Cos1024(int angle); + static int Tan1024(int angle); + static int ASin1024(int angle); + static int ACos1024(int angle); + static int Sin512(int angle); + static int Cos512(int angle); + static int Tan512(int angle); + static int ASin512(int angle); + static int ACos512(int angle); + static int Sin256(int angle); + static int Cos256(int angle); + static int Tan256(int angle); + static int ASin256(int angle); + static int ACos256(int angle); + static int CeilPOT(int n); + static float Abs(float n); + static float Max(float a, float b); + static float Min(float a, float b); + static float Clamp(float v, float a, float b); + static float Sign(float a); + static float Random(); + static float RandomMax(float max); + static float RandomRange(float min, float max); + static int RSDK_GetRandSeed(); + static void RSDK_SetRandSeed(int key); + static int RSDK_RandomInteger(int min, int max); + static int RSDK_RandomIntegerSeeded(int min, int max, int seed); +}; + +#endif /* ENGINE_MATH_MATH_H */ diff --git a/include/Engine/Math/Matrix4x4.h b/include/Engine/Math/Matrix4x4.h new file mode 100644 index 00000000..68f73fe6 --- /dev/null +++ b/include/Engine/Math/Matrix4x4.h @@ -0,0 +1,31 @@ +#ifndef ENGINE_MATH_MATRIX4X4_H +#define ENGINE_MATH_MATRIX4X4_H + + +class Matrix4x4 { +public: + float Values[16]; + + static Matrix4x4* Create(); + static void Identity(Matrix4x4* mat4); + static void Perspective(Matrix4x4* out, float fovy, float aspect, float near, float far); + static void Ortho(Matrix4x4* out, float left, float right, float bottom, float top, float near, float far); + static void Copy(Matrix4x4* out, Matrix4x4* a); + static bool Equals(Matrix4x4* a, Matrix4x4* b); + static void Multiply(Matrix4x4* out, Matrix4x4* a, Matrix4x4* b); + static void Multiply(Matrix4x4* mat, float* a); + static void Translate(Matrix4x4* out, Matrix4x4* a, float x, float y, float z); + static void Scale(Matrix4x4* out, Matrix4x4* a, float x, float y, float z); + static void Rotate(Matrix4x4* out, Matrix4x4* a, float rad, float x, float y, float z); + static void IdentityScale(Matrix4x4* out, float x, float y, float z); + static void IdentityRotationX(Matrix4x4* out, float x); + static void IdentityRotationY(Matrix4x4* out, float y); + static void IdentityRotationZ(Matrix4x4* out, float z); + static void IdentityRotationXYZ(Matrix4x4* out, float x, float y, float z); + static void Transpose(Matrix4x4* out); + static void LookAt(Matrix4x4* out, float eyex, float eyey, float eyez, float centerx, float centery, float centerz, float upx, float upy, float upz); + static void Invert(Matrix4x4* out, Matrix4x4* in); + static void Print(Matrix4x4* out); +}; + +#endif /* ENGINE_MATH_MATRIX4X4_H */ diff --git a/include/Engine/Math/Random.h b/include/Engine/Math/Random.h new file mode 100644 index 00000000..8df55a05 --- /dev/null +++ b/include/Engine/Math/Random.h @@ -0,0 +1,16 @@ +#ifndef ENGINE_MATH_RANDOM_H +#define ENGINE_MATH_RANDOM_H + +#include + +class Random { +public: + static Sint32 Seed; + + static void SetSeed(Sint32 seed); + static float Get(); + static float Max(float max); + static float Range(float min, float max); +}; + +#endif /* ENGINE_MATH_RANDOM_H */ diff --git a/include/Engine/Math/Vector.h b/include/Engine/Math/Vector.h new file mode 100644 index 00000000..55a44b87 --- /dev/null +++ b/include/Engine/Math/Vector.h @@ -0,0 +1,24 @@ +#ifndef ENGINE_MATH_VECTOR_H +#define ENGINE_MATH_VECTOR_H + +#include +#include +#include + +class Vector { +public: + static Vector4 Add(Vector4 v1, Vector4 v2); + static Vector4 Subtract(Vector4 v1, Vector4 v2); + static Vector4 Multiply(Vector4 v, Sint64 t); + static Vector3 Multiply(Vector3 v, Matrix4x4* m); + static Vector2 Interpolate(Vector2 v1, Vector2 v2, Sint64 t); + static Vector3 Interpolate(Vector3 v1, Vector3 v2, Sint64 t); + static Vector4 Interpolate(Vector4 v1, Vector4 v2, Sint64 t); + static Sint64 DotProduct(Vector4 v1, Vector4 v2); + static Sint64 Length(Vector4 v); + static Vector4 Normalize(Vector4 v); + static Sint64 IntersectWithPlane(Vector4 plane, Vector4 normal, Vector4 v1, Vector4 v2); + static Sint64 DistanceToPlane(Vector4 v, Vector4 plane, Vector4 normal); +}; + +#endif /* ENGINE_MATH_VECTOR_H */ diff --git a/include/Engine/Media/Decoder.h b/include/Engine/Media/Decoder.h new file mode 100644 index 00000000..254d7ab7 --- /dev/null +++ b/include/Engine/Media/Decoder.h @@ -0,0 +1,56 @@ +#ifndef ENGINE_MEDIA_DECODER_H +#define ENGINE_MEDIA_DECODER_H + +#include +#include +#include +#include +#include +#include +#include + +class Decoder { +public: + bool Successful; + int StreamIndex; + double ClockSync; + double ClockPos; + PtrBuffer* Buffer[2]; + SDL_mutex* OutputLock; + AVCodecContext* CodecCtx; + AVFormatContext* FormatCtx; + Uint32 Format; // SDL_Format + int (*DecodeFunc)(void*, AVPacket*); + void (*CloseFunc)(void*); + + static void FreeInVideoPacketFunc(void* packet); + void Create(MediaSource* src, int stream_index, int outBufferLength, void (*freeOutFunc)(void*), int thread_count); + void Close(); + ~Decoder(); + int Run(); + int GetCodecInfo(Codec* codec); + int GetOutputFormat(OutputFormat* output); + int GetStreamIndex(); + void SetClockSync(double sync); + void ChangeClockSync(double sync); + int WriteInput(AVPacket* packet); + AVPacket* PeekInput(); + AVPacket* ReadInput(); + bool CanWriteInput(); + void AdvanceInput(); + void ClearInput(); + int WriteOutput(void* packet); + void* PeekOutput(); + void* ReadOutput(); + bool CanWriteOutput(); + void AdvanceOutput(); + void ClearOutput(); + void ForEachOutput(void (*cb)(void*, void*), void* userdata); + Uint32 GetInputLength(); + Uint32 GetOutputLength(); + void ClearBuffers(); + int LockOutput(); + void UnlockOutput(); +}; + +#endif /* ENGINE_MEDIA_DECODER_H */ diff --git a/include/Engine/Media/Decoders/AudioDecoder.h b/include/Engine/Media/Decoders/AudioDecoder.h new file mode 100644 index 00000000..d5c485f9 --- /dev/null +++ b/include/Engine/Media/Decoders/AudioDecoder.h @@ -0,0 +1,34 @@ +#ifndef ENGINE_MEDIA_DECODERS_AUDIODECODER_H +#define ENGINE_MEDIA_DECODERS_AUDIODECODER_H + +#include +#include +#include + +class AudioDecoder : public Decoder { +public: + SwrContext* SWR; + AVFrame* ScratchFrame; + int SampleRate; + int Channels; + int Bytes; + int IsSigned; + + AudioDecoder(MediaSource* src, int stream_index); + void* CreateAudioPacket(const char* data, size_t len, double pts); + static void FreeAudioPacket(void* p); + AVSampleFormat FindAVSampleFormat(int format); + Sint64 FindAVChannelLayout(int channels); + int FindChannelLayout(uint64_t channel_layout); + int FindBytes(AVSampleFormat fmt); + int FindSignedness(AVSampleFormat fmt); + int FindSDLSampleFormat(AVSampleFormat fmt); + int GetOutputFormat(OutputFormat* output); + static void ReadAudio(void* ptr); + static int DecodeFunction(void* ptr, AVPacket* in_packet); + static void CloseFunction(void* ptr); + double GetPTS(); + int GetAudioDecoderData(Uint8* buf, int len); +}; + +#endif /* ENGINE_MEDIA_DECODERS_AUDIODECODER_H */ diff --git a/include/Engine/Media/Decoders/VideoDecoder.h b/include/Engine/Media/Decoders/VideoDecoder.h new file mode 100644 index 00000000..d3db76a3 --- /dev/null +++ b/include/Engine/Media/Decoders/VideoDecoder.h @@ -0,0 +1,29 @@ +#ifndef ENGINE_MEDIA_DECODERS_VIDEODECODER_H +#define ENGINE_MEDIA_DECODERS_VIDEODECODER_H + +#include +#include +#include +#include + +class VideoDecoder : public Decoder { +public: + SwsContext* SWS; + AVFrame* ScratchFrame; + int Width; + int Height; + + VideoDecoder(MediaSource* src, int stream_index); + void* CreateVideoPacket(AVFrame* frame, double pts); + static void FreeVideoPacket(void* p); + AVPixelFormat FindAVPixelFormat(Uint32 format); + int FindSDLPixelFormat(AVPixelFormat fmt); + int GetOutputFormat(OutputFormat* output); + static void ReadVideo(void* ptr); + static int DecodeFunction(void* ptr, AVPacket* in_packet); + static void CloseFunction(void* ptr); + double GetPTS(); + int GetVideoDecoderData(Texture* texture); +}; + +#endif /* ENGINE_MEDIA_DECODERS_VIDEODECODER_H */ diff --git a/include/Engine/Media/MediaPlayer.h b/include/Engine/Media/MediaPlayer.h new file mode 100644 index 00000000..f5acce2e --- /dev/null +++ b/include/Engine/Media/MediaPlayer.h @@ -0,0 +1,60 @@ +#ifndef ENGINE_MEDIA_MEDIAPLAYER_H +#define ENGINE_MEDIA_MEDIAPLAYER_H + +#include +#include +#include +#include + +class MediaPlayer { +public: + enum { + KIT_WAITING_TO_BE_PLAYABLE = 0, ///< Playback stopped or has not started yet. + KIT_PLAYING, ///< Playback started & player is actively decoding. + KIT_PAUSED, ///< Playback paused; player is actively decoding but no new data is given out. + KIT_CLOSED, ///< Playback is stopped and player is closing. + KIT_STOPPED, + }; + Uint32 State; + Decoder* Decoders[3]; + SDL_Thread* DecoderThread; + SDL_mutex* DecoderLock; + MediaSource* Source; + double PauseStarted; + double PausedPosition; + double SeekStarted; + Uint32 WaitState; + + static int DemuxAllStreams(MediaPlayer* player); + static int RunAllDecoders(MediaPlayer* player); + static int DecoderThreadFunc(void* ptr); + static MediaPlayer* Create(MediaSource* src, int video_stream_index, int audio_stream_index, int subtitle_stream_index, int screen_w, int screen_h); + void Close(); + void SetScreenSize(int w, int h); + int GetVideoStream(); + int GetAudioStream(); + int GetSubtitleStream(); + void GetInfo(PlayerInfo* info); + double GetDuration(); + double GetPosition(); + double GetBufferPosition(); + bool ManageWaiting(); + int GetVideoData(Texture* texture); + int GetVideoDataForPaused(Texture* texture); + int GetAudioData(unsigned char* buffer, int length); + int GetSubtitleData(Texture* texture, SDL_Rect* sources, SDL_Rect* targets, int limit); + void SetClockSync(); + void SetClockSyncOffset(double offset); + void ChangeClockSync(double delta); + void Play(); + void Stop(); + void Pause(); + int Seek(double seek_set); + Uint32 GetPlayerState(); + bool IsInputEmpty(); + bool IsOutputEmpty(); + static Uint32 GetInputLength(MediaPlayer* player, int i); + static Uint32 GetOutputLength(MediaPlayer* player, int i); +}; + +#endif /* ENGINE_MEDIA_MEDIAPLAYER_H */ diff --git a/include/Engine/Media/MediaSource.h b/include/Engine/Media/MediaSource.h new file mode 100644 index 00000000..5ec6ce9e --- /dev/null +++ b/include/Engine/Media/MediaSource.h @@ -0,0 +1,30 @@ +#ifndef ENGINE_MEDIA_MEDIASOURCE_H +#define ENGINE_MEDIA_MEDIASOURCE_H + +#include +#include +#include + +class MediaSource { +public: + enum { + STREAMTYPE_UNKNOWN, + STREAMTYPE_VIDEO, + STREAMTYPE_AUDIO, + STREAMTYPE_DATA, + STREAMTYPE_SUBTITLE, + STREAMTYPE_ATTACHMENT + }; + void* FormatCtx; + void* AvioCtx; + Stream* StreamPtr; + + static MediaSource* CreateSourceFromUrl(const char* url); + static MediaSource* CreateSourceFromStream(Stream* stream); + int GetStreamInfo(Uint32* info, int index); + int GetStreamCount(); + int GetBestStream(Uint32 type); + void Close(); +}; + +#endif /* ENGINE_MEDIA_MEDIASOURCE_H */ diff --git a/include/Engine/Media/Utils/MediaPlayerState.h b/include/Engine/Media/Utils/MediaPlayerState.h new file mode 100644 index 00000000..f7c059c0 --- /dev/null +++ b/include/Engine/Media/Utils/MediaPlayerState.h @@ -0,0 +1,21 @@ +#ifndef ENGINE_MEDIA_UTILS_MEDIAPLAYERSTATE_H +#define ENGINE_MEDIA_UTILS_MEDIAPLAYERSTATE_H + +#include + +class MediaPlayerState { +public: + static Uint32 InitFlags; + static Uint32 ThreadCount; + static Uint32 FontHinting; + static Uint32 VideoBufFrames; + static Uint32 AudioBufFrames; + static Uint32 SubtitleBufFrames; + static void* LibassHandle; + static void* AssSharedObjectHandle; + + static double GetSystemTime(); + static bool AttachmentIsFont(void* p); +}; + +#endif /* ENGINE_MEDIA_UTILS_MEDIAPLAYERSTATE_H */ diff --git a/include/Engine/Media/Utils/PtrBuffer.h b/include/Engine/Media/Utils/PtrBuffer.h new file mode 100644 index 00000000..fa96941f --- /dev/null +++ b/include/Engine/Media/Utils/PtrBuffer.h @@ -0,0 +1,28 @@ +#ifndef ENGINE_MEDIA_UTILS_PTRBUFFER_H +#define ENGINE_MEDIA_UTILS_PTRBUFFER_H + +#include +#include + +class PtrBuffer { +public: + Uint32 ReadPtr; + Uint32 WritePtr; + Uint32 Size; + void** Data; + void (*FreeFunc)(void*); + + PtrBuffer(Uint32 size, void (*freeFunc)(void*)); + ~PtrBuffer(); + Uint32 GetLength(); + void Clear(); + void* Read(); + void* Peek(); + void Advance(); + int Write(void* ptr); + void ForEachItemInBuffer(void (*callback)(void*, void*), void* userdata); + void WithEachItemInBuffer(std::function callback, void* userdata); + int IsFull(); +}; + +#endif /* ENGINE_MEDIA_UTILS_PTRBUFFER_H */ diff --git a/include/Engine/Media/Utils/RingBuffer.h b/include/Engine/Media/Utils/RingBuffer.h new file mode 100644 index 00000000..d0129aa8 --- /dev/null +++ b/include/Engine/Media/Utils/RingBuffer.h @@ -0,0 +1,26 @@ +#ifndef ENGINE_MEDIA_UTILS_RINGBUFFER_H +#define ENGINE_MEDIA_UTILS_RINGBUFFER_H + +#include + +class RingBuffer { +public: + int Size; + int Length; + int WritePos; + int ReadPos; + char* Data; + + RingBuffer(Uint32 size); + ~RingBuffer(); + int Write(const char* data, int len); + void ReadData(char* data, const int len); + int Read(char* data, int len); + int Peek(char *data, int len); + int Advance(int len); + int GetLength(); + int GetSize(); + int GetFree(); +}; + +#endif /* ENGINE_MEDIA_UTILS_RINGBUFFER_H */ diff --git a/include/Engine/Network/HTTP.h b/include/Engine/Network/HTTP.h new file mode 100644 index 00000000..b627912e --- /dev/null +++ b/include/Engine/Network/HTTP.h @@ -0,0 +1,13 @@ +#ifndef ENGINE_NETWORK_HTTP_H +#define ENGINE_NETWORK_HTTP_H + +#include +#include +#include + +class HTTP { +public: + static bool GET(const char* url, Uint8** outBuf, size_t* outLen, ObjBoundMethod* callback); +}; + +#endif /* ENGINE_NETWORK_HTTP_H */ diff --git a/include/Engine/Network/WebSocketClient.h b/include/Engine/Network/WebSocketClient.h new file mode 100644 index 00000000..658eb724 --- /dev/null +++ b/include/Engine/Network/WebSocketClient.h @@ -0,0 +1,39 @@ +#ifndef ENGINE_NETWORK_WEBSOCKETCLIENT_H +#define ENGINE_NETWORK_WEBSOCKETCLIENT_H + +#include +#include +#include + +class WebSocketClient { +public: + enum { + CLOSING = 0, + CLOSED = 1, + CONNECTING = 2, + OPEN = 3, + }; + std::vector rxbuf; + std::vector txbuf; + std::vector receivedData; + socket_t socket; + int readyState; + bool useMask; + bool isRxBad; + + static WebSocketClient* New(const char* url); + void Poll(int timeout); + void Dispatch(void(*callback)(void* mem, size_t size)); + size_t BytesToRead(); + size_t ReadBytes(void* data, size_t n); + Uint32 ReadUint32(); + Sint32 ReadSint32(); + float ReadFloat(); + char* ReadString(); + void SendData(int type, const void* message, int64_t message_size); + void SendBinary(const void* message, int64_t message_size); + void SendText(const char* message); + void Close(); +}; + +#endif /* ENGINE_NETWORK_WEBSOCKETCLIENT_H */ diff --git a/include/Engine/Rendering/D3D/D3DRenderer.h b/include/Engine/Rendering/D3D/D3DRenderer.h new file mode 100644 index 00000000..0ea9cf20 --- /dev/null +++ b/include/Engine/Rendering/D3D/D3DRenderer.h @@ -0,0 +1,69 @@ +#ifndef ENGINE_RENDERING_D3D_D3DRENDERER_H +#define ENGINE_RENDERING_D3D_D3DRENDERER_H + +#include +#include +#include +#include +#include +#include +#include + +class D3DRenderer { +public: + static void Init(); + static Uint32 GetWindowFlags(); + static void SetVSync(bool enabled); + static void SetGraphicsFunctions(); + static void Dispose(); + static Texture* CreateTexture(Uint32 format, Uint32 access, Uint32 width, Uint32 height); + static int LockTexture(Texture* texture, void** pixels, int* pitch); + static int UpdateTexture(Texture* texture, SDL_Rect* r, void* pixels, int pitch); + static void UnlockTexture(Texture* texture); + static void DisposeTexture(Texture* texture); + static void SetRenderTarget(Texture* texture); + static void UpdateWindowSize(int width, int height); + static void UpdateViewport(); + static void UpdateClipRect(); + static void UpdateOrtho(float left, float top, float right, float bottom); + static void UpdatePerspective(float fovy, float aspect, float nearv, float farv); + static void UpdateProjectionMatrix(); + static void MakePerspectiveMatrix(Matrix4x4* out, float fov, float near, float far, float aspect); + static void UseShader(void* shader); + static void SetUniformF(int location, int count, float* values); + static void SetUniformI(int location, int count, int* values); + static void SetUniformTexture(Texture* texture, int uniform_index, int slot); + static void Clear(); + static void Present(); + static void SetBlendColor(float r, float g, float b, float a); + static void SetBlendMode(int srcC, int dstC, int srcA, int dstA); + static void SetTintColor(float r, float g, float b, float a); + static void SetTintMode(int mode); + static void SetTintEnabled(bool enabled); + static void SetLineWidth(float n); + static void StrokeLine(float x1, float y1, float x2, float y2); + static void StrokeCircle(float x, float y, float rad, float thickness); + static void StrokeEllipse(float x, float y, float w, float h); + static void StrokeRectangle(float x, float y, float w, float h); + static void FillCircle(float x, float y, float rad); + static void FillEllipse(float x, float y, float w, float h); + static void FillTriangle(float x1, float y1, float x2, float y2, float x3, float y3); + static void FillRectangle(float x, float y, float w, float h); + static void DrawTexture(Texture* texture, float sx, float sy, float sw, float sh, float x, float y, float w, float h); + static void DrawSprite(ISprite* sprite, int animation, int frame, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID); + static void DrawSpritePart(ISprite* sprite, int animation, int frame, int sx, int sy, int sw, int sh, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID); + static void DrawPolygon3D(void* data, int vertexCount, int vertexFlag, Texture* texture, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static void DrawSceneLayer3D(void* layer, int sx, int sy, int sw, int sh, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static void DrawModel(void* model, Uint16 animation, Uint32 frame, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static void DrawModelSkinned(void* model, Uint16 armature, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static void DrawVertexBuffer(Uint32 vertexBufferIndex, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static void BindVertexBuffer(Uint32 vertexBufferIndex); + static void UnbindVertexBuffer(); + static void BindScene3D(Uint32 sceneIndex); + static void ClearScene3D(Uint32 sceneIndex); + static void DrawScene3D(Uint32 sceneIndex, Uint32 drawMode); + static Uint32 CreateTexturedShapeBuffer(float** data, int vertexCount); + static void DrawTexturedShapeBuffer(Texture* texture, Uint32 bufferID, int vertexCount); +}; + +#endif /* ENGINE_RENDERING_D3D_D3DRENDERER_H */ diff --git a/include/Engine/Rendering/FaceInfo.h b/include/Engine/Rendering/FaceInfo.h new file mode 100644 index 00000000..5bea6a49 --- /dev/null +++ b/include/Engine/Rendering/FaceInfo.h @@ -0,0 +1,25 @@ +#ifndef ENGINE_RENDERING_FACEINFO_H +#define ENGINE_RENDERING_FACEINFO_H + +#include +#include +#include +#include + +class FaceInfo { +public: + Uint32 DrawMode; + Uint32 NumVertices; + Uint32 VerticesStartIndex; + bool UseMaterial; + FaceMaterial MaterialInfo; + BlendState Blend; + Uint8 CullMode; + int Depth; + + void SetMaterial(Material* material); + void SetMaterial(Texture* texture); + void SetBlendState(BlendState blendState); +}; + +#endif /* ENGINE_RENDERING_FACEINFO_H */ diff --git a/include/Engine/Rendering/GL/GLRenderer.h b/include/Engine/Rendering/GL/GLRenderer.h new file mode 100644 index 00000000..89dbbfe0 --- /dev/null +++ b/include/Engine/Rendering/GL/GLRenderer.h @@ -0,0 +1,92 @@ +#ifndef ENGINE_RENDERING_GL_GLRENDERER_H +#define ENGINE_RENDERING_GL_GLRENDERER_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class GLRenderer { +public: + static SDL_GLContext Context; + static GLShader* CurrentShader; + static GLShaderContainer* ShaderShape; + static GLShaderContainer* ShaderShape3D; + static GLShaderContainer* ShaderFogLinear; + static GLShaderContainer* ShaderFogExp; + static GLShaderContainer* ShaderYUV; + static GLint DefaultFramebuffer; + static GLint DefaultRenderbuffer; + static GLuint BufferCircleFill; + static GLuint BufferCircleStroke; + static GLuint BufferSquareFill; + + static void Init(); + static Uint32 GetWindowFlags(); + static void SetVSync(bool enabled); + static void SetGraphicsFunctions(); + static void Dispose(); + static Texture* CreateTexture(Uint32 format, Uint32 access, Uint32 width, Uint32 height); + static int LockTexture(Texture* texture, void** pixels, int* pitch); + static int UpdateTexture(Texture* texture, SDL_Rect* src, void* pixels, int pitch); + static int UpdateTextureYUV(Texture* texture, SDL_Rect* src, void* pixelsY, int pitchY, void* pixelsU, int pitchU, void* pixelsV, int pitchV); + static void UnlockTexture(Texture* texture); + static void DisposeTexture(Texture* texture); + static void SetRenderTarget(Texture* texture); + static void ReadFramebuffer(void* pixels, int width, int height); + static void UpdateWindowSize(int width, int height); + static void UpdateViewport(); + static void UpdateClipRect(); + static void UpdateOrtho(float left, float top, float right, float bottom); + static void UpdatePerspective(float fovy, float aspect, float nearv, float farv); + static void UpdateProjectionMatrix(); + static void MakePerspectiveMatrix(Matrix4x4* out, float fov, float near, float far, float aspect); + static void UseShader(void* shader); + static void SetUniformF(int location, int count, float* values); + static void SetUniformI(int location, int count, int* values); + static void SetUniformTexture(Texture* texture, int uniform_index, int slot); + static void UpdateGlobalPalette(); + static void Clear(); + static void Present(); + static void SetBlendColor(float r, float g, float b, float a); + static void SetBlendMode(int srcC, int dstC, int srcA, int dstA); + static void SetTintColor(float r, float g, float b, float a); + static void SetTintMode(int mode); + static void SetTintEnabled(bool enabled); + static void SetLineWidth(float n); + static void StrokeLine(float x1, float y1, float x2, float y2); + static void StrokeCircle(float x, float y, float rad, float thickness); + static void StrokeEllipse(float x, float y, float w, float h); + static void StrokeRectangle(float x, float y, float w, float h); + static void FillCircle(float x, float y, float rad); + static void FillEllipse(float x, float y, float w, float h); + static void FillTriangle(float x1, float y1, float x2, float y2, float x3, float y3); + static void FillRectangle(float x, float y, float w, float h); + static Uint32 CreateTexturedShapeBuffer(float* data, int vertexCount); + static void DrawTexturedShapeBuffer(Texture* texture, Uint32 bufferID, int vertexCount); + static void DrawTexture(Texture* texture, float sx, float sy, float sw, float sh, float x, float y, float w, float h); + static void DrawSprite(ISprite* sprite, int animation, int frame, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID); + static void DrawSpritePart(ISprite* sprite, int animation, int frame, int sx, int sy, int sw, int sh, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID); + static void DrawPolygon3D(void* data, int vertexCount, int vertexFlag, Texture* texture, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static void DrawSceneLayer3D(void* layer, int sx, int sy, int sw, int sh, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static void DrawModel(void* inModel, Uint16 animation, Uint32 frame, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static void DrawModelSkinned(void* inModel, Uint16 armature, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static void DrawVertexBuffer(Uint32 vertexBufferIndex, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static void BindVertexBuffer(Uint32 vertexBufferIndex); + static void UnbindVertexBuffer(); + static void ClearScene3D(Uint32 sceneIndex); + static void DrawScene3D(Uint32 sceneIndex, Uint32 drawMode); + static void* CreateVertexBuffer(Uint32 maxVertices); + static void DeleteVertexBuffer(void* vtxBuf); + static void MakeFrameBufferID(ISprite* sprite, AnimFrame* frame); + static void DeleteFrameBufferID(AnimFrame* frame); + static void SetDepthTesting(bool enable); +}; + +#endif /* ENGINE_RENDERING_GL_GLRENDERER_H */ diff --git a/include/Engine/Rendering/GL/GLShader.h b/include/Engine/Rendering/GL/GLShader.h new file mode 100644 index 00000000..329f4700 --- /dev/null +++ b/include/Engine/Rendering/GL/GLShader.h @@ -0,0 +1,50 @@ +#ifndef ENGINE_RENDERING_GL_GLSHADER_H +#define ENGINE_RENDERING_GL_GLSHADER_H + +#include +#include +#include +#include + +class GLShader { +private: + void AttachAndLink(); + +public: + GLuint ProgramID = 0; + GLuint VertexProgramID = 0; + GLuint FragmentProgramID = 0; + GLint LocProjectionMatrix; + GLint LocModelViewMatrix; + GLint LocPosition; + GLint LocTexCoord; + GLint LocTexture; + GLint LocTextureU; + GLint LocTextureV; + GLint LocPalette; + GLint LocColor; + GLint LocVaryingColor; + GLint LocFogColor; + GLint LocFogLinearStart; + GLint LocFogLinearEnd; + GLint LocFogDensity; + GLint LocFogTable; + char FilenameV[256]; + char FilenameF[256]; + // Cache stuff + float CachedBlendColors[4]; + Matrix4x4* CachedProjectionMatrix = NULL; + Matrix4x4* CachedModelViewMatrix = NULL; + + GLShader(std::string vertexShaderSource, std::string fragmentShaderSource); + GLShader(Stream* streamVS, Stream* streamFS); + bool CheckShaderError(GLuint shader); + bool CheckProgramError(GLuint prog); + GLuint Use(); + GLint GetAttribLocation(const GLchar* identifier); + GLint GetUniformLocation(const GLchar* identifier); + ~GLShader(); + static bool CheckGLError(int line); +}; + +#endif /* ENGINE_RENDERING_GL_GLSHADER_H */ diff --git a/include/Engine/Rendering/GL/GLShaderBuilder.h b/include/Engine/Rendering/GL/GLShaderBuilder.h new file mode 100644 index 00000000..0a46ba5c --- /dev/null +++ b/include/Engine/Rendering/GL/GLShaderBuilder.h @@ -0,0 +1,21 @@ +#ifndef ENGINE_RENDERING_GL_GLSHADERBUILDER_H +#define ENGINE_RENDERING_GL_GLSHADERBUILDER_H + +#include +#include + +class GLShaderBuilder { +private: + static void AddUniformsToShaderText(std::string& shaderText, GLShaderUniforms uniforms); + static void AddInputsToVertexShaderText(std::string& shaderText, GLShaderLinkage inputs); + static void AddOutputsToVertexShaderText(std::string& shaderText, GLShaderLinkage outputs); + static void AddInputsToFragmentShaderText(std::string& shaderText, GLShaderLinkage& inputs); + static string BuildFragmentShaderMainFunc(GLShaderLinkage& inputs, GLShaderUniforms& uniforms); + +public: + static string Vertex(GLShaderLinkage& inputs, GLShaderLinkage& outputs, GLShaderUniforms& uniforms); + static string Fragment(GLShaderLinkage& inputs, GLShaderUniforms& uniforms, std::string mainText); + static string Fragment(GLShaderLinkage& inputs, GLShaderUniforms& uniforms); +}; + +#endif /* ENGINE_RENDERING_GL_GLSHADERBUILDER_H */ diff --git a/include/Engine/Rendering/GL/GLShaderContainer.h b/include/Engine/Rendering/GL/GLShaderContainer.h new file mode 100644 index 00000000..a5b79edf --- /dev/null +++ b/include/Engine/Rendering/GL/GLShaderContainer.h @@ -0,0 +1,27 @@ +#ifndef ENGINE_RENDERING_GL_GLSHADERCONTAINER_H +#define ENGINE_RENDERING_GL_GLSHADERCONTAINER_H +class GLShader; +class GLShader; +class GLShader; + +#include +#include + +class GLShaderContainer { +public: + GLShader *Base = nullptr; + GLShader *Textured = nullptr; + GLShader *PalettizedTextured = nullptr; + + GLShaderContainer(); + GLShaderContainer(GLShaderLinkage vsIn, GLShaderLinkage vsOut, GLShaderLinkage fsIn, GLShaderUniforms vsUni, GLShaderUniforms fsUni); + GLShader* Get(bool useTexturing, bool usePalette); + GLShader* Get(bool useTexturing); + GLShader* Get(); + static GLShaderContainer* Make(bool use_vertex_colors); + static GLShaderContainer* MakeFog(int fog_type); + static GLShaderContainer* MakeYUV(); + ~GLShaderContainer(); +}; + +#endif /* ENGINE_RENDERING_GL_GLSHADERCONTAINER_H */ diff --git a/include/Engine/Rendering/GameTexture.h b/include/Engine/Rendering/GameTexture.h new file mode 100644 index 00000000..587de07e --- /dev/null +++ b/include/Engine/Rendering/GameTexture.h @@ -0,0 +1,20 @@ +#ifndef ENGINE_RENDERING_GAMETEXTURE_H +#define ENGINE_RENDERING_GAMETEXTURE_H + +#include +#include + +class GameTexture { +public: + Texture* TexturePtr = nullptr; + int UnloadPolicy; + bool OwnsTexture = true; + + GameTexture(); + GameTexture(Uint32 width, Uint32 height, int unloadPolicy); + virtual Texture* GetTexture(); + virtual int GetID(); + ~GameTexture(); +}; + +#endif /* ENGINE_RENDERING_GAMETEXTURE_H */ diff --git a/include/Engine/Rendering/Material.h b/include/Engine/Rendering/Material.h new file mode 100644 index 00000000..d9c6feb6 --- /dev/null +++ b/include/Engine/Rendering/Material.h @@ -0,0 +1,31 @@ +#ifndef ENGINE_RENDERING_MATERIAL_H +#define ENGINE_RENDERING_MATERIAL_H + +#include +#include + +class Material { +public: + char* Name = nullptr; + float ColorDiffuse[4]; + float ColorSpecular[4]; + float ColorAmbient[4]; + float ColorEmissive[4]; + float Shininess = 0.0f; + float ShininessStrength = 1.0f; + float Opacity = 1.0f; + char* TextureDiffuseName = nullptr; + char* TextureSpecularName = nullptr; + char* TextureAmbientName = nullptr; + char* TextureEmissiveName = nullptr; + Image* TextureDiffuse = nullptr; + Image* TextureSpecular = nullptr; + Image* TextureAmbient = nullptr; + Image* TextureEmissive = nullptr; + + Material(); + void Dispose(); + ~Material(); +}; + +#endif /* ENGINE_RENDERING_MATERIAL_H */ diff --git a/include/Engine/Rendering/ModelRenderer.h b/include/Engine/Rendering/ModelRenderer.h new file mode 100644 index 00000000..a73cf6f3 --- /dev/null +++ b/include/Engine/Rendering/ModelRenderer.h @@ -0,0 +1,48 @@ +#ifndef ENGINE_RENDERING_MODELRENDERER_H +#define ENGINE_RENDERING_MODELRENDERER_H +class Matrix4x4; + +#include +#include +#include +#include +#include +#include +#include + +class ModelRenderer { +private: + void Init(); + void AddFace(int faceVertexCount, Material* material); + int ClipFace(int faceVertexCount); + void DrawMesh(IModel* model, Mesh* mesh, Skeleton* skeleton, Matrix4x4& mvpMatrix); + void DrawMesh(IModel* model, Mesh* mesh, Uint16 animation, Uint32 frame, Matrix4x4& mvpMatrix); + void DrawMesh(IModel* model, Mesh* mesh, Vector3* positionBuffer, Vector3* normalBuffer, Vector2* uvBuffer, Matrix4x4& mvpMatrix); + void DrawNode(IModel* model, ModelNode* node, Matrix4x4* world); + void DrawModelInternal(IModel* model, Uint16 animation, Uint32 frame); + +public: + PolygonRenderer* PolyRenderer; + VertexBuffer* Buffer; + VertexAttribute* AttribBuffer; + VertexAttribute* Vertex; + FaceInfo* FaceItem; + Matrix4x4* ModelMatrix; + Matrix4x4* ViewMatrix; + Matrix4x4* ProjectionMatrix; + Matrix4x4* NormalMatrix; + Matrix4x4 MVPMatrix; + bool DoProjection; + bool ClipFaces; + Armature* ArmaturePtr; + Uint32 DrawMode; + Uint8 FaceCullMode; + Uint32 CurrentColor; + + ModelRenderer(PolygonRenderer* polyRenderer); + ModelRenderer(VertexBuffer* buffer); + void SetMatrices(Matrix4x4* model, Matrix4x4* view, Matrix4x4* projection, Matrix4x4* normal); + void DrawModel(IModel* model, Uint16 animation, Uint32 frame); +}; + +#endif /* ENGINE_RENDERING_MODELRENDERER_H */ diff --git a/include/Engine/Rendering/PolygonRenderer.h b/include/Engine/Rendering/PolygonRenderer.h new file mode 100644 index 00000000..f017f567 --- /dev/null +++ b/include/Engine/Rendering/PolygonRenderer.h @@ -0,0 +1,43 @@ +#ifndef ENGINE_RENDERING_POLYGONRENDERER_H +#define ENGINE_RENDERING_POLYGONRENDERER_H + +#include +#include +#include +#include +#include +#include +#include +#include + +class PolygonRenderer { +public: + Scene3D* ScenePtr = nullptr; + VertexBuffer* VertexBuf = nullptr; + Matrix4x4* ModelMatrix = nullptr; + Matrix4x4* NormalMatrix = nullptr; + Matrix4x4* ViewMatrix = nullptr; + Matrix4x4* ProjectionMatrix = nullptr; + Uint32 DrawMode = 0; + Uint8 FaceCullMode = 0; + Uint32 CurrentColor = 0; + bool DoProjection = false; + bool DoClipping = false; + bool ClipPolygonsByFrustum = false; + int NumFrustumPlanes = 0; + Frustum ViewFrustum[NUM_FRUSTUM_PLANES]; + + static int FaceSortFunction(const void *a, const void *b); + void BuildFrustumPlanes(float nearClippingPlane, float farClippingPlane); + bool SetBuffers(); + void DrawPolygon3D(VertexAttribute* data, int vertexCount, int vertexFlag, Texture* texture); + void DrawSceneLayer3D(SceneLayer* layer, int sx, int sy, int sw, int sh); + void DrawModel(IModel* model, Uint16 animation, Uint32 frame); + void DrawModelSkinned(IModel* model, Uint16 armature); + void DrawVertexBuffer(); + int ClipPolygon(PolygonClipBuffer& clipper, VertexAttribute* input, int numVertices); + static bool CheckPolygonVisible(VertexAttribute* vertex, int vertexCount); + static void CopyVertices(VertexAttribute* buffer, VertexAttribute* output, int numVertices); +}; + +#endif /* ENGINE_RENDERING_POLYGONRENDERER_H */ diff --git a/include/Engine/Rendering/SDL2/SDL2Renderer.h b/include/Engine/Rendering/SDL2/SDL2Renderer.h new file mode 100644 index 00000000..1640f051 --- /dev/null +++ b/include/Engine/Rendering/SDL2/SDL2Renderer.h @@ -0,0 +1,65 @@ +#ifndef ENGINE_RENDERING_SDL2_SDL2RENDERER_H +#define ENGINE_RENDERING_SDL2_SDL2RENDERER_H + +#include +#include +#include +#include +#include +#include + +class SDL2Renderer { +private: + static SDL_BlendMode GetCustomBlendMode(int srcC, int dstC, int srcA, int dstA); + +public: + static float RenderScale; + + static void Init(); + static Uint32 GetWindowFlags(); + static void SetVSync(bool enabled); + static void SetGraphicsFunctions(); + static void Dispose(); + static Texture* CreateTexture(Uint32 format, Uint32 access, Uint32 width, Uint32 height); + static int LockTexture(Texture* texture, void** pixels, int* pitch); + static int UpdateTexture(Texture* texture, SDL_Rect* src, void* pixels, int pitch); + static int UpdateTextureYUV(Texture* texture, SDL_Rect* src, void* pixelsY, int pitchY, void* pixelsU, int pitchU, void* pixelsV, int pitchV); + static void UnlockTexture(Texture* texture); + static void DisposeTexture(Texture* texture); + static void SetRenderTarget(Texture* texture); + static void CopyScreen(void* pixels, int width, int height); + static void UpdateWindowSize(int width, int height); + static void UpdateViewport(); + static void UpdateClipRect(); + static void UpdateOrtho(float left, float top, float right, float bottom); + static void UpdatePerspective(float fovy, float aspect, float nearv, float farv); + static void UpdateProjectionMatrix(); + static void MakePerspectiveMatrix(Matrix4x4* out, float fov, float near, float far, float aspect); + static void GetMetalSize(int* width, int* height); + static void UseShader(void* shader); + static void SetUniformF(int location, int count, float* values); + static void SetUniformI(int location, int count, int* values); + static void SetUniformTexture(Texture* texture, int uniform_index, int slot); + static void Clear(); + static void Present(); + static void SetBlendColor(float r, float g, float b, float a); + static void SetBlendMode(int srcC, int dstC, int srcA, int dstA); + static void SetTintColor(float r, float g, float b, float a); + static void SetTintMode(int mode); + static void SetTintEnabled(bool enabled); + static void SetLineWidth(float n); + static void StrokeLine(float x1, float y1, float x2, float y2); + static void StrokeCircle(float x, float y, float rad, float thickness); + static void StrokeEllipse(float x, float y, float w, float h); + static void StrokeRectangle(float x, float y, float w, float h); + static void FillCircle(float x, float y, float rad); + static void FillEllipse(float x, float y, float w, float h); + static void FillTriangle(float x1, float y1, float x2, float y2, float x3, float y3); + static void FillRectangle(float x, float y, float w, float h); + static void DrawTexture(Texture* texture, float sx, float sy, float sw, float sh, float x, float y, float w, float h); + static void DrawSprite(ISprite* sprite, int animation, int frame, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID); + static void DrawSpritePart(ISprite* sprite, int animation, int frame, int sx, int sy, int sw, int sh, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID); + static void MakeFrameBufferID(ISprite* sprite, AnimFrame* frame); +}; + +#endif /* ENGINE_RENDERING_SDL2_SDL2RENDERER_H */ diff --git a/include/Engine/Rendering/Shader.h b/include/Engine/Rendering/Shader.h new file mode 100644 index 00000000..f7a6ab5f --- /dev/null +++ b/include/Engine/Rendering/Shader.h @@ -0,0 +1,11 @@ +#ifndef ENGINE_RENDERING_SHADER_H +#define ENGINE_RENDERING_SHADER_H + +#include + +class Shader { +public: + static Shader* New(); +}; + +#endif /* ENGINE_RENDERING_SHADER_H */ diff --git a/include/Engine/Rendering/Software/PolygonRasterizer.h b/include/Engine/Rendering/Software/PolygonRasterizer.h new file mode 100644 index 00000000..263acb54 --- /dev/null +++ b/include/Engine/Rendering/Software/PolygonRasterizer.h @@ -0,0 +1,44 @@ +#ifndef ENGINE_RENDERING_SOFTWARE_POLYGONRASTERIZER_H +#define ENGINE_RENDERING_SOFTWARE_POLYGONRASTERIZER_H + +#include +#include +#include +#include + +class PolygonRasterizer { +public: + static bool DepthTest; + static size_t DepthBufferSize; + static Uint32* DepthBuffer; + static bool UseDepthBuffer; + static bool UseFog; + static float FogStart; + static float FogEnd; + static float FogDensity; + static int FogColor; + static Uint16 FogTable[0x100 + 1]; + + static void DrawBasic(Vector2* positions, Uint32 color, int count, BlendState blendState); + static void DrawBasicBlend(Vector2* positions, int* colors, int count, BlendState blendState); + static void DrawShaded(Vector3* positions, Uint32 color, int count, BlendState blendState); + static void DrawBlendShaded(Vector3* positions, int* colors, int count, BlendState blendState); + static void DrawAffine(Texture* texture, Vector3* positions, Vector2* uvs, Uint32 color, int count, BlendState blendState); + static void DrawBlendAffine(Texture* texture, Vector3* positions, Vector2* uvs, int* colors, int count, BlendState blendState); + static void DrawPerspective(Texture* texture, Vector3* positions, Vector2* uvs, Uint32 color, int count, BlendState blendState); + static void DrawBlendPerspective(Texture* texture, Vector3* positions, Vector2* uvs, int* colors, int count, BlendState blendState); + static void DrawDepth(Vector3* positions, Uint32 color, int count, BlendState blendState); + static void DrawBlendDepth(Vector3* positions, int* colors, int count, BlendState blendState); + static void SetDepthTest(bool enabled); + static void FreeDepthBuffer(void); + static void SetUseDepthBuffer(bool enabled); + static void SetUseFog(bool enabled); + static void SetFogEquation(FogEquation equation); + static void SetFogStart(float start); + static void SetFogEnd(float end); + static void SetFogDensity(float density); + static void SetFogColor(float r, float g, float b); + static void SetFogSmoothness(float smoothness); +}; + +#endif /* ENGINE_RENDERING_SOFTWARE_POLYGONRASTERIZER_H */ diff --git a/include/Engine/Rendering/Software/Scanline.h b/include/Engine/Rendering/Software/Scanline.h new file mode 100644 index 00000000..2577fefb --- /dev/null +++ b/include/Engine/Rendering/Software/Scanline.h @@ -0,0 +1,22 @@ +#ifndef ENGINE_RENDERING_SOFTWARE_SCANLINE_H +#define ENGINE_RENDERING_SOFTWARE_SCANLINE_H + +#include +#include +#include +#include + +class Scanline { +public: + static void Prepare(int y1, int y2); + static void Process(int x1, int y1, int x2, int y2); + static void Process(int color1, int color2, int x1, int y1, int x2, int y2); + static void ProcessDepth(int x1, int y1, int z1, int x2, int y2, int z2); + static void ProcessDepth(int color1, int color2, int x1, int y1, int z1, int x2, int y2, int z2); + static void ProcessUVAffine(Vector2 uv1, Vector2 uv2, int x1, int y1, int z1, int x2, int y2, int z2); + static void ProcessUVAffine(int color1, int color2, Vector2 uv1, Vector2 uv2, int x1, int y1, int z1, int x2, int y2, int z2); + static void ProcessUV(Vector2 uv1, Vector2 uv2, int x1, int y1, int z1, int x2, int y2, int z2); + static void ProcessUV(int color1, int color2, Vector2 uv1, Vector2 uv2, int x1, int y1, int z1, int x2, int y2, int z2); +}; + +#endif /* ENGINE_RENDERING_SOFTWARE_SCANLINE_H */ diff --git a/include/Engine/Rendering/Software/SoftwareRenderer.h b/include/Engine/Rendering/Software/SoftwareRenderer.h new file mode 100644 index 00000000..0b74667c --- /dev/null +++ b/include/Engine/Rendering/Software/SoftwareRenderer.h @@ -0,0 +1,147 @@ +#ifndef ENGINE_RENDERING_SOFTWARE_SOFTWARERENDERER_H +#define ENGINE_RENDERING_SOFTWARE_SOFTWARERENDERER_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class SoftwareRenderer { +private: + static void SetColor(Uint32 color); + static Uint32 GetBlendColor(); + static bool SetupPolygonRenderer(Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static void InitContour(Contour *contourBuffer, int dst_y1, int scanLineCount); + static void RasterizeCircle(int ccx, int ccy, int dst_x1, int dst_y1, int dst_x2, int dst_y2, float rad, Contour *contourBuffer); + static void StrokeThickCircle(float x, float y, float rad, float thickness); + static void DrawShapeTextured(Texture* texturePtr, unsigned numPoints, float* px, float* py, int* pc, float* pu, float* pv); + +public: + static GraphicsFunctions BackendFunctions; + static Uint32 CompareColor; + static TileScanLine TileScanLineBuffer[MAX_FRAMEBUFFER_HEIGHT]; + static Sint32 SpriteDeformBuffer[MAX_FRAMEBUFFER_HEIGHT]; + static bool UseSpriteDeform; + static Contour ContourBuffer[MAX_FRAMEBUFFER_HEIGHT]; + static int MultTable[0x10000]; + static int MultTableInv[0x10000]; + static int MultSubTable[0x10000]; + + static void Init(); + static Uint32 GetWindowFlags(); + static void SetGraphicsFunctions(); + static void Dispose(); + static void RenderStart(); + static void RenderEnd(); + static Texture* CreateTexture(Uint32 format, Uint32 access, Uint32 width, Uint32 height); + static int LockTexture(Texture* texture, void** pixels, int* pitch); + static int UpdateTexture(Texture* texture, SDL_Rect* src, void* pixels, int pitch); + static void UnlockTexture(Texture* texture); + static void DisposeTexture(Texture* texture); + static void SetRenderTarget(Texture* texture); + static void ReadFramebuffer(void* pixels, int width, int height); + static void UpdateWindowSize(int width, int height); + static void UpdateViewport(); + static void UpdateClipRect(); + static void UpdateOrtho(float left, float top, float right, float bottom); + static void UpdatePerspective(float fovy, float aspect, float nearv, float farv); + static void UpdateProjectionMatrix(); + static void MakePerspectiveMatrix(Matrix4x4* out, float fov, float near, float far, float aspect); + static void UseShader(void* shader); + static void SetUniformF(int location, int count, float* values); + static void SetUniformI(int location, int count, int* values); + static void SetUniformTexture(Texture* texture, int uniform_index, int slot); + static void SetFilter(int filter); + static void Clear(); + static void Present(); + static void SetBlendColor(float r, float g, float b, float a); + static void SetBlendMode(int srcC, int dstC, int srcA, int dstA); + static void SetTintColor(float r, float g, float b, float a); + static void SetTintMode(int mode); + static void SetTintEnabled(bool enabled); + static void Resize(int width, int height); + static void SetClip(float x, float y, float width, float height); + static void ClearClip(); + static void Save(); + static void Translate(float x, float y, float z); + static void Rotate(float x, float y, float z); + static void Scale(float x, float y, float z); + static void Restore(); + static int ConvertBlendMode(int blendMode); + static BlendState GetBlendState(); + static bool AlterBlendState(BlendState& state); + static void PixelNoFiltSetOpaque(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt); + static void PixelNoFiltSetTransparent(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt); + static void PixelNoFiltSetAdditive(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt); + static void PixelNoFiltSetSubtract(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt); + static void PixelNoFiltSetMatchEqual(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt); + static void PixelNoFiltSetMatchNotEqual(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt); + static void PixelTintSetOpaque(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt); + static void PixelTintSetTransparent(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt); + static void PixelTintSetAdditive(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt); + static void PixelTintSetSubtract(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt); + static void PixelTintSetMatchEqual(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt); + static void PixelTintSetMatchNotEqual(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt); + static void SetTintFunction(int blendFlags); + static void SetStencilEnabled(bool enabled); + static bool IsStencilEnabled(); + static void SetStencilTestFunc(int stencilTest); + static void SetStencilPassFunc(int stencilOp); + static void SetStencilFailFunc(int stencilOp); + static void SetStencilValue(int value); + static void SetStencilMask(int mask); + static void ClearStencil(); + static void PixelStencil(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt); + static void SetDotMask(int mask); + static void SetDotMaskH(int mask); + static void SetDotMaskV(int mask); + static void SetDotMaskOffsetH(int offset); + static void SetDotMaskOffsetV(int offset); + static void PixelDotMaskH(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt); + static void PixelDotMaskV(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt); + static void PixelDotMaskHV(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt); + static void BindVertexBuffer(Uint32 vertexBufferIndex); + static void UnbindVertexBuffer(); + static void BindScene3D(Uint32 sceneIndex); + static void DrawScene3D(Uint32 sceneIndex, Uint32 drawMode); + static void DrawPolygon3D(void* data, int vertexCount, int vertexFlag, Texture* texture, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static void DrawSceneLayer3D(void* layer, int sx, int sy, int sw, int sh, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static void DrawModel(void* model, Uint16 animation, Uint32 frame, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static void DrawModelSkinned(void* model, Uint16 armature, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static void DrawVertexBuffer(Uint32 vertexBufferIndex, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix); + static PixelFunction GetPixelFunction(int blendFlag); + static void SetLineWidth(float n); + static void StrokeLine(float x1, float y1, float x2, float y2); + static void StrokeCircle(float x, float y, float rad, float thickness); + static void StrokeEllipse(float x, float y, float w, float h); + static void StrokeRectangle(float x, float y, float w, float h); + static void FillCircle(float x, float y, float rad); + static void FillEllipse(float x, float y, float w, float h); + static void FillRectangle(float x, float y, float w, float h); + static void FillTriangle(float x1, float y1, float x2, float y2, float x3, float y3); + static void FillTriangleBlend(float x1, float y1, float x2, float y2, float x3, float y3, int c1, int c2, int c3); + static void FillQuad(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4); + static void FillQuadBlend(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, int c1, int c2, int c3, int c4); + static void DrawTriangleTextured(Texture* texturePtr, float x1, float y1, float x2, float y2, float x3, float y3, int c1, int c2, int c3, float u1, float v1, float u2, float v2, float u3, float v3); + static void DrawQuadTextured(Texture* texturePtr, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, int c1, int c2, int c3, int c4, float u1, float v1, float u2, float v2, float u3, float v3, float u4, float v4); + static void DrawTexture(Texture* texture, float sx, float sy, float sw, float sh, float x, float y, float w, float h); + static void DrawSprite(ISprite* sprite, int animation, int frame, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID); + static void DrawSpritePart(ISprite* sprite, int animation, int frame, int sx, int sy, int sw, int sh, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID); + static void DrawTile(int tile, int x, int y, bool flipX, bool flipY); + static void DrawSceneLayer_InitTileScanLines(SceneLayer* layer, View* currentView); + static void DrawSceneLayer_HorizontalParallax(SceneLayer* layer, View* currentView); + static void DrawSceneLayer_VerticalParallax(SceneLayer* layer, View* currentView); + static void DrawSceneLayer_CustomTileScanLines(SceneLayer* layer, View* currentView); + static void DrawSceneLayer(SceneLayer* layer, View* currentView, int layerIndex, bool useCustomFunction); + static void MakeFrameBufferID(ISprite* sprite, AnimFrame* frame); +}; + +#endif /* ENGINE_RENDERING_SOFTWARE_SOFTWARERENDERER_H */ diff --git a/include/Engine/Rendering/Texture.h b/include/Engine/Rendering/Texture.h new file mode 100644 index 00000000..c9ce37a3 --- /dev/null +++ b/include/Engine/Rendering/Texture.h @@ -0,0 +1,31 @@ +#ifndef ENGINE_RENDERING_TEXTURE_H +#define ENGINE_RENDERING_TEXTURE_H +class Texture; + +#include + +class Texture { +public: + Uint32 Format; + Uint32 Access; + Uint32 Width; + Uint32 Height; + void* Pixels; + int Pitch; + Uint32 ID; + void* DriverData; + Texture* Prev; + Texture* Next; + bool Paletted; + Uint32* PaletteColors; + unsigned NumPaletteColors; + + static Texture* New(Uint32 format, Uint32 access, Uint32 width, Uint32 height); + void SetPalette(Uint32* palette, unsigned numPaletteColors); + bool ConvertToRGBA(); + bool ConvertToPalette(Uint32 *palColors, unsigned numPaletteColors); + void Copy(Texture* source); + void Dispose(); +}; + +#endif /* ENGINE_RENDERING_TEXTURE_H */ diff --git a/include/Engine/Rendering/TextureReference.h b/include/Engine/Rendering/TextureReference.h new file mode 100644 index 00000000..f826bbb8 --- /dev/null +++ b/include/Engine/Rendering/TextureReference.h @@ -0,0 +1,17 @@ +#ifndef ENGINE_RENDERING_TEXTUREREFERENCE_H +#define ENGINE_RENDERING_TEXTUREREFERENCE_H +class Texture; + +#include + +class TextureReference { +public: + Texture* TexturePtr; + unsigned References; + + TextureReference(Texture *ptr); + void AddRef(); + bool TakeRef(); +}; + +#endif /* ENGINE_RENDERING_TEXTUREREFERENCE_H */ diff --git a/include/Engine/Rendering/VertexBuffer.h b/include/Engine/Rendering/VertexBuffer.h new file mode 100644 index 00000000..1b553b49 --- /dev/null +++ b/include/Engine/Rendering/VertexBuffer.h @@ -0,0 +1,26 @@ +#ifndef ENGINE_RENDERING_VERTEXBUFFER_H +#define ENGINE_RENDERING_VERTEXBUFFER_H + +#include +#include +#include + +class VertexBuffer { +public: + VertexAttribute* Vertices = nullptr; // count = max vertex count + FaceInfo* FaceInfoBuffer = nullptr; // count = max face count + void* DriverData = nullptr; + Uint32 Capacity = 0; + Uint32 VertexCount = 0; + Uint32 FaceCount = 0; + Uint32 UnloadPolicy; + + VertexBuffer(); + VertexBuffer(Uint32 numVertices); + void Init(Uint32 numVertices); + void Clear(); + void Resize(Uint32 numVertices); + ~VertexBuffer(); +}; + +#endif /* ENGINE_RENDERING_VERTEXBUFFER_H */ diff --git a/include/Engine/Rendering/ViewTexture.h b/include/Engine/Rendering/ViewTexture.h new file mode 100644 index 00000000..cf3baad4 --- /dev/null +++ b/include/Engine/Rendering/ViewTexture.h @@ -0,0 +1,16 @@ +#ifndef ENGINE_RENDERING_VIEWTEXTURE_H +#define ENGINE_RENDERING_VIEWTEXTURE_H + +#include +#include + +class ViewTexture : public GameTexture { +public: + int ViewIndex; + + ViewTexture(int viewIndex); + virtual Texture* GetTexture(); + virtual int GetID(); +}; + +#endif /* ENGINE_RENDERING_VIEWTEXTURE_H */ diff --git a/include/Engine/ResourceTypes/IModel.h b/include/Engine/ResourceTypes/IModel.h new file mode 100644 index 00000000..586649d7 --- /dev/null +++ b/include/Engine/ResourceTypes/IModel.h @@ -0,0 +1,54 @@ +#ifndef ENGINE_RESOURCETYPES_IMODEL_H +#define ENGINE_RESOURCETYPES_IMODEL_H + +#include +#include +#include +#include +#include +#include + +class IModel { +private: + static Image* TryLoadMaterialImage(std::string imagePath, const char *parentDirectory); + void UpdateChannel(Matrix4x4* out, NodeAnim* channel, Uint32 frame); + +public: + Mesh** Meshes; + size_t MeshCount; + size_t VertexCount; + size_t VertexIndexCount; + Uint8 VertexPerFace; + Material** Materials; + size_t MaterialCount; + ModelAnim** Animations; + size_t AnimationCount; + Armature** ArmatureList; + size_t ArmatureCount; + bool UseVertexAnimation; + Armature* BaseArmature; + Matrix4x4* GlobalInverseMatrix; + + IModel(); + IModel(const char* filename); + bool Load(Stream* stream, const char* filename); + bool HasMaterials(); + static Image* LoadMaterialImage(string imagePath, const char *parentDirectory); + static Image* LoadMaterialImage(const char *imagePath, const char *parentDirectory); + bool HasBones(); + void AnimateNode(ModelNode* node, SkeletalAnim* animation, Uint32 frame, Matrix4x4* parentMatrix); + void Pose(); + void Pose(Armature* armature, SkeletalAnim* animation, Uint32 frame); + Uint32 GetKeyFrame(Uint32 frame); + Sint64 GetInBetween(Uint32 frame); + void DoVertexFrameInterpolation(Mesh* mesh, ModelAnim* animation, Uint32 frame, Vector3** positionBuffer, Vector3** normalBuffer, Vector2** uvBuffer); + void Animate(Armature* armature, ModelAnim* animation, Uint32 frame); + void Animate(Uint16 animation, Uint32 frame); + int GetAnimationIndex(const char* animationName); + int NewArmature(); + void DeleteArmature(size_t index); + void Dispose(); + ~IModel(); +}; + +#endif /* ENGINE_RESOURCETYPES_IMODEL_H */ diff --git a/include/Engine/ResourceTypes/ISound.h b/include/Engine/ResourceTypes/ISound.h new file mode 100644 index 00000000..c591116a --- /dev/null +++ b/include/Engine/ResourceTypes/ISound.h @@ -0,0 +1,26 @@ +#ifndef ENGINE_RESOURCETYPES_ISOUND_H +#define ENGINE_RESOURCETYPES_ISOUND_H + +#include +#include +#include +#include +#include + +class ISound { +public: + SDL_AudioSpec Format; + int BytesPerSample; + SoundFormat* SoundData = NULL; + char Filename[256]; + bool LoadFailed = false; + bool StreamFromFile = false; + + ISound(const char* filename); + ISound(const char* filename, bool streamFromFile); + void Load(const char* filename, bool streamFromFile); + AudioPlayback* CreatePlayer(); + void Dispose(); +}; + +#endif /* ENGINE_RESOURCETYPES_ISOUND_H */ diff --git a/include/Engine/ResourceTypes/ISprite.h b/include/Engine/ResourceTypes/ISprite.h new file mode 100644 index 00000000..857fc2cc --- /dev/null +++ b/include/Engine/ResourceTypes/ISprite.h @@ -0,0 +1,37 @@ +#ifndef ENGINE_RESOURCETYPES_ISPRITE_H +#define ENGINE_RESOURCETYPES_ISPRITE_H + +#include +#include +#include + +class ISprite { +public: + char* Filename = nullptr; + bool LoadFailed = true; + vector Spritesheets; + vector SpritesheetFilenames; + int CollisionBoxCount = 0; + vector Animations; + + ISprite(); + ISprite(const char* filename); + Texture* AddSpriteSheet(const char* filename); + void ReserveAnimationCount(int count); + void AddAnimation(const char* name, int animationSpeed, int frameToLoop); + void AddAnimation(const char* name, int animationSpeed, int frameToLoop, int frmAlloc); + void AddFrame(int duration, int left, int top, int width, int height, int pivotX, int pivotY); + void AddFrame(int duration, int left, int top, int width, int height, int pivotX, int pivotY, int id); + void AddFrame(int animID, int duration, int left, int top, int width, int height, int pivotX, int pivotY, int id); + void RemoveFrames(int animID); + void ConvertToRGBA(); + void ConvertToPalette(unsigned paletteNumber); + bool LoadAnimation(const char* filename); + int FindAnimation(const char* animname); + void LinkAnimation(vector ani); + bool SaveAnimation(const char* filename); + void Dispose(); + ~ISprite(); +}; + +#endif /* ENGINE_RESOURCETYPES_ISPRITE_H */ diff --git a/include/Engine/ResourceTypes/Image.h b/include/Engine/ResourceTypes/Image.h new file mode 100644 index 00000000..b9c2f1d8 --- /dev/null +++ b/include/Engine/ResourceTypes/Image.h @@ -0,0 +1,18 @@ +#ifndef ENGINE_RESOURCETYPES_IMAGE_H +#define ENGINE_RESOURCETYPES_IMAGE_H + +#include +#include + +class Image { +public: + char Filename[256]; + Texture* TexturePtr = NULL; + + Image(const char* filename); + void Dispose(); + ~Image(); + static Texture* LoadTextureFromResource(const char* filename); +}; + +#endif /* ENGINE_RESOURCETYPES_IMAGE_H */ diff --git a/include/Engine/ResourceTypes/ImageFormats/GIF.h b/include/Engine/ResourceTypes/ImageFormats/GIF.h new file mode 100644 index 00000000..fcf35e50 --- /dev/null +++ b/include/Engine/ResourceTypes/ImageFormats/GIF.h @@ -0,0 +1,26 @@ +#ifndef ENGINE_RESOURCETYPES_IMAGEFORMATS_GIF_H +#define ENGINE_RESOURCETYPES_IMAGEFORMATS_GIF_H + +#include +#include +#include + +class GIF : public ImageFormat { +private: + static inline Uint32 ReadCode(Stream* stream, int codeSize, int* blockLength, int* bitCache, int* bitCacheLength); + static inline void WriteCode(Stream* stream, int* offset, int* partial, Uint8* buffer, uint16_t key, int key_size); + inline void WriteFrame(Stream* stream, Uint32* data); + static void* NewNode(Uint16 key, int degree); + static void* NewTree(int degree, int* nkeys); + static void FreeTree(void* root, int degree); + +public: + vector Frames; + + static GIF* Load(const char* filename); + static bool Save(GIF* gif, const char* filename); + bool Save(const char* filename); + ~GIF(); +}; + +#endif /* ENGINE_RESOURCETYPES_IMAGEFORMATS_GIF_H */ diff --git a/include/Engine/ResourceTypes/ImageFormats/ImageFormat.h b/include/Engine/ResourceTypes/ImageFormats/ImageFormat.h new file mode 100644 index 00000000..5866feeb --- /dev/null +++ b/include/Engine/ResourceTypes/ImageFormats/ImageFormat.h @@ -0,0 +1,20 @@ +#ifndef ENGINE_RESOURCETYPES_IMAGEFORMATS_IMAGEFORMAT_H +#define ENGINE_RESOURCETYPES_IMAGEFORMATS_IMAGEFORMAT_H + +#include + +class ImageFormat { +public: + Uint32* Colors = NULL; + Uint32* Data = NULL; + Uint32 Width = 0; + Uint32 Height = 0; + bool Paletted = false; + Uint16 NumPaletteColors = 0; + + Uint32* GetPalette(); + virtual bool Save(const char* filename); + virtual ~ImageFormat(); +}; + +#endif /* ENGINE_RESOURCETYPES_IMAGEFORMATS_IMAGEFORMAT_H */ diff --git a/include/Engine/ResourceTypes/ImageFormats/JPEG.h b/include/Engine/ResourceTypes/ImageFormats/JPEG.h new file mode 100644 index 00000000..df1010eb --- /dev/null +++ b/include/Engine/ResourceTypes/ImageFormats/JPEG.h @@ -0,0 +1,16 @@ +#ifndef ENGINE_RESOURCETYPES_IMAGEFORMATS_JPEG_H +#define ENGINE_RESOURCETYPES_IMAGEFORMATS_JPEG_H + +#include +#include +#include + +class JPEG : public ImageFormat { +public: + static JPEG* Load(const char* filename); + static bool Save(JPEG* jpeg, const char* filename); + bool Save(const char* filename); + ~JPEG(); +}; + +#endif /* ENGINE_RESOURCETYPES_IMAGEFORMATS_JPEG_H */ diff --git a/include/Engine/ResourceTypes/ImageFormats/PNG.h b/include/Engine/ResourceTypes/ImageFormats/PNG.h new file mode 100644 index 00000000..24b51a7a --- /dev/null +++ b/include/Engine/ResourceTypes/ImageFormats/PNG.h @@ -0,0 +1,18 @@ +#ifndef ENGINE_RESOURCETYPES_IMAGEFORMATS_PNG_H +#define ENGINE_RESOURCETYPES_IMAGEFORMATS_PNG_H + +#include +#include +#include + +class PNG : public ImageFormat { +public: + static PNG* Load(const char* filename); + void ReadPixelDataARGB(Uint32* pixelData, int num_channels); + void ReadPixelBitstream(Uint8* pixelData, size_t bit_depth); + static bool Save(PNG* png, const char* filename); + bool Save(const char* filename); + ~PNG(); +}; + +#endif /* ENGINE_RESOURCETYPES_IMAGEFORMATS_PNG_H */ diff --git a/include/Engine/ResourceTypes/ModelFormats/HatchModel.h b/include/Engine/ResourceTypes/ModelFormats/HatchModel.h new file mode 100644 index 00000000..9bd5a5ee --- /dev/null +++ b/include/Engine/ResourceTypes/ModelFormats/HatchModel.h @@ -0,0 +1,42 @@ +#ifndef ENGINE_RESOURCETYPES_MODELFORMATS_HATCHMODEL_H +#define ENGINE_RESOURCETYPES_MODELFORMATS_HATCHMODEL_H + +#include +#include + +class HatchModel { +private: + static Material* ReadMaterial(Stream* stream, const char *parentDirectory); + static void ReadVertexStore(Stream* stream); + static void ReadNormalStore(Stream* stream); + static void ReadTexCoordStore(Stream* stream); + static void ReadColorStore(Stream* stream); + static Vector3 GetStoredVertex(Uint32 idx); + static Vector3 GetStoredNormal(Uint32 idx); + static Vector2 GetStoredTexCoord(Uint32 idx); + static Uint32 GetStoredColor(Uint32 idx); + static void ReadVertexIndices(Sint32* indices, Uint32 triangleCount, Stream* stream); + static Mesh* ReadMesh(IModel* model, Stream* stream); + static void WriteMesh(Mesh* mesh, Stream* stream); + static char* GetMaterialTextureName(const char* name, const char* parentDirectory); + static void WriteColorIndex(Uint32* color, Stream* stream); + static void WriteMaterial(Material* material, Stream* stream, const char* parentDirectory); + +public: + static Sint32 Version; + static Uint32 NumVertexStore; + static Uint32 NumNormalStore; + static Uint32 NumTexCoordStore; + static Uint32 NumColorStore; + static Vector3* VertexStore; + static Vector3* NormalStore; + static Vector2* TexCoordStore; + static Uint32* ColorStore; + + static bool IsMagic(Stream* stream); + static void ReadMaterialInfo(Stream* stream, Uint8 *destColors, char **texName); + static bool Convert(IModel* model, Stream* stream, const char* path); + static bool Save(IModel* model, const char* filename); +}; + +#endif /* ENGINE_RESOURCETYPES_MODELFORMATS_HATCHMODEL_H */ diff --git a/include/Engine/ResourceTypes/ModelFormats/Importer.h b/include/Engine/ResourceTypes/ModelFormats/Importer.h new file mode 100644 index 00000000..c9013643 --- /dev/null +++ b/include/Engine/ResourceTypes/ModelFormats/Importer.h @@ -0,0 +1,24 @@ +#ifndef ENGINE_RESOURCETYPES_MODELFORMATS_IMPORTER_H +#define ENGINE_RESOURCETYPES_MODELFORMATS_IMPORTER_H + +#include +#include +#include + +class ModelImporter { +private: + static Mesh* LoadMesh(IModel* imodel, struct aiMesh* amesh); + static Material* LoadMaterial(IModel* imodel, struct aiMaterial* mat, unsigned i); + static ModelNode* LoadNode(IModel* imodel, ModelNode* parent, const struct aiNode* anode); + static Skeleton* LoadBones(IModel* imodel, Mesh* mesh, struct aiMesh* amesh); + static SkeletalAnim* LoadAnimation(IModel* imodel, ModelAnim* parentAnim, struct aiAnimation* aanim); + static bool DoConversion(const struct aiScene* scene, IModel* imodel); + +public: + static vector MeshIDs; + static char* ParentDirectory; + + static bool Convert(IModel* model, Stream* stream, const char* path); +}; + +#endif /* ENGINE_RESOURCETYPES_MODELFORMATS_IMPORTER_H */ diff --git a/include/Engine/ResourceTypes/ModelFormats/MD3Model.h b/include/Engine/ResourceTypes/ModelFormats/MD3Model.h new file mode 100644 index 00000000..ff9b214a --- /dev/null +++ b/include/Engine/ResourceTypes/ModelFormats/MD3Model.h @@ -0,0 +1,26 @@ +#ifndef ENGINE_RESOURCETYPES_MODELFORMATS_MD3MODEL_H +#define ENGINE_RESOURCETYPES_MODELFORMATS_MD3MODEL_H + +#include +#include + +class MD3Model { +private: + static void DecodeNormal(Uint16 index, float& x, float& y, float& z); + static void ReadShader(Stream* stream); + static void ReadVerticesAndNormals(Vector3* vert, Vector3* norm, Sint32 vertexCount, Stream* stream); + static void ReadUVs(Vector2* uvs, Sint32 vertexCount, Stream* stream); + static void ReadVertexIndices(Sint32* indices, Sint32 triangleCount, Stream* stream); + static Mesh* ReadSurface(IModel* model, Stream* stream, size_t surfaceDataOffset); + +public: + static Sint32 Version; + static bool UseUVKeyframes; + static Sint32 DataEndOffset; + static vector MaterialNames; + + static bool IsMagic(Stream* stream); + static bool Convert(IModel* model, Stream* stream, const char* path); +}; + +#endif /* ENGINE_RESOURCETYPES_MODELFORMATS_MD3MODEL_H */ diff --git a/include/Engine/ResourceTypes/ModelFormats/RSDKModel.h b/include/Engine/ResourceTypes/ModelFormats/RSDKModel.h new file mode 100644 index 00000000..edc947e2 --- /dev/null +++ b/include/Engine/ResourceTypes/ModelFormats/RSDKModel.h @@ -0,0 +1,13 @@ +#ifndef ENGINE_RESOURCETYPES_MODELFORMATS_RSDKMODEL_H +#define ENGINE_RESOURCETYPES_MODELFORMATS_RSDKMODEL_H + +#include +#include + +class RSDKModel { +public: + static bool IsMagic(Stream* stream); + static bool Convert(IModel* model, Stream* stream); +}; + +#endif /* ENGINE_RESOURCETYPES_MODELFORMATS_RSDKMODEL_H */ diff --git a/include/Engine/ResourceTypes/ResourceManager.h b/include/Engine/ResourceTypes/ResourceManager.h new file mode 100644 index 00000000..97bb4ab2 --- /dev/null +++ b/include/Engine/ResourceTypes/ResourceManager.h @@ -0,0 +1,21 @@ +#ifndef ENGINE_RESOURCETYPES_RESOURCEMANAGER_H +#define ENGINE_RESOURCETYPES_RESOURCEMANAGER_H + +#include +#include + +class ResourceManager { +public: + static bool UsingDataFolder; + static bool UsingModPack; + + static void PrefixResourcePath(char* out, size_t outSize, const char* path); + static void PrefixParentPath(char* out, size_t outSize, const char* path); + static void Init(const char* filename); + static void Load(const char* filename); + static bool LoadResource(const char* filename, Uint8** out, size_t* size); + static bool ResourceExists(const char* filename); + static void Dispose(); +}; + +#endif /* ENGINE_RESOURCETYPES_RESOURCEMANAGER_H */ diff --git a/include/Engine/ResourceTypes/SceneFormats/HatchSceneReader.h b/include/Engine/ResourceTypes/SceneFormats/HatchSceneReader.h new file mode 100644 index 00000000..9f8fa02b --- /dev/null +++ b/include/Engine/ResourceTypes/SceneFormats/HatchSceneReader.h @@ -0,0 +1,31 @@ +#ifndef ENGINE_RESOURCETYPES_SCENEFORMATS_HATCHSCENEREADER_H +#define ENGINE_RESOURCETYPES_SCENEFORMATS_HATCHSCENEREADER_H + +#include +#include +#include + +class HatchSceneReader { +private: + static SceneLayer ReadLayer(Stream* r); + static void ReadTileData(Stream* r, SceneLayer layer); + static void ConvertTileData(SceneLayer* layer); + static void ReadScrollData(Stream* r, SceneLayer layer); + static SceneClass* FindClass(SceneHash hash); + static SceneClassProperty* FindProperty(SceneClass* scnClass, SceneHash hash); + static void HashString(char* string, SceneHash* hash); + static void ReadClasses(Stream *r); + static void FreeClasses(); + static bool LoadTileset(const char* parentFolder); + static void ReadEntities(Stream *r); + static void SkipEntityProperties(Stream *r, Uint8 numProps); + static void SkipProperty(Stream *r, Uint8 varType); + +public: + static Uint32 Magic; + + static bool Read(const char* filename, const char* parentFolder); + static bool Read(Stream* r, const char* parentFolder); +}; + +#endif /* ENGINE_RESOURCETYPES_SCENEFORMATS_HATCHSCENEREADER_H */ diff --git a/include/Engine/ResourceTypes/SceneFormats/RSDKSceneReader.h b/include/Engine/ResourceTypes/SceneFormats/RSDKSceneReader.h new file mode 100644 index 00000000..3bbd35bd --- /dev/null +++ b/include/Engine/ResourceTypes/SceneFormats/RSDKSceneReader.h @@ -0,0 +1,25 @@ +#ifndef ENGINE_RESOURCETYPES_SCENEFORMATS_RSDKSCENEREADER_H +#define ENGINE_RESOURCETYPES_SCENEFORMATS_RSDKSCENEREADER_H + +#include +#include + +class RSDKSceneReader { +private: + static void LoadObjectList(); + static void LoadPropertyList(); + static SceneLayer ReadLayer(Stream* r); + static bool LoadTileset(const char* parentFolder); + +public: + static Uint32 Magic; + static bool Initialized; + + static void StageConfig_GetColors(const char* filename); + static void GameConfig_GetColors(const char* filename); + static bool Read(const char* filename, const char* parentFolder); + static bool ReadObjectDefinition(Stream* r, Entity** objSlots, const int maxObjSlots); + static bool Read(Stream* r, const char* parentFolder); +}; + +#endif /* ENGINE_RESOURCETYPES_SCENEFORMATS_RSDKSCENEREADER_H */ diff --git a/include/Engine/ResourceTypes/SceneFormats/TiledMapReader.h b/include/Engine/ResourceTypes/SceneFormats/TiledMapReader.h new file mode 100644 index 00000000..6db3355d --- /dev/null +++ b/include/Engine/ResourceTypes/SceneFormats/TiledMapReader.h @@ -0,0 +1,25 @@ +#ifndef ENGINE_RESOURCETYPES_SCENEFORMATS_TILEDMAPREADER_H +#define ENGINE_RESOURCETYPES_SCENEFORMATS_TILEDMAPREADER_H + +#include +#include + +class TiledMapReader { +private: + static VMValue ParseProperty(XMLNode* property); + static void ParsePropertyNode(XMLNode* node, HashMap* properties); + static ObjArray* ParsePolyPoints(XMLNode* node); + static Tileset* ParseTilesetImage(XMLNode* node, int firstgid, const char* parentFolder); + static void ParseTileAnimation(int tileID, int firstgid, Tileset* tilesetPtr, XMLNode* node); + static void ParseTile(Tileset* tilesetPtr, XMLNode* node); + static void LoadTileset(XMLNode* tileset, const char* parentFolder); + static bool ParseLayer(XMLNode* group); + static bool ParseObjectGroup(XMLNode* group); + static bool ParseGroupable(XMLNode* group); + static bool ParseGroup(XMLNode* group); + +public: + static void Read(const char* sourceF, const char* parentFolder); +}; + +#endif /* ENGINE_RESOURCETYPES_SCENEFORMATS_TILEDMAPREADER_H */ diff --git a/include/Engine/ResourceTypes/SoundFormats/OGG.h b/include/Engine/ResourceTypes/SoundFormats/OGG.h new file mode 100644 index 00000000..23a61cec --- /dev/null +++ b/include/Engine/ResourceTypes/SoundFormats/OGG.h @@ -0,0 +1,28 @@ +#ifndef ENGINE_RESOURCETYPES_SOUNDFORMATS_OGG_H +#define ENGINE_RESOURCETYPES_SOUNDFORMATS_OGG_H + +#include +#include +#include + +class OGG : public SoundFormat { +private: + // OGG Specific + char Vorbis[0x800]; + + static size_t StaticRead(void* mem, size_t size, size_t nmemb, void* ptr); + static Sint32 StaticSeek(void* ptr, Sint64 offset, int whence); + static Sint32 StaticCloseFree(void* ptr); + static Sint32 StaticCloseNoFree(void* ptr); + static long StaticTell(void* ptr); + +public: + static SoundFormat* Load(const char* filename); + size_t SeekSample(int index); + int LoadSamples(size_t count); + int GetSamples(Uint8* buffer, size_t count, Sint32 loopIndex); + virtual void LoadAllSamples(); + void Dispose(); +}; + +#endif /* ENGINE_RESOURCETYPES_SOUNDFORMATS_OGG_H */ diff --git a/include/Engine/ResourceTypes/SoundFormats/SoundFormat.h b/include/Engine/ResourceTypes/SoundFormats/SoundFormat.h new file mode 100644 index 00000000..1510ac50 --- /dev/null +++ b/include/Engine/ResourceTypes/SoundFormats/SoundFormat.h @@ -0,0 +1,35 @@ +#ifndef ENGINE_RESOURCETYPES_SOUNDFORMATS_SOUNDFORMAT_H +#define ENGINE_RESOURCETYPES_SOUNDFORMATS_SOUNDFORMAT_H + +#include +#include +#include + +class SoundFormat { +public: + // Common + Stream* StreamPtr = NULL; + SDL_AudioSpec InputFormat; + vector Samples; + size_t SampleSize; + size_t SampleIndex = 0; + int TotalPossibleSamples; + Uint8* SampleBuffer = NULL; + + virtual int LoadSamples(size_t count); + virtual int GetSamples(Uint8* buffer, size_t count, Sint32 loopIndex); + virtual size_t SeekSample(int index); + virtual size_t TellSample(); + virtual void LoadAllSamples(); + void CopySamples(SoundFormat* dest); + virtual double GetPosition(); + virtual double SetPosition(double seconds); + virtual double GetDuration(); + virtual ~SoundFormat(); + virtual void Close(); + virtual void Dispose(); +protected: + void LoadFinish(); +}; + +#endif /* ENGINE_RESOURCETYPES_SOUNDFORMATS_SOUNDFORMAT_H */ diff --git a/include/Engine/ResourceTypes/SoundFormats/WAV.h b/include/Engine/ResourceTypes/SoundFormats/WAV.h new file mode 100644 index 00000000..487803a4 --- /dev/null +++ b/include/Engine/ResourceTypes/SoundFormats/WAV.h @@ -0,0 +1,20 @@ +#ifndef ENGINE_RESOURCETYPES_SOUNDFORMATS_WAV_H +#define ENGINE_RESOURCETYPES_SOUNDFORMATS_WAV_H + +#include +#include +#include + +class WAV : public SoundFormat { +private: + // WAV Specific + int DataStart = 0; + + +public: + static SoundFormat* Load(const char* filename); + int LoadSamples(size_t count); + void Dispose(); +}; + +#endif /* ENGINE_RESOURCETYPES_SOUNDFORMATS_WAV_H */ diff --git a/include/Engine/Scene.h b/include/Engine/Scene.h new file mode 100644 index 00000000..4532012c --- /dev/null +++ b/include/Engine/Scene.h @@ -0,0 +1,204 @@ +#ifndef ENGINE_SCENE_H +#define ENGINE_SCENE_H +class Entity; + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class Scene { +private: + static void RemoveObject(Entity* obj); + static void RunTileAnimations(); + static void ResetViews(); + static void Iterate(Entity* first, std::function func); + static void IterateAll(Entity* first, std::function func); + static void ResetPriorityListIndex(Entity* first); + static int GetPersistenceScopeForObjectDeletion(); + static void ClearPriorityLists(); + static void DeleteObjects(Entity** first, Entity** last, int* count); + static void RemoveNonPersistentObjects(Entity** first, Entity** last, int* count); + static void DeleteAllObjects(); + static void AddStaticClass(); + static void CallGameStart(); + static void SpawnStaticObject(const char* objectName); + static void ReadRSDKTile(TileConfig* tile, Uint8* line); + static void LoadRSDKTileConfig(int tilesetID, Stream* tileColReader); + static void LoadHCOLTileConfig(size_t tilesetID, Stream* tileColReader); + static void InitTileCollisions(); + static void ClearTileCollisions(TileConfig* cfg, size_t numTiles); + static void SetTileCount(size_t tileCount); + +public: + static int ShowTileCollisionFlag; + static int ShowObjectRegions; + static HashMap* Properties; + static HashMap* ObjectLists; + static HashMap* ObjectRegistries; + static HashMap* StaticObjectLists; + static int StaticObjectCount; + static Entity* StaticObjectFirst; + static Entity* StaticObjectLast; + static int DynamicObjectCount; + static Entity* DynamicObjectFirst; + static Entity* DynamicObjectLast; + static int ObjectCount; + static Entity* ObjectFirst; + static Entity* ObjectLast; + static int BasePriorityPerLayer; + static int PriorityPerLayer; + static DrawGroupList* PriorityLists; + static vector Tilesets; + static vector TileSpriteInfos; + static Uint16 EmptyTile; + static vector Layers; + static bool AnyLayerTileChange; + static int TileCount; + static int TileWidth; + static int TileHeight; + static int BaseTileCount; + static int BaseTilesetCount; + static bool TileCfgLoaded; + static vector TileCfg; + static vector SpriteList; + static vector ImageList; + static vector SoundList; + static vector MusicList; + static vector ModelList; + static vector MediaList; + static vector TextureList; + static vector AnimatorList; + static int Frame; + static bool Paused; + static bool Loaded; + static int TileAnimationEnabled; + static View Views[MAX_SCENE_VIEWS]; + static int ViewCurrent; + static int ViewsActive; + static int CurrentDrawGroup; + static int ObjectViewRenderFlag; + static int TileViewRenderFlag; + static Perf_ViewRender PERF_ViewRender[MAX_SCENE_VIEWS]; + static char NextScene[256]; + static char CurrentScene[256]; + static bool DoRestart; + static bool NoPersistency; + static int TimeEnabled; + static int TimeCounter; + static int Minutes; + static int Seconds; + static int Milliseconds; + static int Filter; + static int CurrentSceneInList; + static char CurrentFolder[256]; + static char CurrentID[256]; + static char CurrentResourceFolder[256]; + static char CurrentCategory[256]; + static int ActiveCategory; + static int DebugMode; + static float CollisionTolerance; + static bool UseCollisionOffset; + static float CollisionMaskAir; + static CollisionBox CollisionOuter; + static CollisionBox CollisionInner; + static Entity* CollisionEntity; + static CollisionSensor Sensors[6]; + static float CollisionMinimumDistance; + static float LowCollisionTolerance; + static float HighCollisionTolerance; + static int FloorAngleTolerance; + static int WallAngleTolerance; + static int RoofAngleTolerance; + static bool ShowHitboxes; + static int DebugHitboxCount; + static DebugHitboxInfo DebugHitboxList[DEBUG_HITBOX_COUNT]; + + static void Add(Entity** first, Entity** last, int* count, Entity* obj); + static void Remove(Entity** first, Entity** last, int* count, Entity* obj); + static void AddToScene(Entity* obj); + static void RemoveFromScene(Entity* obj); + static void Clear(Entity** first, Entity** last, int* count); + static void AddStatic(ObjectList* objectList, Entity* obj); + static void AddDynamic(ObjectList* objectList, Entity* obj); + static void DeleteRemoved(Entity* obj); + static void OnEvent(Uint32 event); + static void SetCurrent(const char* categoryName, const char* sceneName); + static void SetInfoFromCurrentID(); + static void Init(); + static void InitObjectListsAndRegistries(); + static void ResetPerf(); + static void Update(); + static Tileset* GetTileset(int tileID); + static TileAnimator* GetTileAnimator(int tileID); + static void SetViewActive(int viewIndex, bool active); + static void SetViewPriority(int viewIndex, int priority); + static void SortViews(); + static void SetView(int viewIndex); + static bool CheckPosOnScreen(float posX, float posY, float rangeX, float rangeY); + static void RenderView(int viewIndex, bool doPerf); + static void Render(); + static void AfterScene(); + static void Restart(); + static void LoadScene(const char* filename); + static void ProcessSceneTimer(); + static ObjectList* NewObjectList(const char* objectName); + static ObjectList* GetObjectList(const char* objectName, bool callListLoadFunction); + static ObjectList* GetObjectList(const char* objectName); + static ObjectList* GetStaticObjectList(const char* objectName); + static void AddManagers(); + static void FreePriorityLists(); + static void InitPriorityLists(); + static void SetPriorityPerLayer(int count); + static bool AddTileset(char* path); + static void LoadTileCollisions(const char* filename, size_t tilesetID); + static void UnloadTileCollisions(); + static bool GetResourceListSpace(vector* list, ResourceType* resource, size_t& index, bool& foundEmpty); + static bool GetResource(vector* list, ResourceType* resource, size_t& index); + static ISprite* GetSpriteResource(int index); + static void DisposeInScope(Uint32 scope); + static void Dispose(); + static void UnloadTilesets(); + static void SetTile(int layer, int x, int y, int tileID, int flip_x, int flip_y, int collA, int collB); + static int CollisionAt(int x, int y, int collisionField, int collideSide, int* angle); + static int CollisionInLine(int x, int y, int angleMode, int checkLen, int collisionField, bool compareAngle, Sensor* sensor); + static void SetupCollisionConfig(float minDistance, float lowTolerance, float highTolerance, int floorAngleTolerance, int wallAngleTolerance, int roofAngleTolerance); + static int AddDebugHitbox(int type, int dir, Entity* entity, CollisionBox* hitbox); + static bool CheckObjectCollisionTouch(Entity* thisEntity, CollisionBox* thisHitbox, Entity* otherEntity, CollisionBox* otherHitbox); + static bool CheckObjectCollisionCircle(Entity* thisEntity, float thisRadius, Entity* otherEntity, float otherRadius); + static bool CheckObjectCollisionBox(Entity* thisEntity, CollisionBox* thisHitbox, Entity* otherEntity, CollisionBox* otherHitbox, bool setValues); + static bool CheckObjectCollisionPlatform(Entity* thisEntity, CollisionBox* thisHitbox, Entity* otherEntity, CollisionBox* otherHitbox, bool setValues); + static bool ObjectTileCollision(Entity* entity, int cLayers, int cMode, int cPlane, int xOffset, int yOffset, bool setPos); + static bool ObjectTileGrip(Entity* entity, int cLayers, int cMode, int cPlane, float xOffset, float yOffset, float tolerance); + static void ProcessObjectMovement(Entity* entity, CollisionBox* outerBox, CollisionBox* innerBox); + static void ProcessPathGrip(); + static void ProcessAirCollision_Down(); + static void ProcessAirCollision_Up(); + static void SetPathGripSensors(CollisionSensor* sensors); + static void FindFloorPosition(CollisionSensor* sensor); + static void FindLWallPosition(CollisionSensor* sensor); + static void FindRoofPosition(CollisionSensor* sensor); + static void FindRWallPosition(CollisionSensor* sensor); + static void FloorCollision(CollisionSensor* sensor); + static void LWallCollision(CollisionSensor* sensor); + static void RoofCollision(CollisionSensor* sensor); + static void RWallCollision(CollisionSensor* sensor); +}; + +#endif /* ENGINE_SCENE_H */ diff --git a/include/Engine/Scene/SceneInfo.h b/include/Engine/Scene/SceneInfo.h new file mode 100644 index 00000000..c444e558 --- /dev/null +++ b/include/Engine/Scene/SceneInfo.h @@ -0,0 +1,38 @@ +#ifndef ENGINE_SCENE_SCENEINFO_H +#define ENGINE_SCENE_SCENEINFO_H + +#include +#include +#include +#include + +class SceneInfo { +private: + static void FillAttributesHashMap(XMLAttributes* attr, HashMap* map); + +public: + static vector Entries; + static vector Categories; + + static void Dispose(); + static bool IsCategoryValid(int categoryID); + static bool IsEntryValid(int entryID); + static bool IsEntryValidInCategory(size_t categoryID, size_t entryID); + static int GetCategoryID(const char* categoryName); + static int GetEntryID(const char* categoryName, const char* entryName); + static int GetEntryID(const char* categoryName, size_t entryID); + static int GetEntryID(size_t categoryID, size_t entryID); + static int GetEntryPosInCategory(const char *categoryName, const char* entryName); + static int GetEntryPosInCategory(size_t categoryID, const char* entryName); + static int GetEntryIDWithinRange(size_t start, size_t end, const char* entryName); + static string GetParentPath(int entryID); + static string GetFilename(int entryID); + static string GetTileConfigFilename(int entryID); + static char* GetEntryProperty(int entryID, char* property); + static char* GetCategoryProperty(int categoryID, char* property); + static bool HasEntryProperty(int entryID, char* property); + static bool HasCategoryProperty(int categoryID, char* property); + static bool Load(XMLNode* node); +}; + +#endif /* ENGINE_SCENE_SCENEINFO_H */ diff --git a/include/Engine/Scene/SceneLayer.h b/include/Engine/Scene/SceneLayer.h new file mode 100644 index 00000000..8ba727f7 --- /dev/null +++ b/include/Engine/Scene/SceneLayer.h @@ -0,0 +1,68 @@ +#ifndef ENGINE_SCENE_SCENELAYER_H +#define ENGINE_SCENE_SCENELAYER_H + +#include +#include +#include +#include + +class SceneLayer { +public: + char Name[50]; + bool Visible = true; + int Width = 0; + int Height = 0; + Uint32 WidthMask = 0; + Uint32 HeightMask = 0; + Uint32 WidthInBits = 0; + Uint32 HeightInBits = 0; + Uint32 WidthData = 0; + Uint32 HeightData = 0; + Uint32 DataSize = 0; + Uint32 ScrollIndexCount = 0; + int RelativeY = 0x0100; + int ConstantY = 0x0000; + int OffsetX = 0x0000; + int OffsetY = 0x0000; + Uint32* Tiles = NULL; + Uint32* TilesBackup = NULL; + Uint16* TileOffsetY = NULL; + int DeformOffsetA = 0; + int DeformOffsetB = 0; + int DeformSetA[MAX_DEFORM_LINES]; + int DeformSetB[MAX_DEFORM_LINES]; + int DeformSplitLine = 0; + int Flags = 0x0000; + int DrawGroup = 0; + Uint8 DrawBehavior = 0; + HashMap* Properties = NULL; + bool Blending = false; + Uint8 BlendMode = 0; // BlendMode_NORMAL + float Opacity = 1.0f; + bool UsePaletteIndexLines = false; + bool UsingCustomScanlineFunction = false; + ObjFunction CustomScanlineFunction; + bool UsingCustomRenderFunction = false; + ObjFunction CustomRenderFunction; + int ScrollInfoCount = 0; + ScrollingInfo* ScrollInfos = NULL; + int ScrollInfosSplitIndexesCount = 0; + Uint16* ScrollInfosSplitIndexes = NULL; + Uint8* ScrollIndexes = NULL; + Uint32 BufferID = 0; + int VertexCount = 0; + void* TileBatches = NULL; + enum { + FLAGS_COLLIDEABLE = 1, + FLAGS_REPEAT_X = 2, + FLAGS_REPEAT_Y = 4, + }; + + SceneLayer(); + SceneLayer(int w, int h); + bool PropertyExists(char* property); + VMValue PropertyGet(char* property); + void Dispose(); +}; + +#endif /* ENGINE_SCENE_SCENELAYER_H */ diff --git a/include/Engine/Scene/ScrollingIndex.h b/include/Engine/Scene/ScrollingIndex.h new file mode 100644 index 00000000..14ae6c0e --- /dev/null +++ b/include/Engine/Scene/ScrollingIndex.h @@ -0,0 +1,13 @@ +#ifndef ENGINE_SCENE_SCROLLINGINDEX_H +#define ENGINE_SCENE_SCROLLINGINDEX_H + + +class ScrollingIndex { +public: + int Index; + int Size; + int* TileBuffers = NULL; + +}; + +#endif /* ENGINE_SCENE_SCROLLINGINDEX_H */ diff --git a/source/Engine/Scene/ScrollingInfo.cpp b/include/Engine/Scene/ScrollingInfo.h similarity index 53% rename from source/Engine/Scene/ScrollingInfo.cpp rename to include/Engine/Scene/ScrollingInfo.h index b5032afd..469eff48 100644 --- a/source/Engine/Scene/ScrollingInfo.cpp +++ b/include/Engine/Scene/ScrollingInfo.h @@ -1,4 +1,7 @@ -#if INTERFACE +#ifndef ENGINE_SCENE_SCROLLINGINFO_H +#define ENGINE_SCENE_SCROLLINGINFO_H + + class ScrollingInfo { public: int RelativeParallax; @@ -6,5 +9,7 @@ class ScrollingInfo { char CanDeform; int Position; int Offset; + }; -#endif + +#endif /* ENGINE_SCENE_SCROLLINGINFO_H */ diff --git a/source/Engine/Scene/TileConfig.cpp b/include/Engine/Scene/TileConfig.h similarity index 71% rename from source/Engine/Scene/TileConfig.cpp rename to include/Engine/Scene/TileConfig.h index fefc9fd8..b5201fdb 100644 --- a/source/Engine/Scene/TileConfig.cpp +++ b/include/Engine/Scene/TileConfig.h @@ -1,4 +1,7 @@ -#if INTERFACE +#ifndef ENGINE_SCENE_TILECONFIG_H +#define ENGINE_SCENE_TILECONFIG_H + + class TileConfig { public: Uint8 CollisionTop[16]; @@ -11,5 +14,7 @@ class TileConfig { Uint8 AngleBottom; Uint8 Behavior; Uint8 IsCeiling; + }; -#endif + +#endif /* ENGINE_SCENE_TILECONFIG_H */ diff --git a/include/Engine/Scene/TileSpriteInfo.h b/include/Engine/Scene/TileSpriteInfo.h new file mode 100644 index 00000000..4ebe96c4 --- /dev/null +++ b/include/Engine/Scene/TileSpriteInfo.h @@ -0,0 +1,14 @@ +#ifndef ENGINE_SCENE_TILESPRITEINFO_H +#define ENGINE_SCENE_TILESPRITEINFO_H + + +class TileSpriteInfo { +public: + ISprite* Sprite; + int AnimationIndex; + int FrameIndex; + size_t TilesetID; + +}; + +#endif /* ENGINE_SCENE_TILESPRITEINFO_H */ diff --git a/include/Engine/Scene/View.h b/include/Engine/Scene/View.h new file mode 100644 index 00000000..c8e437ae --- /dev/null +++ b/include/Engine/Scene/View.h @@ -0,0 +1,46 @@ +#ifndef ENGINE_SCENE_VIEW_H +#define ENGINE_SCENE_VIEW_H + +#include +#include +#include + +class View { +public: + bool Active = false; + bool Visible = true; + bool Software = false; + int Priority = 0; + float X = 0.0f; + float Y = 0.0f; + float Z = 0.0f; + float RotateX = 0.0f; + float RotateY = 0.0f; + float RotateZ = 0.0f; + float Width = 1.0f; + float Height = 1.0f; + float OutputX = 0.0f; + float OutputY = 0.0f; + float OutputWidth = 1.0f; + float OutputHeight = 1.0f; + int Stride = 1; + float FOV = 45.0f; + float NearPlane = 0.1f; + float FarPlane = 1000.f; + bool UsePerspective = false; + bool UseDrawTarget = false; + bool UseStencil = false; + Texture* DrawTarget = NULL; + Uint8* StencilBuffer = NULL; + size_t StencilBufferSize = 0; + Matrix4x4* ProjectionMatrix = NULL; + Matrix4x4* BaseProjectionMatrix = NULL; + + void SetSize(float w, float h); + void SetStencilEnabled(bool enabled); + void ReallocStencil(); + void ClearStencil(); + void DeleteStencil(); +}; + +#endif /* ENGINE_SCENE_VIEW_H */ diff --git a/include/Engine/TextFormats/INI/INI.h b/include/Engine/TextFormats/INI/INI.h new file mode 100644 index 00000000..39370ad7 --- /dev/null +++ b/include/Engine/TextFormats/INI/INI.h @@ -0,0 +1,42 @@ +#ifndef ENGINE_TEXTFORMATS_INI_INI_H +#define ENGINE_TEXTFORMATS_INI_INI_H + +#include +#include +#include +#include + +class INI { +public: + char* Filename = nullptr; + vector Sections; + + static INI* New(const char* filename); + static INI* Load(const char* filename); + bool Reload(); + bool Save(const char* filename); + bool Save(); + void SetFilename(const char* filename); + bool Read(Stream* stream); + bool Write(Stream* stream); + INISection* FindSection(const char* name); + bool GetString(const char* sectionName, const char* key, char* dest, size_t destSize); + bool GetInteger(const char* sectionName, const char* key, int* dest); + bool GetDecimal(const char* sectionName, const char* key, double* dest); + bool GetBool(const char* sectionName, const char* key, bool* dest); + bool SetString(const char* sectionName, const char* key, const char* value); + bool SetInteger(const char* section, const char* key, int value); + bool SetDecimal(const char* section, const char* key, double value); + bool SetBool(const char* section, const char* key, bool value); + INISection* AddSection(const char* name); + bool RemoveSection(const char* sectionName); + bool SectionExists(const char* sectionName); + int GetSectionCount(); + char* GetProperty(const char* sectionName, const char* key); + bool PropertyExists(const char* sectionName, const char* key); + bool RemoveProperty(const char* sectionName, const char* key); + int GetPropertyCount(const char* sectionName); + void Dispose(); +}; + +#endif /* ENGINE_TEXTFORMATS_INI_INI_H */ diff --git a/include/Engine/TextFormats/XML/XMLParser.h b/include/Engine/TextFormats/XML/XMLParser.h new file mode 100644 index 00000000..eecf742c --- /dev/null +++ b/include/Engine/TextFormats/XML/XMLParser.h @@ -0,0 +1,25 @@ +#ifndef ENGINE_TEXTFORMATS_XML_XMLPARSER_H +#define ENGINE_TEXTFORMATS_XML_XMLPARSER_H + +#include +#include +#include +#include +#include +#include + +class XMLParser { +public: + static bool MatchToken(Token tok, const char* string); + static float TokenToNumber(Token tok); + static XMLNode* Parse(); + static XMLNode* ParseFromStream(MemoryStream* stream); + static XMLNode* ParseFromStream(Stream* streamSrc); + static XMLNode* ParseFromResource(const char* filename); + static char* TokenToString(Token tok); + static void CopyTokenToString(Token tok, char* buffer, size_t size); + static XMLNode* SearchNode(XMLNode* root, const char* search); + static void Free(XMLNode* root); +}; + +#endif /* ENGINE_TEXTFORMATS_XML_XMLPARSER_H */ diff --git a/include/Engine/Types/DrawGroupList.h b/include/Engine/Types/DrawGroupList.h new file mode 100644 index 00000000..323094ed --- /dev/null +++ b/include/Engine/Types/DrawGroupList.h @@ -0,0 +1,26 @@ +#ifndef ENGINE_TYPES_DRAWGROUPLIST_H +#define ENGINE_TYPES_DRAWGROUPLIST_H + +#include +#include + +class DrawGroupList { +public: + vector* Entities = nullptr; + bool EntityDepthSortingEnabled = false; + bool NeedsSorting = false; + + DrawGroupList(); + int Add(Entity* obj); + bool Contains(Entity* obj); + int GetEntityIndex(Entity* obj); + void Remove(Entity* obj); + void Clear(); + void Sort(); + void Init(); + void Dispose(); + ~DrawGroupList(); + int Count(); +}; + +#endif /* ENGINE_TYPES_DRAWGROUPLIST_H */ diff --git a/include/Engine/Types/Entity.h b/include/Engine/Types/Entity.h new file mode 100644 index 00000000..15076623 --- /dev/null +++ b/include/Engine/Types/Entity.h @@ -0,0 +1,129 @@ +#ifndef ENGINE_TYPES_ENTITY_H +#define ENGINE_TYPES_ENTITY_H +class ObjectList; +class ObjectRegistry; +class DrawGroupList; + +#include +#include +#include +#include +#include +#include +#include + +class Entity { +public: + float InitialX = 0; + float InitialY = 0; + int Active = true; + int Pauseable = true; + int Interactable = true; + int Persistence = Persistence_NONE; + int Activity = ACTIVE_BOUNDS; + int InRange = false; + bool Created = false; + bool PostCreated = false; + float X = 0.0f; + float Y = 0.0f; + float Z = 0.0f; + float XSpeed = 0.0f; + float YSpeed = 0.0f; + float GroundSpeed = 0.0f; + float Gravity = 0.0f; + int Ground = false; + int WasOffScreen = false; + int OnScreen = true; + float OnScreenHitboxW = 0.0f; + float OnScreenHitboxH = 0.0f; + float OnScreenRegionTop = 0.0f; + float OnScreenRegionLeft = 0.0f; + float OnScreenRegionRight = 0.0f; + float OnScreenRegionBottom = 0.0f; + int ViewRenderFlag = 0xFFFFFFFF; + int ViewOverrideFlag = 0; + float RenderRegionW = 0.0f; + float RenderRegionH = 0.0f; + float RenderRegionTop = 0.0f; + float RenderRegionLeft = 0.0f; + float RenderRegionRight = 0.0f; + float RenderRegionBottom = 0.0f; + int Angle = 0; + int AngleMode = 0; + float ScaleX = 1.0; + float ScaleY = 1.0; + float Rotation = 0.0; + float Alpha = 1.0; + int AutoPhysics = false; + int Priority = 0; + int PriorityListIndex = -1; + int PriorityOld = -1; + float Depth = 0.0f; + float OldDepth = 0.0f; + float ZDepth = 0.0; + int Sprite = -1; + int CurrentAnimation = -1; + int CurrentFrame = -1; + int CurrentFrameCount = 0; + float AnimationSpeedMult = 1.0; + int AnimationSpeedAdd = 0; + int AutoAnimate = true; + float AnimationSpeed = 0.0; + float AnimationTimer = 0.0; + int AnimationFrameDuration = 0; + int AnimationLoopIndex = 0; + EntityHitbox Hitbox; + int FlipFlag = 0; + float SensorX = 0.0f; + float SensorY = 0.0f; + int SensorCollided = false; + int SensorAngle = 0; + float VelocityX = 0.0f; + float VelocityY = 0.0f; + float GroundVel = 0.0f; + float GravityStrength = 0.0f; + int OnGround = false; + int Direction = 0; + int TileCollisions = false; + int CollisionLayers = 0; + int CollisionPlane = 0; + int CollisionMode = 0; + int SlotID = -1; + bool Removed = false; + Entity* PrevEntity = NULL; + Entity* NextEntity = NULL; + ObjectList* List = NULL; + Entity* PrevEntityInList = NULL; + Entity* NextEntityInList = NULL; + Entity* PrevSceneEntity = NULL; + Entity* NextSceneEntity = NULL; + + void ApplyMotion(); + void Animate(); + void SetAnimation(int animation, int frame); + void ResetAnimation(int animation, int frame); + bool BasicCollideWithObject(Entity* other); + bool CollideWithObject(Entity* other); + int SolidCollideWithObject(Entity* other, int flag); + bool TopSolidCollideWithObject(Entity* other, int flag); + void Copy(Entity* other); + void CopyFields(Entity* other); + void ApplyPhysics(); + virtual void Initialize(); + virtual void Create(); + virtual void PostCreate(); + virtual void UpdateEarly(); + virtual void Update(); + virtual void UpdateLate(); + virtual void OnAnimationFinish(); + virtual void OnSceneLoad(); + virtual void OnSceneRestart(); + virtual void GameStart(); + virtual void RenderEarly(); + virtual void Render(int CamX, int CamY); + virtual void RenderLate(); + virtual void Remove(); + virtual void Dispose(); +}; + +#endif /* ENGINE_TYPES_ENTITY_H */ diff --git a/include/Engine/Types/ObjectList.h b/include/Engine/Types/ObjectList.h new file mode 100644 index 00000000..b253e915 --- /dev/null +++ b/include/Engine/Types/ObjectList.h @@ -0,0 +1,35 @@ +#ifndef ENGINE_TYPES_OBJECTLIST_H +#define ENGINE_TYPES_OBJECTLIST_H + +#include +#include + +class ObjectList { +public: + int EntityCount = 0; + int Activity = ACTIVE_NORMAL; + Entity* EntityFirst = nullptr; + Entity* EntityLast = nullptr; + char* ObjectName; + char* LoadFunctionName; + char* GlobalUpdateFunctionName; + ObjectListPerformance Performance; + Entity* (*SpawnFunction)(ObjectList*) = nullptr; + + ObjectList(const char* name); + ~ObjectList(); + void Add(Entity* obj); + bool Contains(Entity* obj); + void Remove(Entity* obj); + void Clear(); + Entity* Spawn(); + void Iterate(std::function func); + void RemoveNonPersistentFromLinkedList(Entity* first, int persistence); + void RemoveNonPersistentFromLinkedList(Entity* first); + void ResetPerf(); + Entity* GetNth(int n); + Entity* GetClosest(int x, int y); + int Count(); +}; + +#endif /* ENGINE_TYPES_OBJECTLIST_H */ diff --git a/include/Engine/Types/ObjectRegistry.h b/include/Engine/Types/ObjectRegistry.h new file mode 100644 index 00000000..c4b5df6b --- /dev/null +++ b/include/Engine/Types/ObjectRegistry.h @@ -0,0 +1,25 @@ +#ifndef ENGINE_TYPES_OBJECTREGISTRY_H +#define ENGINE_TYPES_OBJECTREGISTRY_H + +#include +#include + +class ObjectRegistry { +public: + vector List; + + void Add(Entity* obj); + bool Contains(Entity* obj); + void Remove(Entity* obj); + void Clear(); + void Iterate(std::function func); + void RemoveNonPersistentFromLinkedList(Entity* first, int persistence); + void RemoveNonPersistentFromLinkedList(Entity* first); + Entity* GetNth(int n); + Entity* GetClosest(int x, int y); + void Dispose(); + ~ObjectRegistry(); + int Count(); +}; + +#endif /* ENGINE_TYPES_OBJECTREGISTRY_H */ diff --git a/include/Engine/Types/Tileset.h b/include/Engine/Types/Tileset.h new file mode 100644 index 00000000..f0368ca6 --- /dev/null +++ b/include/Engine/Types/Tileset.h @@ -0,0 +1,30 @@ +#ifndef ENGINE_TYPES_TILESET_H +#define ENGINE_TYPES_TILESET_H + +#include +#include +#include + +class Tileset { +public: + ISprite* Sprite = nullptr; + char* Filename = nullptr; + int NumCols = 0; + int NumRows = 0; + int TileWidth = 0; + int TileHeight = 0; + size_t StartTile = 0; + size_t FirstGlobalTileID = 0; + size_t TileCount = 0; + unsigned PaletteID = 0; + std::map AnimatorMap; + + Tileset(ISprite* sprite, int tileWidth, int tileHeight, size_t firstgid, size_t startTile, size_t tileCount, char* filename); + void RunAnimations(); + void RestartAnimations(); + void AddTileAnimSequence(int tileID, TileSpriteInfo* tileSpriteInfo, vector& tileIDs, vector& durations); + void AddTileAnimSequence(int tileID, TileSpriteInfo* tileSpriteInfo, ISprite* animSprite, int animID); + TileAnimator* GetTileAnimSequence(int tileID); +}; + +#endif /* ENGINE_TYPES_TILESET_H */ diff --git a/include/Engine/Utilities/ColorUtils.h b/include/Engine/Utilities/ColorUtils.h new file mode 100644 index 00000000..33625c5b --- /dev/null +++ b/include/Engine/Utilities/ColorUtils.h @@ -0,0 +1,29 @@ +#ifndef ENGINE_UTILITIES_COLORUTILS_H +#define ENGINE_UTILITIES_COLORUTILS_H + +#include + +class ColorUtils { +public: + static Uint32 ToRGB(int r, int g, int b); + static Uint32 ToRGB(int r, int g, int b, int a); + static Uint32 ToRGB(float r, float g, float b); + static Uint32 ToRGB(float r, float g, float b, float a); + static Uint32 ToRGB(float *r); + static Uint32 ToRGBA(float *r); + static void SeparateRGB(Uint32 color, float* dest); + static void Separate(Uint32 color, float* dest); + static void SeparateRGB(Uint32 color, Uint8* dest); + static void Separate(Uint32 color, Uint8* dest); + static void SeparateRGB(float* color, Uint8* dest); + static void Separate(float* color, Uint8* dest); + static Uint32 Tint(Uint32 color, Uint32 colorMult); + static Uint32 Tint(Uint32 color, Uint32 colorMult, Uint16 percentage); + static Uint32 Multiply(Uint32 color, Uint32 colorMult); + static Uint32 Blend(Uint32 color1, Uint32 color2, int percent); + static void ConvertFromARGBtoABGR(Uint32* argb, int count); + static void ConvertFromABGRtoARGB(Uint32* argb, int count); + static int NearestColor(Uint8 r, Uint8 g, Uint8 b, Uint32* palette, unsigned numColors); +}; + +#endif /* ENGINE_UTILITIES_COLORUTILS_H */ diff --git a/include/Engine/Utilities/StringUtils.h b/include/Engine/Utilities/StringUtils.h new file mode 100644 index 00000000..219368cc --- /dev/null +++ b/include/Engine/Utilities/StringUtils.h @@ -0,0 +1,30 @@ +#ifndef ENGINE_UTILITIES_STRINGUTILS_H +#define ENGINE_UTILITIES_STRINGUTILS_H + +#include +#include + +class StringUtils { +public: + static char* Create(void* src, size_t length); + static char* Create(string src); + static char* Create(Token token); + static char* Duplicate(const char* src); + static char* Duplicate(const char* src, size_t length); + static char* Resize(char* src, size_t length); + static bool WildcardMatch(const char* first, const char* second); + static bool StartsWith(const char* string, const char* compare); + static char* StrCaseStr(const char* haystack, const char* needle); + static size_t Copy(char* dst, const char* src, size_t sz); + static size_t Concat(char* dst, const char* src, size_t sz); + static bool ToNumber(int* dst, const char* src); + static bool ToDecimal(double* dst, const char* src); + static bool ToNumber(int* dst, string src); + static bool ToDecimal(double* dst, string src); + static char* GetPath(const char* filename); + static char* ConcatPaths(const char* pathA, const char* pathB); + static char* ReplacePathSeparators(const char* path); + static void ReplacePathSeparatorsInPlace(char* path); +}; + +#endif /* ENGINE_UTILITIES_STRINGUTILS_H */ diff --git a/source/Engine/Application.cpp b/source/Engine/Application.cpp index b09c26cd..be343e8b 100644 --- a/source/Engine/Application.cpp +++ b/source/Engine/Application.cpp @@ -1,56 +1,3 @@ -#if INTERFACE -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class Application { -public: - static vector CmdLineArgs; - - static INI* Settings; - static char SettingsFile[4096]; - - static XMLNode* GameConfig; - - static int TargetFPS; - static float CurrentFPS; - static bool Running; - static bool GameStart; - - static SDL_Window* Window; - static char WindowTitle[256]; - static int WindowWidth; - static int WindowHeight; - static int DefaultMonitor; - static Platforms Platform; - - static char EngineVersion[256]; - - static char GameTitle[256]; - static char GameTitleShort[256]; - static char GameVersion[256]; - static char GameDescription[256]; - - static int UpdatesPerFrame; - static bool Stepper; - static bool Step; - - static int MasterVolume; - static int MusicVolume; - static int SoundVolume; - - static int StartSceneNum; - - static bool DevMenuActivated; -}; -#endif - #include #include @@ -168,7 +115,7 @@ void DEBUG_DrawText(char* text, float x, float y) { } } -PUBLIC STATIC void Application::Init(int argc, char* args[]) { +void Application::Init(int argc, char* args[]) { #ifdef MSYS AllocConsole(); freopen_s((FILE **)stdin, "CONIN$", "w", stdin); @@ -297,7 +244,7 @@ PUBLIC STATIC void Application::Init(int argc, char* args[]) { Running = true; } -PUBLIC STATIC void Application::SetTargetFrameRate(int targetFPS) { +void Application::SetTargetFrameRate(int targetFPS) { if (targetFPS < 1) TargetFPS = 1; else if (targetFPS > MAX_TARGET_FRAMERATE) @@ -308,7 +255,7 @@ PUBLIC STATIC void Application::SetTargetFrameRate(int targetFPS) { FrameTimeDesired = 1000.0 / TargetFPS; } -PRIVATE STATIC void Application::MakeEngineVersion() { +void Application::MakeEngineVersion() { std::string versionText = std::to_string(VERSION_MAJOR) + "." + std::to_string(VERSION_MINOR); #ifdef VERSION_PATCH @@ -331,10 +278,10 @@ PRIVATE STATIC void Application::MakeEngineVersion() { StringUtils::Copy(Application::EngineVersion, versionText.c_str(), sizeof(Application::EngineVersion)); } -PUBLIC STATIC bool Application::IsPC() { +bool Application::IsPC() { return Application::Platform == Platforms::Windows || Application::Platform == Platforms::MacOS || Application::Platform == Platforms::Linux; } -PUBLIC STATIC bool Application::IsMobile() { +bool Application::IsMobile() { return Application::Platform == Platforms::iOS || Application::Platform == Platforms::Android; } @@ -354,7 +301,7 @@ double MetricFPSCounterTime = -1; double MetricPresentTime = -1; double MetricFrameTime = 0.0; vector ListList; -PUBLIC STATIC void Application::GetPerformanceSnapshot() { +void Application::GetPerformanceSnapshot() { if (Scene::ObjectLists) { // General Performance Snapshot double types[] = { @@ -474,13 +421,13 @@ PUBLIC STATIC void Application::GetPerformanceSnapshot() { } } -PUBLIC STATIC void Application::SetWindowTitle(const char* title) { +void Application::SetWindowTitle(const char* title) { memset(Application::WindowTitle, 0, sizeof(Application::WindowTitle)); snprintf(Application::WindowTitle, sizeof(Application::WindowTitle), "%s", title); Application::UpdateWindowTitle(); } -PUBLIC STATIC void Application::UpdateWindowTitle() { +void Application::UpdateWindowTitle() { std::string titleText = std::string(Application::WindowTitle); bool paren = false; @@ -526,7 +473,7 @@ PUBLIC STATIC void Application::UpdateWindowTitle() { SDL_SetWindowTitle(Application::Window, titleText.c_str()); } -PRIVATE STATIC void Application::Restart() { +void Application::Restart() { // Reset FPS timer BenchmarkFrameCount = 0; @@ -554,26 +501,26 @@ PRIVATE STATIC void Application::Restart() { else if (vol > 100) \ vol = 100 -PUBLIC STATIC void Application::SetMasterVolume(int volume) { +void Application::SetMasterVolume(int volume) { CLAMP_VOLUME(volume); Application::MasterVolume = volume; AudioManager::MasterVolume = Application::MasterVolume / 100.0f; } -PUBLIC STATIC void Application::SetMusicVolume(int volume) { +void Application::SetMusicVolume(int volume) { CLAMP_VOLUME(volume); Application::MusicVolume = volume; AudioManager::MusicVolume = Application::MusicVolume / 100.0f; } -PUBLIC STATIC void Application::SetSoundVolume(int volume) { +void Application::SetSoundVolume(int volume) { CLAMP_VOLUME(volume); Application::SoundVolume = volume; AudioManager::SoundVolume = Application::SoundVolume / 100.0f; } -PRIVATE STATIC void Application::LoadAudioSettings() { +void Application::LoadAudioSettings() { INI* settings = Application::Settings; int masterVolume = Application::MasterVolume; @@ -601,7 +548,7 @@ PRIVATE STATIC void Application::LoadAudioSettings() { SDL_Keycode KeyBindsSDL[(int)KeyBind::Max]; -PRIVATE STATIC void Application::LoadKeyBinds() { +void Application::LoadKeyBinds() { XMLNode* node = nullptr; if (Application::GameConfig) node = XMLParser::SearchNode(Application::GameConfig->children[0], "keys"); @@ -642,18 +589,18 @@ PRIVATE STATIC void Application::LoadKeyBinds() { #undef GET_KEY } -PRIVATE STATIC void Application::LoadDevSettings() { +void Application::LoadDevSettings() { Application::Settings->GetBool("dev", "devMenu", &DevMenu); Application::Settings->GetBool("dev", "viewPerformance", &ShowFPS); Application::Settings->GetBool("dev", "donothing", &DoNothing); Application::Settings->GetInteger("dev", "fastforward", &UpdatesPerFastForward); } -PUBLIC STATIC bool Application::IsWindowResizeable() { +bool Application::IsWindowResizeable() { return !Application::IsMobile(); } -PUBLIC STATIC void Application::SetWindowSize(int window_w, int window_h) { +void Application::SetWindowSize(int window_w, int window_h) { if (!Application::IsWindowResizeable()) return; @@ -668,11 +615,11 @@ PUBLIC STATIC void Application::SetWindowSize(int window_w, int window_h) { Graphics::Resize(window_w, window_h); } -PUBLIC STATIC bool Application::GetWindowFullscreen() { +bool Application::GetWindowFullscreen() { return !!(SDL_GetWindowFlags(Application::Window) & SDL_WINDOW_FULLSCREEN_DESKTOP); } -PUBLIC STATIC void Application::SetWindowFullscreen(bool isFullscreen) { +void Application::SetWindowFullscreen(bool isFullscreen) { SDL_SetWindowFullscreen(Application::Window, isFullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0); int window_w, window_h; @@ -681,14 +628,14 @@ PUBLIC STATIC void Application::SetWindowFullscreen(bool isFullscreen) { Graphics::Resize(window_w, window_h); } -PUBLIC STATIC void Application::SetWindowBorderless(bool isBorderless) { +void Application::SetWindowBorderless(bool isBorderless) { SDL_SetWindowBordered(Application::Window, (SDL_bool)(!isBorderless)); } -PUBLIC STATIC int Application::GetKeyBind(int bind) { +int Application::GetKeyBind(int bind) { return KeyBinds[bind]; } -PUBLIC STATIC void Application::SetKeyBind(int bind, int key) { +void Application::SetKeyBind(int bind, int key) { KeyBinds[bind] = key; if (key == Key_UNKNOWN) KeyBindsSDL[bind] = SDLK_UNKNOWN; @@ -696,7 +643,7 @@ PUBLIC STATIC void Application::SetKeyBind(int bind, int key) { KeyBindsSDL[bind] = SDL_GetKeyFromScancode(InputManager::KeyToSDLScancode[key]); } -PRIVATE STATIC void Application::PollEvents() { +void Application::PollEvents() { SDL_Event e; while (SDL_PollEvent(&e)) { switch (e.type) { @@ -846,7 +793,7 @@ PRIVATE STATIC void Application::PollEvents() { } } } -PRIVATE STATIC void Application::RunFrame(void* p) { +void Application::RunFrame(void* p) { FrameTimeStart = Clock::GetTicks(); // Event loop @@ -1113,7 +1060,7 @@ PRIVATE STATIC void Application::RunFrame(void* p) { MetricFrameTime = Clock::GetTicks() - FrameTimeStart; } -PRIVATE STATIC void Application::DelayFrame() { +void Application::DelayFrame() { double frameTime = Clock::GetTicks() - FrameTimeStart; double frameDurationRemainder = FrameTimeDesired - frameTime; if (frameDurationRemainder >= 0.0) { @@ -1130,7 +1077,7 @@ PRIVATE STATIC void Application::DelayFrame() { while ((Clock::GetTicks() - FrameTimeStart) < FrameTimeDesired); } } -PUBLIC STATIC void Application::Run(int argc, char* args[]) { +void Application::Run(int argc, char* args[]) { Application::Init(argc, args); if (!Running) return; @@ -1214,7 +1161,7 @@ PUBLIC STATIC void Application::Run(int argc, char* args[]) { #endif } -PUBLIC STATIC void Application::Cleanup() { +void Application::Cleanup() { ResourceManager::Dispose(); AudioManager::Dispose(); InputManager::Dispose(); @@ -1253,7 +1200,7 @@ static void ParseGameConfigBool(XMLNode* node, const char* option, bool& val) { val = !strcmp(read, "true"); } -PRIVATE STATIC void Application::LoadGameConfig() { +void Application::LoadGameConfig() { StartingScene[0] = '\0'; Application::GameConfig = nullptr; @@ -1323,13 +1270,13 @@ PRIVATE STATIC void Application::LoadGameConfig() { XMLParser::CopyTokenToString(node->children[0]->name, StartingScene, sizeof(StartingScene)); } -PRIVATE STATIC void Application::DisposeGameConfig() { +void Application::DisposeGameConfig() { if (Application::GameConfig) XMLParser::Free(Application::GameConfig); Application::GameConfig = nullptr; } -PRIVATE STATIC string Application::ParseGameVersion(XMLNode* versionNode) { +string Application::ParseGameVersion(XMLNode* versionNode) { if (versionNode->children.size() == 1) return versionNode->children[0]->name.ToString(); @@ -1364,7 +1311,7 @@ PRIVATE STATIC string Application::ParseGameVersion(XMLNode* versionNode) { return versionText; } -PRIVATE STATIC void Application::LoadGameInfo() { +void Application::LoadGameInfo() { StringUtils::Copy(Application::GameTitle, "Hatch Game Engine", sizeof(Application::GameTitle)); StringUtils::Copy(Application::GameTitleShort, Application::GameTitle, sizeof(Application::GameTitleShort)); StringUtils::Copy(Application::GameVersion, "1.0", sizeof(Application::GameVersion)); @@ -1398,7 +1345,7 @@ PRIVATE STATIC void Application::LoadGameInfo() { } } -PUBLIC STATIC void Application::LoadSceneInfo() { +void Application::LoadSceneInfo() { if (ResourceManager::ResourceExists("Game/SceneConfig.xml")) { XMLNode* node; @@ -1442,11 +1389,11 @@ PUBLIC STATIC void Application::LoadSceneInfo() { } } -PUBLIC STATIC void Application::InitPlayerControls() { +void Application::InitPlayerControls() { InputManager::InitPlayerControls(); } -PUBLIC STATIC bool Application::LoadSettings(const char* filename) { +bool Application::LoadSettings(const char* filename) { INI* ini = INI::Load(filename); if (ini == nullptr) return false; @@ -1460,23 +1407,23 @@ PUBLIC STATIC bool Application::LoadSettings(const char* filename) { return true; } -PUBLIC STATIC void Application::ReadSettings() { +void Application::ReadSettings() { Application::LoadAudioSettings(); Application::LoadDevSettings(); Application::LoadKeyBinds(); } -PUBLIC STATIC void Application::ReloadSettings() { +void Application::ReloadSettings() { if (Application::Settings && Application::Settings->Reload()) Application::ReadSettings(); } -PUBLIC STATIC void Application::ReloadSettings(const char* filename) { +void Application::ReloadSettings(const char* filename) { if (Application::LoadSettings(filename)) Application::ReadSettings(); } -PUBLIC STATIC void Application::InitSettings(const char* filename) { +void Application::InitSettings(const char* filename) { Application::LoadSettings(filename); // NOTE: If no settings could be loaded, create settings with default values. @@ -1509,21 +1456,21 @@ PUBLIC STATIC void Application::InitSettings(const char* filename) { Application::Settings->GetInteger("display", "multisample", &Graphics::MultisamplingEnabled); Application::Settings->GetInteger("display", "defaultMonitor", &Application::DefaultMonitor); } -PUBLIC STATIC void Application::SaveSettings() { +void Application::SaveSettings() { if (Application::Settings) Application::Settings->Save(); } -PUBLIC STATIC void Application::SaveSettings(const char* filename) { +void Application::SaveSettings(const char* filename) { if (Application::Settings) Application::Settings->Save(filename); } -PUBLIC STATIC void Application::SetSettingsFilename(const char* filename) { +void Application::SetSettingsFilename(const char* filename) { StringUtils::Copy(Application::SettingsFile, filename, sizeof(Application::SettingsFile)); if (Application::Settings) Application::Settings->SetFilename(filename); } -PRIVATE STATIC int Application::HandleAppEvents(void* data, SDL_Event* event) { +int Application::HandleAppEvents(void* data, SDL_Event* event) { switch (event->type) { case SDL_APP_TERMINATING: Log::Print(Log::LOG_VERBOSE, "SDL_APP_TERMINATING"); diff --git a/source/Engine/Audio/AudioManager.cpp b/source/Engine/Audio/AudioManager.cpp index cca12469..18193742 100644 --- a/source/Engine/Audio/AudioManager.cpp +++ b/source/Engine/Audio/AudioManager.cpp @@ -1,42 +1,3 @@ -#if INTERFACE -#include -#include -#include -#include -#include - -class AudioManager { -public: - static SDL_AudioDeviceID Device; - static SDL_AudioSpec DeviceFormat; - static bool AudioEnabled; - - static Uint8 BytesPerSample; - static Uint8* MixBuffer; - static size_t MixBufferSize; - - static deque MusicStack; - static AudioChannel* SoundArray; - static int SoundArrayLength; - - static float MasterVolume; - static float MusicVolume; - static float SoundVolume; - - static float LowPassFilter; - - static Uint8* AudioQueue; - static size_t AudioQueueSize; - static size_t AudioQueueMaxSize; - - enum { - REQUEST_EOF = 0, - REQUEST_ERROR = -1, - REQUEST_CONVERTING = -2, - }; -}; -#endif - #include #include #include @@ -85,7 +46,7 @@ Sint16 mZy[2 * 2]; // 2 per channel float mZxF[2 * 2]; // 2 per channel float mZyF[2 * 2]; // 2 per channel -PUBLIC STATIC void AudioManager::CalculateCoeffs() { +void AudioManager::CalculateCoeffs() { double theta = 2.0 * M_PI * mNormalizedFreq; // normalized frequency has been precalculated as fc/fs double d = 0.5 * (1.0 / mQuality) * sin(theta); double beta = 0.5 * ( (1.0 - d) / (1.0 + d) ); @@ -114,7 +75,7 @@ PUBLIC STATIC void AudioManager::CalculateCoeffs() { b1 = -2.0 * gamma; b2 = 2.0 * beta; } -PUBLIC STATIC Sint16 AudioManager::ProcessSample(Sint16 inSample, int channel) { +Sint16 AudioManager::ProcessSample(Sint16 inSample, int channel) { Sint16 outSample; int idx0 = 2 * channel; int idx1 = idx0 + 1; @@ -135,7 +96,7 @@ PUBLIC STATIC Sint16 AudioManager::ProcessSample(Sint16 inSample, int channel) { return (Sint16)(inSample * (1.0 - AudioManager::LowPassFilter) + outSample * mGain * AudioManager::LowPassFilter); } -PUBLIC STATIC float AudioManager::ProcessSampleFloat(float inSample, int channel) { +float AudioManager::ProcessSampleFloat(float inSample, int channel) { float outSample; int idx0 = 2 * channel; int idx1 = idx0 + 1; @@ -152,7 +113,7 @@ PUBLIC STATIC float AudioManager::ProcessSampleFloat(float inSample, int channe return (float)(inSample * (1.0 - AudioManager::LowPassFilter) + outSample * mGain * AudioManager::LowPassFilter); } -PUBLIC STATIC void AudioManager::Init() { +void AudioManager::Init() { CalculateCoeffs(); SoundArray = (AudioChannel*)Memory::Calloc(SoundArrayLength, sizeof(AudioChannel)); @@ -215,7 +176,7 @@ PUBLIC STATIC void AudioManager::Init() { AudioQueue = (Uint8*)Memory::Calloc(8, AudioQueueMaxSize); } -PUBLIC STATIC void AudioManager::ClampParams(float& pan, float& speed, float& volume) { +void AudioManager::ClampParams(float& pan, float& speed, float& volume) { if (pan < -1.0f) pan = -1.0f; else if (pan > 1.0f) @@ -230,7 +191,7 @@ PUBLIC STATIC void AudioManager::ClampParams(float& pan, float& speed, float& volume = 0.0f; } -PRIVATE STATIC void AudioManager::UpdateChannelPlayer(AudioPlayback* playback, ISound* sound) { +void AudioManager::UpdateChannelPlayer(AudioPlayback* playback, ISound* sound) { if (!playback->SoundData) { playback->SoundData = new SoundFormat; playback->OwnsSoundData = true; @@ -247,10 +208,10 @@ PRIVATE STATIC void AudioManager::UpdateChannelPlayer(AudioPlayback* playback, playback->SoundData->SampleIndex = 0; } -PUBLIC STATIC void AudioManager::SetSound(int channel, ISound* music) { +void AudioManager::SetSound(int channel, ISound* music) { AudioManager::SetSound(channel, music, false, 0, 0.0f, 1.0f, 1.0f, nullptr); } -PUBLIC STATIC void AudioManager::SetSound(int channel, ISound* sound, bool loop, int loopPoint, float pan, float speed, float volume, void* origin) { +void AudioManager::SetSound(int channel, ISound* sound, bool loop, int loopPoint, float pan, float speed, float volume, void* origin) { AudioManager::Lock(); AudioChannel* audio = &SoundArray[channel]; @@ -286,10 +247,10 @@ PUBLIC STATIC void AudioManager::SetSound(int channel, ISound* sound, bool loo AudioManager::Unlock(); } -PUBLIC STATIC int AudioManager::PlaySound(ISound* music) { +int AudioManager::PlaySound(ISound* music) { return AudioManager::PlaySound(music, false, 0, 0.0f, 1.0f, 1.0f, nullptr); } -PUBLIC STATIC int AudioManager::PlaySound(ISound* music, bool loop, int loopPoint, float pan, float speed, float volume, void* origin) { +int AudioManager::PlaySound(ISound* music, bool loop, int loopPoint, float pan, float speed, float volume, void* origin) { for (int i = 0; i < SoundArrayLength; i++) { AudioChannel* audio = &SoundArray[i]; if (!audio->Audio || audio->Stopped) { @@ -301,10 +262,10 @@ PUBLIC STATIC int AudioManager::PlaySound(ISound* music, bool loop, int loopP return -1; } -PUBLIC STATIC void AudioManager::PushMusic(ISound* music, bool loop, Uint32 lp, float pan, float speed, float volume, double fadeInAfterFinished) { +void AudioManager::PushMusic(ISound* music, bool loop, Uint32 lp, float pan, float speed, float volume, double fadeInAfterFinished) { PushMusicAt(music, 0.0, loop, lp, pan, speed, volume, fadeInAfterFinished); } -PUBLIC STATIC void AudioManager::PushMusicAt(ISound* music, double at, bool loop, Uint32 lp, float pan, float speed, float volume, double fadeInAfterFinished) { +void AudioManager::PushMusicAt(ISound* music, double at, bool loop, Uint32 lp, float pan, float speed, float volume, double fadeInAfterFinished) { if (music->LoadFailed) return; AudioManager::Lock(); @@ -343,7 +304,7 @@ PUBLIC STATIC void AudioManager::PushMusicAt(ISound* music, double at, bool lo AudioManager::Unlock(); } -PUBLIC STATIC void AudioManager::RemoveMusic(ISound* music) { +void AudioManager::RemoveMusic(ISound* music) { AudioManager::Lock(); for (size_t i = 0; i < MusicStack.size(); i++) { if (MusicStack[i]->Audio == music) { @@ -353,10 +314,10 @@ PUBLIC STATIC void AudioManager::RemoveMusic(ISound* music) { } AudioManager::Unlock(); } -PUBLIC STATIC bool AudioManager::IsPlayingMusic() { +bool AudioManager::IsPlayingMusic() { return MusicStack.size() > 0; } -PUBLIC STATIC bool AudioManager::IsPlayingMusic(ISound* music) { +bool AudioManager::IsPlayingMusic(ISound* music) { for (size_t i = 0; i < MusicStack.size(); i++) { if (MusicStack[i]->Audio == music) { return true; @@ -364,7 +325,7 @@ PUBLIC STATIC bool AudioManager::IsPlayingMusic(ISound* music) { } return false; } -PUBLIC STATIC void AudioManager::ClearMusic() { +void AudioManager::ClearMusic() { AudioManager::Lock(); for (size_t i = 0; i < MusicStack.size(); i++) { delete MusicStack[i]; @@ -372,7 +333,7 @@ PUBLIC STATIC void AudioManager::ClearMusic() { MusicStack.clear(); AudioManager::Unlock(); } -PUBLIC STATIC void AudioManager::ClearSounds() { +void AudioManager::ClearSounds() { AudioManager::Lock(); for (int i = 0; i < SoundArrayLength; i++) { SoundArray[i].Stopped = true; @@ -383,7 +344,7 @@ PUBLIC STATIC void AudioManager::ClearSounds() { } AudioManager::Unlock(); } -PUBLIC STATIC void AudioManager::FadeOutMusic(double seconds) { +void AudioManager::FadeOutMusic(double seconds) { AudioManager::Lock(); if (MusicStack.size() > 0) { MusicStack[0]->Fading = MusicFade_Out; @@ -392,7 +353,7 @@ PUBLIC STATIC void AudioManager::FadeOutMusic(double seconds) { } AudioManager::Unlock(); } -PUBLIC STATIC void AudioManager::AlterMusic(float pan, float speed, float volume) { +void AudioManager::AlterMusic(float pan, float speed, float volume) { AudioManager::Lock(); if (MusicStack.size() > 0) { AudioManager::ClampParams(pan, speed, volume); @@ -402,7 +363,7 @@ PUBLIC STATIC void AudioManager::AlterMusic(float pan, float speed, float volu } AudioManager::Unlock(); } -PUBLIC STATIC double AudioManager::GetMusicPosition(ISound* music) { +double AudioManager::GetMusicPosition(ISound* music) { AudioManager::Lock(); double position = 0.0; for (size_t i = 0; i < MusicStack.size(); i++) { @@ -415,14 +376,14 @@ PUBLIC STATIC double AudioManager::GetMusicPosition(ISound* music) { return position; } -PUBLIC STATIC void AudioManager::Lock() { +void AudioManager::Lock() { SDL_LockAudioDevice(Device); } -PUBLIC STATIC void AudioManager::Unlock() { +void AudioManager::Unlock() { SDL_UnlockAudioDevice(Device); } -PUBLIC STATIC int AudioManager::GetFreeChannel() { +int AudioManager::GetFreeChannel() { AudioManager::Lock(); int channel = -1; for (int i = 0; i < SoundArrayLength; i++) { @@ -434,7 +395,7 @@ PUBLIC STATIC int AudioManager::GetFreeChannel() { AudioManager::Unlock(); return channel; } -PUBLIC STATIC void AudioManager::AlterChannel(int channel, float pan, float speed, float volume) { +void AudioManager::AlterChannel(int channel, float pan, float speed, float volume) { AudioManager::Lock(); if (!SoundArray[channel].Stopped && !SoundArray[channel].Paused) { AudioManager::ClampParams(pan, speed, volume); @@ -444,14 +405,14 @@ PUBLIC STATIC void AudioManager::AlterChannel(int channel, float pan, float sp } AudioManager::Unlock(); } -PUBLIC STATIC bool AudioManager::AudioIsPlaying(int channel) { +bool AudioManager::AudioIsPlaying(int channel) { bool isPlaying = false; AudioManager::Lock(); isPlaying = !SoundArray[channel].Stopped && !SoundArray[channel].Paused; AudioManager::Unlock(); return isPlaying; } -PUBLIC STATIC bool AudioManager::AudioIsPlaying(ISound* audio) { +bool AudioManager::AudioIsPlaying(ISound* audio) { bool isPlaying = false; AudioManager::Lock(); for (int i = 0; i < SoundArrayLength; i++) { @@ -462,12 +423,12 @@ PUBLIC STATIC bool AudioManager::AudioIsPlaying(ISound* audio) { AudioManager::Unlock(); return isPlaying; } -PUBLIC STATIC void AudioManager::AudioUnpause(int channel) { +void AudioManager::AudioUnpause(int channel) { AudioManager::Lock(); SoundArray[channel].Paused = false; AudioManager::Unlock(); } -PUBLIC STATIC void AudioManager::AudioUnpause(ISound* audio) { +void AudioManager::AudioUnpause(ISound* audio) { AudioManager::Lock(); for (int i = 0; i < SoundArrayLength; i++) { if (SoundArray[i].Audio == audio) @@ -475,12 +436,12 @@ PUBLIC STATIC void AudioManager::AudioUnpause(ISound* audio) { } AudioManager::Unlock(); } -PUBLIC STATIC void AudioManager::AudioPause(int channel) { +void AudioManager::AudioPause(int channel) { AudioManager::Lock(); SoundArray[channel].Paused = true; AudioManager::Unlock(); } -PUBLIC STATIC void AudioManager::AudioPause(ISound* audio) { +void AudioManager::AudioPause(ISound* audio) { AudioManager::Lock(); for (int i = 0; i < SoundArrayLength; i++) { if (SoundArray[i].Audio == audio) @@ -488,12 +449,12 @@ PUBLIC STATIC void AudioManager::AudioPause(ISound* audio) { } AudioManager::Unlock(); } -PUBLIC STATIC void AudioManager::AudioStop(int channel) { +void AudioManager::AudioStop(int channel) { AudioManager::Lock(); SoundArray[channel].Stopped = true; AudioManager::Unlock(); } -PUBLIC STATIC void AudioManager::AudioStop(ISound* audio) { +void AudioManager::AudioStop(ISound* audio) { AudioManager::Lock(); for (int i = 0; i < SoundArrayLength; i++) { if (SoundArray[i].Audio == audio) @@ -501,26 +462,26 @@ PUBLIC STATIC void AudioManager::AudioStop(ISound* audio) { } AudioManager::Unlock(); } -PUBLIC STATIC void AudioManager::AudioUnpauseAll() { +void AudioManager::AudioUnpauseAll() { AudioManager::Lock(); for (int i = 0; i < SoundArrayLength; i++) SoundArray[i].Paused = false; AudioManager::Unlock(); } -PUBLIC STATIC void AudioManager::AudioPauseAll() { +void AudioManager::AudioPauseAll() { AudioManager::Lock(); for (int i = 0; i < SoundArrayLength; i++) SoundArray[i].Paused = true; AudioManager::Unlock(); } -PUBLIC STATIC void AudioManager::AudioStopAll() { +void AudioManager::AudioStopAll() { AudioManager::Lock(); for (int i = 0; i < SoundArrayLength; i++) SoundArray[i].Stopped = true; AudioManager::Unlock(); } -PUBLIC STATIC bool AudioManager::IsOriginPlaying(void* origin, ISound* audio) { +bool AudioManager::IsOriginPlaying(void* origin, ISound* audio) { bool isPlaying = false; AudioManager::Lock(); for (int i = 0; i < SoundArrayLength; i++) { @@ -531,7 +492,7 @@ PUBLIC STATIC bool AudioManager::IsOriginPlaying(void* origin, ISound* audio) AudioManager::Unlock(); return isPlaying; } -PUBLIC STATIC void AudioManager::StopOriginSound(void* origin, ISound* audio) { +void AudioManager::StopOriginSound(void* origin, ISound* audio) { AudioManager::Lock(); for (int i = 0; i < SoundArrayLength; i++) { if (SoundArray[i].Audio == audio && SoundArray[i].Origin == origin) @@ -539,7 +500,7 @@ PUBLIC STATIC void AudioManager::StopOriginSound(void* origin, ISound* audio) } AudioManager::Unlock(); } -PUBLIC STATIC void AudioManager::StopAllOriginSounds(void* origin) { +void AudioManager::StopAllOriginSounds(void* origin) { AudioManager::Lock(); for (int i = 0; i < SoundArrayLength; i++) { if (SoundArray[i].Origin == origin) @@ -548,7 +509,7 @@ PUBLIC STATIC void AudioManager::StopAllOriginSounds(void* origin) { AudioManager::Unlock(); } -PUBLIC STATIC void AudioManager::MixAudioLR(Uint8* dest, Uint8* src, size_t len, float volumeL, float volumeR) { +void AudioManager::MixAudioLR(Uint8* dest, Uint8* src, size_t len, float volumeL, float volumeR) { #define DEFINE_STREAM_PTR(type) type* src##type; type* dest##type #define PAN_STREAM_PTR(type) \ src##type = (type*)(src); \ @@ -579,7 +540,7 @@ PUBLIC STATIC void AudioManager::MixAudioLR(Uint8* dest, Uint8* src, size_t le #undef PAN_STREAM_PTR } -PRIVATE STATIC bool AudioManager::HandleFading(AudioChannel* audio) { +bool AudioManager::HandleFading(AudioChannel* audio) { if (audio->Fading == MusicFade_Out) { audio->FadeTimer -= (double)DeviceFormat.samples / DeviceFormat.freq; if (audio->FadeTimer < 0.0) { @@ -599,7 +560,7 @@ PRIVATE STATIC bool AudioManager::HandleFading(AudioChannel* audio) { } return false; } -PUBLIC STATIC bool AudioManager::AudioPlayMix(AudioChannel* audio, Uint8* stream, int len, float volume) { +bool AudioManager::AudioPlayMix(AudioChannel* audio, Uint8* stream, int len, float volume) { if (AudioManager::HandleFading(audio)) return true; @@ -692,7 +653,7 @@ PUBLIC STATIC bool AudioManager::AudioPlayMix(AudioChannel* audio, Uint8* stre return false; } -PUBLIC STATIC void AudioManager::AudioCallback(void* data, Uint8* stream, int len) { +void AudioManager::AudioCallback(void* data, Uint8* stream, int len) { memset(stream, 0x00, len); if (AudioManager::AudioQueueSize >= (size_t)len) { @@ -749,7 +710,7 @@ PUBLIC STATIC void AudioManager::AudioCallback(void* data, Uint8* stream, int } } -PUBLIC STATIC void AudioManager::Dispose() { +void AudioManager::Dispose() { Memory::Free(SoundArray); Memory::Free(AudioQueue); Memory::Free(MixBuffer); diff --git a/source/Engine/Audio/AudioPlayback.cpp b/source/Engine/Audio/AudioPlayback.cpp index c5df774d..d8fddab0 100644 --- a/source/Engine/Audio/AudioPlayback.cpp +++ b/source/Engine/Audio/AudioPlayback.cpp @@ -1,29 +1,7 @@ -#if INTERFACE -#include -#include - -#include - -class AudioPlayback { -public: - Uint8* Buffer = NULL; - Uint8* UnconvertedSampleBuffer = NULL; - Uint32 BufferedSamples = 0; - SDL_AudioSpec Format; - size_t BytesPerSample = 0; - size_t RequiredSamples = 0; - size_t DeviceBytesPerSample = 0; - SDL_AudioStream* ConversionStream = NULL; - SoundFormat* SoundData = NULL; - bool OwnsSoundData = false; - Sint32 LoopIndex = -1; -}; -#endif - #include #include -PUBLIC AudioPlayback::AudioPlayback(SDL_AudioSpec format, size_t requiredSamples, size_t audioBytesPerSample, size_t deviceBytesPerSample) { +AudioPlayback::AudioPlayback(SDL_AudioSpec format, size_t requiredSamples, size_t audioBytesPerSample, size_t deviceBytesPerSample) { Format = format; RequiredSamples = requiredSamples; BytesPerSample = audioBytesPerSample; @@ -37,7 +15,7 @@ PUBLIC AudioPlayback::AudioPlayback(SDL_AudioSpec format, size_t requiredSa CreateConversionStream(format); } -PUBLIC void AudioPlayback::Change(SDL_AudioSpec format, size_t requiredSamples, size_t audioBytesPerSample, size_t deviceBytesPerSample) { +void AudioPlayback::Change(SDL_AudioSpec format, size_t requiredSamples, size_t audioBytesPerSample, size_t deviceBytesPerSample) { bool formatChanged = format.format != Format.format || format.channels != Format.channels || format.freq != Format.freq; size_t bufSize = requiredSamples * deviceBytesPerSample; @@ -60,7 +38,7 @@ PUBLIC void AudioPlayback::Change(SDL_AudioSpec format, size_t requiredSamples, } } -PRIVATE void AudioPlayback::CreateConversionStream(SDL_AudioSpec format) { +void AudioPlayback::CreateConversionStream(SDL_AudioSpec format) { ConversionStream = SDL_NewAudioStream(Format.format, Format.channels, Format.freq, AudioManager::DeviceFormat.format, AudioManager::DeviceFormat.channels, AudioManager::DeviceFormat.freq); if (ConversionStream == NULL) { Log::Print(Log::LOG_ERROR, "Conversion stream failed to create: %s", SDL_GetError()); @@ -75,7 +53,7 @@ PRIVATE void AudioPlayback::CreateConversionStream(SDL_AudioSpec format) { } } -PUBLIC void AudioPlayback::Dispose() { +void AudioPlayback::Dispose() { if (Buffer) { Memory::Free(Buffer); Buffer = NULL; @@ -98,7 +76,7 @@ PUBLIC void AudioPlayback::Dispose() { } } -PUBLIC int AudioPlayback::RequestSamples(int samples, bool loop, int sample_to_loop_to) { +int AudioPlayback::RequestSamples(int samples, bool loop, int sample_to_loop_to) { if (!SoundData) return AudioManager::REQUEST_ERROR; @@ -164,13 +142,13 @@ PUBLIC int AudioPlayback::RequestSamples(int samples, bool loop, int sample_to_l return received_bytes; } -PUBLIC void AudioPlayback::Seek(int samples) { +void AudioPlayback::Seek(int samples) { if (!SoundData) return; SoundData->SeekSample(samples); } -PUBLIC AudioPlayback::~AudioPlayback() { +AudioPlayback::~AudioPlayback() { Dispose(); } diff --git a/source/Engine/Bytecode/Bytecode.cpp b/source/Engine/Bytecode/Bytecode.cpp index aadfcb44..dcd81e10 100644 --- a/source/Engine/Bytecode/Bytecode.cpp +++ b/source/Engine/Bytecode/Bytecode.cpp @@ -1,21 +1,3 @@ -#if INTERFACE -#include -#include - -class Bytecode { -public: - static const char* Magic; - static Uint32 LatestVersion; - static vector FunctionNames; - - vector Functions; - - Uint8 Version; - bool HasDebugInfo = false; - const char* SourceFilename = nullptr; -}; -#endif - #include #include #include @@ -26,15 +8,15 @@ const char* Bytecode::Magic = "HTVM"; Uint32 Bytecode::LatestVersion = BYTECODE_VERSION; vector Bytecode::FunctionNames{ "", "main" }; -PUBLIC Bytecode::Bytecode() { +Bytecode::Bytecode() { Version = LatestVersion; } -PUBLIC Bytecode::~Bytecode() { +Bytecode::~Bytecode() { Memory::Free((void*)SourceFilename); } -PUBLIC bool Bytecode::Read(BytecodeContainer bytecode, HashMap* tokens) { +bool Bytecode::Read(BytecodeContainer bytecode, HashMap* tokens) { MemoryStream* stream = MemoryStream::New(bytecode.Data, bytecode.Size); if (!stream) return false; @@ -143,7 +125,7 @@ PUBLIC bool Bytecode::Read(BytecodeContainer bytecode, HashMap* to return true; } -PUBLIC void Bytecode::Write(Stream* stream, const char* sourceFilename, HashMap* tokenMap) { +void Bytecode::Write(Stream* stream, const char* sourceFilename, HashMap* tokenMap) { int hasSourceFilename = (sourceFilename != nullptr) ? 1 : 0; int hasDebugInfo = HasDebugInfo ? 1 : 0; diff --git a/source/Engine/Bytecode/Compiler.cpp b/source/Engine/Bytecode/Compiler.cpp index 2c4f3cb4..740866be 100644 --- a/source/Engine/Bytecode/Compiler.cpp +++ b/source/Engine/Bytecode/Compiler.cpp @@ -1,32 +1,3 @@ -#if INTERFACE -#include -#include - -class Compiler { -public: - static Parser parser; - static Scanner scanner; - static ParseRule* Rules; - static vector Functions; - static vector ModuleLocals; - static HashMap* TokenMap; - static bool ShowWarnings; - static bool WriteDebugInfo; - static bool WriteSourceFilename; - - class Compiler* Enclosing = nullptr; - ObjFunction* Function = nullptr; - int Type = 0; - string ClassName; - Local Locals[0x100]; - int LocalCount = 0; - int ScopeDepth = 0; - vector ClassHashList; - vector ClassExtendedList; - vector* UnusedVariables = nullptr; -}; -#endif - #include #include #include @@ -173,7 +144,7 @@ enum FunctionType { TYPE_METHOD, }; -PUBLIC Token Compiler::MakeToken(int type) { +Token Compiler::MakeToken(int type) { Token token; token.Type = type; token.Start = scanner.Start; @@ -183,7 +154,7 @@ PUBLIC Token Compiler::MakeToken(int type) { return token; } -PUBLIC Token Compiler::MakeTokenRaw(int type, const char* message) { +Token Compiler::MakeTokenRaw(int type, const char* message) { Token token; token.Type = type; token.Start = (char*)message; @@ -193,7 +164,7 @@ PUBLIC Token Compiler::MakeTokenRaw(int type, const char* message) { return token; } -PUBLIC Token Compiler::ErrorToken(const char* message) { +Token Compiler::ErrorToken(const char* message) { Token token; token.Type = TOKEN_ERROR; token.Start = (char*)message; @@ -204,49 +175,49 @@ PUBLIC Token Compiler::ErrorToken(const char* message) { return token; } -PUBLIC bool Compiler::IsEOF() { +bool Compiler::IsEOF() { return *scanner.Current == 0; } -PUBLIC bool Compiler::IsDigit(char c) { +bool Compiler::IsDigit(char c) { return c >= '0' && c <= '9'; } -PUBLIC bool Compiler::IsHexDigit(char c) { +bool Compiler::IsHexDigit(char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); } -PUBLIC bool Compiler::IsAlpha(char c) { +bool Compiler::IsAlpha(char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); } -PUBLIC bool Compiler::IsIdentifierStart(char c) { +bool Compiler::IsIdentifierStart(char c) { return IsAlpha(c) || c == '$' || c == '_'; } -PUBLIC bool Compiler::IsIdentifierBody(char c) { +bool Compiler::IsIdentifierBody(char c) { return IsIdentifierStart(c) || IsDigit(c); } -PUBLIC bool Compiler::MatchChar(char expected) { +bool Compiler::MatchChar(char expected) { if (IsEOF()) return false; if (*scanner.Current != expected) return false; scanner.Current++; return true; } -PUBLIC char Compiler::AdvanceChar() { +char Compiler::AdvanceChar() { return *scanner.Current++; // scanner.Current++; // return *(scanner.Current - 1); } -PUBLIC char Compiler::PrevChar() { +char Compiler::PrevChar() { return *(scanner.Current - 1); } -PUBLIC char Compiler::PeekChar() { +char Compiler::PeekChar() { return *scanner.Current; } -PUBLIC char Compiler::PeekNextChar() { +char Compiler::PeekNextChar() { if (IsEOF()) return 0; return *(scanner.Current + 1); } -PUBLIC VIRTUAL void Compiler::SkipWhitespace() { +void Compiler::SkipWhitespace() { while (true) { char c = PeekChar(); switch (c) { @@ -302,14 +273,14 @@ PUBLIC VIRTUAL void Compiler::SkipWhitespace() { } // Token functions -PUBLIC int Compiler::CheckKeyword(int start, int length, const char* rest, int type) { +int Compiler::CheckKeyword(int start, int length, const char* rest, int type) { if (scanner.Current - scanner.Start == start + length && (!rest || memcmp(scanner.Start + start, rest, length) == 0)) return type; return TOKEN_IDENTIFIER; } -PUBLIC VIRTUAL int Compiler::GetKeywordType() { +int Compiler::GetKeywordType() { switch (*scanner.Start) { case 'a': if (scanner.Current - scanner.Start > 1) { @@ -459,7 +430,7 @@ PUBLIC VIRTUAL int Compiler::GetKeywordType() { return TOKEN_IDENTIFIER; } -PUBLIC Token Compiler::StringToken() { +Token Compiler::StringToken() { while (PeekChar() != '"' && !IsEOF()) { bool lineBreak = false; switch (PeekChar()) { @@ -487,7 +458,7 @@ PUBLIC Token Compiler::StringToken() { AdvanceChar(); return MakeToken(TOKEN_STRING); } -PUBLIC Token Compiler::NumberToken() { +Token Compiler::NumberToken() { if (*scanner.Start == '0' && (PeekChar() == 'x' || PeekChar() == 'X')) { AdvanceChar(); // x while (IsHexDigit(PeekChar())) @@ -511,13 +482,13 @@ PUBLIC Token Compiler::NumberToken() { return MakeToken(TOKEN_NUMBER); } -PUBLIC Token Compiler::IdentifierToken() { +Token Compiler::IdentifierToken() { while (IsIdentifierBody(PeekChar())) AdvanceChar(); return MakeToken(GetKeywordType()); } -PUBLIC VIRTUAL Token Compiler::ScanToken() { +Token Compiler::ScanToken() { SkipWhitespace(); scanner.Start = scanner.Current; @@ -563,7 +534,7 @@ PUBLIC VIRTUAL Token Compiler::ScanToken() { return ErrorToken("Unexpected character."); } -PUBLIC void Compiler::AdvanceToken() { +void Compiler::AdvanceToken() { parser.Previous = parser.Current; while (true) { @@ -574,14 +545,14 @@ PUBLIC void Compiler::AdvanceToken() { ErrorAtCurrent(parser.Current.Start); } } -PUBLIC Token Compiler::NextToken() { +Token Compiler::NextToken() { AdvanceToken(); return parser.Previous; } -PUBLIC Token Compiler::PeekToken() { +Token Compiler::PeekToken() { return parser.Current; } -PUBLIC Token Compiler::PeekNextToken() { +Token Compiler::PeekNextToken() { Parser previousParser = parser; Scanner previousScanner = scanner; Token next; @@ -594,15 +565,15 @@ PUBLIC Token Compiler::PeekNextToken() { return next; } -PUBLIC Token Compiler::PrevToken() { +Token Compiler::PrevToken() { return parser.Previous; } -PUBLIC bool Compiler::MatchToken(int expectedType) { +bool Compiler::MatchToken(int expectedType) { if (!CheckToken(expectedType)) return false; AdvanceToken(); return true; } -PUBLIC bool Compiler::MatchAssignmentToken() { +bool Compiler::MatchAssignmentToken() { switch (parser.Current.Type) { case TOKEN_ASSIGNMENT: case TOKEN_ASSIGNMENT_MULTIPLY: @@ -628,10 +599,10 @@ PUBLIC bool Compiler::MatchAssignmentToken() { } return false; } -PUBLIC bool Compiler::CheckToken(int expectedType) { +bool Compiler::CheckToken(int expectedType) { return parser.Current.Type == expectedType; } -PUBLIC void Compiler::ConsumeToken(int type, const char* message) { +void Compiler::ConsumeToken(int type, const char* message) { if (parser.Current.Type == type) { AdvanceToken(); return; @@ -640,7 +611,7 @@ PUBLIC void Compiler::ConsumeToken(int type, const char* message) { ErrorAtCurrent(message); } -PUBLIC void Compiler::SynchronizeToken() { +void Compiler::SynchronizeToken() { parser.PanicMode = false; while (PeekToken().Type != TOKEN_EOF) { @@ -671,7 +642,7 @@ PUBLIC void Compiler::SynchronizeToken() { } // Error handling -PUBLIC bool Compiler::ReportError(int line, bool fatal, const char* string, ...) { +bool Compiler::ReportError(int line, bool fatal, const char* string, ...) { if (!fatal && !Compiler::ShowWarnings) return true; @@ -690,7 +661,7 @@ PUBLIC bool Compiler::ReportError(int line, bool fatal, const char* str return !fatal; } -PUBLIC bool Compiler::ReportErrorPos(int line, int pos, bool fatal, const char* string, ...) { +bool Compiler::ReportErrorPos(int line, int pos, bool fatal, const char* string, ...) { if (!fatal && !Compiler::ShowWarnings) return true; @@ -742,7 +713,7 @@ PUBLIC bool Compiler::ReportErrorPos(int line, int pos, bool fatal, con return false; } -PUBLIC void Compiler::ErrorAt(Token* token, const char* message, bool fatal) { +void Compiler::ErrorAt(Token* token, const char* message, bool fatal) { if (fatal) { if (parser.PanicMode) return; @@ -759,16 +730,16 @@ PUBLIC void Compiler::ErrorAt(Token* token, const char* message, bool f if (fatal) parser.HadError = true; } -PUBLIC void Compiler::Error(const char* message) { +void Compiler::Error(const char* message) { ErrorAt(&parser.Previous, message, true); } -PUBLIC void Compiler::ErrorAtCurrent(const char* message) { +void Compiler::ErrorAtCurrent(const char* message) { ErrorAt(&parser.Current, message, true); } -PUBLIC void Compiler::Warning(const char* message) { +void Compiler::Warning(const char* message) { ErrorAt(&parser.Current, message, false); } -PUBLIC void Compiler::WarningInFunction(const char* format, ...) { +void Compiler::WarningInFunction(const char* format, ...) { if (!Compiler::ShowWarnings) return; @@ -803,19 +774,19 @@ PUBLIC void Compiler::WarningInFunction(const char* format, ...) { free(textBuffer); } -PUBLIC void Compiler::ParseVariable(const char* errorMessage) { +void Compiler::ParseVariable(const char* errorMessage) { ConsumeToken(TOKEN_IDENTIFIER, errorMessage); DeclareVariable(&parser.Previous); } -PUBLIC bool Compiler::IdentifiersEqual(Token* a, Token* b) { +bool Compiler::IdentifiersEqual(Token* a, Token* b) { if (a->Length != b->Length) return false; return memcmp(a->Start, b->Start, a->Length) == 0; } -PUBLIC void Compiler::MarkInitialized() { +void Compiler::MarkInitialized() { if (ScopeDepth == 0) return; Locals[LocalCount - 1].Depth = ScopeDepth; } -PUBLIC void Compiler::DefineVariableToken(Token global) { +void Compiler::DefineVariableToken(Token global) { if (ScopeDepth > 0) { MarkInitialized(); return; @@ -823,7 +794,7 @@ PUBLIC void Compiler::DefineVariableToken(Token global) { EmitByte(OP_DEFINE_GLOBAL); EmitStringHash(global); } -PUBLIC void Compiler::DeclareVariable(Token* name) { +void Compiler::DeclareVariable(Token* name) { if (ScopeDepth == 0) return; for (int i = LocalCount - 1; i >= 0; i--) { @@ -838,15 +809,15 @@ PUBLIC void Compiler::DeclareVariable(Token* name) { AddLocal(*name); } -PUBLIC int Compiler::ParseModuleVariable(const char* errorMessage) { +int Compiler::ParseModuleVariable(const char* errorMessage) { ConsumeToken(TOKEN_IDENTIFIER, errorMessage); return DeclareModuleVariable(&parser.Previous); } -PUBLIC void Compiler::DefineModuleVariable(int local) { +void Compiler::DefineModuleVariable(int local) { EmitByte(OP_DEFINE_MODULE_LOCAL); Compiler::ModuleLocals[local].Depth = 0; } -PUBLIC int Compiler::DeclareModuleVariable(Token* name) { +int Compiler::DeclareModuleVariable(Token* name) { for (int i = Compiler::ModuleLocals.size() - 1; i >= 0; i--) { Local& local = Compiler::ModuleLocals[i]; @@ -856,7 +827,7 @@ PUBLIC int Compiler::DeclareModuleVariable(Token* name) { return AddModuleLocal(*name); } -PRIVATE void Compiler::WarnVariablesUnused() { +void Compiler::WarnVariablesUnused() { if (!Compiler::ShowWarnings) return; @@ -878,7 +849,7 @@ PRIVATE void Compiler::WarnVariablesUnused() { WarningInFunction("%s", message.c_str()); } -PUBLIC void Compiler::EmitSetOperation(Uint8 setOp, int arg, Token name) { +void Compiler::EmitSetOperation(Uint8 setOp, int arg, Token name) { switch (setOp) { case OP_SET_GLOBAL: case OP_SET_PROPERTY: @@ -899,7 +870,7 @@ PUBLIC void Compiler::EmitSetOperation(Uint8 setOp, int arg, Token name) { break; } } -PUBLIC void Compiler::EmitGetOperation(Uint8 getOp, int arg, Token name) { +void Compiler::EmitGetOperation(Uint8 getOp, int arg, Token name) { switch (getOp) { case OP_GET_GLOBAL: case OP_GET_PROPERTY: @@ -919,7 +890,7 @@ PUBLIC void Compiler::EmitGetOperation(Uint8 getOp, int arg, Token name) { break; } } -PUBLIC void Compiler::EmitAssignmentToken(Token assignmentToken) { +void Compiler::EmitAssignmentToken(Token assignmentToken) { switch (assignmentToken.Type) { case TOKEN_ASSIGNMENT_PLUS: EmitByte(OP_ADD); @@ -962,23 +933,23 @@ PUBLIC void Compiler::EmitAssignmentToken(Token assignmentToken) { break; } } -PUBLIC void Compiler::EmitCopy(Uint8 count) { +void Compiler::EmitCopy(Uint8 count) { EmitByte(OP_COPY); EmitByte(count); } -PUBLIC void Compiler::EmitCall(const char *name, int argCount, bool isSuper) { +void Compiler::EmitCall(const char *name, int argCount, bool isSuper) { EmitBytes(OP_INVOKE, argCount); EmitStringHash(name); EmitByte(isSuper ? 1 : 0); } -PUBLIC void Compiler::EmitCall(Token name, int argCount, bool isSuper) { +void Compiler::EmitCall(Token name, int argCount, bool isSuper) { EmitBytes(OP_INVOKE, argCount); EmitStringHash(name); EmitByte(isSuper ? 1 : 0); } -PUBLIC void Compiler::NamedVariable(Token name, bool canAssign) { +void Compiler::NamedVariable(Token name, bool canAssign) { Uint8 getOp, setOp; int arg = ResolveLocal(&name); @@ -1028,14 +999,14 @@ PUBLIC void Compiler::NamedVariable(Token name, bool canAssign) { EmitGetOperation(getOp, arg, name); } } -PUBLIC void Compiler::ScopeBegin() { +void Compiler::ScopeBegin() { ScopeDepth++; } -PUBLIC void Compiler::ScopeEnd() { +void Compiler::ScopeEnd() { ScopeDepth--; ClearToScope(ScopeDepth); } -PUBLIC void Compiler::ClearToScope(int depth) { +void Compiler::ClearToScope(int depth) { int popCount = 0; while (LocalCount > 0 && Locals[LocalCount - 1].Depth > depth) { if (!Locals[LocalCount - 1].Resolved) @@ -1047,7 +1018,7 @@ PUBLIC void Compiler::ClearToScope(int depth) { } PopMultiple(popCount); } -PUBLIC void Compiler::PopToScope(int depth) { +void Compiler::PopToScope(int depth) { int lcl = LocalCount; int popCount = 0; while (lcl > 0 && Locals[lcl - 1].Depth > depth) { @@ -1056,7 +1027,7 @@ PUBLIC void Compiler::PopToScope(int depth) { } PopMultiple(popCount); } -PUBLIC void Compiler::PopMultiple(int count) { +void Compiler::PopMultiple(int count) { if (count == 1) { EmitByte(OP_POP); return; @@ -1070,7 +1041,7 @@ PUBLIC void Compiler::PopMultiple(int count) { count -= max; } } -PUBLIC int Compiler::AddLocal(Token name) { +int Compiler::AddLocal(Token name) { if (LocalCount == 0xFF) { Error("Too many local variables in function."); return -1; @@ -1081,7 +1052,7 @@ PUBLIC int Compiler::AddLocal(Token name) { local->Resolved = false; return LocalCount - 1; } -PUBLIC int Compiler::AddLocal(const char* name, size_t len) { +int Compiler::AddLocal(const char* name, size_t len) { if (LocalCount == 0xFF) { Error("Too many local variables in function."); return -1; @@ -1092,24 +1063,24 @@ PUBLIC int Compiler::AddLocal(const char* name, size_t len) { RenameLocal(local, name, len); return LocalCount - 1; } -PUBLIC int Compiler::AddHiddenLocal(const char* name, size_t len) { +int Compiler::AddHiddenLocal(const char* name, size_t len) { int local = AddLocal(name, len); Locals[local].Resolved = true; MarkInitialized(); return local; } -PUBLIC void Compiler::RenameLocal(Local* local, const char* name, size_t len) { +void Compiler::RenameLocal(Local* local, const char* name, size_t len) { local->Name.Start = (char*)name; local->Name.Length = len; } -PUBLIC void Compiler::RenameLocal(Local* local, const char* name) { +void Compiler::RenameLocal(Local* local, const char* name) { local->Name.Start = (char*)name; local->Name.Length = strlen(name); } -PUBLIC void Compiler::RenameLocal(Local* local, Token name) { +void Compiler::RenameLocal(Local* local, Token name) { local->Name = name; } -PUBLIC int Compiler::ResolveLocal(Token* name) { +int Compiler::ResolveLocal(Token* name) { for (int i = LocalCount - 1; i >= 0; i--) { Local* local = &Locals[i]; if (IdentifiersEqual(name, &local->Name)) { @@ -1122,7 +1093,7 @@ PUBLIC int Compiler::ResolveLocal(Token* name) { } return -1; } -PUBLIC int Compiler::AddModuleLocal(Token name) { +int Compiler::AddModuleLocal(Token name) { if (Compiler::ModuleLocals.size() == 0xFFFF) { Error("Too many locals in module."); return -1; @@ -1134,7 +1105,7 @@ PUBLIC int Compiler::AddModuleLocal(Token name) { Compiler::ModuleLocals.push_back(local); return ((int)Compiler::ModuleLocals.size()) - 1; } -PUBLIC int Compiler::ResolveModuleLocal(Token* name) { +int Compiler::ResolveModuleLocal(Token* name) { for (int i = Compiler::ModuleLocals.size() - 1; i >= 0; i--) { Local& local = Compiler::ModuleLocals[i]; if (IdentifiersEqual(name, &local.Name)) { @@ -1147,7 +1118,7 @@ PUBLIC int Compiler::ResolveModuleLocal(Token* name) { } return -1; } -PUBLIC Uint8 Compiler::GetArgumentList() { +Uint8 Compiler::GetArgumentList() { Uint8 argumentCount = 0; if (!CheckToken(TOKEN_RIGHT_PAREN)) { do { @@ -1165,17 +1136,17 @@ PUBLIC Uint8 Compiler::GetArgumentList() { } Token InstanceToken = Token { 0, NULL, 0, 0, 0 }; -PUBLIC void Compiler::GetThis(bool canAssign) { +void Compiler::GetThis(bool canAssign) { InstanceToken = parser.Previous; GetVariable(false); } -PUBLIC void Compiler::GetSuper(bool canAssign) { +void Compiler::GetSuper(bool canAssign) { InstanceToken = parser.Previous; if (!CheckToken(TOKEN_DOT)) Error("Expect '.' after 'super'."); EmitBytes(OP_GET_LOCAL, 0); } -PUBLIC void Compiler::GetDot(bool canAssign) { +void Compiler::GetDot(bool canAssign) { bool isSuper = InstanceToken.Type == TOKEN_SUPER; InstanceToken.Type = -1; @@ -1227,7 +1198,7 @@ PUBLIC void Compiler::GetDot(bool canAssign) { EmitGetOperation(OP_GET_PROPERTY, -1, nameToken); } } -PUBLIC void Compiler::GetElement(bool canAssign) { +void Compiler::GetElement(bool canAssign) { Token blank; memset(&blank, 0, sizeof(blank)); GetExpression(); @@ -1271,11 +1242,11 @@ PUBLIC void Compiler::GetElement(bool canAssign) { // Reading expressions bool negateConstant = false; -PUBLIC void Compiler::GetGrouping(bool canAssign) { +void Compiler::GetGrouping(bool canAssign) { GetExpression(); ConsumeToken(TOKEN_RIGHT_PAREN, "Expected \")\" after expression."); } -PUBLIC void Compiler::GetLiteral(bool canAssign) { +void Compiler::GetLiteral(bool canAssign) { switch (parser.Previous.Type) { case TOKEN_NULL: EmitByte(OP_NULL); break; case TOKEN_TRUE: EmitByte(OP_TRUE); break; @@ -1284,7 +1255,7 @@ PUBLIC void Compiler::GetLiteral(bool canAssign) { return; // Unreachable. } } -PUBLIC void Compiler::GetInteger(bool canAssign) { +void Compiler::GetInteger(bool canAssign) { int value = 0; char* start = parser.Previous.Start; if (start[0] == '0' && (start[1] == 'x' || start[1] == 'X')) @@ -1298,7 +1269,7 @@ PUBLIC void Compiler::GetInteger(bool canAssign) { EmitConstant(INTEGER_VAL(value)); } -PUBLIC void Compiler::GetDecimal(bool canAssign) { +void Compiler::GetDecimal(bool canAssign) { float value = 0; value = (float)atof(parser.Previous.Start); @@ -1308,7 +1279,7 @@ PUBLIC void Compiler::GetDecimal(bool canAssign) { EmitConstant(DECIMAL_VAL(value)); } -PUBLIC ObjString* Compiler::MakeString(Token token) { +ObjString* Compiler::MakeString(Token token) { ObjString* string = CopyString(token.Start + 1, token.Length - 2); // Escape the string @@ -1347,11 +1318,11 @@ PUBLIC ObjString* Compiler::MakeString(Token token) { return string; } -PUBLIC void Compiler::GetString(bool canAssign) { +void Compiler::GetString(bool canAssign) { ObjString* string = Compiler::MakeString(parser.Previous); EmitConstant(OBJECT_VAL(string)); } -PUBLIC void Compiler::GetArray(bool canAssign) { +void Compiler::GetArray(bool canAssign) { Uint32 count = 0; while (!MatchToken(TOKEN_RIGHT_SQUARE_BRACE)) { @@ -1367,7 +1338,7 @@ PUBLIC void Compiler::GetArray(bool canAssign) { EmitByte(OP_NEW_ARRAY); EmitUint32(count); } -PUBLIC void Compiler::GetMap(bool canAssign) { +void Compiler::GetMap(bool canAssign) { Uint32 count = 0; while (!MatchToken(TOKEN_RIGHT_BRACE)) { @@ -1387,7 +1358,7 @@ PUBLIC void Compiler::GetMap(bool canAssign) { EmitByte(OP_NEW_MAP); EmitUint32(count); } -PUBLIC bool Compiler::IsConstant() { +bool Compiler::IsConstant() { switch (PeekToken().Type) { case TOKEN_NULL: case TOKEN_TRUE: @@ -1414,7 +1385,7 @@ PUBLIC bool Compiler::IsConstant() { return false; } } -PUBLIC void Compiler::GetConstant(bool canAssign) { +void Compiler::GetConstant(bool canAssign) { switch (NextToken().Type) { case TOKEN_NULL: case TOKEN_TRUE: @@ -1450,7 +1421,7 @@ PUBLIC void Compiler::GetConstant(bool canAssign) { break; } } -PUBLIC int Compiler::GetConstantValue() { +int Compiler::GetConstantValue() { int position, constant_index; position = CodePointer(); GetConstant(false); @@ -1458,10 +1429,10 @@ PUBLIC int Compiler::GetConstantValue() { CurrentChunk()->Count = position; return constant_index; } -PUBLIC void Compiler::GetVariable(bool canAssign) { +void Compiler::GetVariable(bool canAssign) { NamedVariable(parser.Previous, canAssign); } -PUBLIC void Compiler::GetLogicalAND(bool canAssign) { +void Compiler::GetLogicalAND(bool canAssign) { int endJump = EmitJump(OP_JUMP_IF_FALSE); EmitByte(OP_POP); @@ -1469,7 +1440,7 @@ PUBLIC void Compiler::GetLogicalAND(bool canAssign) { PatchJump(endJump); } -PUBLIC void Compiler::GetLogicalOR(bool canAssign) { +void Compiler::GetLogicalOR(bool canAssign) { int elseJump = EmitJump(OP_JUMP_IF_FALSE); int endJump = EmitJump(OP_JUMP); @@ -1479,7 +1450,7 @@ PUBLIC void Compiler::GetLogicalOR(bool canAssign) { ParsePrecedence(PREC_OR); PatchJump(endJump); } -PUBLIC void Compiler::GetConditional(bool canAssign) { +void Compiler::GetConditional(bool canAssign) { int thenJump = EmitJump(OP_JUMP_IF_FALSE); EmitByte(OP_POP); ParsePrecedence(PREC_TERNARY); @@ -1492,7 +1463,7 @@ PUBLIC void Compiler::GetConditional(bool canAssign) { ParsePrecedence(PREC_TERNARY); PatchJump(elseJump); } -PUBLIC void Compiler::GetUnary(bool canAssign) { +void Compiler::GetUnary(bool canAssign) { int operatorType = parser.Previous.Type; ParsePrecedence(PREC_UNARY); @@ -1510,7 +1481,7 @@ PUBLIC void Compiler::GetUnary(bool canAssign) { return; // Unreachable. } } -PUBLIC void Compiler::GetNew(bool canAssign) { +void Compiler::GetNew(bool canAssign) { ConsumeToken(TOKEN_IDENTIFIER, "Expect class name."); NamedVariable(parser.Previous, false); @@ -1519,7 +1490,7 @@ PUBLIC void Compiler::GetNew(bool canAssign) { argCount = GetArgumentList(); EmitBytes(OP_NEW, argCount); } -PUBLIC void Compiler::GetBinary(bool canAssign) { +void Compiler::GetBinary(bool canAssign) { Token operato = parser.Previous; int operatorType = operato.Type; @@ -1554,20 +1525,20 @@ PUBLIC void Compiler::GetBinary(bool canAssign) { return; // Unreachable. } } -PUBLIC void Compiler::GetHas(bool canAssign) { +void Compiler::GetHas(bool canAssign) { ConsumeToken(TOKEN_IDENTIFIER, "Expect property name."); EmitByte(OP_HAS_PROPERTY); EmitStringHash(parser.Previous); } -PUBLIC void Compiler::GetSuffix(bool canAssign) { +void Compiler::GetSuffix(bool canAssign) { } -PUBLIC void Compiler::GetCall(bool canAssign) { +void Compiler::GetCall(bool canAssign) { Uint8 argCount = GetArgumentList(); EmitByte(OP_CALL); EmitByte(argCount); } -PUBLIC void Compiler::GetExpression() { +void Compiler::GetExpression() { ParsePrecedence(PREC_ASSIGNMENT); } // Reading statements @@ -1585,17 +1556,17 @@ stack*> SwitchJumpListStack; stack BreakScopeStack; stack ContinueScopeStack; stack SwitchScopeStack; -PUBLIC void Compiler::GetPrintStatement() { +void Compiler::GetPrintStatement() { GetExpression(); ConsumeToken(TOKEN_SEMICOLON, "Expected \";\" after value."); EmitByte(OP_PRINT); } -PUBLIC void Compiler::GetExpressionStatement() { +void Compiler::GetExpressionStatement() { GetExpression(); EmitByte(OP_POP); ConsumeToken(TOKEN_SEMICOLON, "Expected \";\" after expression."); } -PUBLIC void Compiler::GetContinueStatement() { +void Compiler::GetContinueStatement() { if (ContinueJumpListStack.size() == 0) { Error("Can't continue outside of loop."); } @@ -1607,7 +1578,7 @@ PUBLIC void Compiler::GetContinueStatement() { ConsumeToken(TOKEN_SEMICOLON, "Expect ';' after continue."); } -PUBLIC void Compiler::GetDoWhileStatement() { +void Compiler::GetDoWhileStatement() { // Set the start of the loop to before the condition int loopStart = CodePointer(); @@ -1648,7 +1619,7 @@ PUBLIC void Compiler::GetDoWhileStatement() { // Pop jump list off break stack, patch all breaks to this code point EndBreakJumpList(); } -PUBLIC void Compiler::GetReturnStatement() { +void Compiler::GetReturnStatement() { if (Type == TYPE_TOP_LEVEL) { Error("Cannot return from top-level code."); } @@ -1666,7 +1637,7 @@ PUBLIC void Compiler::GetReturnStatement() { EmitByte(OP_RETURN); } } -PUBLIC void Compiler::GetRepeatStatement() { +void Compiler::GetRepeatStatement() { ConsumeToken(TOKEN_LEFT_PAREN, "Expect '(' after 'repeat'."); GetExpression(); ConsumeToken(TOKEN_RIGHT_PAREN, "Expect ')' after condition."); @@ -1689,7 +1660,7 @@ PUBLIC void Compiler::GetRepeatStatement() { EndBreakJumpList(); } -PUBLIC void Compiler::GetSwitchStatement() { +void Compiler::GetSwitchStatement() { Chunk* chunk = CurrentChunk(); StartBreakJumpList(); @@ -1795,7 +1766,7 @@ PUBLIC void Compiler::GetSwitchStatement() { // Pop jump list off break stack, patch all breaks to this code point EndBreakJumpList(); } -PUBLIC void Compiler::GetCaseStatement() { +void Compiler::GetCaseStatement() { if (SwitchJumpListStack.size() == 0) { Error("Cannot use case label outside of switch statement."); } @@ -1830,7 +1801,7 @@ PUBLIC void Compiler::GetCaseStatement() { SwitchJumpListStack.top()->push_back(case_info); } -PUBLIC void Compiler::GetDefaultStatement() { +void Compiler::GetDefaultStatement() { if (SwitchJumpListStack.size() == 0) { Error("Cannot use default label outside of switch statement."); } @@ -1843,7 +1814,7 @@ PUBLIC void Compiler::GetDefaultStatement() { SwitchJumpListStack.top()->push_back(case_info); } -PUBLIC void Compiler::GetWhileStatement() { +void Compiler::GetWhileStatement() { // Set the start of the loop to before the condition int loopStart = CodePointer(); @@ -1882,7 +1853,7 @@ PUBLIC void Compiler::GetWhileStatement() { // Pop jump list off break stack, patch all breaks to this code point EndBreakJumpList(); } -PUBLIC void Compiler::GetBreakStatement() { +void Compiler::GetBreakStatement() { if (BreakJumpListStack.size() == 0) { Error("Cannot break outside of loop or switch statement."); } @@ -1894,14 +1865,14 @@ PUBLIC void Compiler::GetBreakStatement() { ConsumeToken(TOKEN_SEMICOLON, "Expect ';' after break."); } -PUBLIC void Compiler::GetBlockStatement() { +void Compiler::GetBlockStatement() { while (!CheckToken(TOKEN_RIGHT_BRACE) && !CheckToken(TOKEN_EOF)) { GetDeclaration(); } ConsumeToken(TOKEN_RIGHT_BRACE, "Expected \"}\" after block."); } -PUBLIC void Compiler::GetWithStatement() { +void Compiler::GetWithStatement() { enum { WITH_STATE_INIT, WITH_STATE_ITERATE, @@ -2015,7 +1986,7 @@ PUBLIC void Compiler::GetWithStatement() { // End scope (will pop "other") ScopeEnd(); } -PUBLIC void Compiler::GetForStatement() { +void Compiler::GetForStatement() { // Start new scope ScopeBegin(); @@ -2085,7 +2056,7 @@ PUBLIC void Compiler::GetForStatement() { // End new scope ScopeEnd(); } -PUBLIC void Compiler::GetForEachStatement() { +void Compiler::GetForEachStatement() { // Start new scope ScopeBegin(); @@ -2171,7 +2142,7 @@ PUBLIC void Compiler::GetForEachStatement() { // End new scope ScopeEnd(); } -PUBLIC void Compiler::GetIfStatement() { +void Compiler::GetIfStatement() { ConsumeToken(TOKEN_LEFT_PAREN, "Expect '(' after 'if'."); GetExpression(); ConsumeToken(TOKEN_RIGHT_PAREN, "Expect ')' after condition."); @@ -2189,7 +2160,7 @@ PUBLIC void Compiler::GetIfStatement() { PatchJump(elseJump); } -PUBLIC void Compiler::GetStatement() { +void Compiler::GetStatement() { if (MatchToken(TOKEN_PRINT)) { GetPrintStatement(); } @@ -2242,7 +2213,7 @@ PUBLIC void Compiler::GetStatement() { } } // Reading declarations -PUBLIC int Compiler::GetFunction(int type, string className) { +int Compiler::GetFunction(int type, string className) { int index = (int)Compiler::Functions.size(); Compiler* compiler = new Compiler; @@ -2287,10 +2258,10 @@ PUBLIC int Compiler::GetFunction(int type, string className) { return index; } -PUBLIC int Compiler::GetFunction(int type) { +int Compiler::GetFunction(int type) { return GetFunction(type, ""); } -PUBLIC void Compiler::GetMethod(Token className) { +void Compiler::GetMethod(Token className) { ConsumeToken(TOKEN_IDENTIFIER, "Expect method name."); Token constantToken = parser.Previous; @@ -2305,7 +2276,7 @@ PUBLIC void Compiler::GetMethod(Token className) { EmitByte(index); EmitStringHash(constantToken); } -PUBLIC void Compiler::GetVariableDeclaration() { +void Compiler::GetVariableDeclaration() { if (SwitchScopeStack.size() != 0) { if (SwitchScopeStack.top() == ScopeDepth) Error("Cannot initialize variable inside switch statement."); @@ -2329,7 +2300,7 @@ PUBLIC void Compiler::GetVariableDeclaration() { ConsumeToken(TOKEN_SEMICOLON, "Expected \";\" after variable declaration."); } -PUBLIC void Compiler::GetModuleVariableDeclaration() { +void Compiler::GetModuleVariableDeclaration() { ConsumeToken(TOKEN_VAR, "Expected \"var\" after \"local\" declaration."); if (ScopeDepth > 0) { @@ -2352,7 +2323,7 @@ PUBLIC void Compiler::GetModuleVariableDeclaration() { ConsumeToken(TOKEN_SEMICOLON, "Expected \";\" after variable declaration."); } -PUBLIC void Compiler::GetPropertyDeclaration(Token propertyName) { +void Compiler::GetPropertyDeclaration(Token propertyName) { do { ParseVariable("Expected property name."); @@ -2375,7 +2346,7 @@ PUBLIC void Compiler::GetPropertyDeclaration(Token propertyName) { ConsumeToken(TOKEN_SEMICOLON, "Expected \";\" after property declaration."); } -PUBLIC void Compiler::GetClassDeclaration() { +void Compiler::GetClassDeclaration() { ConsumeToken(TOKEN_IDENTIFIER, "Expect class name."); Token className = parser.Previous; @@ -2424,7 +2395,7 @@ PUBLIC void Compiler::GetClassDeclaration() { ConsumeToken(TOKEN_RIGHT_BRACE, "Expect '}' after class body."); } -PUBLIC void Compiler::GetEnumDeclaration() { +void Compiler::GetEnumDeclaration() { Token enumName; bool isNamed = false; @@ -2487,7 +2458,7 @@ PUBLIC void Compiler::GetEnumDeclaration() { ConsumeToken(TOKEN_RIGHT_BRACE, "Expect '}' after enum body."); } -PUBLIC void Compiler::GetImportDeclaration() { +void Compiler::GetImportDeclaration() { bool importModules = MatchToken(TOKEN_FROM); do { @@ -2503,7 +2474,7 @@ PUBLIC void Compiler::GetImportDeclaration() { ConsumeToken(TOKEN_SEMICOLON, "Expected \";\" after \"import\" declaration."); } -PUBLIC void Compiler::GetUsingDeclaration() { +void Compiler::GetUsingDeclaration() { ConsumeToken(TOKEN_NAMESPACE, "Expected \"namespace\" after \"using\" declaration."); if (ScopeDepth > 0) { @@ -2520,7 +2491,7 @@ PUBLIC void Compiler::GetUsingDeclaration() { ConsumeToken(TOKEN_SEMICOLON, "Expected \";\" after \"using\" declaration."); } -PUBLIC void Compiler::GetEventDeclaration() { +void Compiler::GetEventDeclaration() { ConsumeToken(TOKEN_IDENTIFIER, "Expected event name."); Token constantToken = parser.Previous; @@ -2542,7 +2513,7 @@ PUBLIC void Compiler::GetEventDeclaration() { EmitStringHash(constantToken); // } } -PUBLIC void Compiler::GetDeclaration() { +void Compiler::GetDeclaration() { if (MatchToken(TOKEN_CLASS)) GetClassDeclaration(); else if (MatchToken(TOKEN_ENUM)) @@ -2563,7 +2534,7 @@ PUBLIC void Compiler::GetDeclaration() { if (parser.PanicMode) SynchronizeToken(); } -PUBLIC STATIC void Compiler::MakeRules() { +void Compiler::MakeRules() { Rules = (ParseRule*)Memory::TrackedCalloc("Compiler::Rules", TOKEN_EOF + 1, sizeof(ParseRule)); // Single-character tokens. Rules[TOKEN_LEFT_PAREN] = ParseRule { &Compiler::GetGrouping, &Compiler::GetCall, NULL, PREC_CALL }; @@ -2627,11 +2598,11 @@ PUBLIC STATIC void Compiler::MakeRules() { Rules[TOKEN_DECIMAL] = ParseRule { &Compiler::GetDecimal, NULL, NULL, PREC_NONE }; Rules[TOKEN_IDENTIFIER] = ParseRule { &Compiler::GetVariable, NULL, NULL, PREC_NONE }; } -PUBLIC ParseRule* Compiler::GetRule(int type) { +ParseRule* Compiler::GetRule(int type) { return &Compiler::Rules[(int)type]; } -PUBLIC void Compiler::ParsePrecedence(Precedence precedence) { +void Compiler::ParsePrecedence(Precedence precedence) { AdvanceToken(); ParseFn prefixRule = GetRule(parser.Previous.Type)->Prefix; if (prefixRule == NULL) { @@ -2654,43 +2625,43 @@ PUBLIC void Compiler::ParsePrecedence(Precedence precedence) { GetExpression(); } } -PUBLIC Uint32 Compiler::GetHash(char* string) { +Uint32 Compiler::GetHash(char* string) { return Murmur::EncryptString(string); } -PUBLIC Uint32 Compiler::GetHash(Token token) { +Uint32 Compiler::GetHash(Token token) { return Murmur::EncryptData(token.Start, token.Length); } -PUBLIC Chunk* Compiler::CurrentChunk() { +Chunk* Compiler::CurrentChunk() { return &Function->Chunk; } -PUBLIC int Compiler::CodePointer() { +int Compiler::CodePointer() { return CurrentChunk()->Count; } -PUBLIC void Compiler::EmitByte(Uint8 byte) { +void Compiler::EmitByte(Uint8 byte) { CurrentChunk()->Write(byte, (int)((parser.Previous.Pos & 0xFFFF) << 16 | (parser.Previous.Line & 0xFFFF))); } -PUBLIC void Compiler::EmitBytes(Uint8 byte1, Uint8 byte2) { +void Compiler::EmitBytes(Uint8 byte1, Uint8 byte2) { EmitByte(byte1); EmitByte(byte2); } -PUBLIC void Compiler::EmitUint16(Uint16 value) { +void Compiler::EmitUint16(Uint16 value) { EmitByte(value & 0xFF); EmitByte(value >> 8 & 0xFF); } -PUBLIC void Compiler::EmitUint32(Uint32 value) { +void Compiler::EmitUint32(Uint32 value) { EmitByte(value & 0xFF); EmitByte(value >> 8 & 0xFF); EmitByte(value >> 16 & 0xFF); EmitByte(value >> 24 & 0xFF); } -PUBLIC int Compiler::GetConstantIndex(VMValue value) { +int Compiler::GetConstantIndex(VMValue value) { int index = FindConstant(value); if (index < 0) index = MakeConstant(value); return index; } -PUBLIC int Compiler::EmitConstant(VMValue value) { +int Compiler::EmitConstant(VMValue value) { int index = GetConstantIndex(value); EmitByte(OP_CONSTANT); @@ -2698,7 +2669,7 @@ PUBLIC int Compiler::EmitConstant(VMValue value) { return index; } -PUBLIC void Compiler::EmitLoop(int loopStart) { +void Compiler::EmitLoop(int loopStart) { EmitByte(OP_JUMP_BACK); int offset = CurrentChunk()->Count - loopStart + 2; @@ -2707,7 +2678,7 @@ PUBLIC void Compiler::EmitLoop(int loopStart) { EmitByte(offset & 0xFF); EmitByte((offset >> 8) & 0xFF); } -PUBLIC int Compiler::GetJump(int offset) { +int Compiler::GetJump(int offset) { int jump = CurrentChunk()->Count - (offset + 2); if (jump > UINT16_MAX) { Error("Too much code to jump over."); @@ -2715,26 +2686,26 @@ PUBLIC int Compiler::GetJump(int offset) { return jump; } -PUBLIC int Compiler::GetPosition() { +int Compiler::GetPosition() { return CurrentChunk()->Count; } -PUBLIC int Compiler::EmitJump(Uint8 instruction) { +int Compiler::EmitJump(Uint8 instruction) { return EmitJump(instruction, 0xFFFF); } -PUBLIC int Compiler::EmitJump(Uint8 instruction, int jump) { +int Compiler::EmitJump(Uint8 instruction, int jump) { EmitByte(instruction); EmitUint16(jump); return CurrentChunk()->Count - 2; } -PUBLIC void Compiler::PatchJump(int offset, int jump) { +void Compiler::PatchJump(int offset, int jump) { CurrentChunk()->Code[offset] = jump & 0xFF; CurrentChunk()->Code[offset + 1] = (jump >> 8) & 0xFF; } -PUBLIC void Compiler::PatchJump(int offset) { +void Compiler::PatchJump(int offset) { int jump = GetJump(offset); PatchJump(offset, jump); } -PUBLIC void Compiler::EmitStringHash(const char* string) { +void Compiler::EmitStringHash(const char* string) { Uint32 hash = GetHash((char*)string); if (!TokenMap->Exists(hash)) { Token tk; @@ -2744,12 +2715,12 @@ PUBLIC void Compiler::EmitStringHash(const char* string) { } EmitUint32(hash); } -PUBLIC void Compiler::EmitStringHash(Token token) { +void Compiler::EmitStringHash(Token token) { if (!TokenMap->Exists(GetHash(token))) TokenMap->Put(GetHash(token), token); EmitUint32(GetHash(token)); } -PUBLIC void Compiler::EmitReturn() { +void Compiler::EmitReturn() { if (Type == TYPE_CONSTRUCTOR) { EmitBytes(OP_GET_LOCAL, 0); // return the new instance built from the constructor } @@ -2760,11 +2731,11 @@ PUBLIC void Compiler::EmitReturn() { } // Advanced Jumping -PUBLIC void Compiler::StartBreakJumpList() { +void Compiler::StartBreakJumpList() { BreakJumpListStack.push(new vector()); BreakScopeStack.push(ScopeDepth); } -PUBLIC void Compiler::EndBreakJumpList() { +void Compiler::EndBreakJumpList() { vector* top = BreakJumpListStack.top(); for (size_t i = 0; i < top->size(); i++) { int offset = (*top)[i]; @@ -2774,11 +2745,11 @@ PUBLIC void Compiler::EndBreakJumpList() { BreakJumpListStack.pop(); BreakScopeStack.pop(); } -PUBLIC void Compiler::StartContinueJumpList() { +void Compiler::StartContinueJumpList() { ContinueJumpListStack.push(new vector()); ContinueScopeStack.push(ScopeDepth); } -PUBLIC void Compiler::EndContinueJumpList() { +void Compiler::EndContinueJumpList() { vector* top = ContinueJumpListStack.top(); for (size_t i = 0; i < top->size(); i++) { int offset = (*top)[i]; @@ -2788,11 +2759,11 @@ PUBLIC void Compiler::EndContinueJumpList() { ContinueJumpListStack.pop(); ContinueScopeStack.pop(); } -PUBLIC void Compiler::StartSwitchJumpList() { +void Compiler::StartSwitchJumpList() { SwitchJumpListStack.push(new vector()); SwitchScopeStack.push(ScopeDepth + 1); } -PUBLIC void Compiler::EndSwitchJumpList() { +void Compiler::EndSwitchJumpList() { vector* top = SwitchJumpListStack.top(); for (size_t i = 0; i < top->size(); i++) { if (!(*top)[i].IsDefault) { @@ -2805,14 +2776,14 @@ PUBLIC void Compiler::EndSwitchJumpList() { SwitchScopeStack.pop(); } -PUBLIC int Compiler::FindConstant(VMValue value) { +int Compiler::FindConstant(VMValue value) { for (size_t i = 0; i < CurrentChunk()->Constants->size(); i++) { if (ValuesEqual(value, (*CurrentChunk()->Constants)[i])) return (int)i; } return -1; } -PUBLIC int Compiler::MakeConstant(VMValue value) { +int Compiler::MakeConstant(VMValue value) { int constant = CurrentChunk()->AddConstant(value); // if (constant > UINT8_MAX) { // Error("Too many constants in one chunk."); @@ -2821,7 +2792,7 @@ PUBLIC int Compiler::MakeConstant(VMValue value) { return constant; } -PUBLIC bool Compiler::HasThis() { +bool Compiler::HasThis() { switch (Type) { case TYPE_CONSTRUCTOR: case TYPE_METHOD: @@ -2830,18 +2801,18 @@ PUBLIC bool Compiler::HasThis() { return false; } } -PUBLIC void Compiler::SetReceiverName(const char *name) { +void Compiler::SetReceiverName(const char *name) { Local* local = &Locals[0]; local->Name.Start = (char*)name; local->Name.Length = strlen(name); } -PUBLIC void Compiler::SetReceiverName(Token name) { +void Compiler::SetReceiverName(Token name) { Local* local = &Locals[0]; local->Name = name; } // Debugging functions -PUBLIC STATIC int Compiler::HashInstruction(const char* name, Chunk* chunk, int offset) { +int Compiler::HashInstruction(const char* name, Chunk* chunk, int offset) { uint32_t hash = *(uint32_t*)&chunk->Code[offset + 1]; printf("%-16s #%08X", name, hash); if (TokenMap->Exists(hash)) { @@ -2851,22 +2822,22 @@ PUBLIC STATIC int Compiler::HashInstruction(const char* name, Chunk* chunk, i printf("\n"); return offset + 5; } -PUBLIC STATIC int Compiler::ConstantInstruction(const char* name, Chunk* chunk, int offset) { +int Compiler::ConstantInstruction(const char* name, Chunk* chunk, int offset) { int constant = *(int*)&chunk->Code[offset + 1]; printf("%-16s %9d '", name, constant); Values::PrintValue(NULL, (*chunk->Constants)[constant]); printf("'\n"); return offset + 5; } -PUBLIC STATIC int Compiler::SimpleInstruction(const char* name, int offset) { +int Compiler::SimpleInstruction(const char* name, int offset) { printf("%s\n", name); return offset + 1; } -PUBLIC STATIC int Compiler::ByteInstruction(const char* name, Chunk* chunk, int offset) { +int Compiler::ByteInstruction(const char* name, Chunk* chunk, int offset) { printf("%-16s %9d\n", name, chunk->Code[offset + 1]); return offset + 2; } -PUBLIC STATIC int Compiler::LocalInstruction(const char* name, Chunk* chunk, int offset) { +int Compiler::LocalInstruction(const char* name, Chunk* chunk, int offset) { uint8_t slot = chunk->Code[offset + 1]; if (slot > 0) printf("%-16s %9d\n", name, slot); @@ -2874,7 +2845,7 @@ PUBLIC STATIC int Compiler::LocalInstruction(const char* name, Chunk* chunk, printf("%-16s %9d 'this'\n", name, slot); return offset + 2; } -PUBLIC STATIC int Compiler::MethodInstruction(const char* name, Chunk* chunk, int offset) { +int Compiler::MethodInstruction(const char* name, Chunk* chunk, int offset) { uint8_t slot = chunk->Code[offset + 1]; uint32_t hash = *(uint32_t*)&chunk->Code[offset + 2]; printf("%-13s %2d", name, slot); @@ -2887,22 +2858,22 @@ PUBLIC STATIC int Compiler::MethodInstruction(const char* name, Chunk* chunk, printf("\n"); return offset + 6; } -PUBLIC STATIC int Compiler::InvokeInstruction(const char* name, Chunk* chunk, int offset) { +int Compiler::InvokeInstruction(const char* name, Chunk* chunk, int offset) { return Compiler::MethodInstruction(name, chunk, offset) + 1; } -PUBLIC STATIC int Compiler::JumpInstruction(const char* name, int sign, Chunk* chunk, int offset) { +int Compiler::JumpInstruction(const char* name, int sign, Chunk* chunk, int offset) { uint16_t jump = (uint16_t)(chunk->Code[offset + 1]); jump |= chunk->Code[offset + 2] << 8; printf("%-16s %9d -> %d\n", name, offset, offset + 3 + sign * jump); return offset + 3; } -PUBLIC STATIC int Compiler::ClassInstruction(const char* name, Chunk* chunk, int offset) { +int Compiler::ClassInstruction(const char* name, Chunk* chunk, int offset) { return Compiler::HashInstruction(name, chunk, offset) + 1; } -PUBLIC STATIC int Compiler::EnumInstruction(const char* name, Chunk* chunk, int offset) { +int Compiler::EnumInstruction(const char* name, Chunk* chunk, int offset) { return Compiler::HashInstruction(name, chunk, offset); } -PUBLIC STATIC int Compiler::WithInstruction(const char* name, Chunk* chunk, int offset) { +int Compiler::WithInstruction(const char* name, Chunk* chunk, int offset) { uint8_t slot = chunk->Code[offset + 1]; if (slot == 0) { printf("%-16s %9d\n", name, slot); @@ -2913,7 +2884,7 @@ PUBLIC STATIC int Compiler::WithInstruction(const char* name, Chunk* chunk, i printf("%-16s %9d -> %d\n", name, slot, jump); return offset + 4; } -PUBLIC STATIC int Compiler::DebugInstruction(Chunk* chunk, int offset) { +int Compiler::DebugInstruction(Chunk* chunk, int offset) { printf("%04d ", offset); if (offset > 0 && (chunk->Lines[offset] & 0xFFFF) == (chunk->Lines[offset - 1] & 0xFFFF)) { printf(" | "); @@ -3069,7 +3040,7 @@ PUBLIC STATIC int Compiler::DebugInstruction(Chunk* chunk, int offset) { return chunk->Count + 1; } } -PUBLIC STATIC void Compiler::DebugChunk(Chunk* chunk, const char* name, int minArity, int maxArity) { +void Compiler::DebugChunk(Chunk* chunk, const char* name, int minArity, int maxArity) { int optArgCount = maxArity - minArity; if (optArgCount) printf("== %s (argCount: %d, optArgCount: %d) ==\n", name, maxArity, optArgCount); @@ -3089,19 +3060,19 @@ PUBLIC STATIC void Compiler::DebugChunk(Chunk* chunk, const char* name, int mi } // Compiling -PUBLIC STATIC void Compiler::Init() { +void Compiler::Init() { Compiler::MakeRules(); Compiler::ShowWarnings = false; Compiler::WriteDebugInfo = true; Compiler::WriteSourceFilename = true; } -PUBLIC STATIC void Compiler::PrepareCompiling() { +void Compiler::PrepareCompiling() { if (Compiler::TokenMap == NULL) { Compiler::TokenMap = new HashMap(NULL, 8); } } -PUBLIC void Compiler::Initialize(Compiler* enclosing, int scope, int type) { +void Compiler::Initialize(Compiler* enclosing, int scope, int type) { Type = type; LocalCount = 0; ScopeDepth = scope; @@ -3134,7 +3105,7 @@ PUBLIC void Compiler::Initialize(Compiler* enclosing, int scope, int ty SetReceiverName(""); } } -PRIVATE void Compiler::WriteBytecode(Stream* stream, const char* filename) { +void Compiler::WriteBytecode(Stream* stream, const char* filename) { Bytecode* bytecode = new Bytecode(); for (size_t i = 0; i < Compiler::Functions.size(); i++) @@ -3148,7 +3119,7 @@ PRIVATE void Compiler::WriteBytecode(Stream* stream, const char* filenam if (TokenMap) TokenMap->Clear(); } -PUBLIC bool Compiler::Compile(const char* filename, const char* source, const char* output) { +bool Compiler::Compile(const char* filename, const char* source, const char* output) { scanner.Line = 1; scanner.Start = (char*)source; scanner.Current = (char*)source; @@ -3195,7 +3166,7 @@ PUBLIC bool Compiler::Compile(const char* filename, const char* source, return !parser.HadError; } -PUBLIC void Compiler::Finish() { +void Compiler::Finish() { if (UnusedVariables) { WarnVariablesUnused(); delete UnusedVariables; @@ -3204,10 +3175,10 @@ PUBLIC void Compiler::Finish() { EmitReturn(); } -PUBLIC VIRTUAL Compiler::~Compiler() { +Compiler::~Compiler() { } -PUBLIC STATIC void Compiler::FinishCompiling() { +void Compiler::FinishCompiling() { Compiler::Functions.clear(); Compiler::ModuleLocals.clear(); @@ -3216,6 +3187,6 @@ PUBLIC STATIC void Compiler::FinishCompiling() { TokenMap = NULL; } } -PUBLIC STATIC void Compiler::Dispose() { +void Compiler::Dispose() { Memory::Free(Rules); } diff --git a/source/Engine/Bytecode/GarbageCollector.cpp b/source/Engine/Bytecode/GarbageCollector.cpp index 7dd5f01c..2c5e2056 100644 --- a/source/Engine/Bytecode/GarbageCollector.cpp +++ b/source/Engine/Bytecode/GarbageCollector.cpp @@ -1,22 +1,3 @@ -#if INTERFACE -#include -#include - -class GarbageCollector { -public: - static vector GrayList; - static Obj* RootObject; - - static size_t NextGC; - static size_t GarbageSize; - static double MaxTimeAlotted; - - static bool Print; - static bool FilterSweepEnabled; - static int FilterSweepType; -}; -#endif - #include #include @@ -39,12 +20,12 @@ bool GarbageCollector::Print = false; bool GarbageCollector::FilterSweepEnabled = false; int GarbageCollector::FilterSweepType = 0; -PUBLIC STATIC void GarbageCollector::Init() { +void GarbageCollector::Init() { GarbageCollector::RootObject = NULL; GarbageCollector::NextGC = 0x100000; } -PUBLIC STATIC void GarbageCollector::Collect() { +void GarbageCollector::Collect() { GrayList.clear(); double grayElapsed = Clock::GetTicks(); @@ -158,7 +139,7 @@ PUBLIC STATIC void GarbageCollector::Collect() { GarbageCollector::NextGC = GarbageCollector::GarbageSize + (1024 * 1024); } -PRIVATE STATIC void GarbageCollector::FreeValue(VMValue value) { +void GarbageCollector::FreeValue(VMValue value) { if (!IS_OBJECT(value)) return; // If this object is an instance associated with an entity, @@ -172,11 +153,11 @@ PRIVATE STATIC void GarbageCollector::FreeValue(VMValue value) { ScriptManager::FreeValue(value); } -PRIVATE STATIC void GarbageCollector::GrayValue(VMValue value) { +void GarbageCollector::GrayValue(VMValue value) { if (!IS_OBJECT(value)) return; GrayObject(AS_OBJECT(value)); } -PRIVATE STATIC void GarbageCollector::GrayObject(void* obj) { +void GarbageCollector::GrayObject(void* obj) { if (obj == NULL) return; Obj* object = (Obj*)obj; @@ -186,15 +167,15 @@ PRIVATE STATIC void GarbageCollector::GrayObject(void* obj) { GrayList.push_back(object); } -PRIVATE STATIC void GarbageCollector::GrayHashMapItem(Uint32, VMValue value) { +void GarbageCollector::GrayHashMapItem(Uint32, VMValue value) { GrayValue(value); } -PRIVATE STATIC void GarbageCollector::GrayHashMap(void* pointer) { +void GarbageCollector::GrayHashMap(void* pointer) { if (!pointer) return; ((HashMap*)pointer)->ForAll(GrayHashMapItem); } -PRIVATE STATIC void GarbageCollector::BlackenObject(Obj* object) { +void GarbageCollector::BlackenObject(Obj* object) { GrayObject(object->Class); switch (object->Type) { diff --git a/source/Engine/Bytecode/ScriptEntity.cpp b/source/Engine/Bytecode/ScriptEntity.cpp index fffc6613..4eab3bb4 100644 --- a/source/Engine/Bytecode/ScriptEntity.cpp +++ b/source/Engine/Bytecode/ScriptEntity.cpp @@ -1,16 +1,3 @@ -#if INTERFACE -#include -#include - -class ScriptEntity : public Entity { -public: - static bool DisableAutoAnimate; - - ObjInstance* Instance = NULL; - HashMap* Properties; -}; -#endif - #include #include #include @@ -41,7 +28,7 @@ Uint32 Hash_HitboxTop = 0; Uint32 Hash_HitboxRight = 0; Uint32 Hash_HitboxBottom = 0; -PUBLIC void ScriptEntity::Link(ObjInstance* instance) { +void ScriptEntity::Link(ObjInstance* instance) { Instance = instance; Instance->EntityPtr = this; Properties = new HashMap(NULL, 4); @@ -74,7 +61,7 @@ PUBLIC void ScriptEntity::Link(ObjInstance* instance) { LinkFields(); } -PUBLIC void ScriptEntity::LinkFields() { +void ScriptEntity::LinkFields() { /*** * \field X * \type Decimal @@ -704,7 +691,7 @@ PUBLIC void ScriptEntity::LinkFields() { #undef LINK_DEC #undef LINK_BOOL -PRIVATE bool ScriptEntity::GetCallableValue(Uint32 hash, VMValue& value) { +bool ScriptEntity::GetCallableValue(Uint32 hash, VMValue& value) { // First look for a field which may shadow a method. VMValue result; if (Instance->Fields->GetIfExists(hash, &result)) { @@ -725,14 +712,14 @@ PRIVATE bool ScriptEntity::GetCallableValue(Uint32 hash, VMValue& value) { return false; } -PRIVATE ObjFunction* ScriptEntity::GetCallableFunction(Uint32 hash) { +ObjFunction* ScriptEntity::GetCallableFunction(Uint32 hash) { ObjClass* klass = Instance->Object.Class; VMValue result; if (klass->Methods->GetIfExists(hash, &result)) return AS_FUNCTION(result); return NULL; } -PUBLIC bool ScriptEntity::RunFunction(Uint32 hash) { +bool ScriptEntity::RunFunction(Uint32 hash) { if (!Instance) return false; @@ -754,7 +741,7 @@ PUBLIC bool ScriptEntity::RunFunction(Uint32 hash) { return true; } -PUBLIC bool ScriptEntity::RunCreateFunction(VMValue flag) { +bool ScriptEntity::RunCreateFunction(VMValue flag) { // NOTE: // If the function doesn't exist, this is not an error VM side, // treat whatever we call from C++ as a virtual-like function. @@ -780,7 +767,7 @@ PUBLIC bool ScriptEntity::RunCreateFunction(VMValue flag) { return false; } -PUBLIC bool ScriptEntity::RunInitializer() { +bool ScriptEntity::RunInitializer() { if (!HasInitializer(Instance->Object.Class)) return true; @@ -797,7 +784,7 @@ PUBLIC bool ScriptEntity::RunInitializer() { return true; } -PUBLIC bool ScriptEntity::ChangeClass(const char* className) { +bool ScriptEntity::ChangeClass(const char* className) { if (!ScriptManager::ClassExists(className)) return false; @@ -825,7 +812,7 @@ PUBLIC bool ScriptEntity::ChangeClass(const char* className) { return true; } -PUBLIC void ScriptEntity::Copy(ScriptEntity* other, bool copyClass) { +void ScriptEntity::Copy(ScriptEntity* other, bool copyClass) { CopyFields(other); if (copyClass) @@ -842,13 +829,13 @@ PUBLIC void ScriptEntity::Copy(ScriptEntity* other, bool copyClass) { }); } -PUBLIC void ScriptEntity::CopyFields(ScriptEntity* other) { +void ScriptEntity::CopyFields(ScriptEntity* other) { Entity::CopyFields(other); CopyVMFields(other); } -PUBLIC void ScriptEntity::CopyVMFields(ScriptEntity* other) { +void ScriptEntity::CopyVMFields(ScriptEntity* other) { Table* srcFields = Instance->Fields; Table* destFields = other->Instance->Fields; @@ -865,7 +852,7 @@ PUBLIC void ScriptEntity::CopyVMFields(ScriptEntity* other) { } // Events called from C++ -PUBLIC void ScriptEntity::Initialize() { +void ScriptEntity::Initialize() { if (!Instance) return; // Set defaults @@ -933,7 +920,7 @@ PUBLIC void ScriptEntity::Initialize() { RunInitializer(); } -PUBLIC void ScriptEntity::Create(VMValue flag) { +void ScriptEntity::Create(VMValue flag) { if (!Instance) return; Created = true; @@ -943,27 +930,27 @@ PUBLIC void ScriptEntity::Create(VMValue flag) { SetAnimation(0, 0); } } -PUBLIC void ScriptEntity::Create() { +void ScriptEntity::Create() { Create(INTEGER_VAL(0)); } -PUBLIC void ScriptEntity::PostCreate() { +void ScriptEntity::PostCreate() { if (!Instance) return; PostCreated = true; RunFunction(Hash_PostCreate); } -PUBLIC void ScriptEntity::UpdateEarly() { +void ScriptEntity::UpdateEarly() { if (!Active) return; RunFunction(Hash_UpdateEarly); } -PUBLIC void ScriptEntity::Update() { +void ScriptEntity::Update() { if (!Active) return; RunFunction(Hash_Update); } -PUBLIC void ScriptEntity::UpdateLate() { +void ScriptEntity::UpdateLate() { if (!Active) return; RunFunction(Hash_UpdateLate); @@ -973,40 +960,40 @@ PUBLIC void ScriptEntity::UpdateLate() { if (AutoPhysics) ApplyMotion(); } -PUBLIC void ScriptEntity::RenderEarly() { +void ScriptEntity::RenderEarly() { if (!Active) return; RunFunction(Hash_RenderEarly); } -PUBLIC void ScriptEntity::Render(int CamX, int CamY) { +void ScriptEntity::Render(int CamX, int CamY) { if (!Active) return; if (RunFunction(Hash_Render)) { // Default render } } -PUBLIC void ScriptEntity::RenderLate() { +void ScriptEntity::RenderLate() { if (!Active) return; RunFunction(Hash_RenderLate); } -PUBLIC void ScriptEntity::OnAnimationFinish() { +void ScriptEntity::OnAnimationFinish() { RunFunction(Hash_OnAnimationFinish); } -PUBLIC void ScriptEntity::OnSceneLoad() { +void ScriptEntity::OnSceneLoad() { if (!Active) return; RunFunction(Hash_OnSceneLoad); } -PUBLIC void ScriptEntity::OnSceneRestart() { +void ScriptEntity::OnSceneRestart() { if (!Active) return; RunFunction(Hash_OnSceneRestart); } -PUBLIC void ScriptEntity::GameStart() { +void ScriptEntity::GameStart() { RunFunction(Hash_GameStart); } -PUBLIC void ScriptEntity::Remove() { +void ScriptEntity::Remove() { if (Removed) return; if (!Instance) return; @@ -1015,7 +1002,7 @@ PUBLIC void ScriptEntity::Remove() { Active = false; Removed = true; } -PUBLIC void ScriptEntity::Dispose() { +void ScriptEntity::Dispose() { Entity::Dispose(); if (Properties) { delete Properties; @@ -1053,7 +1040,7 @@ bool TestEntityCollision(Entity* other, Entity* self) { return self->CollideWithObject(other); } -PUBLIC STATIC bool ScriptEntity::VM_Getter(Obj* object, Uint32 hash, VMValue* result, Uint32 threadID) { +bool ScriptEntity::VM_Getter(Obj* object, Uint32 hash, VMValue* result, Uint32 threadID) { Entity* self = GetScriptEntity(object); if (self == nullptr) return false; @@ -1081,7 +1068,7 @@ PUBLIC STATIC bool ScriptEntity::VM_Getter(Obj* object, Uint32 hash, VMValue* re return false; } -PUBLIC STATIC bool ScriptEntity::VM_Setter(Obj* object, Uint32 hash, VMValue value, Uint32 threadID) { +bool ScriptEntity::VM_Setter(Obj* object, Uint32 hash, VMValue value, Uint32 threadID) { Entity* self = GetScriptEntity(object); if (self == nullptr) return false; @@ -1116,7 +1103,7 @@ PUBLIC STATIC bool ScriptEntity::VM_Setter(Obj* object, Uint32 hash, VMValue val * \param frame (Integer): The frame index. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_SetAnimation(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_SetAnimation(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 3); Entity* self = GET_ENTITY(0); int animation = GET_ARG(1, GetInteger); @@ -1150,7 +1137,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_SetAnimation(int argCount, VMValue* args, * \param frame (Integer): The frame index. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_ResetAnimation(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_ResetAnimation(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 3); Entity* self = GET_ENTITY(0); int animation = GET_ARG(1, GetInteger); @@ -1183,7 +1170,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_ResetAnimation(int argCount, VMValue* arg * \desc Animates the entity. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_Animate(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_Animate(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 1); Entity* self = GET_ENTITY(0); if (self) @@ -1197,7 +1184,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_Animate(int argCount, VMValue* args, Uint * \return Returns an Integer value. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_GetIDWithinClass(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_GetIDWithinClass(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 1); Entity* self = GET_ENTITY(0); if (!self || !self->List) @@ -1223,7 +1210,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_GetIDWithinClass(int argCount, VMValue* a * \param registry (String): The registry name. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_AddToRegistry(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_AddToRegistry(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 2); Entity* self = GET_ENTITY(0); char* registry = GET_ARG(1, GetString); @@ -1251,7 +1238,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_AddToRegistry(int argCount, VMValue* args * \return Returns a Boolean value. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_IsInRegistry(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_IsInRegistry(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 2); Entity* self = GET_ENTITY(0); char* registry = GET_ARG(1, GetString); @@ -1269,7 +1256,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_IsInRegistry(int argCount, VMValue* args, * \param registry (String): The registry name. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_RemoveFromRegistry(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_RemoveFromRegistry(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 2); Entity* self = GET_ENTITY(0); char* registry = GET_ARG(1, GetString); @@ -1288,7 +1275,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_RemoveFromRegistry(int argCount, VMValue* * \desc Applies gravity and velocities to the entity. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_ApplyMotion(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_ApplyMotion(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 1); Entity* self = GET_ENTITY(0); if (IsValidEntity(self)) @@ -1306,7 +1293,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_ApplyMotion(int argCount, VMValue* args, * \return Returns true if the specified positions and ranges are within the specified view, false if otherwise. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_InView(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_InView(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 6); // Entity* self = (Entity*)AS_INSTANCE(args[0])->EntityPtr; int view = GET_ARG(1, GetInteger); @@ -1330,7 +1317,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_InView(int argCount, VMValue* args, Uint3 * \return Returns the entity that was collided with, or null if it did not collide with any entity. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_CollidedWithObject(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_CollidedWithObject(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 2); ScriptEntity* self = GET_ENTITY(0); @@ -1377,7 +1364,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_CollidedWithObject(int argCount, VMValue* * \param hitbox (Integer): The hitbox ID. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_GetHitboxFromSprite(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_GetHitboxFromSprite(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 5); ScriptEntity* self = GET_ENTITY(0); ISprite* sprite = GET_ARG(1, GetSprite); @@ -1419,7 +1406,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_GetHitboxFromSprite(int argCount, VMValue * \return Returns an array containing the hitbox top, left, right and bottom sides in that order. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_ReturnHitboxFromSprite(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_ReturnHitboxFromSprite(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 5); ScriptEntity* self = GET_ENTITY(0); ISprite* sprite = GET_ARG(1, GetSprite); @@ -1462,7 +1449,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_ReturnHitboxFromSprite(int argCount, VMVa * \return Returns true if the entity collided, false if otherwise. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_CollideWithObject(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_CollideWithObject(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 2); ScriptEntity* self = GET_ENTITY(0); ScriptEntity* other = GET_ENTITY(1); @@ -1477,7 +1464,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_CollideWithObject(int argCount, VMValue* * \return Returns true if the entity collided, false if otherwise. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_SolidCollideWithObject(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_SolidCollideWithObject(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 3); ScriptEntity* self = GET_ENTITY(0); ScriptEntity* other = GET_ENTITY(1); @@ -1493,7 +1480,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_SolidCollideWithObject(int argCount, VMVa * \return Returns true if the entity collided, false if otherwise. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_TopSolidCollideWithObject(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_TopSolidCollideWithObject(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 3); ScriptEntity* self = GET_ENTITY(0); ScriptEntity* other = GET_ENTITY(1); @@ -1503,7 +1490,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_TopSolidCollideWithObject(int argCount, V return INTEGER_VAL(self->TopSolidCollideWithObject(other, flag)); } -PUBLIC STATIC VMValue ScriptEntity::VM_ApplyPhysics(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_ApplyPhysics(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 1); ScriptEntity* self = GET_ENTITY(0); if (IsValidEntity(self)) @@ -1518,7 +1505,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_ApplyPhysics(int argCount, VMValue* args, * \return Returns true if the property exists, false if otherwise. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_PropertyExists(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_PropertyExists(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 2); ScriptEntity* self = GET_ENTITY(0); char* property = GET_ARG(1, GetString); @@ -1533,7 +1520,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_PropertyExists(int argCount, VMValue* arg * \return Returns the property if it exists, and null if the property does not exist. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_PropertyGet(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_PropertyGet(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 2); ScriptEntity* self = GET_ENTITY(0); char* property = GET_ARG(1, GetString); @@ -1549,7 +1536,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_PropertyGet(int argCount, VMValue* args, * \param visible (Boolean): Whether the entity will be visible or not on the specified view. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_SetViewVisibility(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_SetViewVisibility(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 3); ScriptEntity* self = GET_ENTITY(0); int viewIndex = GET_ARG(1, GetInteger); @@ -1570,7 +1557,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_SetViewVisibility(int argCount, VMValue* * \param visible (Boolean): Whether the entity will always be visible or not on the specified view. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_SetViewOverride(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_SetViewOverride(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 3); ScriptEntity* self = GET_ENTITY(0); int viewIndex = GET_ARG(1, GetInteger); @@ -1591,7 +1578,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_SetViewOverride(int argCount, VMValue* ar * \param drawGroup (Integer): The draw group. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_AddToDrawGroup(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_AddToDrawGroup(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 2); ScriptEntity* self = GET_ENTITY(0); if (!IsValidEntity(self)) @@ -1612,7 +1599,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_AddToDrawGroup(int argCount, VMValue* arg * \return Returns true if the entity is in the specified draw group, false if otherwise. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_IsInDrawGroup(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_IsInDrawGroup(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 2); ScriptEntity* self = GET_ENTITY(0); if (!IsValidEntity(self)) @@ -1630,7 +1617,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_IsInDrawGroup(int argCount, VMValue* args * \param drawGroup (Integer): The draw group. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_RemoveFromDrawGroup(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_RemoveFromDrawGroup(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 2); ScriptEntity* self = GET_ENTITY(0); if (!IsValidEntity(self)) @@ -1653,7 +1640,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_RemoveFromDrawGroup(int argCount, VMValue * \return Returns the channel index where the sound began to play, or -1 if no channel was available. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_PlaySound(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_PlaySound(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckAtLeastArgCount(argCount, 2); ScriptEntity* self = GET_ENTITY(0); ISound* audio = GET_ARG(1, GetSound); @@ -1678,7 +1665,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_PlaySound(int argCount, VMValue* args, Ui * \return Returns the channel index where the sound began to play, or -1 if no channel was available. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_LoopSound(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_LoopSound(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckAtLeastArgCount(argCount, 2); ScriptEntity* self = GET_ENTITY(0); ISound* audio = GET_ARG(1, GetSound); @@ -1699,7 +1686,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_LoopSound(int argCount, VMValue* args, Ui * \param sound (Integer): The sound index to interrupt. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_StopSound(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_StopSound(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 2); ScriptEntity* self = GET_ENTITY(0); ISound* audio = GET_ARG(1, GetSound); @@ -1712,7 +1699,7 @@ PUBLIC STATIC VMValue ScriptEntity::VM_StopSound(int argCount, VMValue* args, Ui * \desc Stops all sounds the entity is playing. * \ns Instance */ -PUBLIC STATIC VMValue ScriptEntity::VM_StopAllSounds(int argCount, VMValue* args, Uint32 threadID) { +VMValue ScriptEntity::VM_StopAllSounds(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 1); ScriptEntity* self = GET_ENTITY(0); if (IsValidEntity(self)) diff --git a/source/Engine/Bytecode/ScriptManager.cpp b/source/Engine/Bytecode/ScriptManager.cpp index 1bb7ef96..933de5ae 100644 --- a/source/Engine/Bytecode/ScriptManager.cpp +++ b/source/Engine/Bytecode/ScriptManager.cpp @@ -1,40 +1,3 @@ -#if INTERFACE -need_t ScriptEntity; - -#include -#include -#include -#include -#include -#include -#include - -#include - -class ScriptManager { -public: - static bool LoadAllClasses; - - static HashMap* Globals; - static HashMap* Constants; - - static std::set FreedGlobals; - - static VMThread Threads[8]; - static Uint32 ThreadCount; - - static vector ModuleList; - - static HashMap* Sources; - static HashMap* Classes; - static HashMap* Tokens; - static vector AllNamespaces; - static vector ClassImplList; - - static SDL_mutex* GlobalLock; -}; -#endif - #include #include #include @@ -79,7 +42,7 @@ static Uint32 VMBranchLimit = 0; // #define DEBUG_STRESS_GC -PUBLIC STATIC void ScriptManager::RequestGarbageCollection() { +void ScriptManager::RequestGarbageCollection() { #ifndef DEBUG_STRESS_GC if (GarbageCollector::GarbageSize > GarbageCollector::NextGC) #endif @@ -92,7 +55,7 @@ PUBLIC STATIC void ScriptManager::RequestGarbageCollection() { Log::Print(Log::LOG_INFO, "%04X: Freed garbage from %u to %u (%d), next GC at %d", Scene::Frame, (Uint32)startSize, (Uint32)GarbageCollector::GarbageSize, GarbageCollector::GarbageSize - startSize, GarbageCollector::NextGC); } } -PUBLIC STATIC void ScriptManager::ForceGarbageCollection() { +void ScriptManager::ForceGarbageCollection() { if (ScriptManager::Lock()) { if (ScriptManager::ThreadCount > 1) { ScriptManager::Unlock(); @@ -105,12 +68,12 @@ PUBLIC STATIC void ScriptManager::ForceGarbageCollection() { } } -PUBLIC STATIC void ScriptManager::ResetStack() { +void ScriptManager::ResetStack() { Threads[0].ResetStack(); } // #region Life Cycle -PUBLIC STATIC void ScriptManager::Init() { +void ScriptManager::Init() { if (Globals == NULL) Globals = new HashMap(NULL, 8); if (Constants == NULL) @@ -153,7 +116,7 @@ PUBLIC STATIC void ScriptManager::Init() { ThreadCount = 1; } #ifdef VM_DEBUG -PRIVATE STATIC Uint32 ScriptManager::GetBranchLimit() { +Uint32 ScriptManager::GetBranchLimit() { int branchLimit = 0; if (Application::Settings->GetInteger("dev", "branchLimit", &branchLimit) == true) { @@ -172,12 +135,12 @@ PRIVATE STATIC Uint32 ScriptManager::GetBranchLimit() { return (Uint32)branchLimit; } #endif -PUBLIC STATIC void ScriptManager::DisposeGlobalValueTable(HashMap* globals) { +void ScriptManager::DisposeGlobalValueTable(HashMap* globals) { globals->ForAll(FreeGlobalValue); globals->Clear(); delete globals; } -PUBLIC STATIC void ScriptManager::Dispose() { +void ScriptManager::Dispose() { // NOTE: Remove GC-able values from these tables so they may be cleaned up. if (Globals) Globals->ForAll(RemoveNonGlobalableValue); @@ -233,7 +196,7 @@ PUBLIC STATIC void ScriptManager::Dispose() { SDL_DestroyMutex(GlobalLock); } -PRIVATE STATIC void ScriptManager::RemoveNonGlobalableValue(Uint32 hash, VMValue value) { +void ScriptManager::RemoveNonGlobalableValue(Uint32 hash, VMValue value) { if (IS_OBJECT(value)) { switch (OBJECT_TYPE(value)) { case OBJ_CLASS: @@ -250,7 +213,7 @@ PRIVATE STATIC void ScriptManager::RemoveNonGlobalableValue(Uint32 hash, VMVa } } } -PRIVATE STATIC void ScriptManager::FreeNativeValue(Uint32 hash, VMValue value) { +void ScriptManager::FreeNativeValue(Uint32 hash, VMValue value) { if (IS_OBJECT(value)) { switch (OBJECT_TYPE(value)) { case OBJ_NATIVE: @@ -262,7 +225,7 @@ PRIVATE STATIC void ScriptManager::FreeNativeValue(Uint32 hash, VMValue value } } } -PRIVATE STATIC void ScriptManager::FreeFunction(ObjFunction* function) { +void ScriptManager::FreeFunction(ObjFunction* function) { /* printf("OBJ_FUNCTION: %p (%s)\n", function, function->Name ? @@ -281,7 +244,7 @@ PRIVATE STATIC void ScriptManager::FreeFunction(ObjFunction* function) { FREE_OBJ(function, ObjFunction); } -PRIVATE STATIC void ScriptManager::FreeModule(ObjModule* module) { +void ScriptManager::FreeModule(ObjModule* module) { if (module->SourceFilename != NULL) FreeValue(OBJECT_VAL(module->SourceFilename)); @@ -296,7 +259,7 @@ PRIVATE STATIC void ScriptManager::FreeModule(ObjModule* module) { FREE_OBJ(module, ObjModule); } -PRIVATE STATIC void ScriptManager::FreeClass(ObjClass* klass) { +void ScriptManager::FreeClass(ObjClass* klass) { // Subfunctions are already freed as a byproduct of the ModuleList, // so just do natives. klass->Methods->ForAll(FreeNativeValue); @@ -311,7 +274,7 @@ PRIVATE STATIC void ScriptManager::FreeClass(ObjClass* klass) { FREE_OBJ(klass, ObjClass); } -PRIVATE STATIC void ScriptManager::FreeEnumeration(ObjEnum* enumeration) { +void ScriptManager::FreeEnumeration(ObjEnum* enumeration) { // An enumeration does not own its values, so it's not allowed // to free them. delete enumeration->Fields; @@ -321,7 +284,7 @@ PRIVATE STATIC void ScriptManager::FreeEnumeration(ObjEnum* enumeration) { FREE_OBJ(enumeration, ObjEnum); } -PRIVATE STATIC void ScriptManager::FreeNamespace(ObjNamespace* ns) { +void ScriptManager::FreeNamespace(ObjNamespace* ns) { // A namespace does not own its values, so it's not allowed // to free them. delete ns->Fields; @@ -331,14 +294,14 @@ PRIVATE STATIC void ScriptManager::FreeNamespace(ObjNamespace* ns) { FREE_OBJ(ns, ObjNamespace); } -PUBLIC STATIC void ScriptManager::FreeString(ObjString* string) { +void ScriptManager::FreeString(ObjString* string) { if (string->Chars != NULL) Memory::Free(string->Chars); string->Chars = NULL; FREE_OBJ(string, ObjString); } -PUBLIC STATIC void ScriptManager::FreeGlobalValue(Uint32 hash, VMValue value) { +void ScriptManager::FreeGlobalValue(Uint32 hash, VMValue value) { if (IS_OBJECT(value)) { Obj* object = AS_OBJECT(value); if (FreedGlobals.find(object) != FreedGlobals.end()) @@ -380,7 +343,7 @@ PUBLIC STATIC void ScriptManager::FreeGlobalValue(Uint32 hash, VMValue value) } } } -PRIVATE STATIC void ScriptManager::FreeModules() { +void ScriptManager::FreeModules() { Log::Print(Log::LOG_VERBOSE, "Freeing %d modules...", ModuleList.size()); for (size_t i = 0; i < ModuleList.size(); i++) { FreeModule(ModuleList[i]); @@ -391,7 +354,7 @@ PRIVATE STATIC void ScriptManager::FreeModules() { // #endregion // #region ValueFuncs -PUBLIC STATIC VMValue ScriptManager::CastValueAsString(VMValue v, bool prettyPrint) { +VMValue ScriptManager::CastValueAsString(VMValue v, bool prettyPrint) { if (IS_STRING(v)) return v; @@ -405,10 +368,10 @@ PUBLIC STATIC VMValue ScriptManager::CastValueAsString(VMValue v, bool prettyPri free(buffer); return v; } -PUBLIC STATIC VMValue ScriptManager::CastValueAsString(VMValue v) { +VMValue ScriptManager::CastValueAsString(VMValue v) { return CastValueAsString(v, false); } -PUBLIC STATIC VMValue ScriptManager::CastValueAsInteger(VMValue v) { +VMValue ScriptManager::CastValueAsInteger(VMValue v) { float a; switch (v.Type) { case VAL_DECIMAL: @@ -425,7 +388,7 @@ PUBLIC STATIC VMValue ScriptManager::CastValueAsInteger(VMValue v) { } return NULL_VAL; } -PUBLIC STATIC VMValue ScriptManager::CastValueAsDecimal(VMValue v) { +VMValue ScriptManager::CastValueAsDecimal(VMValue v) { int a; switch (v.Type) { case VAL_DECIMAL: @@ -442,7 +405,7 @@ PUBLIC STATIC VMValue ScriptManager::CastValueAsDecimal(VMValue v) { } return NULL_VAL; } -PUBLIC STATIC VMValue ScriptManager::Concatenate(VMValue va, VMValue vb) { +VMValue ScriptManager::Concatenate(VMValue va, VMValue vb) { ObjString* a = AS_STRING(va); ObjString* b = AS_STRING(vb); @@ -455,7 +418,7 @@ PUBLIC STATIC VMValue ScriptManager::Concatenate(VMValue va, VMValue vb) { return OBJECT_VAL(result); } -PUBLIC STATIC bool ScriptManager::ValuesSortaEqual(VMValue a, VMValue b) { +bool ScriptManager::ValuesSortaEqual(VMValue a, VMValue b) { if ((a.Type == VAL_DECIMAL && b.Type == VAL_INTEGER) || (a.Type == VAL_INTEGER && b.Type == VAL_DECIMAL)) { float a_d = AS_DECIMAL(CastValueAsDecimal(a)); @@ -477,7 +440,7 @@ PUBLIC STATIC bool ScriptManager::ValuesSortaEqual(VMValue a, VMValue b) { return ScriptManager::ValuesEqual(a, b); } -PUBLIC STATIC bool ScriptManager::ValuesEqual(VMValue a, VMValue b) { +bool ScriptManager::ValuesEqual(VMValue a, VMValue b) { if (a.Type == VAL_LINKED_INTEGER) goto SKIP_CHECK; if (a.Type == VAL_LINKED_DECIMAL) goto SKIP_CHECK; if (b.Type == VAL_LINKED_INTEGER) goto SKIP_CHECK; @@ -500,7 +463,7 @@ PUBLIC STATIC bool ScriptManager::ValuesEqual(VMValue a, VMValue b) { } return false; } -PUBLIC STATIC bool ScriptManager::ValueFalsey(VMValue a) { +bool ScriptManager::ValueFalsey(VMValue a) { if (a.Type == VAL_NULL) return true; switch (a.Type) { @@ -513,7 +476,7 @@ PUBLIC STATIC bool ScriptManager::ValueFalsey(VMValue a) { return false; } -PUBLIC STATIC VMValue ScriptManager::DelinkValue(VMValue val) { +VMValue ScriptManager::DelinkValue(VMValue val) { if (IS_LINKED_DECIMAL(val)) return DECIMAL_VAL(AS_DECIMAL(val)); if (IS_LINKED_INTEGER(val)) @@ -522,7 +485,7 @@ PUBLIC STATIC VMValue ScriptManager::DelinkValue(VMValue val) { return val; } -PUBLIC STATIC bool ScriptManager::DoIntegerConversion(VMValue& value, Uint32 threadID) { +bool ScriptManager::DoIntegerConversion(VMValue& value, Uint32 threadID) { VMValue result = ScriptManager::CastValueAsInteger(value); if (IS_NULL(result)) { // Conversion failed @@ -532,7 +495,7 @@ PUBLIC STATIC bool ScriptManager::DoIntegerConversion(VMValue& value, Uint32 thr value = result; return true; } -PUBLIC STATIC bool ScriptManager::DoDecimalConversion(VMValue& value, Uint32 threadID) { +bool ScriptManager::DoDecimalConversion(VMValue& value, Uint32 threadID) { VMValue result = ScriptManager::CastValueAsDecimal(value); if (IS_NULL(result)) { // Conversion failed @@ -543,7 +506,7 @@ PUBLIC STATIC bool ScriptManager::DoDecimalConversion(VMValue& value, Uint32 thr return true; } -PUBLIC STATIC void ScriptManager::FreeValue(VMValue value) { +void ScriptManager::FreeValue(VMValue value) { if (IS_OBJECT(value)) { Obj* objectPointer = AS_OBJECT(value); switch (OBJECT_TYPE(value)) { @@ -611,18 +574,18 @@ PUBLIC STATIC void ScriptManager::FreeValue(VMValue value) { // #endregion // #region GlobalFuncs -PUBLIC STATIC bool ScriptManager::Lock() { +bool ScriptManager::Lock() { if (ScriptManager::ThreadCount == 1) return true; return SDL_LockMutex(GlobalLock) == 0; } -PUBLIC STATIC void ScriptManager::Unlock() { +void ScriptManager::Unlock() { if (ScriptManager::ThreadCount > 1) SDL_UnlockMutex(GlobalLock); } -PUBLIC STATIC void ScriptManager::DefineMethod(VMThread* thread, ObjFunction* function, Uint32 hash) { +void ScriptManager::DefineMethod(VMThread* thread, ObjFunction* function, Uint32 hash) { VMValue methodValue = OBJECT_VAL(function); ObjClass* klass = AS_CLASS(thread->Peek(0)); @@ -635,7 +598,7 @@ PUBLIC STATIC void ScriptManager::DefineMethod(VMThread* thread, ObjFunction* thread->Pop(); } -PUBLIC STATIC void ScriptManager::DefineNative(ObjClass* klass, const char* name, NativeFn function) { +void ScriptManager::DefineNative(ObjClass* klass, const char* name, NativeFn function) { if (function == NULL) return; if (klass == NULL) return; if (name == NULL) return; @@ -643,7 +606,7 @@ PUBLIC STATIC void ScriptManager::DefineNative(ObjClass* klass, const char* n if (!klass->Methods->Exists(name)) klass->Methods->Put(name, OBJECT_VAL(NewNative(function))); } -PUBLIC STATIC void ScriptManager::GlobalLinkInteger(ObjClass* klass, const char* name, int* value) { +void ScriptManager::GlobalLinkInteger(ObjClass* klass, const char* name, int* value) { if (name == NULL) return; if (klass == NULL) { @@ -653,7 +616,7 @@ PUBLIC STATIC void ScriptManager::GlobalLinkInteger(ObjClass* klass, const ch klass->Methods->Put(name, INTEGER_LINK_VAL(value)); } } -PUBLIC STATIC void ScriptManager::GlobalLinkDecimal(ObjClass* klass, const char* name, float* value) { +void ScriptManager::GlobalLinkDecimal(ObjClass* klass, const char* name, float* value) { if (name == NULL) return; if (klass == NULL) { @@ -663,21 +626,21 @@ PUBLIC STATIC void ScriptManager::GlobalLinkDecimal(ObjClass* klass, const ch klass->Methods->Put(name, DECIMAL_LINK_VAL(value)); } } -PUBLIC STATIC void ScriptManager::GlobalConstInteger(ObjClass* klass, const char* name, int value) { +void ScriptManager::GlobalConstInteger(ObjClass* klass, const char* name, int value) { if (name == NULL) return; if (klass == NULL) Constants->Put(name, INTEGER_VAL(value)); else klass->Methods->Put(name, INTEGER_VAL(value)); } -PUBLIC STATIC void ScriptManager::GlobalConstDecimal(ObjClass* klass, const char* name, float value) { +void ScriptManager::GlobalConstDecimal(ObjClass* klass, const char* name, float value) { if (name == NULL) return; if (klass == NULL) Constants->Put(name, DECIMAL_VAL(value)); else klass->Methods->Put(name, DECIMAL_VAL(value)); } -PUBLIC STATIC ObjClass* ScriptManager::GetClassParent(ObjClass* klass) { +ObjClass* ScriptManager::GetClassParent(ObjClass* klass) { if (!klass->Parent && klass->ParentHash) { VMValue parent; if (ScriptManager::Globals->GetIfExists(klass->ParentHash, &parent) && IS_CLASS(parent)) @@ -685,7 +648,7 @@ PUBLIC STATIC ObjClass* ScriptManager::GetClassParent(ObjClass* klass) { } return klass->Parent; } -PUBLIC STATIC VMValue ScriptManager::GetClassMethod(ObjClass* klass, Uint32 hash) { +VMValue ScriptManager::GetClassMethod(ObjClass* klass, Uint32 hash) { VMValue method; if (klass->Methods->GetIfExists(hash, &method)) { return method; @@ -698,10 +661,10 @@ PUBLIC STATIC VMValue ScriptManager::GetClassMethod(ObjClass* klass, Uint32 hash return NULL_VAL; } -PUBLIC STATIC void ScriptManager::LinkStandardLibrary() { +void ScriptManager::LinkStandardLibrary() { StandardLibrary::Link(); } -PUBLIC STATIC void ScriptManager::LinkExtensions() { +void ScriptManager::LinkExtensions() { } // #endregion @@ -717,7 +680,7 @@ PUBLIC STATIC void ScriptManager::LinkExtensions() { #endif // #region ObjectFuncs -PUBLIC STATIC bool ScriptManager::RunBytecode(BytecodeContainer bytecodeContainer, Uint32 filenameHash) { +bool ScriptManager::RunBytecode(BytecodeContainer bytecodeContainer, Uint32 filenameHash) { Bytecode* bytecode = new Bytecode(); if (!bytecode->Read(bytecodeContainer, Tokens)) { delete bytecode; @@ -750,7 +713,7 @@ PUBLIC STATIC bool ScriptManager::RunBytecode(BytecodeContainer bytecodeConta return true; } -PUBLIC STATIC bool ScriptManager::CallFunction(char* functionName) { +bool ScriptManager::CallFunction(char* functionName) { if (!Globals->Exists(functionName)) return false; @@ -762,7 +725,7 @@ PUBLIC STATIC bool ScriptManager::CallFunction(char* functionName) { Threads[0].RunEntityFunction(function, 0); return true; } -PUBLIC STATIC Entity* ScriptManager::SpawnObject(const char* objectName) { +Entity* ScriptManager::SpawnObject(const char* objectName) { ObjClass* klass = GetObjectClass(objectName); if (!klass) { Log::Print(Log::LOG_ERROR, "Could not find class of %s!", objectName); @@ -776,14 +739,14 @@ PUBLIC STATIC Entity* ScriptManager::SpawnObject(const char* objectName) { return object; } -PUBLIC STATIC Uint32 ScriptManager::MakeFilenameHash(char *filename) { +Uint32 ScriptManager::MakeFilenameHash(char *filename) { size_t length = strlen(filename); char* dot = strrchr(filename, '.'); if (dot) length = dot - filename; return CombinedHash::EncryptData((const void*)filename, length); } -PUBLIC STATIC BytecodeContainer ScriptManager::GetBytecodeFromFilenameHash(Uint32 filenameHash) { +BytecodeContainer ScriptManager::GetBytecodeFromFilenameHash(Uint32 filenameHash) { if (Sources->Exists(filenameHash)) return Sources->Get(filenameHash); @@ -813,20 +776,20 @@ PUBLIC STATIC BytecodeContainer ScriptManager::GetBytecodeFromFilenameHash(Uint3 return bytecode; } -PUBLIC STATIC bool ScriptManager::ClassExists(const char* objectName) { +bool ScriptManager::ClassExists(const char* objectName) { return SourceFileMap::ClassMap->Exists(objectName); } -PUBLIC STATIC bool ScriptManager::LoadScript(char* filename) { +bool ScriptManager::LoadScript(char* filename) { if (!filename || !*filename) return false; Uint32 hash = MakeFilenameHash(filename); return LoadScript(hash); } -PUBLIC STATIC bool ScriptManager::LoadScript(const char* filename) { +bool ScriptManager::LoadScript(const char* filename) { return LoadScript((char*)filename); } -PUBLIC STATIC bool ScriptManager::LoadScript(Uint32 hash) { +bool ScriptManager::LoadScript(Uint32 hash) { if (!Sources->Exists(hash)) { BytecodeContainer bytecode = ScriptManager::GetBytecodeFromFilenameHash(hash); if (!bytecode.Data) @@ -837,7 +800,7 @@ PUBLIC STATIC bool ScriptManager::LoadScript(Uint32 hash) { return true; } -PUBLIC STATIC bool ScriptManager::LoadObjectClass(const char* objectName, bool addNativeFunctions) { +bool ScriptManager::LoadObjectClass(const char* objectName, bool addNativeFunctions) { if (!objectName || !*objectName) return false; @@ -886,7 +849,7 @@ PUBLIC STATIC bool ScriptManager::LoadObjectClass(const char* objectName, boo return true; } -PUBLIC STATIC void ScriptManager::AddNativeObjectFunctions(ObjClass* klass) { +void ScriptManager::AddNativeObjectFunctions(ObjClass* klass) { #define DEF_NATIVE(name) ScriptManager::DefineNative(klass, #name, ScriptEntity::VM_##name) DEF_NATIVE(InView); DEF_NATIVE(Animate); @@ -916,7 +879,7 @@ PUBLIC STATIC void ScriptManager::AddNativeObjectFunctions(ObjClass* klass) { DEF_NATIVE(StopAllSounds); #undef DEF_NATIVE } -PUBLIC STATIC ObjClass* ScriptManager::GetObjectClass(const char* className) { +ObjClass* ScriptManager::GetObjectClass(const char* className) { VMValue value = Globals->Get(className); if (IS_CLASS(value)) @@ -924,10 +887,10 @@ PUBLIC STATIC ObjClass* ScriptManager::GetObjectClass(const char* className) { return nullptr; } -PUBLIC STATIC Entity* ScriptManager::ObjectSpawnFunction(ObjectList* list) { +Entity* ScriptManager::ObjectSpawnFunction(ObjectList* list) { return ScriptManager::SpawnObject(list->ObjectName); } -PUBLIC STATIC void ScriptManager::LoadClasses() { +void ScriptManager::LoadClasses() { SourceFileMap::ClassMap->ForAll([](Uint32, vector* filenameHashList) -> void { for (size_t fn = 0; fn < filenameHashList->size(); fn++) { Uint32 filenameHash = (*filenameHashList)[fn]; diff --git a/source/Engine/Bytecode/SourceFileMap.cpp b/source/Engine/Bytecode/SourceFileMap.cpp index 68d4e8ab..39a91086 100644 --- a/source/Engine/Bytecode/SourceFileMap.cpp +++ b/source/Engine/Bytecode/SourceFileMap.cpp @@ -1,18 +1,3 @@ -#if INTERFACE -#include -#include -class SourceFileMap { -public: - static bool Initialized; - static HashMap* Checksums; - static HashMap*>* ClassMap; - static Uint32 DirectoryChecksum; - static Uint32 Magic; - - static bool DoLogging; -}; -#endif - #include #include @@ -33,7 +18,7 @@ Uint32 SourceFileMap::Magic = *(Uint32*)"HMAP"; bool SourceFileMap::DoLogging = false; -PUBLIC STATIC void SourceFileMap::CheckInit() { +void SourceFileMap::CheckInit() { if (SourceFileMap::Initialized) return; if (SourceFileMap::Checksums == NULL) { @@ -100,7 +85,7 @@ PUBLIC STATIC void SourceFileMap::CheckInit() { SourceFileMap::Initialized = true; } -PUBLIC STATIC void SourceFileMap::CheckForUpdate() { +void SourceFileMap::CheckForUpdate() { SourceFileMap::CheckInit(); #ifndef NO_SCRIPT_COMPILING @@ -276,7 +261,7 @@ PUBLIC STATIC void SourceFileMap::CheckForUpdate() { #endif } -PUBLIC STATIC void SourceFileMap::Dispose() { +void SourceFileMap::Dispose() { if (SourceFileMap::Checksums) { delete SourceFileMap::Checksums; } diff --git a/source/Engine/Bytecode/StandardLibrary.cpp b/source/Engine/Bytecode/StandardLibrary.cpp index a9b6968b..6b5c1061 100644 --- a/source/Engine/Bytecode/StandardLibrary.cpp +++ b/source/Engine/Bytecode/StandardLibrary.cpp @@ -1,14 +1,3 @@ -#if INTERFACE -#include -#include -#include - -class StandardLibrary { -public: - -}; -#endif - #include #include @@ -356,45 +345,45 @@ namespace LOCAL { // NOTE: // Integers specifically need to be whole integers. // Floats can be just any countable real number. -PUBLIC STATIC int StandardLibrary::GetInteger(VMValue* args, int index, Uint32 threadID) { +int StandardLibrary::GetInteger(VMValue* args, int index, Uint32 threadID) { return LOCAL::GetInteger(args, index, threadID); } -PUBLIC STATIC float StandardLibrary::GetDecimal(VMValue* args, int index, Uint32 threadID) { +float StandardLibrary::GetDecimal(VMValue* args, int index, Uint32 threadID) { return LOCAL::GetDecimal(args, index, threadID); } -PUBLIC STATIC char* StandardLibrary::GetString(VMValue* args, int index, Uint32 threadID) { +char* StandardLibrary::GetString(VMValue* args, int index, Uint32 threadID) { return LOCAL::GetString(args, index, threadID); } -PUBLIC STATIC ObjString* StandardLibrary::GetVMString(VMValue* args, int index, Uint32 threadID) { +ObjString* StandardLibrary::GetVMString(VMValue* args, int index, Uint32 threadID) { return LOCAL::GetVMString(args, index, threadID); } -PUBLIC STATIC ObjArray* StandardLibrary::GetArray(VMValue* args, int index, Uint32 threadID) { +ObjArray* StandardLibrary::GetArray(VMValue* args, int index, Uint32 threadID) { return LOCAL::GetArray(args, index, threadID); } -PUBLIC STATIC ObjMap* StandardLibrary::GetMap(VMValue* args, int index, Uint32 threadID) { +ObjMap* StandardLibrary::GetMap(VMValue* args, int index, Uint32 threadID) { return LOCAL::GetMap(args, index, threadID); } -PUBLIC STATIC ISprite* StandardLibrary::GetSprite(VMValue* args, int index, Uint32 threadID) { +ISprite* StandardLibrary::GetSprite(VMValue* args, int index, Uint32 threadID) { return LOCAL::GetSprite(args, index, threadID); } -PUBLIC STATIC ISound* StandardLibrary::GetSound(VMValue* args, int index, Uint32 threadID) { +ISound* StandardLibrary::GetSound(VMValue* args, int index, Uint32 threadID) { return LOCAL::GetSound(args, index, threadID); } -PUBLIC STATIC ObjInstance* StandardLibrary::GetInstance(VMValue* args, int index, Uint32 threadID) { +ObjInstance* StandardLibrary::GetInstance(VMValue* args, int index, Uint32 threadID) { return LOCAL::GetInstance(args, index, threadID); } -PUBLIC STATIC ObjFunction* StandardLibrary::GetFunction(VMValue* args, int index, Uint32 threadID) { +ObjFunction* StandardLibrary::GetFunction(VMValue* args, int index, Uint32 threadID) { return LOCAL::GetFunction(args, index, threadID); } -PUBLIC STATIC void StandardLibrary::CheckArgCount(int argCount, int expects) { +void StandardLibrary::CheckArgCount(int argCount, int expects) { Uint32 threadID = 0; if (argCount != expects) { if (THROW_ERROR("Expected %d arguments but got %d.", expects, argCount) == ERROR_RES_CONTINUE) ScriptManager::Threads[threadID].ReturnFromNative(); } } -PUBLIC STATIC void StandardLibrary::CheckAtLeastArgCount(int argCount, int expects) { +void StandardLibrary::CheckAtLeastArgCount(int argCount, int expects) { Uint32 threadID = 0; if (argCount < expects) { if (THROW_ERROR("Expected at least %d arguments but got %d.", expects, argCount) == ERROR_RES_CONTINUE) @@ -16423,7 +16412,7 @@ ObjNamespace* InitNamespace(const char* nsName) { return ns; } -PUBLIC STATIC void StandardLibrary::Link() { +void StandardLibrary::Link() { ObjClass* klass; for (int i = 0; i < 0x100; i++) { @@ -19355,6 +19344,6 @@ PUBLIC STATIC void StandardLibrary::Link() { #undef DEF_ENUM_CLASS #undef DEF_ENUM_NAMED } -PUBLIC STATIC void StandardLibrary::Dispose() { +void StandardLibrary::Dispose() { } diff --git a/source/Engine/Bytecode/TypeImpl/ArrayImpl.cpp b/source/Engine/Bytecode/TypeImpl/ArrayImpl.cpp index dce38d6a..f16f0c18 100644 --- a/source/Engine/Bytecode/TypeImpl/ArrayImpl.cpp +++ b/source/Engine/Bytecode/TypeImpl/ArrayImpl.cpp @@ -1,20 +1,10 @@ -#if INTERFACE -#include -#include - -class ArrayImpl { -public: - static ObjClass *Class; -}; -#endif - #include #include #include ObjClass* ArrayImpl::Class = nullptr; -PUBLIC STATIC void ArrayImpl::Init() { +void ArrayImpl::Init() { const char *name = "$$ArrayImpl"; Class = NewClass(Murmur::EncryptString(name)); @@ -28,7 +18,7 @@ PUBLIC STATIC void ArrayImpl::Init() { #define GET_ARG(argIndex, argFunction) (StandardLibrary::argFunction(args, argIndex, threadID)) -PUBLIC STATIC VMValue ArrayImpl::VM_Iterate(int argCount, VMValue* args, Uint32 threadID) { +VMValue ArrayImpl::VM_Iterate(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 2); ObjArray* array = GET_ARG(0, GetArray); @@ -44,7 +34,7 @@ PUBLIC STATIC VMValue ArrayImpl::VM_Iterate(int argCount, VMValue* args, Uint32 return NULL_VAL; } -PUBLIC STATIC VMValue ArrayImpl::VM_IteratorValue(int argCount, VMValue* args, Uint32 threadID) { +VMValue ArrayImpl::VM_IteratorValue(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 2); ObjArray* array = GET_ARG(0, GetArray); diff --git a/source/Engine/Bytecode/TypeImpl/FunctionImpl.cpp b/source/Engine/Bytecode/TypeImpl/FunctionImpl.cpp index 7550f495..01842710 100644 --- a/source/Engine/Bytecode/TypeImpl/FunctionImpl.cpp +++ b/source/Engine/Bytecode/TypeImpl/FunctionImpl.cpp @@ -1,20 +1,10 @@ -#if INTERFACE -#include -#include - -class FunctionImpl { -public: - static ObjClass *Class; -}; -#endif - #include #include #include ObjClass* FunctionImpl::Class = nullptr; -PUBLIC STATIC void FunctionImpl::Init() { +void FunctionImpl::Init() { const char *name = "$$FunctionImpl"; Class = NewClass(Murmur::EncryptString(name)); @@ -27,7 +17,7 @@ PUBLIC STATIC void FunctionImpl::Init() { #define GET_ARG(argIndex, argFunction) (StandardLibrary::argFunction(args, argIndex, threadID)) -PUBLIC STATIC VMValue FunctionImpl::VM_Bind(int argCount, VMValue* args, Uint32 threadID) { +VMValue FunctionImpl::VM_Bind(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 2); ObjFunction* function = GET_ARG(0, GetFunction); diff --git a/source/Engine/Bytecode/TypeImpl/MapImpl.cpp b/source/Engine/Bytecode/TypeImpl/MapImpl.cpp index de686198..98357d42 100644 --- a/source/Engine/Bytecode/TypeImpl/MapImpl.cpp +++ b/source/Engine/Bytecode/TypeImpl/MapImpl.cpp @@ -1,20 +1,10 @@ -#if INTERFACE -#include -#include - -class MapImpl { -public: - static ObjClass *Class; -}; -#endif - #include #include #include ObjClass* MapImpl::Class = nullptr; -PUBLIC STATIC void MapImpl::Init() { +void MapImpl::Init() { const char *name = "$$MapImpl"; Class = NewClass(Murmur::EncryptString(name)); @@ -29,7 +19,7 @@ PUBLIC STATIC void MapImpl::Init() { #define GET_ARG(argIndex, argFunction) (StandardLibrary::argFunction(args, argIndex, threadID)) -PUBLIC STATIC VMValue MapImpl::VM_GetKeys(int argCount, VMValue* args, Uint32 threadID) { +VMValue MapImpl::VM_GetKeys(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 1); ObjMap* map = GET_ARG(0, GetMap); @@ -43,7 +33,7 @@ PUBLIC STATIC VMValue MapImpl::VM_GetKeys(int argCount, VMValue* args, Uint32 th return OBJECT_VAL(array); } -PUBLIC STATIC VMValue MapImpl::VM_Iterate(int argCount, VMValue* args, Uint32 threadID) { +VMValue MapImpl::VM_Iterate(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 2); ObjMap* map = GET_ARG(0, GetMap); @@ -60,7 +50,7 @@ PUBLIC STATIC VMValue MapImpl::VM_Iterate(int argCount, VMValue* args, Uint32 th return NULL_VAL; } -PUBLIC STATIC VMValue MapImpl::VM_IteratorValue(int argCount, VMValue* args, Uint32 threadID) { +VMValue MapImpl::VM_IteratorValue(int argCount, VMValue* args, Uint32 threadID) { StandardLibrary::CheckArgCount(argCount, 2); ObjMap* map = GET_ARG(0, GetMap); diff --git a/source/Engine/Bytecode/TypeImpl/StringImpl.cpp b/source/Engine/Bytecode/TypeImpl/StringImpl.cpp index 83114f4f..82875c8d 100644 --- a/source/Engine/Bytecode/TypeImpl/StringImpl.cpp +++ b/source/Engine/Bytecode/TypeImpl/StringImpl.cpp @@ -1,20 +1,10 @@ -#if INTERFACE -#include -#include - -class StringImpl { -public: - static ObjClass *Class; -}; -#endif - #include #include #include ObjClass* StringImpl::Class = nullptr; -PUBLIC STATIC void StringImpl::Init() { +void StringImpl::Init() { const char *name = "$$StringImpl"; Class = NewClass(Murmur::EncryptString(name)); @@ -29,7 +19,7 @@ PUBLIC STATIC void StringImpl::Init() { #define THROW_ERROR(...) ScriptManager::Threads[threadID].ThrowRuntimeError(false, __VA_ARGS__) -PUBLIC STATIC bool StringImpl::VM_ElementGet(Obj* object, VMValue at, VMValue* result, Uint32 threadID) { +bool StringImpl::VM_ElementGet(Obj* object, VMValue at, VMValue* result, Uint32 threadID) { ObjString* string = (ObjString*)object; if (!IS_INTEGER(at)) { @@ -55,7 +45,7 @@ PUBLIC STATIC bool StringImpl::VM_ElementGet(Obj* object, VMValue at, VMValue* r return true; } #if 0 -PUBLIC STATIC bool StringImpl::VM_ElementSet(Obj* object, VMValue at, VMValue value, Uint32 threadID) { +bool StringImpl::VM_ElementSet(Obj* object, VMValue at, VMValue value, Uint32 threadID) { ObjString* string = (ObjString*)object; if (!IS_INTEGER(at)) { diff --git a/source/Engine/Bytecode/VMThread.cpp b/source/Engine/Bytecode/VMThread.cpp index 92c79c18..c3b6b0c4 100644 --- a/source/Engine/Bytecode/VMThread.cpp +++ b/source/Engine/Bytecode/VMThread.cpp @@ -1,39 +1,3 @@ -#if INTERFACE -#include -#include -#include - -class VMThread { -public: - VMValue Stack[STACK_SIZE_MAX]; - VMValue* StackTop = Stack; - VMValue RegisterValue; - - CallFrame Frames[FRAMES_MAX]; - Uint32 FrameCount; - Uint32 ReturnFrame; - - VMValue FunctionToInvoke; - VMValue InterpretResult; - - enum ThreadState { - CREATED = 0, - RUNNING = 1, - WAITING = 2, - CLOSED = 3, - }; - - char Name[THREAD_NAME_MAX]; - Uint32 ID; - - bool DebugInfo; - Uint32 BranchLimit; - - static bool InstructionIgnoreMap[0x100]; - static std::jmp_buf JumpBuffer; -}; -#endif - #include #include #include @@ -108,7 +72,7 @@ std::jmp_buf VMThread::JumpBuffer; return ERROR_RES_CONTINUE; \ } -PRIVATE string VMThread::GetFunctionName(ObjFunction* function) { +string VMThread::GetFunctionName(ObjFunction* function) { std::string functionName(GetToken(function->NameHash)); if (functionName == "main") @@ -123,7 +87,7 @@ PRIVATE string VMThread::GetFunctionName(ObjFunction* function) { return functionName; } -PUBLIC STATIC char* VMThread::GetToken(Uint32 hash) { +char* VMThread::GetToken(Uint32 hash) { static char GetTokenBuffer[256]; if (__Tokens__ && __Tokens__->Exists(hash)) @@ -132,7 +96,7 @@ PUBLIC STATIC char* VMThread::GetToken(Uint32 hash) { snprintf(GetTokenBuffer, 15, "%X", hash); return GetTokenBuffer; } -PUBLIC STATIC char* VMThread::GetVariableOrMethodName(Uint32 hash) { +char* VMThread::GetVariableOrMethodName(Uint32 hash) { static char GetTokenBuffer[256]; if (__Tokens__ && __Tokens__->Exists(hash)) { @@ -144,7 +108,7 @@ PUBLIC STATIC char* VMThread::GetVariableOrMethodName(Uint32 hash) { return GetTokenBuffer; } -PRIVATE void VMThread::PrintStackTrace(PrintBuffer* buffer, const char* errorString) { +void VMThread::PrintStackTrace(PrintBuffer* buffer, const char* errorString) { int line; char* source; @@ -194,7 +158,7 @@ PRIVATE void VMThread::PrintStackTrace(PrintBuffer* buffer, const char* error buffer_printf(buffer, "\n"); } } -PUBLIC void VMThread::MakeErrorMessage(PrintBuffer* buffer, const char* errorString) { +void VMThread::MakeErrorMessage(PrintBuffer* buffer, const char* errorString) { if (FrameCount > 0) PrintStackTrace(buffer, errorString); else if (IS_OBJECT(FunctionToInvoke)) { @@ -227,7 +191,7 @@ PUBLIC void VMThread::MakeErrorMessage(PrintBuffer* buffer, const char* error buffer_printf(buffer, "%s\n", errorString); } } -PUBLIC int VMThread::ThrowRuntimeError(bool fatal, const char* errorMessage, ...) { +int VMThread::ThrowRuntimeError(bool fatal, const char* errorMessage, ...) { bool showMessageBox = true; if (VMThread::InstructionIgnoreMap[000000000]) { showMessageBox = false; @@ -241,7 +205,7 @@ PUBLIC int VMThread::ThrowRuntimeError(bool fatal, const char* errorMessage, return ERROR_RES_CONTINUE; } -PUBLIC void VMThread::PrintStack() { +void VMThread::PrintStack() { int i = 0; printf("Stack:\n"); for (VMValue* v = StackTop - 1; v >= Stack; v--) { @@ -251,13 +215,13 @@ PUBLIC void VMThread::PrintStack() { i--; } } -PUBLIC void VMThread::ReturnFromNative() throw() { +void VMThread::ReturnFromNative() throw() { } // #endregion // #region Stack stuff -PUBLIC void VMThread::Push(VMValue value) { +void VMThread::Push(VMValue value) { if (StackSize() == STACK_SIZE_MAX) { if (ThrowRuntimeError(true, "Stack overflow! \nStack Top: %p \nStack: %p\nCount: %d", StackTop, Stack, StackSize()) == ERROR_RES_CONTINUE) return; @@ -265,7 +229,7 @@ PUBLIC void VMThread::Push(VMValue value) { *(StackTop++) = value; } -PUBLIC VMValue VMThread::Pop() { +VMValue VMThread::Pop() { if (StackTop == Stack) { if (ThrowRuntimeError(true, "Stack underflow!") == ERROR_RES_CONTINUE) return *StackTop; @@ -274,17 +238,17 @@ PUBLIC VMValue VMThread::Pop() { StackTop--; return *StackTop; } -PUBLIC void VMThread::Pop(unsigned amount) { +void VMThread::Pop(unsigned amount) { while (amount-- > 0) Pop(); } -PUBLIC VMValue VMThread::Peek(int offset) { +VMValue VMThread::Peek(int offset) { return *(StackTop - offset - 1); } -PUBLIC Uint32 VMThread::StackSize() { +Uint32 VMThread::StackSize() { return (Uint32)(StackTop - Stack); } -PUBLIC void VMThread::ResetStack() { +void VMThread::ResetStack() { // bool debugInstruction = ID == 1; // if (debugInstruction) printf("reset stack\n"); @@ -302,25 +266,25 @@ enum ThreadReturnCodes { }; // NOTE: These should be inlined -PUBLIC Uint8 VMThread::ReadByte(CallFrame* frame) { +Uint8 VMThread::ReadByte(CallFrame* frame) { frame->IP += sizeof(Uint8); return *(Uint8*)(frame->IP - sizeof(Uint8)); } -PUBLIC Uint16 VMThread::ReadUInt16(CallFrame* frame) { +Uint16 VMThread::ReadUInt16(CallFrame* frame) { frame->IP += sizeof(Uint16); return *(Uint16*)(frame->IP - sizeof(Uint16)); } -PUBLIC Uint32 VMThread::ReadUInt32(CallFrame* frame) { +Uint32 VMThread::ReadUInt32(CallFrame* frame) { frame->IP += sizeof(Uint32); return *(Uint32*)(frame->IP - sizeof(Uint32)); } -PUBLIC Sint16 VMThread::ReadSInt16(CallFrame* frame) { +Sint16 VMThread::ReadSInt16(CallFrame* frame) { return (Sint16)ReadUInt16(frame); } -PUBLIC Sint32 VMThread::ReadSInt32(CallFrame* frame) { +Sint32 VMThread::ReadSInt32(CallFrame* frame) { return (Sint32)ReadUInt32(frame); } -PUBLIC VMValue VMThread::ReadConstant(CallFrame* frame) { +VMValue VMThread::ReadConstant(CallFrame* frame) { return (*frame->Function->Chunk.Constants)[ReadUInt32(frame)]; } @@ -335,7 +299,7 @@ PUBLIC VMValue VMThread::ReadConstant(CallFrame* frame) { } #ifdef VM_DEBUG -PUBLIC bool VMThread::ShowBranchLimitMessage(const char* errorMessage, ...) { +bool VMThread::ShowBranchLimitMessage(const char* errorMessage, ...) { va_list args; char errorString[2048]; va_start(args, errorMessage); @@ -395,18 +359,18 @@ PUBLIC bool VMThread::ShowBranchLimitMessage(const char* errorMessage, ...) { return true; } -PRIVATE bool VMThread::CheckBranchLimit(CallFrame* frame) { +bool VMThread::CheckBranchLimit(CallFrame* frame) { if (BranchLimit && ++frame->BranchCount >= BranchLimit) { return ShowBranchLimitMessage("Hit branch limit!"); } return true; } -PRIVATE bool VMThread::DoJump(CallFrame* frame, int offset) { +bool VMThread::DoJump(CallFrame* frame, int offset) { frame->IP += offset; return CheckBranchLimit(frame); } -PRIVATE bool VMThread::DoJumpBack(CallFrame* frame, int offset) { +bool VMThread::DoJumpBack(CallFrame* frame, int offset) { frame->IP -= offset; return CheckBranchLimit(frame); } @@ -434,7 +398,7 @@ PRIVATE bool VMThread::DoJumpBack(CallFrame* frame, int offset) { #define JUMP_BACK(offset) { frame->IP -= offset; } #endif -PUBLIC int VMThread::RunInstruction() { +int VMThread::RunInstruction() { // NOTE: MSVC cannot take advantage of the dispatch table. #ifdef USING_VM_DISPATCH_TABLE #define VM_ADD_DISPATCH(op) &&START_ ## op @@ -1877,7 +1841,7 @@ PUBLIC int VMThread::RunInstruction() { return INTERPRET_OK; } -PUBLIC void VMThread::RunInstructionSet() { +void VMThread::RunInstructionSet() { while (true) { // if (!ScriptManager::Lock()) break; @@ -1893,7 +1857,7 @@ PUBLIC void VMThread::RunInstructionSet() { } // #endregion -PUBLIC void VMThread::RunValue(VMValue value, int argCount) { +void VMThread::RunValue(VMValue value, int argCount) { int lastReturnFrame = ReturnFrame; ReturnFrame = FrameCount; @@ -1901,7 +1865,7 @@ PUBLIC void VMThread::RunValue(VMValue value, int argCount) { RunInstructionSet(); ReturnFrame = lastReturnFrame; } -PUBLIC void VMThread::RunFunction(ObjFunction* func, int argCount) { +void VMThread::RunFunction(ObjFunction* func, int argCount) { VMValue* lastStackTop = StackTop; int lastReturnFrame = ReturnFrame; @@ -1913,7 +1877,7 @@ PUBLIC void VMThread::RunFunction(ObjFunction* func, int argCount) { ReturnFrame = lastReturnFrame; StackTop = lastStackTop; } -PUBLIC void VMThread::InvokeForEntity(VMValue value, int argCount) { +void VMThread::InvokeForEntity(VMValue value, int argCount) { VMValue* lastStackTop = StackTop; int lastReturnFrame = ReturnFrame; @@ -1935,7 +1899,7 @@ PUBLIC void VMThread::InvokeForEntity(VMValue value, int argCount) { ReturnFrame = lastReturnFrame; StackTop = lastStackTop; } -PUBLIC VMValue VMThread::RunEntityFunction(ObjFunction* function, int argCount) { +VMValue VMThread::RunEntityFunction(ObjFunction* function, int argCount) { VMValue* lastStackTop = StackTop; int lastReturnFrame = ReturnFrame; @@ -1951,7 +1915,7 @@ PUBLIC VMValue VMThread::RunEntityFunction(ObjFunction* function, int argCount) return InterpretResult; } -PUBLIC void VMThread::CallInitializer(VMValue value) { +void VMThread::CallInitializer(VMValue value) { FunctionToInvoke = value; ObjFunction* initializer = AS_FUNCTION(value); @@ -1973,7 +1937,7 @@ PUBLIC void VMThread::CallInitializer(VMValue value) { FunctionToInvoke = NULL_VAL; } -PRIVATE bool VMThread::GetProperty(Obj* object, ObjClass* klass, Uint32 hash, bool checkFields, ValueGetFn getter) { +bool VMThread::GetProperty(Obj* object, ObjClass* klass, Uint32 hash, bool checkFields, ValueGetFn getter) { if (ScriptManager::Lock()) { VMValue value; @@ -2012,13 +1976,13 @@ PRIVATE bool VMThread::GetProperty(Obj* object, ObjClass* klass, Uint32 hash, ScriptManager::Unlock(); return false; } -PRIVATE bool VMThread::GetProperty(Obj* object, ObjClass* klass, Uint32 hash, bool checkFields) { +bool VMThread::GetProperty(Obj* object, ObjClass* klass, Uint32 hash, bool checkFields) { return GetProperty(object, klass, hash, true, klass->PropertyGet); } -PRIVATE bool VMThread::GetProperty(Obj* object, ObjClass* klass, Uint32 hash) { +bool VMThread::GetProperty(Obj* object, ObjClass* klass, Uint32 hash) { return GetProperty(object, klass, hash, true); } -PRIVATE bool VMThread::HasProperty(Obj* object, ObjClass* klass, Uint32 hash, bool checkFields, ValueGetFn getter) { +bool VMThread::HasProperty(Obj* object, ObjClass* klass, Uint32 hash, bool checkFields, ValueGetFn getter) { if (ScriptManager::Lock()) { if (checkFields && klass->Fields->Exists(hash)) { // Fields have priority over methods @@ -2044,13 +2008,13 @@ PRIVATE bool VMThread::HasProperty(Obj* object, ObjClass* klass, Uint32 hash, ScriptManager::Unlock(); return false; } -PRIVATE bool VMThread::HasProperty(Obj* object, ObjClass* klass, Uint32 hash, bool checkFields) { +bool VMThread::HasProperty(Obj* object, ObjClass* klass, Uint32 hash, bool checkFields) { return HasProperty(object, klass, checkFields, klass->PropertyGet); } -PRIVATE bool VMThread::HasProperty(Obj* object, ObjClass* klass, Uint32 hash) { +bool VMThread::HasProperty(Obj* object, ObjClass* klass, Uint32 hash) { return HasProperty(object, klass, true); } -PRIVATE bool VMThread::SetProperty(Table* fields, Uint32 hash, VMValue field, VMValue value) { +bool VMThread::SetProperty(Table* fields, Uint32 hash, VMValue field, VMValue value) { switch (field.Type) { case VAL_LINKED_INTEGER: if (!ScriptManager::DoIntegerConversion(value, this->ID)) @@ -2067,18 +2031,18 @@ PRIVATE bool VMThread::SetProperty(Table* fields, Uint32 hash, VMValue field, } return true; } -PRIVATE bool VMThread::BindMethod(VMValue receiver, VMValue method) { +bool VMThread::BindMethod(VMValue receiver, VMValue method) { ObjBoundMethod* bound = NewBoundMethod(receiver, AS_FUNCTION(method)); Push(OBJECT_VAL(bound)); return true; } -PRIVATE bool VMThread::CallBoundMethod(ObjBoundMethod* bound, int argCount) { +bool VMThread::CallBoundMethod(ObjBoundMethod* bound, int argCount) { // Replace the bound method with the receiver so it's in the // right slot when the method is called. StackTop[-argCount - 1] = bound->Receiver; return Call(bound->Method, argCount); } -PRIVATE bool VMThread::CallValue(VMValue callee, int argCount) { +bool VMThread::CallValue(VMValue callee, int argCount) { bool result = false; if (ScriptManager::Lock() && IS_OBJECT(callee)) { switch (OBJECT_TYPE(callee)) { @@ -2114,7 +2078,7 @@ PRIVATE bool VMThread::CallValue(VMValue callee, int argCount) { ScriptManager::Unlock(); return result; } -PRIVATE bool VMThread::CallForObject(VMValue callee, int argCount) { +bool VMThread::CallForObject(VMValue callee, int argCount) { if (ScriptManager::Lock()) { // Special case for native functions if (OBJECT_TYPE(callee) == OBJ_NATIVE) { @@ -2143,7 +2107,7 @@ PRIVATE bool VMThread::CallForObject(VMValue callee, int argCount) { } return false; } -PRIVATE bool VMThread::InstantiateClass(VMValue callee, int argCount) { +bool VMThread::InstantiateClass(VMValue callee, int argCount) { if (ScriptManager::Lock()) { bool result = false; if (!IS_OBJECT(callee) || OBJECT_TYPE(callee) != OBJ_CLASS) { @@ -2172,7 +2136,7 @@ PRIVATE bool VMThread::InstantiateClass(VMValue callee, int argCount) { return false; } -PUBLIC bool VMThread::Call(ObjFunction* function, int argCount) { +bool VMThread::Call(ObjFunction* function, int argCount) { if (function->MinArity < function->Arity) { if (argCount < function->MinArity) { ThrowRuntimeError(false, "Expected at least %d arguments to function call, got %d.", function->MinArity, argCount); @@ -2213,7 +2177,7 @@ PUBLIC bool VMThread::Call(ObjFunction* function, int argCount) { return true; } -PUBLIC bool VMThread::InvokeFromClass(ObjClass* klass, Uint32 hash, int argCount) { +bool VMThread::InvokeFromClass(ObjClass* klass, Uint32 hash, int argCount) { if (ScriptManager::Lock()) { VMValue method; if (klass->Methods->GetIfExists(hash, &method)) { @@ -2232,7 +2196,7 @@ PUBLIC bool VMThread::InvokeFromClass(ObjClass* klass, Uint32 hash, int argCo } return false; } -PUBLIC bool VMThread::InvokeForInstance(Uint32 hash, int argCount, bool isSuper) { +bool VMThread::InvokeForInstance(Uint32 hash, int argCount, bool isSuper) { ObjInstance* instance = AS_INSTANCE(Peek(argCount)); ObjClass* klass = instance->Object.Class; @@ -2258,7 +2222,7 @@ PUBLIC bool VMThread::InvokeForInstance(Uint32 hash, int argCount, bool isSup } return InvokeFromClass(klass, hash, argCount); } -PRIVATE bool VMThread::DoClassExtension(VMValue value, VMValue originalValue, bool clearSrc) { +bool VMThread::DoClassExtension(VMValue value, VMValue originalValue, bool clearSrc) { ObjClass* src = AS_CLASS(value); ObjClass* dst = AS_CLASS(originalValue); @@ -2276,7 +2240,7 @@ PRIVATE bool VMThread::DoClassExtension(VMValue value, VMValue originalValue, return true; } -PUBLIC bool VMThread::Import(VMValue value) { +bool VMThread::Import(VMValue value) { bool result = false; if (ScriptManager::Lock()) { if (!IS_OBJECT(value) || OBJECT_TYPE(value) != OBJ_STRING) { @@ -2298,7 +2262,7 @@ PUBLIC bool VMThread::Import(VMValue value) { ScriptManager::Unlock(); return result; } -PUBLIC bool VMThread::ImportModule(VMValue value) { +bool VMThread::ImportModule(VMValue value) { bool result = false; if (ScriptManager::Lock()) { if (!IS_OBJECT(value) || OBJECT_TYPE(value) != OBJ_STRING) { @@ -2327,7 +2291,7 @@ PUBLIC bool VMThread::ImportModule(VMValue value) { // If one of the operators is a decimal, they both become one -PUBLIC VMValue VMThread::Values_Multiply() { +VMValue VMThread::Values_Multiply() { VMValue b = Peek(0); VMValue a = Peek(1); @@ -2346,7 +2310,7 @@ PUBLIC VMValue VMThread::Values_Multiply() { int b_d = AS_INTEGER(b); return INTEGER_VAL(a_d * b_d); } -PUBLIC VMValue VMThread::Values_Division() { +VMValue VMThread::Values_Division() { VMValue b = Pop(); VMValue a = Pop(); @@ -2370,7 +2334,7 @@ PUBLIC VMValue VMThread::Values_Division() { } return INTEGER_VAL(a_d / b_d); } -PUBLIC VMValue VMThread::Values_Modulo() { +VMValue VMThread::Values_Modulo() { VMValue b = Pop(); VMValue a = Pop(); @@ -2386,7 +2350,7 @@ PUBLIC VMValue VMThread::Values_Modulo() { int b_d = AS_INTEGER(b); return INTEGER_VAL(a_d % b_d); } -PUBLIC VMValue VMThread::Values_Plus() { +VMValue VMThread::Values_Plus() { VMValue b = Peek(0); VMValue a = Peek(1); if (IS_STRING(a) || IS_STRING(b)) { @@ -2417,7 +2381,7 @@ PUBLIC VMValue VMThread::Values_Plus() { Pop(); return INTEGER_VAL(a_d + b_d); } -PUBLIC VMValue VMThread::Values_Minus() { +VMValue VMThread::Values_Minus() { VMValue b = Peek(0); VMValue a = Peek(1); @@ -2436,7 +2400,7 @@ PUBLIC VMValue VMThread::Values_Minus() { int b_d = AS_INTEGER(b); return INTEGER_VAL(a_d - b_d); } -PUBLIC VMValue VMThread::Values_BitwiseLeft() { +VMValue VMThread::Values_BitwiseLeft() { VMValue b = Pop(); VMValue a = Pop(); @@ -2452,7 +2416,7 @@ PUBLIC VMValue VMThread::Values_BitwiseLeft() { int b_d = AS_INTEGER(b); return INTEGER_VAL(a_d << b_d); } -PUBLIC VMValue VMThread::Values_BitwiseRight() { +VMValue VMThread::Values_BitwiseRight() { VMValue b = Pop(); VMValue a = Pop(); @@ -2468,7 +2432,7 @@ PUBLIC VMValue VMThread::Values_BitwiseRight() { int b_d = AS_INTEGER(b); return INTEGER_VAL(a_d >> b_d); } -PUBLIC VMValue VMThread::Values_BitwiseAnd() { +VMValue VMThread::Values_BitwiseAnd() { VMValue b = Pop(); VMValue a = Pop(); @@ -2484,7 +2448,7 @@ PUBLIC VMValue VMThread::Values_BitwiseAnd() { int b_d = AS_INTEGER(b); return INTEGER_VAL(a_d & b_d); } -PUBLIC VMValue VMThread::Values_BitwiseXor() { +VMValue VMThread::Values_BitwiseXor() { VMValue b = Pop(); VMValue a = Pop(); @@ -2500,7 +2464,7 @@ PUBLIC VMValue VMThread::Values_BitwiseXor() { int b_d = AS_INTEGER(b); return INTEGER_VAL(a_d ^ b_d); } -PUBLIC VMValue VMThread::Values_BitwiseOr() { +VMValue VMThread::Values_BitwiseOr() { VMValue b = Pop(); VMValue a = Pop(); @@ -2516,7 +2480,7 @@ PUBLIC VMValue VMThread::Values_BitwiseOr() { int b_d = AS_INTEGER(b); return INTEGER_VAL(a_d | b_d); } -PUBLIC VMValue VMThread::Values_LogicalAND() { +VMValue VMThread::Values_LogicalAND() { VMValue b = Pop(); VMValue a = Pop(); @@ -2533,7 +2497,7 @@ PUBLIC VMValue VMThread::Values_LogicalAND() { int b_d = AS_INTEGER(b); return INTEGER_VAL(a_d && b_d); } -PUBLIC VMValue VMThread::Values_LogicalOR() { +VMValue VMThread::Values_LogicalOR() { VMValue b = Pop(); VMValue a = Pop(); @@ -2550,7 +2514,7 @@ PUBLIC VMValue VMThread::Values_LogicalOR() { int b_d = AS_INTEGER(b); return INTEGER_VAL(a_d || b_d); } -PUBLIC VMValue VMThread::Values_LessThan() { +VMValue VMThread::Values_LessThan() { VMValue b = Pop(); VMValue a = Pop(); @@ -2566,7 +2530,7 @@ PUBLIC VMValue VMThread::Values_LessThan() { int b_d = AS_INTEGER(b); return INTEGER_VAL(a_d < b_d); } -PUBLIC VMValue VMThread::Values_GreaterThan() { +VMValue VMThread::Values_GreaterThan() { VMValue b = Pop(); VMValue a = Pop(); @@ -2582,7 +2546,7 @@ PUBLIC VMValue VMThread::Values_GreaterThan() { int b_d = AS_INTEGER(b); return INTEGER_VAL(a_d > b_d); } -PUBLIC VMValue VMThread::Values_LessThanOrEqual() { +VMValue VMThread::Values_LessThanOrEqual() { VMValue b = Pop(); VMValue a = Pop(); @@ -2598,7 +2562,7 @@ PUBLIC VMValue VMThread::Values_LessThanOrEqual() { int b_d = AS_INTEGER(b); return INTEGER_VAL(a_d <= b_d); } -PUBLIC VMValue VMThread::Values_GreaterThanOrEqual() { +VMValue VMThread::Values_GreaterThanOrEqual() { VMValue b = Pop(); VMValue a = Pop(); @@ -2614,7 +2578,7 @@ PUBLIC VMValue VMThread::Values_GreaterThanOrEqual() { int b_d = AS_INTEGER(b); return INTEGER_VAL(a_d >= b_d); } -PUBLIC VMValue VMThread::Values_Increment() { +VMValue VMThread::Values_Increment() { VMValue a = Pop(); CHECK_IS_NUM(a, "increment", INTEGER_VAL(0)); @@ -2626,7 +2590,7 @@ PUBLIC VMValue VMThread::Values_Increment() { int a_d = AS_INTEGER(a); return INTEGER_VAL(++a_d); } -PUBLIC VMValue VMThread::Values_Decrement() { +VMValue VMThread::Values_Decrement() { VMValue a = Pop(); CHECK_IS_NUM(a, "decrement", INTEGER_VAL(0)); @@ -2638,7 +2602,7 @@ PUBLIC VMValue VMThread::Values_Decrement() { int a_d = AS_INTEGER(a); return INTEGER_VAL(--a_d); } -PUBLIC VMValue VMThread::Values_Negate() { +VMValue VMThread::Values_Negate() { VMValue a = Pop(); CHECK_IS_NUM(a, "negate", INTEGER_VAL(0)); @@ -2648,7 +2612,7 @@ PUBLIC VMValue VMThread::Values_Negate() { } return INTEGER_VAL(-AS_INTEGER(a)); } -PUBLIC VMValue VMThread::Values_LogicalNOT() { +VMValue VMThread::Values_LogicalNOT() { VMValue a = Pop(); // HACK: Yikes. @@ -2667,14 +2631,14 @@ PUBLIC VMValue VMThread::Values_LogicalNOT() { return INTEGER_VAL(false); } -PUBLIC VMValue VMThread::Values_BitwiseNOT() { +VMValue VMThread::Values_BitwiseNOT() { VMValue a = Pop(); if (a.Type == VAL_DECIMAL) { return DECIMAL_VAL((float)(~(int)AS_DECIMAL(a))); } return INTEGER_VAL(~AS_INTEGER(a)); } -PUBLIC VMValue VMThread::Value_TypeOf() { +VMValue VMThread::Value_TypeOf() { const char *valueType = "unknown"; VMValue value = Pop(); diff --git a/source/Engine/Bytecode/Values.cpp b/source/Engine/Bytecode/Values.cpp index 91e9b85d..8c105084 100644 --- a/source/Engine/Bytecode/Values.cpp +++ b/source/Engine/Bytecode/Values.cpp @@ -1,13 +1,3 @@ -#if INTERFACE -#include -#include -#include - -class Values { -public: -}; -#endif - #include #include @@ -15,16 +5,16 @@ class Values { #include // NOTE: This is for printing, not string conversion -PUBLIC STATIC void Values::PrintValue(VMValue value) { +void Values::PrintValue(VMValue value) { Values::PrintValue(NULL, value); } -PUBLIC STATIC void Values::PrintValue(PrintBuffer* buffer, VMValue value) { +void Values::PrintValue(PrintBuffer* buffer, VMValue value) { Values::PrintValue(buffer, value, 0, false); } -PUBLIC STATIC void Values::PrintValue(PrintBuffer* buffer, VMValue value, bool prettyPrint) { +void Values::PrintValue(PrintBuffer* buffer, VMValue value, bool prettyPrint) { Values::PrintValue(buffer, value, 0, prettyPrint); } -PUBLIC STATIC void Values::PrintValue(PrintBuffer* buffer, VMValue value, int indent, bool prettyPrint) { +void Values::PrintValue(PrintBuffer* buffer, VMValue value, int indent, bool prettyPrint) { switch (value.Type) { case VAL_NULL: buffer_printf(buffer, "null"); @@ -44,7 +34,7 @@ PUBLIC STATIC void Values::PrintValue(PrintBuffer* buffer, VMValue value, int in buffer_printf(buffer, "", value.Type); } } -PUBLIC STATIC void Values::PrintObject(PrintBuffer* buffer, VMValue value, int indent, bool prettyPrint) { +void Values::PrintObject(PrintBuffer* buffer, VMValue value, int indent, bool prettyPrint) { switch (OBJECT_TYPE(value)) { case OBJ_CLASS: buffer_printf(buffer, "", AS_CLASS(value)->Name ? AS_CLASS(value)->Name->Chars : "(null)"); diff --git a/source/Engine/Diagnostics/Clock.cpp b/source/Engine/Diagnostics/Clock.cpp index cda13327..e39a568b 100644 --- a/source/Engine/Diagnostics/Clock.cpp +++ b/source/Engine/Diagnostics/Clock.cpp @@ -1,11 +1,3 @@ -#if INTERFACE -#include - -class Clock { -public: -}; -#endif - #include #include @@ -30,7 +22,7 @@ class Clock { std::chrono::steady_clock::time_point GameStartTime; stack ClockStack; -PUBLIC STATIC void Clock::Init() { +void Clock::Init() { #ifdef USE_WIN32_CLOCK LARGE_INTEGER Win32_Frequency; @@ -52,7 +44,7 @@ PUBLIC STATIC void Clock::Init() { GameStartTime = std::chrono::steady_clock::now(); } -PUBLIC STATIC void Clock::Start() { +void Clock::Start() { #ifdef USE_WIN32_CLOCK if (Win32_PerformanceFrequencyEnabled) { Win32_ClockStack.push(Clock::GetTicks()); @@ -62,7 +54,7 @@ PUBLIC STATIC void Clock::Start() { ClockStack.push(std::chrono::steady_clock::now()); } -PUBLIC STATIC double Clock::GetTicks() { +double Clock::GetTicks() { #ifdef USE_WIN32_CLOCK if (Win32_PerformanceFrequencyEnabled) { LARGE_INTEGER ticks; @@ -76,7 +68,7 @@ PUBLIC STATIC double Clock::GetTicks() { return (std::chrono::steady_clock::now() - GameStartTime).count() / 1000000.0; } -PUBLIC STATIC double Clock::End() { +double Clock::End() { #ifdef USE_WIN32_CLOCK if (Win32_PerformanceFrequencyEnabled) { auto t1 = Win32_ClockStack.top(); @@ -91,7 +83,7 @@ PUBLIC STATIC double Clock::End() { ClockStack.pop(); return (t2 - t1).count() / 1000000.0; } -PUBLIC STATIC void Clock::Delay(double milliseconds) { +void Clock::Delay(double milliseconds) { #ifdef USE_WIN32_CLOCK if (Win32_PerformanceFrequencyEnabled) { Sleep((DWORD)milliseconds); diff --git a/source/Engine/Diagnostics/Log.cpp b/source/Engine/Diagnostics/Log.cpp index 8306c86b..f29f744b 100644 --- a/source/Engine/Diagnostics/Log.cpp +++ b/source/Engine/Diagnostics/Log.cpp @@ -1,20 +1,3 @@ -#if INTERFACE -class Log { -public: - enum LogLevels { - LOG_VERBOSE = -1, - LOG_INFO = 0, - LOG_WARN = 1, - LOG_ERROR = 2, - LOG_IMPORTANT = 3, - }; - - static int LogLevel; - static const char* LogFilename; - static bool WriteToFile; -}; -#endif - #include #include @@ -47,7 +30,7 @@ bool Log_Initialized = false; #define USING_COLOR_CODES 1 #endif -PUBLIC STATIC void Log::Init() { +void Log::Init() { if (Log_Initialized) return; @@ -84,11 +67,11 @@ PUBLIC STATIC void Log::Init() { Log_Initialized = true; } -PUBLIC STATIC void Log::SetLogLevel(int sev) { +void Log::SetLogLevel(int sev) { Log::LogLevel = sev; } -PUBLIC STATIC void Log::Print(int sev, const char* format, ...) { +void Log::Print(int sev, const char* format, ...) { #ifdef USING_COLOR_CODES int ColorCode = 0; #endif diff --git a/source/Engine/Diagnostics/Memory.cpp b/source/Engine/Diagnostics/Memory.cpp index f972733a..cd39c93e 100644 --- a/source/Engine/Diagnostics/Memory.cpp +++ b/source/Engine/Diagnostics/Memory.cpp @@ -1,32 +1,13 @@ -#if INTERFACE - -#include - -class Memory { -private: - static vector TrackedMemory; - static vector TrackedSizes; - static vector TrackedMemoryNames; -public: - static size_t MemoryUsage; - static bool IsTracking; -}; -#endif - #include #include -// #if defined(ANDROID) -// #define NOTRACK -// #endif - vector Memory::TrackedMemory; vector Memory::TrackedSizes; vector Memory::TrackedMemoryNames; size_t Memory::MemoryUsage = 0; bool Memory::IsTracking = false; -PUBLIC STATIC void Memory::Memset4(void* dst, Uint32 val, size_t dwords) { +void Memory::Memset4(void* dst, Uint32 val, size_t dwords) { #if defined(__GNUC__) && defined(i386) int u0, u1, u2; __asm__ __volatile__ ( @@ -53,7 +34,7 @@ PUBLIC STATIC void Memory::Memset4(void* dst, Uint32 val, size_t dwords) { #endif } -PUBLIC STATIC void* Memory::Malloc(size_t size) { +void* Memory::Malloc(size_t size) { void* mem = malloc(size); if (Memory::IsTracking) { if (mem) { @@ -69,7 +50,7 @@ PUBLIC STATIC void* Memory::Malloc(size_t size) { } return mem; } -PUBLIC STATIC void* Memory::Calloc(size_t count, size_t size) { +void* Memory::Calloc(size_t count, size_t size) { void* mem = calloc(count, size); if (Memory::IsTracking) { if (mem) { @@ -85,7 +66,7 @@ PUBLIC STATIC void* Memory::Calloc(size_t count, size_t size) { } return mem; } -PUBLIC STATIC void* Memory::Realloc(void* pointer, size_t size) { +void* Memory::Realloc(void* pointer, size_t size) { void* mem = realloc(pointer, size); if (Memory::IsTracking) { if (mem) { @@ -106,7 +87,7 @@ PUBLIC STATIC void* Memory::Realloc(void* pointer, size_t size) { return mem; } // Tracking functions -PUBLIC STATIC void* Memory::TrackedMalloc(const char* identifier, size_t size) { +void* Memory::TrackedMalloc(const char* identifier, size_t size) { void* mem = malloc(size); if (Memory::IsTracking) { if (mem) { @@ -125,7 +106,7 @@ PUBLIC STATIC void* Memory::TrackedMalloc(const char* identifier, size_t size) } return mem; } -PUBLIC STATIC void* Memory::TrackedCalloc(const char* identifier, size_t count, size_t size) { +void* Memory::TrackedCalloc(const char* identifier, size_t count, size_t size) { void* mem = calloc(count, size); if (Memory::IsTracking) { if (mem) { @@ -141,7 +122,7 @@ PUBLIC STATIC void* Memory::TrackedCalloc(const char* identifier, size_t count, } return mem; } -PUBLIC STATIC void Memory::Track(void* pointer, const char* identifier) { +void Memory::Track(void* pointer, const char* identifier) { if (Memory::IsTracking) { for (Uint32 i = 0; i < TrackedMemory.size(); i++) { if (TrackedMemory[i] == pointer) { @@ -151,7 +132,7 @@ PUBLIC STATIC void Memory::Track(void* pointer, const char* identifier) { } } } -PUBLIC STATIC void Memory::Track(void* pointer, size_t size, const char* identifier) { +void Memory::Track(void* pointer, size_t size, const char* identifier) { if (Memory::IsTracking) { for (Uint32 i = 0; i < TrackedMemory.size(); i++) { if (TrackedMemory[i] == pointer) { @@ -166,13 +147,13 @@ PUBLIC STATIC void Memory::Track(void* pointer, size_t size, const char* ident TrackedMemoryNames.push_back(identifier); } } -PUBLIC STATIC void Memory::TrackLast(const char* identifier) { +void Memory::TrackLast(const char* identifier) { if (Memory::IsTracking) { if (TrackedMemoryNames.size() == 0) return; TrackedMemoryNames[TrackedMemoryNames.size() - 1] = identifier; } } -PUBLIC STATIC void Memory::Free(void* pointer) { +void Memory::Free(void* pointer) { if (Memory::IsTracking) { #ifdef DEBUG for (Uint32 i = 0; i < TrackedMemory.size(); i++) { @@ -202,7 +183,7 @@ PUBLIC STATIC void Memory::Free(void* pointer) { free(pointer); } -PUBLIC STATIC void Memory::Remove(void* pointer) { +void Memory::Remove(void* pointer) { if (!pointer) return; if (Memory::IsTracking) { for (Uint32 i = 0; i < TrackedMemory.size(); i++) { @@ -219,7 +200,7 @@ PUBLIC STATIC void Memory::Remove(void* pointer) { } } -PUBLIC STATIC const char* Memory::GetName(void* pointer) { +const char* Memory::GetName(void* pointer) { if (Memory::IsTracking) { for (Uint32 i = 0; i < TrackedMemory.size(); i++) { if (TrackedMemory[i] == pointer) { @@ -230,19 +211,19 @@ PUBLIC STATIC const char* Memory::GetName(void* pointer) { return NULL; } -PUBLIC STATIC void Memory::ClearTrackedMemory() { +void Memory::ClearTrackedMemory() { TrackedMemoryNames.clear(); TrackedMemory.clear(); TrackedSizes.clear(); } -PUBLIC STATIC size_t Memory::CheckLeak() { +size_t Memory::CheckLeak() { size_t total = 0; for (Uint32 i = 0; i < TrackedMemory.size(); i++) { total += TrackedSizes[i]; } return total; } -PUBLIC STATIC void Memory::PrintLeak() { +void Memory::PrintLeak() { size_t total = 0; Log::Print(Log::LOG_VERBOSE, "Printing unfreed memory... (%u count)", TrackedMemory.size()); for (Uint32 i = 0; i < TrackedMemory.size(); i++) { diff --git a/source/Engine/Diagnostics/PerformanceMeasure.cpp b/source/Engine/Diagnostics/PerformanceMeasure.cpp index 7fb55be5..47531dd1 100644 --- a/source/Engine/Diagnostics/PerformanceMeasure.cpp +++ b/source/Engine/Diagnostics/PerformanceMeasure.cpp @@ -1,20 +1,9 @@ -#if INTERFACE -#include -#include - -class PerformanceMeasure { -public: - static bool Initialized; - static Perf_ViewRender PERF_ViewRender[MAX_SCENE_VIEWS]; -}; -#endif - #include bool PerformanceMeasure::Initialized = false; Perf_ViewRender PerformanceMeasure::PERF_ViewRender[MAX_SCENE_VIEWS]; -PUBLIC STATIC void PerformanceMeasure::Init() { +void PerformanceMeasure::Init() { if (PerformanceMeasure::Initialized) return; diff --git a/source/Engine/Diagnostics/RemoteDebug.cpp b/source/Engine/Diagnostics/RemoteDebug.cpp index 2a59b3ae..f14095d9 100644 --- a/source/Engine/Diagnostics/RemoteDebug.cpp +++ b/source/Engine/Diagnostics/RemoteDebug.cpp @@ -1,25 +1,17 @@ -#if INTERFACE -class RemoteDebug { -public: - static bool Initialized; - static bool UsingRemoteDebug; -}; -#endif - #include #include bool RemoteDebug::Initialized = false; bool RemoteDebug::UsingRemoteDebug = false; -PUBLIC STATIC void RemoteDebug::Init() { +void RemoteDebug::Init() { if (RemoteDebug::Initialized) return; RemoteDebug::Initialized = true; } -PUBLIC STATIC bool RemoteDebug::AwaitResponse() { +bool RemoteDebug::AwaitResponse() { // To be used inside a for loop while awaiting a response from the remote debugger return true; } diff --git a/source/Engine/Extensions/Discord.cpp b/source/Engine/Extensions/Discord.cpp index 1c79c302..65673a05 100644 --- a/source/Engine/Extensions/Discord.cpp +++ b/source/Engine/Extensions/Discord.cpp @@ -1,20 +1,7 @@ -#if INTERFACE - -#include - -class Discord { -public: - static bool Initialized; -}; -#endif - #include #include #ifdef WIN32 -// #pragma pack(push, 8) -// #include -// #pragma pack(pop) #include @@ -30,21 +17,10 @@ void (*_Discord_Shutdown)(void) = NULL; bool Discord::Initialized = false; -// struct DiscordUser { -// char* username; -// char* discriminator; -// char* userId; -// }; -// void Discord_Ready(const DiscordUser* connectedUser) { Discord::Initialized = true; } -// void Discord_Disconnected(int errcode, const char* message) { } -// void Discord_Error(int errcode, const char* message) { } -// void Discord_Spectate(const char* secret) { } - -// Discord::Init("623985235150766081", ""); - -PUBLIC STATIC void Discord::Init(const char* application_id, const char* steam_id) { - #ifdef HAS_DISCORD_RPC +void Discord::Init(const char* application_id, const char* steam_id) { + Discord::Initialized = false; +#ifdef HAS_DISCORD_RPC library = SDL_LoadObject("discord-rpc.dll"); if (!library) return; @@ -57,78 +33,51 @@ PUBLIC STATIC void Discord::Init(const char* application_id, const char* steam_i DiscordEventHandlers handlers; memset(&handlers, 0, sizeof(handlers)); - // handlers.ready = Discord_Ready; - // handlers.errored = Discord_Error; - // handlers.disconnected = Discord_Disconnected; - _Discord_Initialize(application_id, &handlers, 1, steam_id); - // struct Application { - // struct IDiscordCore* core; - // struct IDiscordUsers* users; - // }; - // - // struct Application app; - // // Don't forget to memset or otherwise initialize your classes! - // memset(&app, 0, sizeof(app)); - // - // struct IDiscordCoreEvents events; - // memset(&events, 0, sizeof(events)); - // - // struct DiscordCreateParams params; - // params.client_id = 379010971139702784; - // params.flags = DiscordCreateFlags_Default; - // params.events = &events; - // params.event_data = &app; - // - // DiscordCreate(DISCORD_VERSION, ¶ms, &app.core); Discord::Initialized = true; Discord::UpdatePresence(NULL); - return; - #endif - - Discord::Initialized = false; +#endif } -PUBLIC STATIC void Discord::UpdatePresence(char* details) { +void Discord::UpdatePresence(char* details) { Discord::UpdatePresence(details, NULL); } -PUBLIC STATIC void Discord::UpdatePresence(char* details, char* state) { +void Discord::UpdatePresence(char* details, char* state) { Discord::UpdatePresence(details, state, NULL); } -PUBLIC STATIC void Discord::UpdatePresence(char* details, char* state, char* image_key) { +void Discord::UpdatePresence(char* details, char* state, char* image_key) { Discord::UpdatePresence(details, state, image_key, 0, 0); } -PUBLIC STATIC void Discord::UpdatePresence(char* details, char* state, char* image_key, time_t start_time) { +void Discord::UpdatePresence(char* details, char* state, char* image_key, time_t start_time) { Discord::UpdatePresence(details, state, image_key, 0, 0, start_time); } -PUBLIC STATIC void Discord::UpdatePresence(char* details, char* state, char* image_key, int party_size, int party_max) { +void Discord::UpdatePresence(char* details, char* state, char* image_key, int party_size, int party_max) { Discord::UpdatePresence(details, state, image_key, party_size, party_max, 0); } -PUBLIC STATIC void Discord::UpdatePresence(char* details, char* state, char* image_key, int party_size, int party_max, time_t start_time) { +void Discord::UpdatePresence(char* details, char* state, char* image_key, int party_size, int party_max, time_t start_time) { if (!Discord::Initialized) return; - #ifdef HAS_DISCORD_RPC +#ifdef HAS_DISCORD_RPC DiscordRichPresence discordPresence; memset(&discordPresence, 0, sizeof(discordPresence)); discordPresence.details = details; discordPresence.state = state; discordPresence.largeImageKey = image_key; - //discordPresence.partyId = 0; discordPresence.partySize = party_size; discordPresence.partyMax = party_max; discordPresence.startTimestamp = start_time; discordPresence.instance = 1; _Discord_UpdatePresence(&discordPresence); - #endif +#endif } -PUBLIC STATIC void Discord::Dispose() { +void Discord::Dispose() { if (!Discord::Initialized) return; - #ifdef HAS_DISCORD_RPC +#ifdef HAS_DISCORD_RPC _Discord_Shutdown(); SDL_UnloadObject(library); - #endif +#endif } diff --git a/source/Engine/Filesystem/Directory.cpp b/source/Engine/Filesystem/Directory.cpp index ac0bd65e..ea3bb8ce 100644 --- a/source/Engine/Filesystem/Directory.cpp +++ b/source/Engine/Filesystem/Directory.cpp @@ -1,12 +1,3 @@ -#if INTERFACE - -#include - -class Directory { -private: -}; -#endif - #include #include @@ -25,7 +16,7 @@ bool CompareFunction(char* i, char* j) { return strcmp(i, j) < 0; } -PUBLIC STATIC bool Directory::Exists(const char* path) { +bool Directory::Exists(const char* path) { #if WIN32 DWORD ftyp = GetFileAttributesA(path); if (ftyp == INVALID_FILE_ATTRIBUTES) return false; // Something is wrong with your path @@ -39,7 +30,7 @@ PUBLIC STATIC bool Directory::Exists(const char* path) { #endif return false; } -PUBLIC STATIC bool Directory::Create(const char* path) { +bool Directory::Create(const char* path) { #if WIN32 return CreateDirectoryA(path, NULL); #else @@ -47,7 +38,7 @@ PUBLIC STATIC bool Directory::Create(const char* path) { #endif } -PUBLIC STATIC bool Directory::GetCurrentWorkingDirectory(char* out, size_t sz) { +bool Directory::GetCurrentWorkingDirectory(char* out, size_t sz) { #if WIN32 return _getcwd(out, sz) != NULL; #else @@ -55,7 +46,7 @@ PUBLIC STATIC bool Directory::GetCurrentWorkingDirectory(char* out, siz #endif } -PUBLIC STATIC void Directory::GetFiles(vector* files, const char* path, const char* searchPattern, bool allDirs) { +void Directory::GetFiles(vector* files, const char* path, const char* searchPattern, bool allDirs) { #if WIN32 char winPath[MAX_PATH_SIZE]; snprintf(winPath, MAX_PATH_SIZE, "%s%s*", path, path[strlen(path) - 1] == '/' ? "" : "/"); @@ -126,13 +117,13 @@ PUBLIC STATIC void Directory::GetFiles(vector* files, const char std::sort(files->begin(), files->end(), CompareFunction); #endif } -PUBLIC STATIC vector Directory::GetFiles(const char* path, const char* searchPattern, bool allDirs) { +vector Directory::GetFiles(const char* path, const char* searchPattern, bool allDirs) { vector files; Directory::GetFiles(&files, path, searchPattern, allDirs); return files; } -PUBLIC STATIC void Directory::GetDirectories(vector* files, const char* path, const char* searchPattern, bool allDirs) { +void Directory::GetDirectories(vector* files, const char* path, const char* searchPattern, bool allDirs) { #if WIN32 char winPath[MAX_PATH_SIZE]; snprintf(winPath, MAX_PATH_SIZE, "%s%s*", path, path[strlen(path) - 1] == '/' ? "" : "/"); @@ -200,7 +191,7 @@ PUBLIC STATIC void Directory::GetDirectories(vector* files, cons } #endif } -PUBLIC STATIC vector Directory::GetDirectories(const char* path, const char* searchPattern, bool allDirs) { +vector Directory::GetDirectories(const char* path, const char* searchPattern, bool allDirs) { vector files; Directory::GetDirectories(&files, path, searchPattern, allDirs); return files; diff --git a/source/Engine/Filesystem/File.cpp b/source/Engine/Filesystem/File.cpp index 8b379c13..7e2b108e 100644 --- a/source/Engine/Filesystem/File.cpp +++ b/source/Engine/Filesystem/File.cpp @@ -1,12 +1,3 @@ -#if INTERFACE - -#include - -class File { -private: -}; -#endif - #include #include @@ -22,7 +13,7 @@ class File { #include #endif -PUBLIC STATIC bool File::Exists(const char* path) { +bool File::Exists(const char* path) { #if WIN32 return _access(path, 0) != -1; #elif MACOSX @@ -60,7 +51,7 @@ PUBLIC STATIC bool File::Exists(const char* path) { #endif } -PUBLIC STATIC size_t File::ReadAllBytes(const char* path, char** out) { +size_t File::ReadAllBytes(const char* path, char** out) { FileStream* stream; if ((stream = FileStream::New(path, FileStream::READ_ACCESS))) { size_t size = stream->Length(); @@ -75,7 +66,7 @@ PUBLIC STATIC size_t File::ReadAllBytes(const char* path, char** out) { return 0; } -PUBLIC STATIC bool File::WriteAllBytes(const char* path, const char* bytes, size_t len) { +bool File::WriteAllBytes(const char* path, const char* bytes, size_t len) { if (!path) return false; if (!*path) return false; if (!bytes) return false; diff --git a/source/Engine/FontFace.cpp b/source/Engine/FontFace.cpp index f3681d7b..0ef905c0 100644 --- a/source/Engine/FontFace.cpp +++ b/source/Engine/FontFace.cpp @@ -1,17 +1,3 @@ -#if INTERFACE -#include -#include -#include - -#include -#include - -class FontFace { -public: - -}; -#endif - #include #include #include @@ -149,7 +135,7 @@ FT_Package* PackBoxes(FT_GlyphBox* boxes, int boxCount, int defWidth, int de return package; } -PUBLIC STATIC ISprite* FontFace::SpriteFromFont(Stream* stream, int pixelSize, char* filename) { +ISprite* FontFace::SpriteFromFont(Stream* stream, int pixelSize, char* filename) { #ifdef USING_FREETYPE if (!ftInitialized) { diff --git a/source/Engine/Graphics.cpp b/source/Engine/Graphics.cpp index eb520063..a7e3ae9c 100644 --- a/source/Engine/Graphics.cpp +++ b/source/Engine/Graphics.cpp @@ -1,101 +1,3 @@ -#if INTERFACE -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -need_t ISprite; -need_t IModel; - -class Graphics { -public: - static HashMap* TextureMap; - static map SpriteSheetTextureMap; - static bool VsyncEnabled; - static int MultisamplingEnabled; - static int FontDPI; - static bool SupportsBatching; - static bool TextureBlend; - static bool TextureInterpolate; - static Uint32 PreferredPixelFormat; - - static Uint32 MaxTextureWidth; - static Uint32 MaxTextureHeight; - static Texture* TextureHead; - - static vector VertexBuffers; - static Scene3D Scene3Ds[MAX_3D_SCENES]; - - static stack StateStack; - static stack MatrixStack; - - static Matrix4x4* ModelViewMatrix; - - static Viewport CurrentViewport; - static Viewport BackupViewport; - static ClipArea CurrentClip; - static ClipArea BackupClip; - - static View* CurrentView; - - static float BlendColors[4]; - static float TintColors[4]; - - static int BlendMode; - static int TintMode; - - static int StencilTest; - static int StencilOpPass; - static int StencilOpFail; - - static void* FramebufferPixels; - static size_t FramebufferSize; - - static Uint32 PaletteColors[MAX_PALETTE_COUNT][0x100]; - static Uint8 PaletteIndexLines[MAX_FRAMEBUFFER_HEIGHT]; - static bool PaletteUpdated; - - static Texture* PaletteTexture; - - static Texture* CurrentRenderTarget; - static Sint32 CurrentScene3D; - static Sint32 CurrentVertexBuffer; - - static void* CurrentShader; - static bool SmoothFill; - static bool SmoothStroke; - - static float PixelOffset; - static bool NoInternalTextures; - static bool UsePalettes; - static bool UsePaletteIndexLines; - static bool UseTinting; - static bool UseDepthTesting; - static bool UseSoftwareRenderer; - - static unsigned CurrentFrame; - - // Rendering functions - static GraphicsFunctions Internal; - static GraphicsFunctions* GfxFunctions; - static const char* Renderer; -}; -#endif - #include #include @@ -182,7 +84,7 @@ GraphicsFunctions Graphics::Internal; GraphicsFunctions* Graphics::GfxFunctions = &Graphics::Internal; const char* Graphics::Renderer = "default"; -PUBLIC STATIC void Graphics::Init() { +void Graphics::Init() { Graphics::TextureMap = new HashMap(NULL, 32); Graphics::ModelViewMatrix = Matrix4x4::Create(); @@ -214,7 +116,7 @@ PUBLIC STATIC void Graphics::Init() { Log::Print(Log::LOG_VERBOSE, "Multisample: false"); Log::Print(Log::LOG_VERBOSE, "Max Texture Size: %d x %d", Graphics::MaxTextureWidth, Graphics::MaxTextureHeight); } -PUBLIC STATIC void Graphics::ChooseBackend() { +void Graphics::ChooseBackend() { char renderer[64]; SoftwareRenderer::SetGraphicsFunctions(); @@ -271,13 +173,13 @@ PUBLIC STATIC void Graphics::ChooseBackend() { SDL2Renderer::SetGraphicsFunctions(); } } -PUBLIC STATIC Uint32 Graphics::GetWindowFlags() { +Uint32 Graphics::GetWindowFlags() { return Graphics::GfxFunctions->GetWindowFlags(); } -PUBLIC STATIC void Graphics::SetVSync(bool enabled) { +void Graphics::SetVSync(bool enabled) { Graphics::GfxFunctions->SetVSync(enabled); } -PUBLIC STATIC void Graphics::Reset() { +void Graphics::Reset() { Graphics::UseSoftwareRenderer = false; Graphics::UsePalettes = false; Graphics::UsePaletteIndexLines = false; @@ -307,7 +209,7 @@ PUBLIC STATIC void Graphics::Reset() { Graphics::StencilOpPass = StencilOp_Keep; Graphics::StencilOpFail = StencilOp_Keep; } -PUBLIC STATIC void Graphics::Dispose() { +void Graphics::Dispose() { for (Uint32 i = 0; i < Graphics::VertexBuffers.size(); i++) Graphics::DeleteVertexBuffer(i); Graphics::VertexBuffers.clear(); @@ -336,7 +238,7 @@ PUBLIC STATIC void Graphics::Dispose() { Memory::Free(Graphics::FramebufferPixels); } -PUBLIC STATIC Point Graphics::ProjectToScreen(float x, float y, float z) { +Point Graphics::ProjectToScreen(float x, float y, float z) { Point p; float vec4[4]; Matrix4x4* matrix; @@ -352,7 +254,7 @@ PUBLIC STATIC Point Graphics::ProjectToScreen(float x, float y, float z) { return p; } -PUBLIC STATIC Texture* Graphics::CreateTexture(Uint32 format, Uint32 access, Uint32 width, Uint32 height) { +Texture* Graphics::CreateTexture(Uint32 format, Uint32 access, Uint32 width, Uint32 height) { Texture* texture; if (Graphics::GfxFunctions == &SoftwareRenderer::BackendFunctions || Graphics::NoInternalTextures) { @@ -374,33 +276,33 @@ PUBLIC STATIC Texture* Graphics::CreateTexture(Uint32 format, Uint32 access, Uin return texture; } -PUBLIC STATIC Texture* Graphics::CreateTextureFromPixels(Uint32 width, Uint32 height, void* pixels, int pitch) { +Texture* Graphics::CreateTextureFromPixels(Uint32 width, Uint32 height, void* pixels, int pitch) { Texture* texture = Graphics::CreateTexture(SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STATIC, width, height); if (texture) Graphics::UpdateTexture(texture, NULL, pixels, pitch); return texture; } -PUBLIC STATIC Texture* Graphics::CreateTextureFromSurface(SDL_Surface* surface) { +Texture* Graphics::CreateTextureFromSurface(SDL_Surface* surface) { Texture* texture = Graphics::CreateTexture(surface->format->format, SDL_TEXTUREACCESS_STATIC, surface->w, surface->h); if (texture) Graphics::GfxFunctions->UpdateTexture(texture, NULL, surface->pixels, surface->pitch); return texture; } -PUBLIC STATIC int Graphics::LockTexture(Texture* texture, void** pixels, int* pitch) { +int Graphics::LockTexture(Texture* texture, void** pixels, int* pitch) { if (Graphics::GfxFunctions == &SoftwareRenderer::BackendFunctions || Graphics::NoInternalTextures) return 1; return Graphics::GfxFunctions->LockTexture(texture, pixels, pitch); } -PUBLIC STATIC int Graphics::UpdateTexture(Texture* texture, SDL_Rect* src, void* pixels, int pitch) { +int Graphics::UpdateTexture(Texture* texture, SDL_Rect* src, void* pixels, int pitch) { memcpy(texture->Pixels, pixels, sizeof(Uint32) * texture->Width * texture->Height); if (Graphics::GfxFunctions == &SoftwareRenderer::BackendFunctions || Graphics::NoInternalTextures) return 1; return Graphics::GfxFunctions->UpdateTexture(texture, src, pixels, pitch); } -PUBLIC STATIC int Graphics::UpdateYUVTexture(Texture* texture, SDL_Rect* src, Uint8* pixelsY, int pitchY, Uint8* pixelsU, int pitchU, Uint8* pixelsV, int pitchV) { +int Graphics::UpdateYUVTexture(Texture* texture, SDL_Rect* src, Uint8* pixelsY, int pitchY, Uint8* pixelsU, int pitchU, Uint8* pixelsV, int pitchV) { if (!Graphics::GfxFunctions->UpdateYUVTexture) return 0; if (Graphics::GfxFunctions == &SoftwareRenderer::BackendFunctions || @@ -408,21 +310,21 @@ PUBLIC STATIC int Graphics::UpdateYUVTexture(Texture* texture, SDL_Rect* sr return 1; return Graphics::GfxFunctions->UpdateYUVTexture(texture, src, pixelsY, pitchY, pixelsU, pitchU, pixelsV, pitchV); } -PUBLIC STATIC int Graphics::SetTexturePalette(Texture* texture, void* palette, unsigned numPaletteColors) { +int Graphics::SetTexturePalette(Texture* texture, void* palette, unsigned numPaletteColors) { texture->SetPalette((Uint32*)palette, numPaletteColors); if (Graphics::GfxFunctions == &SoftwareRenderer::BackendFunctions || !Graphics::GfxFunctions->SetTexturePalette || Graphics::NoInternalTextures) return 1; return Graphics::GfxFunctions->SetTexturePalette(texture, palette, numPaletteColors); } -PUBLIC STATIC int Graphics::ConvertTextureToRGBA(Texture* texture) { +int Graphics::ConvertTextureToRGBA(Texture* texture) { texture->ConvertToRGBA(); if (Graphics::GfxFunctions == &SoftwareRenderer::BackendFunctions || Graphics::NoInternalTextures) return 1; return Graphics::GfxFunctions->UpdateTexture(texture, NULL, texture->Pixels, texture->Pitch); } -PUBLIC STATIC int Graphics::ConvertTextureToPalette(Texture* texture, unsigned paletteNumber) { +int Graphics::ConvertTextureToPalette(Texture* texture, unsigned paletteNumber) { Uint32* colors = (Uint32*)Memory::TrackedMalloc("Texture::Colors", 256 * sizeof(Uint32)); if (!colors) return 0; @@ -445,10 +347,10 @@ PUBLIC STATIC int Graphics::ConvertTextureToPalette(Texture* texture, unsig return ok; } -PUBLIC STATIC void Graphics::UnlockTexture(Texture* texture) { +void Graphics::UnlockTexture(Texture* texture) { Graphics::GfxFunctions->UnlockTexture(texture); } -PUBLIC STATIC void Graphics::DisposeTexture(Texture* texture) { +void Graphics::DisposeTexture(Texture* texture) { Graphics::GfxFunctions->DisposeTexture(texture); if (texture->Next) @@ -463,7 +365,7 @@ PUBLIC STATIC void Graphics::DisposeTexture(Texture* texture) { Memory::Free(texture); } -PUBLIC STATIC TextureReference* Graphics::GetSpriteSheet(string sheetPath) { +TextureReference* Graphics::GetSpriteSheet(string sheetPath) { if (Graphics::SpriteSheetTextureMap.count(sheetPath) != 0) { TextureReference* textureRef = Graphics::SpriteSheetTextureMap.at(sheetPath); textureRef->AddRef(); @@ -472,7 +374,7 @@ PUBLIC STATIC TextureReference* Graphics::GetSpriteSheet(string sheetPath) { return nullptr; } -PUBLIC STATIC TextureReference* Graphics::AddSpriteSheet(string sheetPath, Texture* texture) { +TextureReference* Graphics::AddSpriteSheet(string sheetPath, Texture* texture) { TextureReference *ref = Graphics::GetSpriteSheet(sheetPath); if (ref == nullptr) { ref = new TextureReference(texture); @@ -480,7 +382,7 @@ PUBLIC STATIC TextureReference* Graphics::AddSpriteSheet(string sheetPath, Textu } return ref; } -PUBLIC STATIC void Graphics::DisposeSpriteSheet(string sheetPath) { +void Graphics::DisposeSpriteSheet(string sheetPath) { if (Graphics::SpriteSheetTextureMap.count(sheetPath) != 0) { TextureReference* textureRef = Graphics::SpriteSheetTextureMap.at(sheetPath); if (textureRef->TakeRef()) { @@ -490,7 +392,7 @@ PUBLIC STATIC void Graphics::DisposeSpriteSheet(string sheetPath) { } } } -PUBLIC STATIC void Graphics::DeleteSpriteSheetMap() { +void Graphics::DeleteSpriteSheetMap() { for (std::map::iterator it = Graphics::SpriteSheetTextureMap.begin(); it != Graphics::SpriteSheetTextureMap.end(); it++) @@ -502,7 +404,7 @@ PUBLIC STATIC void Graphics::DeleteSpriteSheetMap() { Graphics::SpriteSheetTextureMap.clear(); } -PUBLIC STATIC Uint32 Graphics::CreateVertexBuffer(Uint32 maxVertices, int unloadPolicy) { +Uint32 Graphics::CreateVertexBuffer(Uint32 maxVertices, int unloadPolicy) { Uint32 idx = 0xFFFFFFFF; for (Uint32 i = 0; i < Graphics::VertexBuffers.size(); i++) { @@ -532,7 +434,7 @@ PUBLIC STATIC Uint32 Graphics::CreateVertexBuffer(Uint32 maxVertices, int unlo return idx; } -PUBLIC STATIC void Graphics::DeleteVertexBuffer(Uint32 vertexBufferIndex) { +void Graphics::DeleteVertexBuffer(Uint32 vertexBufferIndex) { if (vertexBufferIndex < 0 || vertexBufferIndex >= Graphics::VertexBuffers.size()) return; if (!Graphics::VertexBuffers[vertexBufferIndex]) @@ -545,33 +447,33 @@ PUBLIC STATIC void Graphics::DeleteVertexBuffer(Uint32 vertexBufferIndex) { Graphics::VertexBuffers[vertexBufferIndex] = NULL; } -PUBLIC STATIC void Graphics::UseShader(void* shader) { +void Graphics::UseShader(void* shader) { Graphics::CurrentShader = shader; Graphics::GfxFunctions->UseShader(shader); } -PUBLIC STATIC void Graphics::SetTextureInterpolation(bool interpolate) { +void Graphics::SetTextureInterpolation(bool interpolate) { Graphics::TextureInterpolate = interpolate; } -PUBLIC STATIC void Graphics::Clear() { +void Graphics::Clear() { Graphics::GfxFunctions->Clear(); } -PUBLIC STATIC void Graphics::Present() { +void Graphics::Present() { Graphics::GfxFunctions->Present(); Graphics::CurrentFrame++; } -PUBLIC STATIC void Graphics::SoftwareStart() { +void Graphics::SoftwareStart() { Graphics::GfxFunctions = &SoftwareRenderer::BackendFunctions; SoftwareRenderer::RenderStart(); } -PUBLIC STATIC void Graphics::SoftwareEnd() { +void Graphics::SoftwareEnd() { SoftwareRenderer::RenderEnd(); Graphics::GfxFunctions = &Graphics::Internal; Graphics::UpdateTexture(Graphics::CurrentRenderTarget, NULL, Graphics::CurrentRenderTarget->Pixels, Graphics::CurrentRenderTarget->Width * 4); } -PUBLIC STATIC void Graphics::UpdateGlobalPalette() { +void Graphics::UpdateGlobalPalette() { if (!Graphics::GfxFunctions->UpdateGlobalPalette) return; @@ -588,7 +490,7 @@ PUBLIC STATIC void Graphics::UpdateGlobalPalette() { Graphics::GfxFunctions->UpdateGlobalPalette(); } -PUBLIC STATIC void Graphics::UnloadSceneData() { +void Graphics::UnloadSceneData() { for (Uint32 i = 0; i < Graphics::VertexBuffers.size(); i++) { VertexBuffer* buffer = Graphics::VertexBuffers[i]; if (!buffer || buffer->UnloadPolicy > SCOPE_SCENE) @@ -606,7 +508,7 @@ PUBLIC STATIC void Graphics::UnloadSceneData() { } } -PUBLIC STATIC void Graphics::SetRenderTarget(Texture* texture) { +void Graphics::SetRenderTarget(Texture* texture) { if (texture && !Graphics::CurrentRenderTarget) { Graphics::BackupViewport = Graphics::CurrentViewport; Graphics::BackupClip = Graphics::CurrentClip; @@ -631,7 +533,7 @@ PUBLIC STATIC void Graphics::SetRenderTarget(Texture* texture) { Graphics::GfxFunctions->UpdateViewport(); Graphics::GfxFunctions->UpdateClipRect(); } -PUBLIC STATIC void Graphics::CopyScreen(int source_x, int source_y, int source_w, int source_h, int dest_x, int dest_y, int dest_w, int dest_h, Texture* texture) { +void Graphics::CopyScreen(int source_x, int source_y, int source_w, int source_h, int dest_x, int dest_y, int dest_w, int dest_h, Texture* texture) { if (!Graphics::GfxFunctions->ReadFramebuffer) return; @@ -669,22 +571,22 @@ PUBLIC STATIC void Graphics::CopyScreen(int source_x, int source_y, int sour } } } -PUBLIC STATIC void Graphics::UpdateOrtho(float width, float height) { +void Graphics::UpdateOrtho(float width, float height) { Graphics::GfxFunctions->UpdateOrtho(0.0f, 0.0f, width, height); } -PUBLIC STATIC void Graphics::UpdateOrthoFlipped(float width, float height) { +void Graphics::UpdateOrthoFlipped(float width, float height) { Graphics::GfxFunctions->UpdateOrtho(0.0f, height, width, 0.0f); } -PUBLIC STATIC void Graphics::UpdatePerspective(float fovy, float aspect, float nearv, float farv) { +void Graphics::UpdatePerspective(float fovy, float aspect, float nearv, float farv) { Graphics::GfxFunctions->UpdatePerspective(fovy, aspect, nearv, farv); } -PUBLIC STATIC void Graphics::UpdateProjectionMatrix() { +void Graphics::UpdateProjectionMatrix() { Graphics::GfxFunctions->UpdateProjectionMatrix(); } -PUBLIC STATIC void Graphics::MakePerspectiveMatrix(Matrix4x4* out, float fov, float near, float far, float aspect) { +void Graphics::MakePerspectiveMatrix(Matrix4x4* out, float fov, float near, float far, float aspect) { Graphics::GfxFunctions->MakePerspectiveMatrix(out, fov, near, far, aspect); } -PUBLIC STATIC void Graphics::CalculateMVPMatrix(Matrix4x4* output, Matrix4x4* modelMatrix, Matrix4x4* viewMatrix, Matrix4x4* projMatrix) { +void Graphics::CalculateMVPMatrix(Matrix4x4* output, Matrix4x4* modelMatrix, Matrix4x4* viewMatrix, Matrix4x4* projMatrix) { if (viewMatrix && projMatrix) { Matrix4x4 modelView; @@ -700,7 +602,7 @@ PUBLIC STATIC void Graphics::CalculateMVPMatrix(Matrix4x4* output, Matrix4x4 else Matrix4x4::Identity(output); } -PUBLIC STATIC void Graphics::SetViewport(float x, float y, float w, float h) { +void Graphics::SetViewport(float x, float y, float w, float h) { Viewport* vp = &Graphics::CurrentViewport; if (x < 0) { vp->X = 0.0; @@ -724,14 +626,14 @@ PUBLIC STATIC void Graphics::SetViewport(float x, float y, float w, float h) } Graphics::GfxFunctions->UpdateViewport(); } -PUBLIC STATIC void Graphics::ResetViewport() { +void Graphics::ResetViewport() { Graphics::SetViewport(-1.0, 0.0, 0.0, 0.0); } -PUBLIC STATIC void Graphics::Resize(int width, int height) { +void Graphics::Resize(int width, int height) { Graphics::GfxFunctions->UpdateWindowSize(width, height); } -PUBLIC STATIC void Graphics::SetClip(int x, int y, int width, int height) { +void Graphics::SetClip(int x, int y, int width, int height) { Graphics::CurrentClip.Enabled = true; Graphics::CurrentClip.X = x; Graphics::CurrentClip.Y = y; @@ -739,12 +641,12 @@ PUBLIC STATIC void Graphics::SetClip(int x, int y, int width, int height) { Graphics::CurrentClip.Height = height; Graphics::GfxFunctions->UpdateClipRect(); } -PUBLIC STATIC void Graphics::ClearClip() { +void Graphics::ClearClip() { Graphics::CurrentClip.Enabled = false; Graphics::GfxFunctions->UpdateClipRect(); } -PUBLIC STATIC void Graphics::Save() { +void Graphics::Save() { Matrix4x4* top = MatrixStack.top(); Matrix4x4* push = Matrix4x4::Create(); Matrix4x4::Copy(push, top); @@ -757,18 +659,18 @@ PUBLIC STATIC void Graphics::Save() { MatrixStack.push(push); ModelViewMatrix = push; } -PUBLIC STATIC void Graphics::Translate(float x, float y, float z) { +void Graphics::Translate(float x, float y, float z) { Matrix4x4::Translate(ModelViewMatrix, ModelViewMatrix, x, y, z); } -PUBLIC STATIC void Graphics::Rotate(float x, float y, float z) { +void Graphics::Rotate(float x, float y, float z) { Matrix4x4::Rotate(ModelViewMatrix, ModelViewMatrix, x, 1.0, 0.0, 0.0); Matrix4x4::Rotate(ModelViewMatrix, ModelViewMatrix, y, 0.0, 1.0, 0.0); Matrix4x4::Rotate(ModelViewMatrix, ModelViewMatrix, z, 0.0, 0.0, 1.0); } -PUBLIC STATIC void Graphics::Scale(float x, float y, float z) { +void Graphics::Scale(float x, float y, float z) { Matrix4x4::Scale(ModelViewMatrix, ModelViewMatrix, x, y, z); } -PUBLIC STATIC void Graphics::Restore() { +void Graphics::Restore() { if (MatrixStack.size() == 1) return; delete MatrixStack.top(); @@ -777,7 +679,7 @@ PUBLIC STATIC void Graphics::Restore() { ModelViewMatrix = MatrixStack.top(); } -PUBLIC STATIC BlendState Graphics::GetBlendState() { +BlendState Graphics::GetBlendState() { BlendState state; state.Opacity = (int)(Graphics::BlendColors[3] * 0xFF); state.Mode = Graphics::BlendMode; @@ -789,7 +691,7 @@ PUBLIC STATIC BlendState Graphics::GetBlendState() { return state; } -PUBLIC STATIC void Graphics::PushState() { +void Graphics::PushState() { if (StateStack.size() == 256) { Log::Print(Log::LOG_ERROR, "Graphics::PushState stack too big!"); exit(-1); @@ -814,7 +716,7 @@ PUBLIC STATIC void Graphics::PushState() { Graphics::Save(); } -PUBLIC STATIC void Graphics::PopState() { +void Graphics::PopState() { if (StateStack.size() == 0) return; GraphicsState state = StateStack.top(); @@ -843,14 +745,14 @@ PUBLIC STATIC void Graphics::PopState() { Graphics::Restore(); } -PUBLIC STATIC void Graphics::SetBlendColor(float r, float g, float b, float a) { +void Graphics::SetBlendColor(float r, float g, float b, float a) { Graphics::BlendColors[0] = Math::Clamp(r, 0.0f, 1.0f); Graphics::BlendColors[1] = Math::Clamp(g, 0.0f, 1.0f); Graphics::BlendColors[2] = Math::Clamp(b, 0.0f, 1.0f); Graphics::BlendColors[3] = Math::Clamp(a, 0.0f, 1.0f); Graphics::GfxFunctions->SetBlendColor(r, g, b, a); } -PUBLIC STATIC void Graphics::SetBlendMode(int blendMode) { +void Graphics::SetBlendMode(int blendMode) { Graphics::BlendMode = blendMode; switch (blendMode) { case BlendMode_NORMAL: @@ -879,75 +781,75 @@ PUBLIC STATIC void Graphics::SetBlendMode(int blendMode) { BlendFactor_SRC_ALPHA, BlendFactor_INV_SRC_ALPHA); } } -PUBLIC STATIC void Graphics::SetBlendMode(int srcC, int dstC, int srcA, int dstA) { +void Graphics::SetBlendMode(int srcC, int dstC, int srcA, int dstA) { Graphics::GfxFunctions->SetBlendMode(srcC, dstC, srcA, dstA); } -PUBLIC STATIC void Graphics::SetTintColor(float r, float g, float b, float a) { +void Graphics::SetTintColor(float r, float g, float b, float a) { Graphics::TintColors[0] = Math::Clamp(r, 0.0f, 1.0f); Graphics::TintColors[1] = Math::Clamp(g, 0.0f, 1.0f); Graphics::TintColors[2] = Math::Clamp(b, 0.0f, 1.0f); Graphics::TintColors[3] = Math::Clamp(a, 0.0f, 1.0f); Graphics::GfxFunctions->SetTintColor(r, g, b, a); } -PUBLIC STATIC void Graphics::SetTintMode(int mode) { +void Graphics::SetTintMode(int mode) { Graphics::TintMode = mode; Graphics::GfxFunctions->SetTintMode(mode); } -PUBLIC STATIC void Graphics::SetTintEnabled(bool enabled) { +void Graphics::SetTintEnabled(bool enabled) { Graphics::UseTinting = enabled; Graphics::GfxFunctions->SetTintEnabled(enabled); } -PUBLIC STATIC void Graphics::SetLineWidth(float n) { +void Graphics::SetLineWidth(float n) { Graphics::GfxFunctions->SetLineWidth(n); } -PUBLIC STATIC void Graphics::StrokeLine(float x1, float y1, float x2, float y2) { +void Graphics::StrokeLine(float x1, float y1, float x2, float y2) { Graphics::GfxFunctions->StrokeLine(x1, y1, x2, y2); } -PUBLIC STATIC void Graphics::StrokeCircle(float x, float y, float rad, float thickness) { +void Graphics::StrokeCircle(float x, float y, float rad, float thickness) { Graphics::GfxFunctions->StrokeCircle(x, y, rad, thickness); } -PUBLIC STATIC void Graphics::StrokeEllipse(float x, float y, float w, float h) { +void Graphics::StrokeEllipse(float x, float y, float w, float h) { Graphics::GfxFunctions->StrokeEllipse(x, y, w, h); } -PUBLIC STATIC void Graphics::StrokeTriangle(float x1, float y1, float x2, float y2, float x3, float y3) { +void Graphics::StrokeTriangle(float x1, float y1, float x2, float y2, float x3, float y3) { Graphics::GfxFunctions->StrokeLine(x1, y1, x2, y2); Graphics::GfxFunctions->StrokeLine(x2, y2, x3, y3); Graphics::GfxFunctions->StrokeLine(x3, y3, x1, y1); } -PUBLIC STATIC void Graphics::StrokeRectangle(float x, float y, float w, float h) { +void Graphics::StrokeRectangle(float x, float y, float w, float h) { Graphics::GfxFunctions->StrokeRectangle(x, y, w, h); } -PUBLIC STATIC void Graphics::FillCircle(float x, float y, float rad) { +void Graphics::FillCircle(float x, float y, float rad) { Graphics::GfxFunctions->FillCircle(x, y, rad); } -PUBLIC STATIC void Graphics::FillEllipse(float x, float y, float w, float h) { +void Graphics::FillEllipse(float x, float y, float w, float h) { Graphics::GfxFunctions->FillEllipse(x, y, w, h); } -PUBLIC STATIC void Graphics::FillTriangle(float x1, float y1, float x2, float y2, float x3, float y3) { +void Graphics::FillTriangle(float x1, float y1, float x2, float y2, float x3, float y3) { Graphics::GfxFunctions->FillTriangle(x1, y1, x2, y2, x3, y3); } -PUBLIC STATIC void Graphics::FillRectangle(float x, float y, float w, float h) { +void Graphics::FillRectangle(float x, float y, float w, float h) { Graphics::GfxFunctions->FillRectangle(x, y, w, h); } -PUBLIC STATIC void Graphics::DrawTexture(Texture* texture, float sx, float sy, float sw, float sh, float x, float y, float w, float h) { +void Graphics::DrawTexture(Texture* texture, float sx, float sy, float sw, float sh, float x, float y, float w, float h) { Graphics::GfxFunctions->DrawTexture(texture, sx, sy, sw, sh, x, y, w, h); } -PUBLIC STATIC void Graphics::DrawSprite(ISprite* sprite, int animation, int frame, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID) { +void Graphics::DrawSprite(ISprite* sprite, int animation, int frame, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID) { Graphics::GfxFunctions->DrawSprite(sprite, animation, frame, x, y, flipX, flipY, scaleW, scaleH, rotation, paletteID); } -PUBLIC STATIC void Graphics::DrawSpritePart(ISprite* sprite, int animation, int frame, int sx, int sy, int sw, int sh, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID) { +void Graphics::DrawSpritePart(ISprite* sprite, int animation, int frame, int sx, int sy, int sw, int sh, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID) { Graphics::GfxFunctions->DrawSpritePart(sprite, animation, frame, sx, sy, sw, sh, x, y, flipX, flipY, scaleW, scaleH, rotation, paletteID); } -PUBLIC STATIC void Graphics::DrawSprite(ISprite* sprite, int animation, int frame, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation) { +void Graphics::DrawSprite(ISprite* sprite, int animation, int frame, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation) { DrawSprite(sprite, animation, frame, x, y, flipX, flipY, scaleW, scaleH, rotation, 0); } -PUBLIC STATIC void Graphics::DrawSpritePart(ISprite* sprite, int animation, int frame, int sx, int sy, int sw, int sh, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation) { +void Graphics::DrawSpritePart(ISprite* sprite, int animation, int frame, int sx, int sy, int sw, int sh, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation) { DrawSpritePart(sprite, animation, frame, sx, sy, sw, sh, x, y, flipX, flipY, scaleW, scaleH, rotation, 0); } -PUBLIC STATIC void Graphics::DrawTile(int tile, int x, int y, bool flipX, bool flipY) { +void Graphics::DrawTile(int tile, int x, int y, bool flipX, bool flipY) { // If possible, uses optimized software-renderer call instead. if (Graphics::GfxFunctions == &SoftwareRenderer::BackendFunctions) { SoftwareRenderer::DrawTile(tile, x, y, flipX, flipY); @@ -957,7 +859,7 @@ PUBLIC STATIC void Graphics::DrawTile(int tile, int x, int y, bool flipX, bo TileSpriteInfo info = Scene::TileSpriteInfos[tile]; DrawSprite(info.Sprite, info.AnimationIndex, info.FrameIndex, x, y, flipX, flipY, 1.0f, 1.0f, 0.0f); } -PUBLIC STATIC void Graphics::DrawSceneLayer_HorizontalParallax(SceneLayer* layer, View* currentView) { +void Graphics::DrawSceneLayer_HorizontalParallax(SceneLayer* layer, View* currentView) { int tileWidth = Scene::TileWidth; int tileWidthHalf = tileWidth >> 1; int tileHeight = Scene::TileHeight; @@ -1225,10 +1127,10 @@ PUBLIC STATIC void Graphics::DrawSceneLayer_HorizontalParallax(SceneLayer* l } } } -PUBLIC STATIC void Graphics::DrawSceneLayer_VerticalParallax(SceneLayer* layer, View* currentView) { +void Graphics::DrawSceneLayer_VerticalParallax(SceneLayer* layer, View* currentView) { } -PUBLIC STATIC void Graphics::DrawSceneLayer(SceneLayer* layer, View* currentView, int layerIndex, bool useCustomFunction) { +void Graphics::DrawSceneLayer(SceneLayer* layer, View* currentView, int layerIndex, bool useCustomFunction) { // If possible, uses optimized software-renderer call instead. if (Graphics::GfxFunctions == &SoftwareRenderer::BackendFunctions) { SoftwareRenderer::DrawSceneLayer(layer, currentView, layerIndex, useCustomFunction); @@ -1252,7 +1154,7 @@ PUBLIC STATIC void Graphics::DrawSceneLayer(SceneLayer* layer, View* current break; } } -PUBLIC STATIC void Graphics::RunCustomSceneLayerFunction(ObjFunction* func, int layerIndex) { +void Graphics::RunCustomSceneLayerFunction(ObjFunction* func, int layerIndex) { VMThread* thread = &ScriptManager::Threads[0]; if (func->Arity == 0) { thread->RunEntityFunction(func, 0); @@ -1264,27 +1166,27 @@ PUBLIC STATIC void Graphics::RunCustomSceneLayerFunction(ObjFunction* func, } // 3D drawing -PUBLIC STATIC void Graphics::DrawPolygon3D(void* data, int vertexCount, int vertexFlag, Texture* texture, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +void Graphics::DrawPolygon3D(void* data, int vertexCount, int vertexFlag, Texture* texture, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { if (Graphics::GfxFunctions->DrawPolygon3D) Graphics::GfxFunctions->DrawPolygon3D(data, vertexCount, vertexFlag, texture, modelMatrix, normalMatrix); } -PUBLIC STATIC void Graphics::DrawSceneLayer3D(void* layer, int sx, int sy, int sw, int sh, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +void Graphics::DrawSceneLayer3D(void* layer, int sx, int sy, int sw, int sh, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { if (Graphics::GfxFunctions->DrawSceneLayer3D) Graphics::GfxFunctions->DrawSceneLayer3D(layer, sx, sy, sw, sh, modelMatrix, normalMatrix); } -PUBLIC STATIC void Graphics::DrawModel(void* model, Uint16 animation, Uint32 frame, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +void Graphics::DrawModel(void* model, Uint16 animation, Uint32 frame, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { if (Graphics::GfxFunctions->DrawModel) Graphics::GfxFunctions->DrawModel(model, animation, frame, modelMatrix, normalMatrix); } -PUBLIC STATIC void Graphics::DrawModelSkinned(void* model, Uint16 armature, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +void Graphics::DrawModelSkinned(void* model, Uint16 armature, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { if (Graphics::GfxFunctions->DrawModelSkinned) Graphics::GfxFunctions->DrawModelSkinned(model, armature, modelMatrix, normalMatrix); } -PUBLIC STATIC void Graphics::DrawVertexBuffer(Uint32 vertexBufferIndex, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +void Graphics::DrawVertexBuffer(Uint32 vertexBufferIndex, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { if (Graphics::GfxFunctions->DrawVertexBuffer) Graphics::GfxFunctions->DrawVertexBuffer(vertexBufferIndex, modelMatrix, normalMatrix); } -PUBLIC STATIC void Graphics::BindVertexBuffer(Uint32 vertexBufferIndex) { +void Graphics::BindVertexBuffer(Uint32 vertexBufferIndex) { if (vertexBufferIndex < 0 || vertexBufferIndex >= MAX_VERTEX_BUFFERS) { UnbindVertexBuffer(); return; @@ -1294,12 +1196,12 @@ PUBLIC STATIC void Graphics::BindVertexBuffer(Uint32 vertexBufferIndex) { Graphics::GfxFunctions->BindVertexBuffer(vertexBufferIndex); CurrentVertexBuffer = vertexBufferIndex; } -PUBLIC STATIC void Graphics::UnbindVertexBuffer() { +void Graphics::UnbindVertexBuffer() { if (Graphics::GfxFunctions->UnbindVertexBuffer) Graphics::GfxFunctions->UnbindVertexBuffer(); CurrentVertexBuffer = -1; } -PUBLIC STATIC void Graphics::BindScene3D(Uint32 sceneIndex) { +void Graphics::BindScene3D(Uint32 sceneIndex) { if (sceneIndex < 0 || sceneIndex >= MAX_3D_SCENES) return; @@ -1318,7 +1220,7 @@ PUBLIC STATIC void Graphics::BindScene3D(Uint32 sceneIndex) { Graphics::GfxFunctions->BindScene3D(sceneIndex); CurrentScene3D = sceneIndex; } -PUBLIC STATIC void Graphics::ClearScene3D(Uint32 sceneIndex) { +void Graphics::ClearScene3D(Uint32 sceneIndex) { if (sceneIndex < 0 || sceneIndex >= MAX_3D_SCENES) return; @@ -1328,12 +1230,12 @@ PUBLIC STATIC void Graphics::ClearScene3D(Uint32 sceneIndex) { if (Graphics::GfxFunctions->ClearScene3D) Graphics::GfxFunctions->ClearScene3D(sceneIndex); } -PUBLIC STATIC void Graphics::DrawScene3D(Uint32 sceneIndex, Uint32 drawMode) { +void Graphics::DrawScene3D(Uint32 sceneIndex, Uint32 drawMode) { if (Graphics::GfxFunctions->DrawScene3D) Graphics::GfxFunctions->DrawScene3D(sceneIndex, drawMode); } -PUBLIC STATIC Uint32 Graphics::CreateScene3D(int unloadPolicy) { +Uint32 Graphics::CreateScene3D(int unloadPolicy) { for (Uint32 i = 0; i < MAX_3D_SCENES; i++) { if (!Graphics::Scene3Ds[i].Initialized) { Graphics::InitScene3D(i, 0); @@ -1344,7 +1246,7 @@ PUBLIC STATIC Uint32 Graphics::CreateScene3D(int unloadPolicy) { return 0xFFFFFFFF; } -PUBLIC STATIC void Graphics::DeleteScene3D(Uint32 sceneIndex) { +void Graphics::DeleteScene3D(Uint32 sceneIndex) { if (sceneIndex < 0 || sceneIndex >= MAX_3D_SCENES) return; @@ -1358,7 +1260,7 @@ PUBLIC STATIC void Graphics::DeleteScene3D(Uint32 sceneIndex) { scene->Initialized = false; } } -PUBLIC STATIC void Graphics::InitScene3D(Uint32 sceneIndex, Uint32 numVertices) { +void Graphics::InitScene3D(Uint32 sceneIndex, Uint32 numVertices) { if (sceneIndex < 0 || sceneIndex >= MAX_3D_SCENES) return; @@ -1383,7 +1285,7 @@ PUBLIC STATIC void Graphics::InitScene3D(Uint32 sceneIndex, Uint32 numVertic scene->Clear(); } -PUBLIC STATIC void Graphics::MakeSpritePolygon(VertexAttribute data[4], float x, float y, float z, int flipX, int flipY, float scaleX, float scaleY, Texture* texture, int frameX, int frameY, int frameW, int frameH) { +void Graphics::MakeSpritePolygon(VertexAttribute data[4], float x, float y, float z, int flipX, int flipY, float scaleX, float scaleY, Texture* texture, int frameX, int frameY, int frameW, int frameH) { data[3].Position.X = FP16_TO(x); data[3].Position.Y = FP16_TO(y - (frameH * scaleY)); data[3].Position.Z = FP16_TO(z); @@ -1407,7 +1309,7 @@ PUBLIC STATIC void Graphics::MakeSpritePolygon(VertexAttribute data[4], floa Graphics::MakeSpritePolygonUVs(data, flipX, flipY, texture, frameX, frameY, frameW, frameH); } -PUBLIC STATIC void Graphics::MakeSpritePolygonUVs(VertexAttribute data[4], int flipX, int flipY, Texture* texture, int frameX, int frameY, int frameW, int frameH) { +void Graphics::MakeSpritePolygonUVs(VertexAttribute data[4], int flipX, int flipY, Texture* texture, int frameX, int frameY, int frameW, int frameH) { Sint64 textureWidth = FP16_TO(texture->Width); Sint64 textureHeight = FP16_TO(texture->Height); @@ -1447,21 +1349,21 @@ PUBLIC STATIC void Graphics::MakeSpritePolygonUVs(VertexAttribute data[4], i data[0].UV.Y = FP16_DIVIDE(FP16_TO(top_v), textureHeight); } -PUBLIC STATIC void Graphics::MakeFrameBufferID(ISprite* sprite, AnimFrame* frame) { +void Graphics::MakeFrameBufferID(ISprite* sprite, AnimFrame* frame) { if (Graphics::GfxFunctions->MakeFrameBufferID) Graphics::GfxFunctions->MakeFrameBufferID(sprite, frame); } -PUBLIC STATIC void Graphics::DeleteFrameBufferID(AnimFrame* frame) { +void Graphics::DeleteFrameBufferID(AnimFrame* frame) { if (Graphics::GfxFunctions->DeleteFrameBufferID) Graphics::GfxFunctions->DeleteFrameBufferID(frame); } -PUBLIC STATIC void Graphics::SetDepthTesting(bool enabled) { +void Graphics::SetDepthTesting(bool enabled) { if (Graphics::GfxFunctions->SetDepthTesting) Graphics::GfxFunctions->SetDepthTesting(enabled); } -PUBLIC STATIC bool Graphics::SpriteRangeCheck(ISprite* sprite, int animation, int frame) { +bool Graphics::SpriteRangeCheck(ISprite* sprite, int animation, int frame) { //#ifdef DEBUG if (!sprite) return true; if (animation < 0 || animation >= (int)sprite->Animations.size()) { @@ -1476,47 +1378,47 @@ PUBLIC STATIC bool Graphics::SpriteRangeCheck(ISprite* sprite, int animation return false; } -PUBLIC STATIC void Graphics::ConvertFromARGBtoNative(Uint32* argb, int count) { +void Graphics::ConvertFromARGBtoNative(Uint32* argb, int count) { if (Graphics::PreferredPixelFormat == SDL_PIXELFORMAT_ABGR8888) ColorUtils::ConvertFromARGBtoABGR(argb, count); } -PUBLIC STATIC void Graphics::ConvertFromNativeToARGB(Uint32* argb, int count) { +void Graphics::ConvertFromNativeToARGB(Uint32* argb, int count) { if (Graphics::PreferredPixelFormat == SDL_PIXELFORMAT_ABGR8888) ColorUtils::ConvertFromABGRtoARGB(argb, count); } -PUBLIC STATIC void Graphics::SetStencilEnabled(bool enabled) { +void Graphics::SetStencilEnabled(bool enabled) { if (Graphics::GfxFunctions->SetStencilEnabled) Graphics::GfxFunctions->SetStencilEnabled(enabled); } -PUBLIC STATIC bool Graphics::GetStencilEnabled() { +bool Graphics::GetStencilEnabled() { if (Graphics::GfxFunctions->IsStencilEnabled) return Graphics::GfxFunctions->IsStencilEnabled(); return false; } -PUBLIC STATIC void Graphics::SetStencilTestFunc(int stencilTest) { +void Graphics::SetStencilTestFunc(int stencilTest) { if (stencilTest >= StencilTest_Never && stencilTest <= StencilTest_GEqual) { StencilTest = stencilTest; if (Graphics::GfxFunctions->SetStencilTestFunc) Graphics::GfxFunctions->SetStencilTestFunc(stencilTest); } } -PUBLIC STATIC void Graphics::SetStencilPassFunc(int stencilOp) { +void Graphics::SetStencilPassFunc(int stencilOp) { if (stencilOp >= StencilOp_Keep && stencilOp <= StencilOp_DecrWrap) { StencilOpPass = stencilOp; if (Graphics::GfxFunctions->SetStencilPassFunc) Graphics::GfxFunctions->SetStencilPassFunc(stencilOp); } } -PUBLIC STATIC void Graphics::SetStencilFailFunc(int stencilOp) { +void Graphics::SetStencilFailFunc(int stencilOp) { if (stencilOp >= StencilOp_Keep && stencilOp <= StencilOp_DecrWrap) { StencilOpFail = stencilOp; if (Graphics::GfxFunctions->SetStencilFailFunc) Graphics::GfxFunctions->SetStencilFailFunc(stencilOp); } } -PUBLIC STATIC void Graphics::SetStencilValue(int value) { +void Graphics::SetStencilValue(int value) { if (value < 0) value = 0; else if (value > 255) @@ -1524,7 +1426,7 @@ PUBLIC STATIC void Graphics::SetStencilValue(int value) { if (Graphics::GfxFunctions->SetStencilValue) Graphics::GfxFunctions->SetStencilValue(value); } -PUBLIC STATIC void Graphics::SetStencilMask(int mask) { +void Graphics::SetStencilMask(int mask) { if (mask < 0) mask = 0; else if (mask > 255) @@ -1532,7 +1434,7 @@ PUBLIC STATIC void Graphics::SetStencilMask(int mask) { if (Graphics::GfxFunctions->SetStencilMask) Graphics::GfxFunctions->SetStencilMask(mask); } -PUBLIC STATIC void Graphics::ClearStencil() { +void Graphics::ClearStencil() { if (Graphics::GfxFunctions->ClearStencil) Graphics::GfxFunctions->ClearStencil(); } diff --git a/source/Engine/Hashing/CRC32.cpp b/source/Engine/Hashing/CRC32.cpp index 64d6d577..1c87c35e 100644 --- a/source/Engine/Hashing/CRC32.cpp +++ b/source/Engine/Hashing/CRC32.cpp @@ -1,26 +1,16 @@ -#if INTERFACE - -#include - -class CRC32 { -public: - -}; -#endif - #include -PUBLIC STATIC Uint32 CRC32::EncryptString(char* data) { +Uint32 CRC32::EncryptString(char* data) { return CRC32::EncryptData(data, strlen(data)); } -PUBLIC STATIC Uint32 CRC32::EncryptString(const char* message) { +Uint32 CRC32::EncryptString(const char* message) { return CRC32::EncryptString((char*)message); } -PUBLIC STATIC Uint32 CRC32::EncryptData(const void* data, size_t size) { +Uint32 CRC32::EncryptData(const void* data, size_t size) { return CRC32::EncryptData(data, size, 0xFFFFFFFFU); } -PUBLIC STATIC Uint32 CRC32::EncryptData(const void* data, size_t size, Uint32 crc) { +Uint32 CRC32::EncryptData(const void* data, size_t size, Uint32 crc) { int j; Uint32 byte, mask; Uint8* message = (Uint8*)data; diff --git a/source/Engine/Hashing/CombinedHash.cpp b/source/Engine/Hashing/CombinedHash.cpp index 50b3fb4c..35c83f80 100644 --- a/source/Engine/Hashing/CombinedHash.cpp +++ b/source/Engine/Hashing/CombinedHash.cpp @@ -1,27 +1,17 @@ -#if INTERFACE - -#include - -class CombinedHash { -public: - -}; -#endif - #include #include #include -PUBLIC STATIC Uint32 CombinedHash::EncryptString(char* data) { +Uint32 CombinedHash::EncryptString(char* data) { Uint8 objMD5[16]; return CRC32::EncryptData(MD5::EncryptString(objMD5, data), 16); } -PUBLIC STATIC Uint32 CombinedHash::EncryptString(const char* message) { +Uint32 CombinedHash::EncryptString(const char* message) { return CombinedHash::EncryptString((char*)message); } -PUBLIC STATIC Uint32 CombinedHash::EncryptData(const void* message, size_t len) { +Uint32 CombinedHash::EncryptData(const void* message, size_t len) { Uint8 objMD5[16]; return CRC32::EncryptData(MD5::EncryptData(objMD5, (void*)message, len), 16); } diff --git a/source/Engine/Hashing/FNV1A.cpp b/source/Engine/Hashing/FNV1A.cpp index 7f9e9338..2fda016c 100644 --- a/source/Engine/Hashing/FNV1A.cpp +++ b/source/Engine/Hashing/FNV1A.cpp @@ -1,16 +1,6 @@ -#if INTERFACE - -#include - -class FNV1A { -public: - -}; -#endif - #include -PUBLIC STATIC Uint32 FNV1A::EncryptString(char* message) { +Uint32 FNV1A::EncryptString(char* message) { Uint32 hash = 0x811C9DC5U; while (*message) { @@ -20,14 +10,14 @@ PUBLIC STATIC Uint32 FNV1A::EncryptString(char* message) { } return hash; } -PUBLIC STATIC Uint32 FNV1A::EncryptString(const char* message) { +Uint32 FNV1A::EncryptString(const char* message) { return FNV1A::EncryptString((char*)message); } -PUBLIC STATIC Uint32 FNV1A::EncryptData(const void* data, size_t size) { +Uint32 FNV1A::EncryptData(const void* data, size_t size) { return FNV1A::EncryptData(data, size, 0x811C9DC5U); } -PUBLIC STATIC Uint32 FNV1A::EncryptData(const void* data, size_t size, Uint32 hash) { +Uint32 FNV1A::EncryptData(const void* data, size_t size, Uint32 hash) { size_t i = size; char* message = (char*)data; while (i) { diff --git a/source/Engine/Hashing/MD5.cpp b/source/Engine/Hashing/MD5.cpp index 54c7bc85..583c7d64 100644 --- a/source/Engine/Hashing/MD5.cpp +++ b/source/Engine/Hashing/MD5.cpp @@ -1,13 +1,3 @@ -#if INTERFACE - -#include - -class MD5 { -public: - -}; -#endif - #include #define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) @@ -33,7 +23,7 @@ class MD5 { (dst)[2] = (Uint8)((src) >> 16); \ (dst)[3] = (Uint8)((src) >> 24); -PRIVATE STATIC void* MD5::Body(Uint32* pa, Uint32* pb, Uint32* pc, Uint32* pd, void *data, unsigned long size) { +void* MD5::Body(Uint32* pa, Uint32* pb, Uint32* pc, Uint32* pd, void *data, unsigned long size) { Uint32 saved_a, saved_b, saved_c, saved_d; Uint8* ptr = (Uint8*)data; @@ -140,14 +130,14 @@ PRIVATE STATIC void* MD5::Body(Uint32* pa, Uint32* pb, Uint32* pc, Uint32* pd, v return ptr; } -PUBLIC STATIC Uint8* MD5::EncryptString(Uint8* dest, char* message) { +Uint8* MD5::EncryptString(Uint8* dest, char* message) { return MD5::EncryptData(dest, message, strlen(message)); } -PUBLIC STATIC Uint8* MD5::EncryptString(Uint8* dest, const char* message) { +Uint8* MD5::EncryptString(Uint8* dest, const char* message) { return MD5::EncryptString(dest, (char*)message); } -PUBLIC STATIC Uint8* MD5::EncryptData(Uint8* dest, void* data, size_t size) { +Uint8* MD5::EncryptData(Uint8* dest, void* data, size_t size) { // Init Uint8 buffer[64]; size_t lo = 0, hi = 0; diff --git a/source/Engine/Hashing/Murmur.cpp b/source/Engine/Hashing/Murmur.cpp index 346b0d10..4ec7fb65 100644 --- a/source/Engine/Hashing/Murmur.cpp +++ b/source/Engine/Hashing/Murmur.cpp @@ -1,27 +1,17 @@ -#if INTERFACE - -#include - -class Murmur { -public: - -}; -#endif - #include #include -PUBLIC STATIC Uint32 Murmur::EncryptString(char* message) { +Uint32 Murmur::EncryptString(char* message) { return Murmur::EncryptData(message, strlen(message), 0xDEADBEEF); } -PUBLIC STATIC Uint32 Murmur::EncryptString(const char* message) { +Uint32 Murmur::EncryptString(const char* message) { return Murmur::EncryptString((char*)message); } -PUBLIC STATIC Uint32 Murmur::EncryptData(const void* data, size_t size) { +Uint32 Murmur::EncryptData(const void* data, size_t size) { return Murmur::EncryptData(data, size, 0xDEADBEEF); } -PUBLIC STATIC Uint32 Murmur::EncryptData(const void* key, size_t size, Uint32 hash) { +Uint32 Murmur::EncryptData(const void* key, size_t size, Uint32 hash) { const unsigned int m = 0x5bd1e995; const int r = 24; unsigned int h = hash ^ (Uint32)size; diff --git a/source/Engine/IO/Compression/Huffman.cpp b/source/Engine/IO/Compression/Huffman.cpp index a7e10998..ded20d25 100644 --- a/source/Engine/IO/Compression/Huffman.cpp +++ b/source/Engine/IO/Compression/Huffman.cpp @@ -1,14 +1,6 @@ -#if INTERFACE -#include -class Huffman { -public: - -}; -#endif - #include -PUBLIC STATIC bool Huffman::Decompress(uint8_t* in, size_t in_sz, uint8_t* out, size_t out_sz) { +bool Huffman::Decompress(uint8_t* in, size_t in_sz, uint8_t* out, size_t out_sz) { #define datat_t uint8_t datat_t* in_head = (datat_t*)in; datat_t* out_head = (datat_t*)out; @@ -23,26 +15,11 @@ PUBLIC STATIC bool Huffman::Decompress(uint8_t* in, size_t in_sz, uint8_t* out, return false; // get tree size - // if (!buffer_read(buffer, &tree[0], 1, callback, userdata)) { - // free(tree); - // return false; - // } tree[0] = *in_head++; - printf("Tree Size: %X (%d)\n", tree[0], tree[0]); // read tree - // if (!buffer_read(buffer, &tree[1], (((size_t)tree[0])+1)*2-1, callback, userdata)) { - // free(tree); - // return false; - // } int len_to_read = (tree[0] + 1) * 2 - 1; memcpy(&tree[1], in_head, len_to_read); - printf("Tree Size To Read: %X (%d)\n", len_to_read, len_to_read); - printf("Nodes: "); - for (int i = 0; i < len_to_read; i++) { - printf("%02X ", tree[1 + i]); - } - printf("\n"); in_head += len_to_read; uint32_t word = 0; // 32-bits of input bitstream @@ -81,8 +58,6 @@ PUBLIC STATIC bool Huffman::Decompress(uint8_t* in, size_t in_sz, uint8_t* out, | (wordbuf[1] << 8) | (wordbuf[2] << 16) | (wordbuf[3] << 24); - - printf("New Word: %08X\n", word); } // read the current node's offset value @@ -95,9 +70,6 @@ PUBLIC STATIC bool Huffman::Decompress(uint8_t* in, size_t in_sz, uint8_t* out, // point to the "right" child child++; - printf("r node: %zu (%02X)\n", node, tree[node]); - printf("r child: %zu (%02X)\n", child, tree[child]); - // "right" child is a data node if (tree[node] & 0x40) { // copy the child node into the output buffer and apply mask @@ -106,8 +78,6 @@ PUBLIC STATIC bool Huffman::Decompress(uint8_t* in, size_t in_sz, uint8_t* out, *out_head++ = tree[child] & dataMask; --size; - printf("found: node (%02X), child (%02X)\n", tree[node], tree[child]); - // start over at the root node node = 1; } @@ -118,8 +88,6 @@ PUBLIC STATIC bool Huffman::Decompress(uint8_t* in, size_t in_sz, uint8_t* out, else { // pointed to the "left" child - printf("l node: %zu (%02X)\n", node, tree[node]); - printf("l child: %zu (%02X)\n", child, tree[child]); // "left" child is a data node if (tree[node] & 0x80) { // copy the child node into the output buffer and apply mask @@ -128,8 +96,6 @@ PUBLIC STATIC bool Huffman::Decompress(uint8_t* in, size_t in_sz, uint8_t* out, *out_head++ = tree[child] & dataMask; --size; - printf("found: node (%02X), child (%02X)\n", tree[node], tree[child]); - // start over at the root node node = 1; } diff --git a/source/Engine/IO/Compression/LZ11.cpp b/source/Engine/IO/Compression/LZ11.cpp index d9f8899b..659e7dd8 100644 --- a/source/Engine/IO/Compression/LZ11.cpp +++ b/source/Engine/IO/Compression/LZ11.cpp @@ -1,19 +1,10 @@ -#if INTERFACE -#include -class LZ11 { -public: - -}; -#endif - #include -PUBLIC STATIC bool LZ11::Decompress(uint8_t* in, size_t in_sz, uint8_t* out, size_t out_sz) { - typedef uint8_t datat_t; +bool LZ11::Decompress(uint8_t* in, size_t in_sz, uint8_t* out, size_t out_sz) { int i; - datat_t flags; - datat_t* in_head = (datat_t*)in; - datat_t* out_head = (datat_t*)out; + uint8_t flags; + uint8_t* in_head = (uint8_t*)in; + uint8_t* out_head = (uint8_t*)out; size_t size = out_sz; int bits = sizeof(flags) << 3; @@ -25,26 +16,18 @@ PUBLIC STATIC bool LZ11::Decompress(uint8_t* in, size_t in_sz, uint8_t* out, siz // 0: raw byte // 1: compressed block flags = *in_head++; - if (in_head >= in_sz + (datat_t*)in) + if (in_head >= in_sz + (uint8_t*)in) return false; - // printf("Flag: %04X (", flags); - for (i = 0; i < bits; i++) { - // if (!(i & 7) && i) - // printf(" "); - // printf("%d", ((flags << i) & mask) >> (bits - 1)); - } - // printf(")\n"); - // the first flag cannot start with 1, as that needs data to pull from for (i = 0; i < bits && size > 0; i++, flags <<= 1) { // Compressed block if (flags & 0x80) { - datat_t displen[4]; + uint8_t displen[4]; displen[0] = *in_head++; - if (in_head >= in_sz + (datat_t*)in) + if (in_head >= in_sz + (uint8_t*)in) return false; size_t len; // length @@ -53,8 +36,8 @@ PUBLIC STATIC bool LZ11::Decompress(uint8_t* in, size_t in_sz, uint8_t* out, siz switch (displen[pos] >> 4) { case 0: // extended block - displen[1] = *in_head++; if (in_head >= in_sz + (datat_t*)in) return false; - displen[2] = *in_head++; if (in_head >= in_sz + (datat_t*)in) return false; + displen[1] = *in_head++; if (in_head >= in_sz + (uint8_t*)in) return false; + displen[2] = *in_head++; if (in_head >= in_sz + (uint8_t*)in) return false; len = displen[pos++] << 4; len |= displen[pos] >> 4; @@ -62,9 +45,9 @@ PUBLIC STATIC bool LZ11::Decompress(uint8_t* in, size_t in_sz, uint8_t* out, siz break; case 1: // extra extended block - displen[1] = *in_head++; if (in_head >= in_sz + (datat_t*)in) return false; - displen[2] = *in_head++; if (in_head >= in_sz + (datat_t*)in) return false; - displen[3] = *in_head++; if (in_head >= in_sz + (datat_t*)in) return false; + displen[1] = *in_head++; if (in_head >= in_sz + (uint8_t*)in) return false; + displen[2] = *in_head++; if (in_head >= in_sz + (uint8_t*)in) return false; + displen[3] = *in_head++; if (in_head >= in_sz + (uint8_t*)in) return false; len = (displen[pos++] & 0x0F) << 12; len |= (displen[pos++]) << 4; @@ -73,9 +56,7 @@ PUBLIC STATIC bool LZ11::Decompress(uint8_t* in, size_t in_sz, uint8_t* out, siz break; default: // normal block - // if (!buffer_get(buffer, &displen[1], callback, userdata)) - // return false; - displen[1] = *in_head++; if (in_head >= in_sz + (datat_t*)in) return false; + displen[1] = *in_head++; if (in_head >= in_sz + (uint8_t*)in) return false; len = (displen[pos] >> 4) + 1; break; @@ -89,22 +70,15 @@ PUBLIC STATIC bool LZ11::Decompress(uint8_t* in, size_t in_sz, uint8_t* out, siz size -= len; - // iov_iter in = out; - // iov_sub(&in, disp + 1); - // iov_memmove(&out, &in, len); - - datat_t* sup = out_head - (disp + 1); - // printf("Len: %d\n", lol); + uint8_t* sup = out_head - (disp + 1); while (len-- > 0) { - // printf("Out (cmp): %04X\n", *sup); *out_head++ = *sup++; } } // Uncompressed block else { - // printf("Out (raw): %04X\n", *in_head); // copy a raw byte from the input to the output - *out_head++ = *in_head++; if (in_head >= in_sz + (datat_t*)in) return false; + *out_head++ = *in_head++; if (in_head >= in_sz + (uint8_t*)in) return false; --size; } } diff --git a/source/Engine/IO/Compression/LZSS.cpp b/source/Engine/IO/Compression/LZSS.cpp index 2070efb8..9b06964a 100644 --- a/source/Engine/IO/Compression/LZSS.cpp +++ b/source/Engine/IO/Compression/LZSS.cpp @@ -1,67 +1,5 @@ -#if INTERFACE -#include -class LZSS { -public: - -}; -#endif - #include -PUBLIC STATIC bool LZSS::Decompress(uint8_t* in, size_t in_sz, uint8_t* out, size_t out_sz) { - /* - uint8_t flags = 0; - uint8_t mask = 0; - unsigned int len; - unsigned int disp; - - while(size > 0) - { - if(mask == 0) - { - // read in the flags data - // from bit 7 to bit 0: - // 0: raw byte - // 1: compressed block - if(!buffer_get(buffer, &flags, callback, userdata)) - return false; - mask = 0x80; - } - - if(flags & mask) // compressed block - { - uint8_t displen[2]; - if(!buffer_get(buffer, &displen[0], callback, userdata) - || !buffer_get(buffer, &displen[1], callback, userdata)) - return false; - - // disp: displacement - // len: length - len = ((displen[0] & 0xF0) >> 4) + 3; - disp = displen[0] & 0x0F; - disp = disp << 8 | displen[1]; - - if(len > size) - len = size; - - size -= len; - - iov_iter in = out; - iov_sub(&in, disp+1); - iov_memmove(&out, &in, len); - } - else // uncompressed block - { - // copy a raw byte from the input to the output - if(!buffer_get(buffer, iov_addr(&out), callback, userdata)) - return false; - - --size; - iov_increment(&out); - } - - mask >>= 1; - } -//*/ - return true; +bool LZSS::Decompress(uint8_t* in, size_t in_sz, uint8_t* out, size_t out_sz) { + return true; } diff --git a/source/Engine/IO/Compression/RunLength.cpp b/source/Engine/IO/Compression/RunLength.cpp index 272b8d7d..badea381 100644 --- a/source/Engine/IO/Compression/RunLength.cpp +++ b/source/Engine/IO/Compression/RunLength.cpp @@ -1,14 +1,6 @@ -#if INTERFACE -#include -class RunLength { -public: - -}; -#endif - #include -PUBLIC STATIC bool RunLength::Decompress(uint8_t* in, size_t in_sz, uint8_t* out, size_t out_sz) { +bool RunLength::Decompress(uint8_t* in, size_t in_sz, uint8_t* out, size_t out_sz) { uint8_t byte; size_t len; uint8_t* in_head = in; diff --git a/source/Engine/IO/Compression/ZLibStream.cpp b/source/Engine/IO/Compression/ZLibStream.cpp index 686f7428..85e08b31 100644 --- a/source/Engine/IO/Compression/ZLibStream.cpp +++ b/source/Engine/IO/Compression/ZLibStream.cpp @@ -1,16 +1,3 @@ -#if INTERFACE -#include -#include -class ZLibStream : public Stream { -public: - Stream* other_stream = NULL; - uint32_t mode = 0; - - void* memory = NULL; - size_t memory_size = 0; -}; -#endif - #include #include @@ -20,7 +7,7 @@ class ZLibStream : public Stream { #define MINIZ_HEADER_FILE_ONLY #include -PUBLIC STATIC ZLibStream* ZLibStream::New(Stream* other_stream, uint32_t mode) { +ZLibStream* ZLibStream::New(Stream* other_stream, uint32_t mode) { ZLibStream* stream = new ZLibStream; if (!stream) { return NULL; @@ -51,7 +38,7 @@ PUBLIC STATIC ZLibStream* ZLibStream::New(Stream* other_stream, uint32_t mode) { return NULL; } -PUBLIC void ZLibStream::Close() { +void ZLibStream::Close() { if (memory) { Memory::Free(memory); memory_size = 0; @@ -60,37 +47,37 @@ PUBLIC void ZLibStream::Close() { Stream::Close(); } -PUBLIC void ZLibStream::Seek(Sint64 offset) { +void ZLibStream::Seek(Sint64 offset) { // pointer = pointer_start + offset; } -PUBLIC void ZLibStream::SeekEnd(Sint64 offset) { +void ZLibStream::SeekEnd(Sint64 offset) { // pointer = pointer_start + size - offset; } -PUBLIC void ZLibStream::Skip(Sint64 offset) { +void ZLibStream::Skip(Sint64 offset) { // pointer = pointer + offset; } -PUBLIC size_t ZLibStream::Position() { +size_t ZLibStream::Position() { // return pointer - pointer_start; return 0; } -PUBLIC size_t ZLibStream::Length() { +size_t ZLibStream::Length() { // return pointer - pointer_start; return 0; } -PUBLIC size_t ZLibStream::ReadBytes(void* data, size_t n) { +size_t ZLibStream::ReadBytes(void* data, size_t n) { memcpy(data, memory, n); // pointer += n; return n; } -PUBLIC size_t ZLibStream::WriteBytes(void* data, size_t n) { +size_t ZLibStream::WriteBytes(void* data, size_t n) { // memcpy(pointer, data, n); // pointer += n; return n; } -PUBLIC STATIC void ZLibStream::Decompress(void* dst, size_t dstLen, void* src, size_t srcLen) { +void ZLibStream::Decompress(void* dst, size_t dstLen, void* src, size_t srcLen) { z_stream infstream; infstream.zalloc = Z_NULL; infstream.zfree = Z_NULL; @@ -106,7 +93,7 @@ PUBLIC STATIC void ZLibStream::Decompress(void* dst, size_t dstLen, void* inflateEnd(&infstream); } -PRIVATE void ZLibStream::Decompress(void* in, size_t inLen) { +void ZLibStream::Decompress(void* in, size_t inLen) { z_stream infstream; infstream.zalloc = Z_NULL; infstream.zfree = Z_NULL; diff --git a/source/Engine/IO/FileStream.cpp b/source/Engine/IO/FileStream.cpp index bb24e683..dc207e71 100644 --- a/source/Engine/IO/FileStream.cpp +++ b/source/Engine/IO/FileStream.cpp @@ -1,20 +1,3 @@ -#if INTERFACE -#include -#include -class FileStream : public Stream { -public: - FILE* f; - size_t size; - enum { - READ_ACCESS = 0, - WRITE_ACCESS = 1, - APPEND_ACCESS = 2, - SAVEGAME_ACCESS = 16, - PREFERENCES_ACCESS = 32, - }; -}; -#endif - #include #include #include @@ -25,7 +8,7 @@ extern "C" { } #endif -PUBLIC STATIC FileStream* FileStream::New(const char* filename, Uint32 access) { +FileStream* FileStream::New(const char* filename, Uint32 access) { FileStream* stream = new (std::nothrow) FileStream; if (!stream) { return NULL; @@ -131,32 +114,32 @@ PUBLIC STATIC FileStream* FileStream::New(const char* filename, Uint32 access) { return NULL; } -PUBLIC void FileStream::Close() { +void FileStream::Close() { fclose(f); f = NULL; Stream::Close(); } -PUBLIC void FileStream::Seek(Sint64 offset) { +void FileStream::Seek(Sint64 offset) { fseek(f, offset, SEEK_SET); } -PUBLIC void FileStream::SeekEnd(Sint64 offset) { +void FileStream::SeekEnd(Sint64 offset) { fseek(f, offset, SEEK_END); } -PUBLIC void FileStream::Skip(Sint64 offset) { +void FileStream::Skip(Sint64 offset) { fseek(f, offset, SEEK_CUR); } -PUBLIC size_t FileStream::Position() { +size_t FileStream::Position() { return ftell(f); } -PUBLIC size_t FileStream::Length() { +size_t FileStream::Length() { return size; } -PUBLIC size_t FileStream::ReadBytes(void* data, size_t n) { +size_t FileStream::ReadBytes(void* data, size_t n) { // if (!f) Log::Print(Log::LOG_ERROR, "Attempt to read from closed stream.") return fread(data, 1, n, f); } -PUBLIC size_t FileStream::WriteBytes(void* data, size_t n) { +size_t FileStream::WriteBytes(void* data, size_t n) { return fwrite(data, 1, n, f); } diff --git a/source/Engine/IO/MemoryStream.cpp b/source/Engine/IO/MemoryStream.cpp index 36cbcfdd..22eb2ee2 100644 --- a/source/Engine/IO/MemoryStream.cpp +++ b/source/Engine/IO/MemoryStream.cpp @@ -1,19 +1,7 @@ -#if INTERFACE -#include -#include -class MemoryStream : public Stream { -public: - Uint8* pointer = NULL; - Uint8* pointer_start = NULL; - size_t size = 0; - bool owns_memory = false; -}; -#endif - #include #include -PUBLIC STATIC MemoryStream* MemoryStream::New(size_t size) { +MemoryStream* MemoryStream::New(size_t size) { void* data = Memory::Malloc(size); MemoryStream* stream = MemoryStream::New(data, size); if (!stream) { @@ -24,7 +12,7 @@ PUBLIC STATIC MemoryStream* MemoryStream::New(size_t size) { } return stream; } -PUBLIC STATIC MemoryStream* MemoryStream::New(Stream* other) { +MemoryStream* MemoryStream::New(Stream* other) { MemoryStream* stream = MemoryStream::New(other->Length()); if (stream) { other->CopyTo(stream); @@ -32,7 +20,7 @@ PUBLIC STATIC MemoryStream* MemoryStream::New(Stream* other) { } return stream; } -PUBLIC STATIC MemoryStream* MemoryStream::New(void* data, size_t size) { +MemoryStream* MemoryStream::New(void* data, size_t size) { MemoryStream* stream = new (std::nothrow) MemoryStream; if (!stream) { return NULL; @@ -52,29 +40,29 @@ PUBLIC STATIC MemoryStream* MemoryStream::New(void* data, size_t size) { return NULL; } -PUBLIC void MemoryStream::Close() { +void MemoryStream::Close() { if (owns_memory) Memory::Free(pointer_start); Stream::Close(); } -PUBLIC void MemoryStream::Seek(Sint64 offset) { +void MemoryStream::Seek(Sint64 offset) { pointer = pointer_start + offset; } -PUBLIC void MemoryStream::SeekEnd(Sint64 offset) { +void MemoryStream::SeekEnd(Sint64 offset) { pointer = pointer_start + size + offset; } -PUBLIC void MemoryStream::Skip(Sint64 offset) { +void MemoryStream::Skip(Sint64 offset) { pointer = pointer + offset; } -PUBLIC size_t MemoryStream::Position() { +size_t MemoryStream::Position() { return pointer - pointer_start; } -PUBLIC size_t MemoryStream::Length() { +size_t MemoryStream::Length() { return size; } -PUBLIC size_t MemoryStream::ReadBytes(void* data, size_t n) { +size_t MemoryStream::ReadBytes(void* data, size_t n) { if (n > size - Position()) { n = size - Position(); } @@ -84,7 +72,7 @@ PUBLIC size_t MemoryStream::ReadBytes(void* data, size_t n) { pointer += n; return n; } -PUBLIC Uint32 MemoryStream::ReadCompressed(void* out) { +Uint32 MemoryStream::ReadCompressed(void* out) { Uint32 compressed_size = ReadUInt32() - 4; Uint32 uncompressed_size = ReadUInt32BE(); @@ -93,7 +81,7 @@ PUBLIC Uint32 MemoryStream::ReadCompressed(void* out) { return uncompressed_size; } -PUBLIC Uint32 MemoryStream::ReadCompressed(void* out, size_t outSz) { +Uint32 MemoryStream::ReadCompressed(void* out, size_t outSz) { Uint32 compressed_size = ReadUInt32() - 4; ReadUInt32BE(); // Uint32 uncompressed_size = ReadUInt32BE(); @@ -103,7 +91,7 @@ PUBLIC Uint32 MemoryStream::ReadCompressed(void* out, size_t outSz return (Uint32)outSz; } -PUBLIC size_t MemoryStream::WriteBytes(void* data, size_t n) { +size_t MemoryStream::WriteBytes(void* data, size_t n) { if (Position() + n > size) { size_t pos = Position(); pointer_start = (unsigned char*)Memory::Realloc(pointer_start, pos + n); diff --git a/source/Engine/IO/NetworkStream.cpp b/source/Engine/IO/NetworkStream.cpp index 2aa1b81a..14ec9eb3 100644 --- a/source/Engine/IO/NetworkStream.cpp +++ b/source/Engine/IO/NetworkStream.cpp @@ -1,21 +1,7 @@ -#if INTERFACE -#include -#include -class NetworkStream : public Stream { -public: - FILE* f; - size_t size; - enum { - SERVER_SOCKET = 0, - CLIENT_SOCKET = 1, - }; -}; -#endif - #include #include -PUBLIC STATIC NetworkStream* NetworkStream::New(const char* filename, Uint32 access) { +NetworkStream* NetworkStream::New(const char* filename, Uint32 access) { NetworkStream* stream = new NetworkStream; if (!stream) { return NULL; @@ -55,32 +41,32 @@ PUBLIC STATIC NetworkStream* NetworkStream::New(const char* filename, Uint32 acc return NULL; } -PUBLIC void NetworkStream::Close() { +void NetworkStream::Close() { fclose(f); f = NULL; Stream::Close(); } -PUBLIC void NetworkStream::Seek(Sint64 offset) { +void NetworkStream::Seek(Sint64 offset) { fseek(f, offset, SEEK_SET); } -PUBLIC void NetworkStream::SeekEnd(Sint64 offset) { +void NetworkStream::SeekEnd(Sint64 offset) { fseek(f, offset, SEEK_END); } -PUBLIC void NetworkStream::Skip(Sint64 offset) { +void NetworkStream::Skip(Sint64 offset) { fseek(f, offset, SEEK_CUR); } -PUBLIC size_t NetworkStream::Position() { +size_t NetworkStream::Position() { return ftell(f); } -PUBLIC size_t NetworkStream::Length() { +size_t NetworkStream::Length() { return size; } -PUBLIC size_t NetworkStream::ReadBytes(void* data, size_t n) { +size_t NetworkStream::ReadBytes(void* data, size_t n) { // if (!f) Log::Print(Log::LOG_ERROR, "Attempt to read from closed stream.") return fread(data, 1, n, f); } -PUBLIC size_t NetworkStream::WriteBytes(void* data, size_t n) { +size_t NetworkStream::WriteBytes(void* data, size_t n) { return fwrite(data, 1, n, f); } diff --git a/source/Engine/IO/ResourceStream.cpp b/source/Engine/IO/ResourceStream.cpp index 976abd9c..c8e75c45 100644 --- a/source/Engine/IO/ResourceStream.cpp +++ b/source/Engine/IO/ResourceStream.cpp @@ -1,19 +1,8 @@ -#if INTERFACE -#include -#include -class ResourceStream : public Stream { -public: - Uint8* pointer = NULL; - Uint8* pointer_start = NULL; - size_t size = 0; -}; -#endif - #include #include -PUBLIC STATIC ResourceStream* ResourceStream::New(const char* filename) { +ResourceStream* ResourceStream::New(const char* filename) { ResourceStream* stream = new (std::nothrow) ResourceStream; if (!stream) { return NULL; @@ -34,27 +23,27 @@ PUBLIC STATIC ResourceStream* ResourceStream::New(const char* filename) { return NULL; } -PUBLIC void ResourceStream::Close() { +void ResourceStream::Close() { Memory::Free(pointer_start); Stream::Close(); } -PUBLIC void ResourceStream::Seek(Sint64 offset) { +void ResourceStream::Seek(Sint64 offset) { pointer = pointer_start + offset; } -PUBLIC void ResourceStream::SeekEnd(Sint64 offset) { +void ResourceStream::SeekEnd(Sint64 offset) { pointer = pointer_start + size + offset; } -PUBLIC void ResourceStream::Skip(Sint64 offset) { +void ResourceStream::Skip(Sint64 offset) { pointer = pointer + offset; } -PUBLIC size_t ResourceStream::Position() { +size_t ResourceStream::Position() { return pointer - pointer_start; } -PUBLIC size_t ResourceStream::Length() { +size_t ResourceStream::Length() { return size; } -PUBLIC size_t ResourceStream::ReadBytes(void* data, size_t n) { +size_t ResourceStream::ReadBytes(void* data, size_t n) { if (n > size - Position()) { n = size - Position(); } @@ -64,7 +53,7 @@ PUBLIC size_t ResourceStream::ReadBytes(void* data, size_t n) { pointer += n; return n; } -PUBLIC size_t ResourceStream::WriteBytes(void* data, size_t n) { +size_t ResourceStream::WriteBytes(void* data, size_t n) { // Cannot write to a resource. return 0; } diff --git a/source/Engine/IO/SDLStream.cpp b/source/Engine/IO/SDLStream.cpp index 618dbf7c..c24cd46e 100644 --- a/source/Engine/IO/SDLStream.cpp +++ b/source/Engine/IO/SDLStream.cpp @@ -1,21 +1,6 @@ -#if INTERFACE -#include -#include -#include -class SDLStream : public Stream { -public: - SDL_RWops* f; - enum { - READ_ACCESS = 0, - WRITE_ACCESS = 1, - APPEND_ACCESS = 2, - }; -}; -#endif - #include -PUBLIC STATIC SDLStream* SDLStream::New(const char* filename, Uint32 access) { +SDLStream* SDLStream::New(const char* filename, Uint32 access) { SDLStream* stream = new SDLStream; if (!stream) { return NULL; @@ -40,32 +25,32 @@ PUBLIC STATIC SDLStream* SDLStream::New(const char* filename, Uint32 access) { return NULL; } -PUBLIC void SDLStream::Close() { +void SDLStream::Close() { SDL_RWclose(f); f = NULL; Stream::Close(); } -PUBLIC void SDLStream::Seek(Sint64 offset) { +void SDLStream::Seek(Sint64 offset) { SDL_RWseek(f, offset, RW_SEEK_SET); } -PUBLIC void SDLStream::SeekEnd(Sint64 offset) { +void SDLStream::SeekEnd(Sint64 offset) { SDL_RWseek(f, offset, RW_SEEK_END); } -PUBLIC void SDLStream::Skip(Sint64 offset) { +void SDLStream::Skip(Sint64 offset) { SDL_RWseek(f, offset, RW_SEEK_CUR); } -PUBLIC size_t SDLStream::Position() { +size_t SDLStream::Position() { return SDL_RWtell(f); } -PUBLIC size_t SDLStream::Length() { +size_t SDLStream::Length() { return SDL_RWsize(f); } -PUBLIC size_t SDLStream::ReadBytes(void* data, size_t n) { +size_t SDLStream::ReadBytes(void* data, size_t n) { // if (!f) Log::Print(Log::LOG_ERROR, "Attempt to read from closed stream.") return SDL_RWread(f, data, 1, n); } -PUBLIC size_t SDLStream::WriteBytes(void* data, size_t n) { +size_t SDLStream::WriteBytes(void* data, size_t n) { return SDL_RWwrite(f, data, 1, n); } diff --git a/source/Engine/IO/Serializer.cpp b/source/Engine/IO/Serializer.cpp index cffe5bfa..db800339 100644 --- a/source/Engine/IO/Serializer.cpp +++ b/source/Engine/IO/Serializer.cpp @@ -1,57 +1,3 @@ -#if INTERFACE -#include -#include - -class Serializer { -public: - std::map ObjToID; - std::vector ObjList; - Stream* StreamPtr; - - size_t StoredStreamPos; - size_t StoredChunkPos; - Uint32 CurrentChunkType; - - struct Chunk { - Uint32 Type; - size_t Offset; - size_t Size; - }; - std::vector ChunkList; - Serializer::Chunk LastChunk; - - struct String { - Uint32 Length; - char* Chars; - }; - std::vector StringList; - - enum { - CHUNK_OBJS = MakeFourCC("OBJS"), - CHUNK_TEXT = MakeFourCC("TEXT") - }; - - enum { - VAL_TYPE_NULL, - VAL_TYPE_INTEGER, - VAL_TYPE_DECIMAL, - VAL_TYPE_OBJECT, - - END = 0xFF - }; - - enum { - OBJ_TYPE_UNIMPLEMENTED, - OBJ_TYPE_STRING, - OBJ_TYPE_ARRAY, - OBJ_TYPE_MAP - }; - - static Uint32 Magic; - static Uint32 Version; -}; -#endif - #include #include @@ -59,7 +5,7 @@ class Serializer { Uint32 Serializer::Magic = 0x9D939FF0; Uint32 Serializer::Version = 0x00000001; -PUBLIC Serializer::Serializer(Stream* stream) { +Serializer::Serializer(Stream* stream) { StreamPtr = stream; ObjToID.clear(); ObjList.clear(); @@ -67,7 +13,7 @@ PUBLIC Serializer::Serializer(Stream* stream) { StringList.clear(); } -PRIVATE void Serializer::WriteValue(VMValue val) { +void Serializer::WriteValue(VMValue val) { switch (val.Type) { case VAL_DECIMAL: case VAL_LINKED_DECIMAL: { @@ -106,7 +52,7 @@ PRIVATE void Serializer::WriteValue(VMValue val) { } } -PRIVATE void Serializer::WriteObject(Obj* obj) { +void Serializer::WriteObject(Obj* obj) { switch (obj->Type) { case OBJ_STRING: { WriteObjectPreamble(Serializer::OBJ_TYPE_STRING); @@ -161,7 +107,7 @@ PRIVATE void Serializer::WriteObject(Obj* obj) { PatchObjectSize(); } -PRIVATE void Serializer::WriteObjectsChunk() { +void Serializer::WriteObjectsChunk() { BeginChunk(Serializer::CHUNK_OBJS); StreamPtr->WriteUInt32(ObjList.size()); @@ -173,7 +119,7 @@ PRIVATE void Serializer::WriteObjectsChunk() { AddChunkToList(); } -PRIVATE void Serializer::WriteTextChunk() { +void Serializer::WriteTextChunk() { BeginChunk(Serializer::CHUNK_TEXT); StreamPtr->WriteUInt32(StringList.size()); @@ -190,19 +136,19 @@ PRIVATE void Serializer::WriteTextChunk() { ChunkList.insert(ChunkList.begin(), LastChunk); } -PRIVATE Uint32 Serializer::GetUniqueObjectID(Obj* obj) { +Uint32 Serializer::GetUniqueObjectID(Obj* obj) { if (ObjToID.count(obj)) return ObjToID[obj]; return 0xFFFFFFFF; } -PRIVATE void Serializer::BeginChunk(Uint32 type) { +void Serializer::BeginChunk(Uint32 type) { CurrentChunkType = type; StoredChunkPos = StreamPtr->Position(); } -PRIVATE void Serializer::FinishChunk() { +void Serializer::FinishChunk() { LastChunk.Type = CurrentChunkType; LastChunk.Offset = StoredChunkPos; LastChunk.Size = StreamPtr->Position() - StoredChunkPos; @@ -211,18 +157,18 @@ PRIVATE void Serializer::FinishChunk() { StreamPtr->WriteByte(Serializer::END); } -PRIVATE void Serializer::AddChunkToList() { +void Serializer::AddChunkToList() { ChunkList.push_back(LastChunk); } -PRIVATE void Serializer::WriteObjectPreamble(Uint8 type) { +void Serializer::WriteObjectPreamble(Uint8 type) { StreamPtr->WriteByte(type); StreamPtr->WriteUInt32(0); // To be patched in later StoredStreamPos = StreamPtr->Position(); } -PRIVATE void Serializer::PatchObjectSize() { +void Serializer::PatchObjectSize() { size_t curPos = StreamPtr->Position(); size_t size = curPos - StoredStreamPos; StreamPtr->Seek(StoredStreamPos - 4); @@ -230,7 +176,7 @@ PRIVATE void Serializer::PatchObjectSize() { StreamPtr->Seek(curPos); } -PRIVATE void Serializer::AddUniqueString(char* chars, size_t length) { +void Serializer::AddUniqueString(char* chars, size_t length) { if (StringList.size() >= 0xFFFFFFFF) return; @@ -245,7 +191,7 @@ PRIVATE void Serializer::AddUniqueString(char* chars, size_t length) { StringList.push_back(str); } -PRIVATE Uint32 Serializer::GetUniqueStringID(char* chars, size_t length) { +Uint32 Serializer::GetUniqueStringID(char* chars, size_t length) { for (size_t i = 0; i < StringList.size(); i++) { if (StringList[i].Length == length && !memcmp(StringList[i].Chars, chars, length)) return (Uint32)i; @@ -254,7 +200,7 @@ PRIVATE Uint32 Serializer::GetUniqueStringID(char* chars, size_t length) { return 0xFFFFFFFF; } -PRIVATE void Serializer::AddUniqueObject(Obj* obj) { +void Serializer::AddUniqueObject(Obj* obj) { if (ObjToID.count(obj) || ObjList.size() >= 0xFFFFFFFF) return; @@ -292,7 +238,7 @@ PRIVATE void Serializer::AddUniqueObject(Obj* obj) { } } -PUBLIC void Serializer::Store(VMValue val) { +void Serializer::Store(VMValue val) { // Write header StreamPtr->WriteUInt32(Serializer::Magic); StreamPtr->WriteUInt32(Serializer::Version); @@ -345,7 +291,7 @@ PUBLIC void Serializer::Store(VMValue val) { ObjList.clear(); } -PRIVATE void Serializer::GetObject() { +void Serializer::GetObject() { Uint8 type = StreamPtr->ReadByte(); Uint32 size = StreamPtr->ReadUInt32(); switch (type) { @@ -388,7 +334,7 @@ PRIVATE void Serializer::GetObject() { } } -PRIVATE void Serializer::ReadObject(Obj* obj) { +void Serializer::ReadObject(Obj* obj) { Uint8 type = StreamPtr->ReadByte(); Uint32 size = StreamPtr->ReadUInt32(); switch (type) { @@ -428,7 +374,7 @@ PRIVATE void Serializer::ReadObject(Obj* obj) { } } -PRIVATE VMValue Serializer::ReadValue() { +VMValue Serializer::ReadValue() { Uint8 type = StreamPtr->ReadByte(); switch (type) { case Serializer::VAL_TYPE_INTEGER: @@ -455,7 +401,7 @@ PRIVATE VMValue Serializer::ReadValue() { return NULL_VAL; } -PUBLIC bool Serializer::ReadObjectsChunk() { +bool Serializer::ReadObjectsChunk() { // Read the object count Uint32 count = StreamPtr->ReadUInt32(); if (!count) @@ -479,7 +425,7 @@ PUBLIC bool Serializer::ReadObjectsChunk() { return StreamPtr->ReadByte() == Serializer::END; } -PUBLIC bool Serializer::ReadTextChunk() { +bool Serializer::ReadTextChunk() { // Read the count Uint32 count = StreamPtr->ReadUInt32(); @@ -499,7 +445,7 @@ PUBLIC bool Serializer::ReadTextChunk() { return StreamPtr->ReadByte() == Serializer::END; } -PUBLIC VMValue Serializer::Retrieve() { +VMValue Serializer::Retrieve() { Uint32 magic = StreamPtr->ReadUInt32(); if (magic != Serializer::Magic) { Log::Print(Log::LOG_ERROR, "Invalid magic!"); diff --git a/source/Engine/IO/Stream.cpp b/source/Engine/IO/Stream.cpp index 2f8f84c3..1ce953bc 100644 --- a/source/Engine/IO/Stream.cpp +++ b/source/Engine/IO/Stream.cpp @@ -1,11 +1,3 @@ -#if INTERFACE -#include -#include -class Stream { -public: -}; -#endif - #include #include #include @@ -14,23 +6,23 @@ class Stream { type data; \ ReadBytes(&data, sizeof(data)); -PUBLIC VIRTUAL void Stream::Close() { - delete this; +void Stream::Close() { + delete this; } -PUBLIC VIRTUAL void Stream::Seek(Sint64 offset) { +void Stream::Seek(Sint64 offset) { } -PUBLIC VIRTUAL void Stream::SeekEnd(Sint64 offset) { +void Stream::SeekEnd(Sint64 offset) { } -PUBLIC VIRTUAL void Stream::Skip(Sint64 offset) { +void Stream::Skip(Sint64 offset) { } -PUBLIC VIRTUAL size_t Stream::Position() { - return 0; +size_t Stream::Position() { + return 0; } -PUBLIC VIRTUAL size_t Stream::Length() { - return 0; +size_t Stream::Length() { + return 0; } -PUBLIC VIRTUAL size_t Stream::ReadBytes(void* data, size_t n) { +size_t Stream::ReadBytes(void* data, size_t n) { #if DEBUG if (Position() + n > Length()) { Log::Print(Log::LOG_ERROR, "Attempted to read past stream."); @@ -39,51 +31,51 @@ PUBLIC VIRTUAL size_t Stream::ReadBytes(void* data, size_t n) { #endif return 0; } -PUBLIC Uint8 Stream::ReadByte() { +Uint8 Stream::ReadByte() { READ_TYPE_MACRO(Uint8); return data; } -PUBLIC Uint16 Stream::ReadUInt16() { +Uint16 Stream::ReadUInt16() { READ_TYPE_MACRO(Uint16); return data; } -PUBLIC Uint16 Stream::ReadUInt16BE() { +Uint16 Stream::ReadUInt16BE() { return (Uint16)(ReadByte() << 8 | ReadByte()); } -PUBLIC Uint32 Stream::ReadUInt32() { +Uint32 Stream::ReadUInt32() { READ_TYPE_MACRO(Uint32); return data; } -PUBLIC Uint32 Stream::ReadUInt32BE() { +Uint32 Stream::ReadUInt32BE() { return (Uint32)(ReadByte() << 24 | ReadByte() << 16 | ReadByte() << 8 | ReadByte()); } -PUBLIC Uint64 Stream::ReadUInt64() { +Uint64 Stream::ReadUInt64() { READ_TYPE_MACRO(Uint64); return data; } -PUBLIC Sint16 Stream::ReadInt16() { +Sint16 Stream::ReadInt16() { READ_TYPE_MACRO(Sint16); return data; } -PUBLIC Sint16 Stream::ReadInt16BE() { +Sint16 Stream::ReadInt16BE() { return (Sint16)(ReadByte() << 8 | ReadByte()); } -PUBLIC Sint32 Stream::ReadInt32() { +Sint32 Stream::ReadInt32() { READ_TYPE_MACRO(Sint32); return data; } -PUBLIC Sint32 Stream::ReadInt32BE() { +Sint32 Stream::ReadInt32BE() { return (Sint32)(ReadByte() << 24 | ReadByte() << 16 | ReadByte() << 8 | ReadByte()); } -PUBLIC Sint64 Stream::ReadInt64() { +Sint64 Stream::ReadInt64() { READ_TYPE_MACRO(Sint64); return data; } -PUBLIC float Stream::ReadFloat() { +float Stream::ReadFloat() { READ_TYPE_MACRO(float); return data; } -PUBLIC char* Stream::ReadLine() { +char* Stream::ReadLine() { Uint8 byte = 0; size_t start = Position(); while ((byte = ReadByte()) != '\n' && byte); @@ -97,7 +89,7 @@ PUBLIC char* Stream::ReadLine() { return data; } -PUBLIC char* Stream::ReadString() { +char* Stream::ReadString() { size_t start = Position(); while (ReadByte()); @@ -110,10 +102,10 @@ PUBLIC char* Stream::ReadString() { return data; } -PUBLIC void Stream::SkipString() { +void Stream::SkipString() { while (ReadByte()); } -PUBLIC Uint16* Stream::ReadUnicodeString() { +Uint16* Stream::ReadUnicodeString() { size_t start = Position(); while (ReadUInt16()); @@ -125,8 +117,8 @@ PUBLIC Uint16* Stream::ReadUnicodeString() { return data; } -PUBLIC char* Stream::ReadHeaderedString() { - Uint8 size = ReadByte(); +char* Stream::ReadHeaderedString() { + Uint8 size = ReadByte(); char* data = (char*)Memory::TrackedMalloc("Stream::ReadHeaderedString", size + 1); ReadBytes(data, size); @@ -134,7 +126,7 @@ PUBLIC char* Stream::ReadHeaderedString() { return data; } -PUBLIC VIRTUAL Uint32 Stream::ReadCompressed(void* out) { +Uint32 Stream::ReadCompressed(void* out) { Uint32 compressed_size = ReadUInt32() - 4; Uint32 uncompressed_size = ReadUInt32BE(); @@ -146,7 +138,7 @@ PUBLIC VIRTUAL Uint32 Stream::ReadCompressed(void* out) { return uncompressed_size; } -PUBLIC VIRTUAL Uint32 Stream::ReadCompressed(void* out, size_t outSz) { +Uint32 Stream::ReadCompressed(void* out, size_t outSz) { Uint32 compressed_size = ReadUInt32() - 4; ReadUInt32BE(); // uncompressed_size @@ -159,60 +151,60 @@ PUBLIC VIRTUAL Uint32 Stream::ReadCompressed(void* out, size_t outSz) { return (Uint32)outSz; } -PUBLIC VIRTUAL size_t Stream::WriteBytes(void* data, size_t n) { +size_t Stream::WriteBytes(void* data, size_t n) { return 0; } -PUBLIC void Stream::WriteByte(Uint8 data) { +void Stream::WriteByte(Uint8 data) { WriteBytes(&data, sizeof(data)); } -PUBLIC void Stream::WriteUInt16(Uint16 data) { +void Stream::WriteUInt16(Uint16 data) { WriteBytes(&data, sizeof(data)); } -PUBLIC void Stream::WriteUInt16BE(Uint16 data) { +void Stream::WriteUInt16BE(Uint16 data) { WriteByte(data >> 8 & 0xFF); WriteByte(data & 0xFF); } -PUBLIC void Stream::WriteUInt32(Uint32 data) { +void Stream::WriteUInt32(Uint32 data) { WriteBytes(&data, sizeof(data)); } -PUBLIC void Stream::WriteUInt32BE(Uint32 data) { +void Stream::WriteUInt32BE(Uint32 data) { WriteByte(data >> 24 & 0xFF); WriteByte(data >> 16 & 0xFF); WriteByte(data >> 8 & 0xFF); WriteByte(data & 0xFF); } -PUBLIC void Stream::WriteUInt64(Uint64 data) { +void Stream::WriteUInt64(Uint64 data) { WriteBytes(&data, sizeof(data)); } -PUBLIC void Stream::WriteInt16(Sint16 data) { +void Stream::WriteInt16(Sint16 data) { WriteBytes(&data, sizeof(data)); } -PUBLIC void Stream::WriteInt16BE(Sint16 data) { +void Stream::WriteInt16BE(Sint16 data) { WriteUInt16BE((Uint16)data); } -PUBLIC void Stream::WriteInt32(Sint32 data) { + void Stream::WriteInt32(Sint32 data) { WriteBytes(&data, sizeof(data)); } -PUBLIC void Stream::WriteInt32BE(Sint32 data) { +void Stream::WriteInt32BE(Sint32 data) { WriteUInt32BE((Sint32)data); } -PUBLIC void Stream::WriteInt64(Sint64 data) { +void Stream::WriteInt64(Sint64 data) { WriteBytes(&data, sizeof(data)); } -PUBLIC void Stream::WriteFloat(float data) { +void Stream::WriteFloat(float data) { WriteBytes(&data, sizeof(data)); } -PUBLIC void Stream::WriteString(const char* string) { +void Stream::WriteString(const char* string) { size_t size = strlen(string) + 1; WriteBytes((void*)string, size); } -PUBLIC void Stream::WriteHeaderedString(const char* string) { +void Stream::WriteHeaderedString(const char* string) { size_t size = strlen(string) + 1; WriteByte((Uint8)size); WriteBytes((void*)string, size); } -PUBLIC void Stream::CopyTo(Stream* dest) { +void Stream::CopyTo(Stream* dest) { size_t length = Length() - Position(); void* memory = Memory::Malloc(length); @@ -224,5 +216,5 @@ PUBLIC void Stream::CopyTo(Stream* dest) { Memory::Free(memory); } -PUBLIC VIRTUAL Stream::~Stream() { +Stream::~Stream() { } diff --git a/source/Engine/Includes/StandardSDL2.h b/source/Engine/Includes/StandardSDL2.h index 41c735c7..7057dff4 100644 --- a/source/Engine/Includes/StandardSDL2.h +++ b/source/Engine/Includes/StandardSDL2.h @@ -5,13 +5,8 @@ // SDL2 includes #include #elif MACOSX - #if USING_FRAMEWORK - // SDL2 includes - #include - #else - // SDL2 includes - #include - #endif + // SDL2 includes + #include #elif SWITCH // SDL2 includes #include diff --git a/source/Engine/Input/Controller.cpp b/source/Engine/Input/Controller.cpp index 54c0d755..5f3caffe 100644 --- a/source/Engine/Input/Controller.cpp +++ b/source/Engine/Input/Controller.cpp @@ -1,35 +1,12 @@ -#if INTERFACE -#include -#include -#include -#include - -class Controller { -public: - ControllerType Type; - bool Connected; - - bool* ButtonsPressed; - bool* ButtonsHeld; - float* AxisValues; - - ControllerRumble* Rumble; - - SDL_GameController* Device; - SDL_Joystick* JoystickDevice; - SDL_JoystickID JoystickID; -}; -#endif - #include #include -PUBLIC Controller::Controller(int index) { +Controller::Controller(int index) { Reset(); Open(index); } -PUBLIC Controller::~Controller() { +Controller::~Controller() { Close(); } @@ -75,7 +52,7 @@ static SDL_GameControllerAxis AxisEnums[] = { #undef CONST_AXIS -PRIVATE STATIC ControllerType Controller::DetermineType(void* gamecontroller) { +ControllerType Controller::DetermineType(void* gamecontroller) { switch (SDL_GameControllerGetType((SDL_GameController*)gamecontroller)) { case SDL_CONTROLLER_TYPE_XBOX360: return ControllerType::Xbox360; @@ -110,7 +87,7 @@ PRIVATE STATIC ControllerType Controller::DetermineType(void* gamecontroller) { } } -PUBLIC bool Controller::Open(int index) { +bool Controller::Open(int index) { Device = SDL_GameControllerOpen(index); if (!Device) return false; @@ -130,7 +107,7 @@ PUBLIC bool Controller::Open(int index) { return true; } -PUBLIC void Controller::Close() { +void Controller::Close() { if (Rumble) { Rumble->Stop(); delete Rumble; @@ -156,7 +133,7 @@ PUBLIC void Controller::Close() { Reset(); } -PUBLIC void Controller::Reset() { +void Controller::Reset() { Type = ControllerType::Unknown; Connected = false; Device = nullptr; @@ -165,38 +142,38 @@ PUBLIC void Controller::Reset() { JoystickID = -1; } -PUBLIC char* Controller::GetName() { +char* Controller::GetName() { return (char*)SDL_GameControllerName(Device); } // Sets the LEDs in some controllers -PUBLIC void Controller::SetPlayerIndex(int index) { +void Controller::SetPlayerIndex(int index) { SDL_GameControllerSetPlayerIndex(Device, index); } -PUBLIC bool Controller::GetButton(int button) { +bool Controller::GetButton(int button) { if (button >= (int)ControllerButton::Max) return false; return SDL_GameControllerGetButton(Device, ButtonEnums[button]); } -PUBLIC bool Controller::IsButtonHeld(int button) { +bool Controller::IsButtonHeld(int button) { if (button < 0 || button >= (int)ControllerButton::Max) return false; return ButtonsHeld[button]; } -PUBLIC bool Controller::IsButtonPressed(int button) { +bool Controller::IsButtonPressed(int button) { if (button < 0 || button >= (int)ControllerButton::Max) return false; return ButtonsPressed[button]; } -PUBLIC float Controller::GetAxis(int axis) { +float Controller::GetAxis(int axis) { if (axis < 0 || axis >= (int)ControllerAxis::Max) return 0.0f; return AxisValues[axis]; } -PUBLIC void Controller::Update() { +void Controller::Update() { if (Rumble) Rumble->Update(); @@ -212,30 +189,30 @@ PUBLIC void Controller::Update() { } } -PUBLIC bool Controller::IsXbox() { +bool Controller::IsXbox() { return Type == ControllerType::Xbox360 || Type == ControllerType::XboxOne || Type == ControllerType::XboxSeriesXS || Type == ControllerType::XboxElite; } -PUBLIC bool Controller::IsPlayStation() { +bool Controller::IsPlayStation() { return Type == ControllerType::PS3 || Type == ControllerType::PS4 || Type == ControllerType::PS5; } -PUBLIC bool Controller::IsJoyCon() { +bool Controller::IsJoyCon() { return Type == ControllerType::SwitchJoyConLeft || Type == ControllerType::SwitchJoyConRight; } -PUBLIC bool Controller::HasShareButton() { +bool Controller::HasShareButton() { return Type == ControllerType::XboxSeriesXS || Type == ControllerType::SwitchPro || Type == ControllerType::SwitchJoyConLeft; } -PUBLIC bool Controller::HasMicrophoneButton() { +bool Controller::HasMicrophoneButton() { return Type == ControllerType::PS5 || Type == ControllerType::AmazonLuna; } -PUBLIC bool Controller::HasPaddles() { +bool Controller::HasPaddles() { return Type == ControllerType::XboxElite; } diff --git a/source/Engine/Input/ControllerRumble.h b/source/Engine/Input/ControllerRumble.h index 2b67727b..c97e6fd0 100644 --- a/source/Engine/Input/ControllerRumble.h +++ b/source/Engine/Input/ControllerRumble.h @@ -1,6 +1,8 @@ #ifndef CONTROLLERRUMBLE_H #define CONTROLLERRUMBLE_H +#include + struct ControllerRumble { float LargeMotorFrequency; float SmallMotorFrequency; diff --git a/source/Engine/Input/Input.h b/source/Engine/Input/Input.h index b88fa2d8..d012c8db 100644 --- a/source/Engine/Input/Input.h +++ b/source/Engine/Input/Input.h @@ -1,6 +1,8 @@ #ifndef INPUT_H #define INPUT_H +#include + enum Keyboard { Key_UNKNOWN = -1, diff --git a/source/Engine/Input/InputAction.cpp b/source/Engine/Input/InputAction.cpp index ceeb5bf8..d09ff11c 100644 --- a/source/Engine/Input/InputAction.cpp +++ b/source/Engine/Input/InputAction.cpp @@ -1,20 +1,9 @@ -#if INTERFACE -#include -#include - -class InputAction { -public: - unsigned ID; - string Name; -}; -#endif - #include -PUBLIC InputAction::InputAction(const char* name, unsigned id) { +InputAction::InputAction(const char* name, unsigned id) { Name = std::string(name); ID = id; } -PUBLIC InputAction::~InputAction() { +InputAction::~InputAction() { } diff --git a/source/Engine/Input/InputPlayer.cpp b/source/Engine/Input/InputPlayer.cpp index 9f5bbfb4..ee0f31a9 100644 --- a/source/Engine/Input/InputPlayer.cpp +++ b/source/Engine/Input/InputPlayer.cpp @@ -1,45 +1,12 @@ -#if INTERFACE -#include -#include -#include - -class InputPlayer { -public: - int ID; - - vector Binds; - vector DefaultBinds; - - PlayerInputStatus Status[InputDevice_MAX]; - PlayerInputStatus AllStatus; - - vector NumHeld; - vector NumPressed; - vector NumReleased; - - bool AnyHeld; - bool AnyPressed; - bool AnyReleased; - - vector ControllerState; - - bool IsUsingDevice[InputDevice_MAX]; - - int ControllerIndex = -1; - - const char* ConfigFilename = nullptr; -}; -#endif - #include #include #include -PUBLIC InputPlayer::InputPlayer(int id) { +InputPlayer::InputPlayer(int id) { ID = id; } -PUBLIC void InputPlayer::SetNumActions(size_t num) { +void InputPlayer::SetNumActions(size_t num) { size_t oldNum = Binds.size(); Binds.resize(num); @@ -66,12 +33,12 @@ PUBLIC void InputPlayer::SetNumActions(size_t num) { AllStatus.SetNumActions(num); } -PUBLIC void InputPlayer::ClearBinds() { +void InputPlayer::ClearBinds() { for (size_t i = 0; i < Binds.size(); i++) { Binds[i].Clear(); } } -PUBLIC void InputPlayer::ResetBinds() { +void InputPlayer::ResetBinds() { for (size_t i = 0; i < DefaultBinds.size(); i++) { Binds[i].Clear(); @@ -82,7 +49,7 @@ PUBLIC void InputPlayer::ResetBinds() { } } -PUBLIC void InputPlayer::Update() { +void InputPlayer::Update() { IsUsingDevice[InputDevice_Keyboard] = false; IsUsingDevice[InputDevice_Controller] = false; @@ -164,13 +131,13 @@ PUBLIC void InputPlayer::Update() { } } -PRIVATE size_t InputPlayer::PushBindToList(PlayerInputConfig& config, InputBind* def) { +size_t InputPlayer::PushBindToList(PlayerInputConfig& config, InputBind* def) { config.Binds.push_back(def); return config.Binds.size() - 1; } -PRIVATE bool InputPlayer::ReplaceBindInList(PlayerInputConfig& config, InputBind* def, unsigned index) { +bool InputPlayer::ReplaceBindInList(PlayerInputConfig& config, InputBind* def, unsigned index) { if (index >= 0 && index < config.Binds.size()) { if (config.Binds[index]) delete config.Binds[index]; @@ -181,7 +148,7 @@ PRIVATE bool InputPlayer::ReplaceBindInList(PlayerInputConfig& config, InputBind return false; } -PRIVATE bool InputPlayer::RemoveBindFromList(PlayerInputConfig& config, unsigned index) { +bool InputPlayer::RemoveBindFromList(PlayerInputConfig& config, unsigned index) { if (index >= 0 && index < config.Binds.size()) { config.Binds.erase(config.Binds.begin() + index); return true; @@ -190,7 +157,7 @@ PRIVATE bool InputPlayer::RemoveBindFromList(PlayerInputConfig& config, unsigned return false; } -PUBLIC int InputPlayer::AddBind(unsigned num, InputBind* bind) { +int InputPlayer::AddBind(unsigned num, InputBind* bind) { if (num < Binds.size()) { return (int)PushBindToList(Binds[num], bind); } @@ -198,46 +165,46 @@ PUBLIC int InputPlayer::AddBind(unsigned num, InputBind* bind) { return -1; } -PUBLIC bool InputPlayer::ReplaceBind(unsigned num, InputBind* bind, unsigned index) { +bool InputPlayer::ReplaceBind(unsigned num, InputBind* bind, unsigned index) { if (num < Binds.size()) { return ReplaceBindInList(Binds[num], bind, index); } return false; } -PUBLIC bool InputPlayer::RemoveBind(unsigned num, unsigned index) { +bool InputPlayer::RemoveBind(unsigned num, unsigned index) { if (num < Binds.size()) { return RemoveBindFromList(Binds[num], index); } return false; } -PRIVATE InputBind* InputPlayer::GetBindAtIndex(PlayerInputConfig& config, unsigned index) { +InputBind* InputPlayer::GetBindAtIndex(PlayerInputConfig& config, unsigned index) { if (config.Binds.size() > 0 && index < config.Binds.size()) return config.Binds[index]; return nullptr; } -PRIVATE size_t InputPlayer::GetBindCount(PlayerInputConfig& config) { +size_t InputPlayer::GetBindCount(PlayerInputConfig& config) { return config.Binds.size(); } -PUBLIC InputBind* InputPlayer::GetBind(unsigned num, unsigned index) { +InputBind* InputPlayer::GetBind(unsigned num, unsigned index) { if (num < Binds.size()) return GetBindAtIndex(Binds[num], index); return nullptr; } -PUBLIC size_t InputPlayer::GetBindCount(unsigned num) { +size_t InputPlayer::GetBindCount(unsigned num) { if (num < Binds.size()) return GetBindCount(Binds[num]); return 0; } -PUBLIC int InputPlayer::AddDefaultBind(unsigned num, InputBind* bind) { +int InputPlayer::AddDefaultBind(unsigned num, InputBind* bind) { if (num < DefaultBinds.size()) { return (int)PushBindToList(DefaultBinds[num], bind); } @@ -245,7 +212,7 @@ PUBLIC int InputPlayer::AddDefaultBind(unsigned num, InputBind* bind) { return -1; } -PRIVATE void InputPlayer::CopyDefaultBinds(InputPlayer& src, bool filter, int filterType) { +void InputPlayer::CopyDefaultBinds(InputPlayer& src, bool filter, int filterType) { for (size_t i = 0; i < src.Binds.size(); i++) { PlayerInputConfig& config = src.Binds[i]; for (size_t j = 0; j < config.Binds.size(); j++) { @@ -256,43 +223,43 @@ PRIVATE void InputPlayer::CopyDefaultBinds(InputPlayer& src, bool filter, int fi } } -PUBLIC void InputPlayer::CopyDefaultBinds(InputPlayer& src) { +void InputPlayer::CopyDefaultBinds(InputPlayer& src) { CopyDefaultBinds(src, false, 0); } -PUBLIC void InputPlayer::CopyDefaultBinds(InputPlayer& src, int filterType) { +void InputPlayer::CopyDefaultBinds(InputPlayer& src, int filterType) { CopyDefaultBinds(src, true, filterType); } -PUBLIC bool InputPlayer::ReplaceDefaultBind(unsigned num, InputBind* bind, unsigned index) { +bool InputPlayer::ReplaceDefaultBind(unsigned num, InputBind* bind, unsigned index) { if (num < DefaultBinds.size()) { return ReplaceBindInList(DefaultBinds[num], bind, index); } return false; } -PUBLIC bool InputPlayer::RemoveDefaultBind(unsigned num, unsigned index) { +bool InputPlayer::RemoveDefaultBind(unsigned num, unsigned index) { if (num < DefaultBinds.size()) { return RemoveBindFromList(DefaultBinds[num], index); } return false; } -PUBLIC InputBind* InputPlayer::GetDefaultBind(unsigned num, unsigned index) { +InputBind* InputPlayer::GetDefaultBind(unsigned num, unsigned index) { if (num < DefaultBinds.size()) return GetBindAtIndex(DefaultBinds[num], index); return nullptr; } -PUBLIC size_t InputPlayer::GetDefaultBindCount(unsigned num) { +size_t InputPlayer::GetDefaultBindCount(unsigned num) { if (num < DefaultBinds.size()) return GetBindCount(DefaultBinds[num]); return 0; } -PUBLIC bool InputPlayer::IsBindIndexValid(unsigned num, unsigned index) { +bool InputPlayer::IsBindIndexValid(unsigned num, unsigned index) { if (num < Binds.size()) { return index < Binds[num].Binds.size(); } @@ -300,17 +267,17 @@ PUBLIC bool InputPlayer::IsBindIndexValid(unsigned num, unsigned index) { return false; } -PUBLIC void InputPlayer::ClearBinds(unsigned num) { +void InputPlayer::ClearBinds(unsigned num) { if (num < Binds.size()) Binds[num].Binds.clear(); } -PUBLIC void InputPlayer::ClearDefaultBinds(unsigned num) { +void InputPlayer::ClearDefaultBinds(unsigned num) { if (num < DefaultBinds.size()) DefaultBinds[num].Binds.clear(); } -PRIVATE void InputPlayer::ResetBindList(PlayerInputConfig &dest, PlayerInputConfig &src) { +void InputPlayer::ResetBindList(PlayerInputConfig &dest, PlayerInputConfig &src) { dest.Binds.clear(); for (size_t i = 0; i < src.Binds.size(); i++) { @@ -318,13 +285,13 @@ PRIVATE void InputPlayer::ResetBindList(PlayerInputConfig &dest, PlayerInputConf } } -PUBLIC void InputPlayer::ResetBind(unsigned num) { +void InputPlayer::ResetBind(unsigned num) { if (num < Binds.size() && num < DefaultBinds.size()) { ResetBindList(Binds[num], DefaultBinds[num]); } } -PRIVATE bool InputPlayer::CheckInputBindState(InputBind* bind, bool held) { +bool InputPlayer::CheckInputBindState(InputBind* bind, bool held) { if (bind->IsDefined() && bind->Type == INPUT_BIND_KEYBOARD) { KeyboardBind* keyBind = static_cast(bind); @@ -342,7 +309,7 @@ PRIVATE bool InputPlayer::CheckInputBindState(InputBind* bind, bool held) { return false; } -PRIVATE bool InputPlayer::CheckIfInputHeld(unsigned actionID, unsigned device) { +bool InputPlayer::CheckIfInputHeld(unsigned actionID, unsigned device) { if (actionID >= InputManager::Actions.size()) return false; @@ -362,7 +329,7 @@ PRIVATE bool InputPlayer::CheckIfInputHeld(unsigned actionID, unsigned device) { return false; } -PRIVATE bool InputPlayer::CheckIfInputPressed(unsigned actionID, unsigned device) { +bool InputPlayer::CheckIfInputPressed(unsigned actionID, unsigned device) { if (actionID >= InputManager::Actions.size()) return false; @@ -383,74 +350,74 @@ PRIVATE bool InputPlayer::CheckIfInputPressed(unsigned actionID, unsigned device return false; } -PUBLIC bool InputPlayer::IsInputHeld(unsigned actionID, unsigned device) { +bool InputPlayer::IsInputHeld(unsigned actionID, unsigned device) { if (actionID >= InputManager::Actions.size() || device >= InputDevice_Controller) return false; Uint8 state = Status[device].State[actionID]; return state == INPUT_STATE_PRESSED || state == INPUT_STATE_HELD; } -PUBLIC bool InputPlayer::IsInputPressed(unsigned actionID, unsigned device) { +bool InputPlayer::IsInputPressed(unsigned actionID, unsigned device) { if (actionID >= InputManager::Actions.size() || device >= InputDevice_Controller) return false; return Status[device].State[actionID] == INPUT_STATE_PRESSED; } -PUBLIC bool InputPlayer::IsInputReleased(unsigned actionID, unsigned device) { +bool InputPlayer::IsInputReleased(unsigned actionID, unsigned device) { if (actionID >= InputManager::Actions.size() || device >= InputDevice_Controller) return false; return Status[device].State[actionID] == INPUT_STATE_RELEASED; } -PUBLIC bool InputPlayer::IsAnyInputHeld(unsigned device) { +bool InputPlayer::IsAnyInputHeld(unsigned device) { if (device >= InputDevice_Controller) return false; return Status[device].NumHeld != 0; } -PUBLIC bool InputPlayer::IsAnyInputPressed(unsigned device) { +bool InputPlayer::IsAnyInputPressed(unsigned device) { if (device >= InputDevice_Controller) return false; return Status[device].NumPressed != 0; } -PUBLIC bool InputPlayer::IsAnyInputReleased(unsigned device) { +bool InputPlayer::IsAnyInputReleased(unsigned device) { if (device >= InputDevice_Controller) return false; return Status[device].NumReleased != 0; } -PUBLIC bool InputPlayer::IsInputHeld(unsigned actionID) { +bool InputPlayer::IsInputHeld(unsigned actionID) { if (actionID >= InputManager::Actions.size()) return false; Uint8 state = AllStatus.State[actionID]; return state == INPUT_STATE_PRESSED || state == INPUT_STATE_HELD; } -PUBLIC bool InputPlayer::IsInputPressed(unsigned actionID) { +bool InputPlayer::IsInputPressed(unsigned actionID) { if (actionID >= InputManager::Actions.size()) return false; return AllStatus.State[actionID] == INPUT_STATE_PRESSED; } -PUBLIC bool InputPlayer::IsInputReleased(unsigned actionID) { +bool InputPlayer::IsInputReleased(unsigned actionID) { if (actionID >= InputManager::Actions.size()) return false; return AllStatus.State[actionID] == INPUT_STATE_RELEASED; } -PUBLIC bool InputPlayer::IsAnyInputHeld() { +bool InputPlayer::IsAnyInputHeld() { return AnyHeld; } -PUBLIC bool InputPlayer::IsAnyInputPressed() { +bool InputPlayer::IsAnyInputPressed() { return AnyPressed; } -PUBLIC bool InputPlayer::IsAnyInputReleased() { +bool InputPlayer::IsAnyInputReleased() { return AnyReleased; } -PUBLIC float InputPlayer::GetAnalogActionInput(unsigned actionID) { +float InputPlayer::GetAnalogActionInput(unsigned actionID) { if (actionID >= InputManager::Actions.size()) return false; @@ -464,11 +431,11 @@ PUBLIC float InputPlayer::GetAnalogActionInput(unsigned actionID) { return result; } -PRIVATE bool InputPlayer::IsControllerBindHeld(unsigned num) { +bool InputPlayer::IsControllerBindHeld(unsigned num) { Uint8 state = ControllerState[num]; return state == INPUT_STATE_PRESSED || state == INPUT_STATE_HELD; } -PRIVATE bool InputPlayer::IsControllerBindPressed(unsigned num) { +bool InputPlayer::IsControllerBindPressed(unsigned num) { return ControllerState[num] == INPUT_STATE_PRESSED; } @@ -522,7 +489,7 @@ static bool CheckControllerBindHeld(PlayerInputConfig& config, Controller* contr return false; } -PRIVATE void InputPlayer::UpdateControllerBind(unsigned num) { +void InputPlayer::UpdateControllerBind(unsigned num) { Controller* controller = InputManager::GetController(ControllerIndex); if (CheckControllerBindHeld(Binds[num], controller)) { @@ -536,7 +503,7 @@ PRIVATE void InputPlayer::UpdateControllerBind(unsigned num) { else if (ControllerState[num] != INPUT_STATE_UNPUSHED) ControllerState[num] = INPUT_STATE_UNPUSHED; } -PRIVATE bool InputPlayer::GetAnalogControllerBind(unsigned num, float& result) { +bool InputPlayer::GetAnalogControllerBind(unsigned num, float& result) { if (ControllerIndex == -1) return false; diff --git a/source/Engine/InputManager.cpp b/source/Engine/InputManager.cpp index 48644b70..76dd4129 100644 --- a/source/Engine/InputManager.cpp +++ b/source/Engine/InputManager.cpp @@ -1,40 +1,3 @@ -#if INTERFACE -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class InputManager { -public: - static float MouseX; - static float MouseY; - static int MouseDown; - static int MousePressed; - static int MouseReleased; - - static Uint8 KeyboardState[0x120]; - static Uint8 KeyboardStateLast[0x120]; - static Uint16 KeymodState; - static SDL_Scancode KeyToSDLScancode[NUM_KEYBOARD_KEYS]; - - static int NumControllers; - static vector Controllers; - - static SDL_TouchID TouchDevice; - static void* TouchStates; - - static vector Players; - static vector Actions; -}; -#endif - #include #include @@ -69,7 +32,7 @@ struct TouchState { bool Released; }; -PUBLIC STATIC void InputManager::Init() { +void InputManager::Init() { memset(KeyboardState, 0, NUM_KEYBOARD_KEYS); memset(KeyboardStateLast, 0, NUM_KEYBOARD_KEYS); @@ -95,7 +58,7 @@ namespace NameMap { BijectiveMap* Axes; } -PRIVATE STATIC void InputManager::InitStringLookup() { +void InputManager::InitStringLookup() { NameMap::Keys = new BijectiveMap(); NameMap::Buttons = new BijectiveMap(); NameMap::Axes = new BijectiveMap(); @@ -268,17 +231,17 @@ PRIVATE STATIC void InputManager::InitStringLookup() { KeymodStrToFlags.insert({ "capslock", KB_MODIFIER_CAPS }); } -PUBLIC STATIC char* InputManager::GetKeyName(int key) { +char* InputManager::GetKeyName(int key) { if (!NameMap::Keys->Exists(key)) return nullptr; return (char*)NameMap::Keys->Get(key); } -PUBLIC STATIC char* InputManager::GetButtonName(int button) { +char* InputManager::GetButtonName(int button) { if (!NameMap::Buttons->Exists(button)) return nullptr; return (char*)NameMap::Buttons->Get(button); } -PUBLIC STATIC char* InputManager::GetAxisName(int axis) { +char* InputManager::GetAxisName(int axis) { if (!NameMap::Axes->Exists(axis)) return nullptr; return (char*)NameMap::Axes->Get(axis); @@ -296,19 +259,19 @@ PUBLIC STATIC char* InputManager::GetAxisName(int axis) { return found; \ } -PUBLIC STATIC int InputManager::ParseKeyName(const char* key) { +int InputManager::ParseKeyName(const char* key) { FIND_IN_BIJECTIVE(NameMap::Keys, key); } -PUBLIC STATIC int InputManager::ParseButtonName(const char* button) { +int InputManager::ParseButtonName(const char* button) { FIND_IN_BIJECTIVE(NameMap::Buttons, button); } -PUBLIC STATIC int InputManager::ParseAxisName(const char* axis) { +int InputManager::ParseAxisName(const char* axis) { FIND_IN_BIJECTIVE(NameMap::Axes, axis); } #undef FIND_IN_BIJECTIVE -PUBLIC STATIC Controller* InputManager::OpenController(int index) { +Controller* InputManager::OpenController(int index) { Controller* controller = new Controller(index); if (controller->Device == nullptr) { Log::Print(Log::LOG_ERROR, "Opening controller %d failed: %s", index, SDL_GetError()); @@ -320,7 +283,7 @@ PUBLIC STATIC Controller* InputManager::OpenController(int index) { return controller; } -PUBLIC STATIC void InputManager::InitControllers() { +void InputManager::InitControllers() { int numControllers = 0; int numJoysticks = SDL_NumJoysticks(); for (int i = 0; i < numJoysticks; i++) { @@ -345,7 +308,7 @@ PUBLIC STATIC void InputManager::InitControllers() { } } -PRIVATE STATIC int InputManager::FindController(int joystickID) { +int InputManager::FindController(int joystickID) { for (int i = 0; i < InputManager::NumControllers; i++) { Controller* controller = InputManager::Controllers[i]; if (controller->Connected && controller->JoystickID == joystickID) @@ -355,7 +318,7 @@ PRIVATE STATIC int InputManager::FindController(int joystickID) { return -1; } -PUBLIC STATIC bool InputManager::AddController(int index) { +bool InputManager::AddController(int index) { Controller* controller; for (int i = 0; i < InputManager::NumControllers; i++) { controller = InputManager::Controllers[i]; @@ -373,7 +336,7 @@ PUBLIC STATIC bool InputManager::AddController(int index) { return true; } -PUBLIC STATIC void InputManager::RemoveController(int joystickID) { +void InputManager::RemoveController(int joystickID) { int controller_id = InputManager::FindController(joystickID); if (controller_id == -1) return; @@ -381,7 +344,7 @@ PUBLIC STATIC void InputManager::RemoveController(int joystickID) { InputManager::Controllers[controller_id]->Close(); } -PUBLIC STATIC void InputManager::Poll() { +void InputManager::Poll() { if (Application::Platform == Platforms::iOS || Application::Platform == Platforms::Android || Application::Platform == Platforms::Switch) { @@ -492,134 +455,134 @@ PUBLIC STATIC void InputManager::Poll() { InputManager::Players[i].Update(); } -PUBLIC STATIC Uint16 InputManager::CheckKeyModifiers(Uint16 modifiers) { +Uint16 InputManager::CheckKeyModifiers(Uint16 modifiers) { return (KeymodState & modifiers) == modifiers; } -PUBLIC STATIC bool InputManager::IsKeyDown(int key) { +bool InputManager::IsKeyDown(int key) { int scancode = (int)KeyToSDLScancode[key]; return KeyboardState[scancode]; } -PUBLIC STATIC bool InputManager::IsKeyPressed(int key) { +bool InputManager::IsKeyPressed(int key) { int scancode = (int)KeyToSDLScancode[key]; return KeyboardState[scancode] && !KeyboardStateLast[scancode]; } -PUBLIC STATIC bool InputManager::IsKeyReleased(int key) { +bool InputManager::IsKeyReleased(int key) { int scancode = (int)KeyToSDLScancode[key]; return !KeyboardState[scancode] && KeyboardStateLast[scancode]; } -PUBLIC STATIC Controller* InputManager::GetController(int index) { +Controller* InputManager::GetController(int index) { if (index >= 0 && index < InputManager::NumControllers) { return InputManager::Controllers[index]; } return nullptr; } -PUBLIC STATIC bool InputManager::ControllerIsConnected(int index) { +bool InputManager::ControllerIsConnected(int index) { Controller* controller = GetController(index); if (controller) return controller->Connected; return false; } -PUBLIC STATIC bool InputManager::ControllerIsXbox(int index) { +bool InputManager::ControllerIsXbox(int index) { Controller* controller = GetController(index); if (controller) return controller->IsXbox(); return false; } -PUBLIC STATIC bool InputManager::ControllerIsPlayStation(int index) { +bool InputManager::ControllerIsPlayStation(int index) { Controller* controller = GetController(index); if (controller) return controller->IsPlayStation(); return false; } -PUBLIC STATIC bool InputManager::ControllerIsJoyCon(int index) { +bool InputManager::ControllerIsJoyCon(int index) { Controller* controller = GetController(index); if (controller) return controller->IsJoyCon(); return false; } -PUBLIC STATIC bool InputManager::ControllerHasShareButton(int index) { +bool InputManager::ControllerHasShareButton(int index) { Controller* controller = GetController(index); if (controller) return controller->HasShareButton(); return false; } -PUBLIC STATIC bool InputManager::ControllerHasMicrophoneButton(int index) { +bool InputManager::ControllerHasMicrophoneButton(int index) { Controller* controller = GetController(index); if (controller) return controller->HasMicrophoneButton(); return false; } -PUBLIC STATIC bool InputManager::ControllerHasPaddles(int index) { +bool InputManager::ControllerHasPaddles(int index) { Controller* controller = GetController(index); if (controller) return controller->HasPaddles(); return false; } -PUBLIC STATIC bool InputManager::ControllerIsButtonHeld(int index, int button) { +bool InputManager::ControllerIsButtonHeld(int index, int button) { Controller* controller = GetController(index); if (controller) return controller->IsButtonHeld(button); return false; } -PUBLIC STATIC bool InputManager::ControllerIsButtonPressed(int index, int button) { +bool InputManager::ControllerIsButtonPressed(int index, int button) { Controller* controller = GetController(index); if (controller) return controller->IsButtonPressed(button); return false; } -PUBLIC STATIC float InputManager::ControllerGetAxis(int index, int axis) { +float InputManager::ControllerGetAxis(int index, int axis) { Controller* controller = GetController(index); if (controller) return controller->GetAxis(axis); return 0.0f; } -PUBLIC STATIC int InputManager::ControllerGetType(int index) { +int InputManager::ControllerGetType(int index) { Controller* controller = GetController(index); if (controller) return (int)controller->Type; return (int)ControllerType::Unknown; } -PUBLIC STATIC char* InputManager::ControllerGetName(int index) { +char* InputManager::ControllerGetName(int index) { Controller* controller = GetController(index); if (controller) return controller->GetName(); return nullptr; } -PUBLIC STATIC void InputManager::ControllerSetPlayerIndex(int index, int player_index) { +void InputManager::ControllerSetPlayerIndex(int index, int player_index) { Controller* controller = GetController(index); if (controller) controller->SetPlayerIndex(player_index); } -PUBLIC STATIC bool InputManager::ControllerHasRumble(int index) { +bool InputManager::ControllerHasRumble(int index) { Controller* controller = GetController(index); if (controller) return controller->Rumble != nullptr; return false; } -PUBLIC STATIC bool InputManager::ControllerIsRumbleActive(int index) { +bool InputManager::ControllerIsRumbleActive(int index) { Controller* controller = GetController(index); if (controller && controller->Rumble) return controller->Rumble->Active; return false; } -PUBLIC STATIC bool InputManager::ControllerRumble(int index, float large_frequency, float small_frequency, int duration) { +bool InputManager::ControllerRumble(int index, float large_frequency, float small_frequency, int duration) { Controller* controller = GetController(index); if (controller && controller->Rumble) return controller->Rumble->Enable(large_frequency, small_frequency, (Uint32)duration); return false; } -PUBLIC STATIC bool InputManager::ControllerRumble(int index, float strength, int duration) { +bool InputManager::ControllerRumble(int index, float strength, int duration) { return ControllerRumble(index, strength, strength, duration); } -PUBLIC STATIC void InputManager::ControllerStopRumble(int index) { +void InputManager::ControllerStopRumble(int index) { Controller* controller = GetController(index); if (controller && controller->Rumble) controller->Rumble->Stop(); } -PUBLIC STATIC void InputManager::ControllerStopRumble() { +void InputManager::ControllerStopRumble() { for (int i = 0; i < InputManager::NumControllers; i++) { Controller* controller = InputManager::Controllers[i]; if (!controller || !controller->Rumble) @@ -629,62 +592,62 @@ PUBLIC STATIC void InputManager::ControllerStopRumble() { controller->Rumble->Stop(); } } -PUBLIC STATIC bool InputManager::ControllerIsRumblePaused(int index) { +bool InputManager::ControllerIsRumblePaused(int index) { Controller* controller = GetController(index); if (controller && controller->Rumble) return controller->Rumble->Paused; return false; } -PUBLIC STATIC void InputManager::ControllerSetRumblePaused(int index, bool paused) { +void InputManager::ControllerSetRumblePaused(int index, bool paused) { Controller* controller = GetController(index); if (controller && controller->Rumble) controller->Rumble->SetPaused(paused); } -PUBLIC STATIC bool InputManager::ControllerSetLargeMotorFrequency(int index, float frequency) { +bool InputManager::ControllerSetLargeMotorFrequency(int index, float frequency) { Controller* controller = GetController(index); if (controller && controller->Rumble) return controller->Rumble->SetLargeMotorFrequency(frequency); return false; } -PUBLIC STATIC bool InputManager::ControllerSetSmallMotorFrequency(int index, float frequency) { +bool InputManager::ControllerSetSmallMotorFrequency(int index, float frequency) { Controller* controller = GetController(index); if (controller && controller->Rumble) return controller->Rumble->SetSmallMotorFrequency(frequency); return false; } -PUBLIC STATIC float InputManager::TouchGetX(int touch_index) { +float InputManager::TouchGetX(int touch_index) { if (touch_index < 0 || touch_index >= NUM_TOUCH_STATES) return 0.0f; TouchState* states = (TouchState*)TouchStates; return states[touch_index].X; } -PUBLIC STATIC float InputManager::TouchGetY(int touch_index) { +float InputManager::TouchGetY(int touch_index) { if (touch_index < 0 || touch_index >= NUM_TOUCH_STATES) return 0.0f; TouchState* states = (TouchState*)TouchStates; return states[touch_index].Y; } -PUBLIC STATIC bool InputManager::TouchIsDown(int touch_index) { +bool InputManager::TouchIsDown(int touch_index) { if (touch_index < 0 || touch_index >= NUM_TOUCH_STATES) return false; TouchState* states = (TouchState*)TouchStates; return states[touch_index].Down; } -PUBLIC STATIC bool InputManager::TouchIsPressed(int touch_index) { +bool InputManager::TouchIsPressed(int touch_index) { if (touch_index < 0 || touch_index >= NUM_TOUCH_STATES) return false; TouchState* states = (TouchState*)TouchStates; return states[touch_index].Pressed; } -PUBLIC STATIC bool InputManager::TouchIsReleased(int touch_index) { +bool InputManager::TouchIsReleased(int touch_index) { if (touch_index < 0 || touch_index >= NUM_TOUCH_STATES) return false; TouchState* states = (TouchState*)TouchStates; return states[touch_index].Released; } -PUBLIC STATIC int InputManager::AddPlayer() { +int InputManager::AddPlayer() { int id = (int)Players.size(); InputPlayer player(id); @@ -695,10 +658,10 @@ PUBLIC STATIC int InputManager::AddPlayer() { return id; } -PUBLIC STATIC int InputManager::GetPlayerCount() { +int InputManager::GetPlayerCount() { return (int)Players.size(); } -PUBLIC STATIC void InputManager::SetPlayerControllerIndex(unsigned playerID, int index) { +void InputManager::SetPlayerControllerIndex(unsigned playerID, int index) { if (playerID >= Players.size()) return; @@ -707,13 +670,13 @@ PUBLIC STATIC void InputManager::SetPlayerControllerIndex(unsigned playerID, in Players[playerID].ControllerIndex = index; } -PUBLIC STATIC int InputManager::GetPlayerControllerIndex(unsigned playerID) { +int InputManager::GetPlayerControllerIndex(unsigned playerID) { if (playerID >= Players.size()) return -1; return Players[playerID].ControllerIndex; } -PUBLIC STATIC bool InputManager::IsActionHeld(unsigned playerID, unsigned actionID) { +bool InputManager::IsActionHeld(unsigned playerID, unsigned actionID) { if (playerID >= Players.size()) return false; @@ -721,7 +684,7 @@ PUBLIC STATIC bool InputManager::IsActionHeld(unsigned playerID, unsigned actio return player.IsInputHeld(actionID); } -PUBLIC STATIC bool InputManager::IsActionPressed(unsigned playerID, unsigned actionID) { +bool InputManager::IsActionPressed(unsigned playerID, unsigned actionID) { if (playerID >= Players.size()) return false; @@ -729,7 +692,7 @@ PUBLIC STATIC bool InputManager::IsActionPressed(unsigned playerID, unsigned ac return player.IsInputPressed(actionID); } -PUBLIC STATIC bool InputManager::IsActionReleased(unsigned playerID, unsigned actionID) { +bool InputManager::IsActionReleased(unsigned playerID, unsigned actionID) { if (playerID >= Players.size()) return false; @@ -737,7 +700,7 @@ PUBLIC STATIC bool InputManager::IsActionReleased(unsigned playerID, unsigned a return player.IsInputReleased(actionID); } -PUBLIC STATIC bool InputManager::IsAnyActionHeld(unsigned playerID) { +bool InputManager::IsAnyActionHeld(unsigned playerID) { if (playerID >= Players.size()) return false; @@ -745,7 +708,7 @@ PUBLIC STATIC bool InputManager::IsAnyActionHeld(unsigned playerID) { return player.IsAnyInputHeld(); } -PUBLIC STATIC bool InputManager::IsAnyActionPressed(unsigned playerID) { +bool InputManager::IsAnyActionPressed(unsigned playerID) { if (playerID >= Players.size()) return false; @@ -753,7 +716,7 @@ PUBLIC STATIC bool InputManager::IsAnyActionPressed(unsigned playerID) { return player.IsAnyInputPressed(); } -PUBLIC STATIC bool InputManager::IsAnyActionReleased(unsigned playerID) { +bool InputManager::IsAnyActionReleased(unsigned playerID) { if (playerID >= Players.size()) return false; @@ -761,7 +724,7 @@ PUBLIC STATIC bool InputManager::IsAnyActionReleased(unsigned playerID) { return player.IsAnyInputReleased(); } -PUBLIC STATIC bool InputManager::IsActionHeld(unsigned playerID, unsigned actionID, unsigned device) { +bool InputManager::IsActionHeld(unsigned playerID, unsigned actionID, unsigned device) { if (playerID >= Players.size()) return false; @@ -769,7 +732,7 @@ PUBLIC STATIC bool InputManager::IsActionHeld(unsigned playerID, unsigned actio return player.IsInputHeld(actionID, device); } -PUBLIC STATIC bool InputManager::IsActionPressed(unsigned playerID, unsigned actionID, unsigned device) { +bool InputManager::IsActionPressed(unsigned playerID, unsigned actionID, unsigned device) { if (playerID >= Players.size()) return false; @@ -777,7 +740,7 @@ PUBLIC STATIC bool InputManager::IsActionPressed(unsigned playerID, unsigned ac return player.IsInputPressed(actionID, device); } -PUBLIC STATIC bool InputManager::IsActionReleased(unsigned playerID, unsigned actionID, unsigned device) { +bool InputManager::IsActionReleased(unsigned playerID, unsigned actionID, unsigned device) { if (playerID >= Players.size()) return false; @@ -785,7 +748,7 @@ PUBLIC STATIC bool InputManager::IsActionReleased(unsigned playerID, unsigned a return player.IsInputReleased(actionID, device); } -PUBLIC STATIC bool InputManager::IsAnyActionHeld(unsigned playerID, unsigned device) { +bool InputManager::IsAnyActionHeld(unsigned playerID, unsigned device) { if (playerID >= Players.size()) return false; @@ -793,7 +756,7 @@ PUBLIC STATIC bool InputManager::IsAnyActionHeld(unsigned playerID, unsigned de return player.IsAnyInputHeld(device); } -PUBLIC STATIC bool InputManager::IsAnyActionPressed(unsigned playerID, unsigned device) { +bool InputManager::IsAnyActionPressed(unsigned playerID, unsigned device) { if (playerID >= Players.size()) return false; @@ -801,7 +764,7 @@ PUBLIC STATIC bool InputManager::IsAnyActionPressed(unsigned playerID, unsigned return player.IsAnyInputPressed(device); } -PUBLIC STATIC bool InputManager::IsAnyActionReleased(unsigned playerID, unsigned device) { +bool InputManager::IsAnyActionReleased(unsigned playerID, unsigned device) { if (playerID >= Players.size()) return false; @@ -809,7 +772,7 @@ PUBLIC STATIC bool InputManager::IsAnyActionReleased(unsigned playerID, unsigne return player.IsAnyInputReleased(device); } -PUBLIC STATIC bool InputManager::IsPlayerUsingDevice(unsigned playerID, unsigned device) { +bool InputManager::IsPlayerUsingDevice(unsigned playerID, unsigned device) { if (playerID >= Players.size() || device >= InputDevice_MAX) return false; @@ -817,7 +780,7 @@ PUBLIC STATIC bool InputManager::IsPlayerUsingDevice(unsigned playerID, unsigne return player.IsUsingDevice[device]; } -PUBLIC STATIC float InputManager::GetAnalogActionInput(unsigned playerID, unsigned actionID) { +float InputManager::GetAnalogActionInput(unsigned playerID, unsigned actionID) { if (playerID >= Players.size()) return 0.0f; @@ -826,7 +789,7 @@ PUBLIC STATIC float InputManager::GetAnalogActionInput(unsigned playerID, unsign return player.GetAnalogActionInput(actionID); } -PUBLIC STATIC InputBind* InputManager::GetPlayerInputBind(unsigned playerID, unsigned actionID, unsigned index, bool isDefault) { +InputBind* InputManager::GetPlayerInputBind(unsigned playerID, unsigned actionID, unsigned index, bool isDefault) { if (playerID >= Players.size()) return nullptr; @@ -837,7 +800,7 @@ PUBLIC STATIC InputBind* InputManager::GetPlayerInputBind(unsigned playerID, uns else return player.GetBind(actionID, index); } -PUBLIC STATIC bool InputManager::SetPlayerInputBind(unsigned playerID, unsigned actionID, InputBind* bind, unsigned index, bool isDefault) { +bool InputManager::SetPlayerInputBind(unsigned playerID, unsigned actionID, InputBind* bind, unsigned index, bool isDefault) { if (playerID >= Players.size()) return false; @@ -848,7 +811,7 @@ PUBLIC STATIC bool InputManager::SetPlayerInputBind(unsigned playerID, unsigned else return player.ReplaceBind(actionID, bind, index); } -PUBLIC STATIC int InputManager::AddPlayerInputBind(unsigned playerID, unsigned actionID, InputBind* bind, bool isDefault) { +int InputManager::AddPlayerInputBind(unsigned playerID, unsigned actionID, InputBind* bind, bool isDefault) { if (playerID >= Players.size()) return -1; @@ -859,7 +822,7 @@ PUBLIC STATIC int InputManager::AddPlayerInputBind(unsigned playerID, unsigned else return player.AddBind(actionID, bind); } -PUBLIC STATIC bool InputManager::RemovePlayerInputBind(unsigned playerID, unsigned actionID, unsigned index, bool isDefault) { +bool InputManager::RemovePlayerInputBind(unsigned playerID, unsigned actionID, unsigned index, bool isDefault) { if (playerID >= Players.size()) return false; @@ -870,7 +833,7 @@ PUBLIC STATIC bool InputManager::RemovePlayerInputBind(unsigned playerID, unsig else return player.RemoveBind(actionID, index); } -PUBLIC STATIC int InputManager::GetPlayerInputBindCount(unsigned playerID, unsigned actionID, bool isDefault) { +int InputManager::GetPlayerInputBindCount(unsigned playerID, unsigned actionID, bool isDefault) { if (playerID >= Players.size()) return 0; @@ -882,7 +845,7 @@ PUBLIC STATIC int InputManager::GetPlayerInputBindCount(unsigned playerID, unsig return player.GetBindCount(actionID); } -PUBLIC STATIC void InputManager::ClearPlayerBinds(unsigned playerID, unsigned actionID, bool isDefault) { +void InputManager::ClearPlayerBinds(unsigned playerID, unsigned actionID, bool isDefault) { if (playerID >= Players.size()) return; @@ -894,7 +857,7 @@ PUBLIC STATIC void InputManager::ClearPlayerBinds(unsigned playerID, unsigned a player.ClearBinds(actionID); } -PUBLIC STATIC bool InputManager::IsBindIndexValid(unsigned playerID, unsigned actionID, unsigned index) { +bool InputManager::IsBindIndexValid(unsigned playerID, unsigned actionID, unsigned index) { if (playerID >= Players.size()) return false; @@ -903,7 +866,7 @@ PUBLIC STATIC bool InputManager::IsBindIndexValid(unsigned playerID, unsigned a return player.IsBindIndexValid(actionID, index); } -PUBLIC STATIC void InputManager::ResetPlayerBinds(unsigned playerID) { +void InputManager::ResetPlayerBinds(unsigned playerID) { if (playerID >= Players.size()) return; @@ -912,11 +875,11 @@ PUBLIC STATIC void InputManager::ResetPlayerBinds(unsigned playerID) { player.ResetBinds(); } -PUBLIC STATIC void InputManager::ClearPlayers() { +void InputManager::ClearPlayers() { Players.clear(); } -PUBLIC STATIC int InputManager::RegisterAction(const char* name) { +int InputManager::RegisterAction(const char* name) { int id = GetActionID(name); if (id != -1) return id; @@ -932,7 +895,7 @@ PUBLIC STATIC int InputManager::RegisterAction(const char* name) { return id; } -PUBLIC STATIC int InputManager::GetActionID(const char* name) { +int InputManager::GetActionID(const char* name) { if (name != nullptr && name[0] != '\0') { for (size_t i = 0; i < Actions.size(); i++) { if (strcmp(Actions[i].Name.c_str(), name) == 0) @@ -942,14 +905,14 @@ PUBLIC STATIC int InputManager::GetActionID(const char* name) { return -1; } -PUBLIC STATIC void InputManager::ClearInputs() { +void InputManager::ClearInputs() { Actions.clear(); for (size_t i = 0; i < Players.size(); i++) Players[i].SetNumActions(0); } -PUBLIC STATIC void InputManager::InitPlayerControls() { +void InputManager::InitPlayerControls() { if (!Application::GameConfig) return; @@ -1011,7 +974,7 @@ PUBLIC STATIC void InputManager::InitPlayerControls() { } } -PRIVATE STATIC void InputManager::ParsePlayerControls(InputPlayer& player, XMLNode* node) { +void InputManager::ParsePlayerControls(InputPlayer& player, XMLNode* node) { for (size_t i = 0; i < node->children.size(); i++) { XMLNode* child = node->children[i]; if (XMLParser::MatchToken(child->name, "default")) { @@ -1052,7 +1015,7 @@ PRIVATE STATIC void InputManager::ParsePlayerControls(InputPlayer& player, XMLNo } } -PRIVATE STATIC Uint16 InputManager::ParseKeyModifiers(string& str, string& actionName) { +Uint16 InputManager::ParseKeyModifiers(string& str, string& actionName) { Uint16 flags = 0; std::stringstream strStream(str); @@ -1078,7 +1041,7 @@ PRIVATE STATIC Uint16 InputManager::ParseKeyModifiers(string& str, string& actio return flags; } -PRIVATE STATIC void InputManager::ParseDefaultInputBinds(InputPlayer& player, int actionID, string& actionName, XMLNode* node) { +void InputManager::ParseDefaultInputBinds(InputPlayer& player, int actionID, string& actionName, XMLNode* node) { for (size_t i = 0; i < node->children.size(); i++) { XMLNode* child = node->children[i]; @@ -1153,7 +1116,7 @@ PRIVATE STATIC void InputManager::ParseDefaultInputBinds(InputPlayer& player, in } } -PUBLIC STATIC void InputManager::Dispose() { +void InputManager::Dispose() { InputManager::ControllerStopRumble(); // Close controllers diff --git a/source/Engine/Math/Clipper.cpp b/source/Engine/Math/Clipper.cpp index 314167c0..1b3efb26 100644 --- a/source/Engine/Math/Clipper.cpp +++ b/source/Engine/Math/Clipper.cpp @@ -1,16 +1,7 @@ -#if INTERFACE -#include -#include - -class Clipper { -public: -}; -#endif - #include #include -PRIVATE STATIC void Clipper::AddPoint(VertexAttribute* buf, VertexAttribute* v1, VertexAttribute* v2, Vector4 p1, Vector4 p2, Sint64 t) { +void Clipper::AddPoint(VertexAttribute* buf, VertexAttribute* v1, VertexAttribute* v2, Vector4 p1, Vector4 p2, Sint64 t) { Vector4 diff = Vector::Subtract(p2, p1); Vector4 newPosition = Vector::Add(p1, Vector::Multiply(diff, t)); @@ -31,7 +22,7 @@ PRIVATE STATIC void Clipper::AddPoint(VertexAttribute* buf, VertexAttribute* v1, #undef DO_INTERP } -PRIVATE STATIC bool Clipper::ClipEdge(Frustum frustum, VertexAttribute* v1, VertexAttribute* v2, PolygonClipBuffer* output) { +bool Clipper::ClipEdge(Frustum frustum, VertexAttribute* v1, VertexAttribute* v2, PolygonClipBuffer* output) { VertexAttribute* buffer = &output->Buffer[output->NumPoints]; Vector4 pos1 = v1->Position; @@ -90,7 +81,7 @@ PRIVATE STATIC bool Clipper::ClipEdge(Frustum frustum, VertexAttribute* v1, Vert return true; } -PRIVATE STATIC int Clipper::ClipPolygon(Frustum frustum, PolygonClipBuffer* output, VertexAttribute* input, int vertexCount) { +int Clipper::ClipPolygon(Frustum frustum, PolygonClipBuffer* output, VertexAttribute* input, int vertexCount) { // Not even a triangle? if (vertexCount < 3) return 0; @@ -110,7 +101,7 @@ PRIVATE STATIC int Clipper::ClipPolygon(Frustum frustum, PolygonClipBuffer* out return output->NumPoints; } -PUBLIC STATIC int Clipper::FrustumClip(PolygonClipBuffer* output, Frustum* frustum, int num, VertexAttribute* input, int vertexCount) { +int Clipper::FrustumClip(PolygonClipBuffer* output, Frustum* frustum, int num, VertexAttribute* input, int vertexCount) { PolygonClipBuffer temp[NUM_FRUSTUM_PLANES]; VertexAttribute* buffer = input; diff --git a/source/Engine/Math/Ease.cpp b/source/Engine/Math/Ease.cpp index 9324126d..43637845 100644 --- a/source/Engine/Math/Ease.cpp +++ b/source/Engine/Math/Ease.cpp @@ -1,11 +1,3 @@ -#if INTERFACE -#include -class Ease { -public: - -}; -#endif - #include #include @@ -14,57 +6,57 @@ class Ease { #define PI 3.1415926545 #endif -PUBLIC STATIC float Ease::InSine(float t) { +float Ease::InSine(float t) { t = Math::Clamp(t, 0.0f, 1.0f); return sin(1.5707963 * t); } -PUBLIC STATIC float Ease::OutSine(float t) { +float Ease::OutSine(float t) { t = Math::Clamp(t, 0.0f, 1.0f); t -= 1.0; return 1 + sin(1.5707963 * t); } -PUBLIC STATIC float Ease::InOutSine(float t) { +float Ease::InOutSine(float t) { t = Math::Clamp(t, 0.0f, 1.0f); return 0.5 * (1 + sin(3.1415926 * (t - 0.5))); } -PUBLIC STATIC float Ease::InQuad(float t) { +float Ease::InQuad(float t) { t = Math::Clamp(t, 0.0f, 1.0f); return t * t; } -PUBLIC STATIC float Ease::OutQuad(float t) { +float Ease::OutQuad(float t) { t = Math::Clamp(t, 0.0f, 1.0f); return t * (2 - t); } -PUBLIC STATIC float Ease::InOutQuad(float t) { +float Ease::InOutQuad(float t) { t = Math::Clamp(t, 0.0f, 1.0f); return t < 0.5 ? 2 * t * t : t * (4 - 2 * t) - 1; } -PUBLIC STATIC float Ease::InCubic(float t) { +float Ease::InCubic(float t) { t = Math::Clamp(t, 0.0f, 1.0f); return t * t * t; } -PUBLIC STATIC float Ease::OutCubic(float t) { +float Ease::OutCubic(float t) { t = Math::Clamp(t, 0.0f, 1.0f); t -= 1.0; return 1 + t * t * t; } -PUBLIC STATIC float Ease::InOutCubic(float t) { +float Ease::InOutCubic(float t) { t = Math::Clamp(t, 0.0f, 1.0f); if (t >= 0.5) t -= 1.0; return t < 0.5 ? 4 * t * t * t : 1 + t * (2 * (t - 1)) * (2 * (t - 2)); } -PUBLIC STATIC float Ease::InQuart(float t) { +float Ease::InQuart(float t) { t = Math::Clamp(t, 0.0f, 1.0f); t *= t; return t * t; } -PUBLIC STATIC float Ease::OutQuart(float t) { +float Ease::OutQuart(float t) { t = Math::Clamp(t, 0.0f, 1.0f); t = (t - 1) * (t - 1); return 1 - t * t; } -PUBLIC STATIC float Ease::InOutQuart(float t) { +float Ease::InOutQuart(float t) { t = Math::Clamp(t, 0.0f, 1.0f); if (t < 0.5) { t *= t; @@ -75,17 +67,17 @@ PUBLIC STATIC float Ease::InOutQuart(float t) { return 1 - 8 * t * t; } } -PUBLIC STATIC float Ease::InQuint(float t) { +float Ease::InQuint(float t) { t = Math::Clamp(t, 0.0f, 1.0f); float t2 = t * t; return t * t2 * t2; } -PUBLIC STATIC float Ease::OutQuint(float t) { +float Ease::OutQuint(float t) { t = Math::Clamp(t, 0.0f, 1.0f); float t2 = (t - 1) * (t - 1); return 1 + t * t2 * t2; } -PUBLIC STATIC float Ease::InOutQuint(float t) { +float Ease::InOutQuint(float t) { t = Math::Clamp(t, 0.0f, 1.0f); float t2; if (t < 0.5) { @@ -98,15 +90,15 @@ PUBLIC STATIC float Ease::InOutQuint(float t) { return 1.0f - 16.0f * t * t2 * t2; } } -PUBLIC STATIC float Ease::InExpo(float t) { +float Ease::InExpo(float t) { t = Math::Clamp(t, 0.0f, 1.0f); return (pow(2, 8 * t) - 1) / 255; } -PUBLIC STATIC float Ease::OutExpo(float t) { +float Ease::OutExpo(float t) { t = Math::Clamp(t, 0.0f, 1.0f); return 1 - pow(2, -8 * t); } -PUBLIC STATIC float Ease::InOutExpo(float t) { +float Ease::InOutExpo(float t) { t = Math::Clamp(t, 0.0f, 1.0f); if (t < 0.5) { return (pow(2, 16 * t) - 1) / 510; @@ -115,15 +107,15 @@ PUBLIC STATIC float Ease::InOutExpo(float t) { return 1 - 0.5 * pow(2, -16 * (t - 0.5)); } } -PUBLIC STATIC float Ease::InCirc(float t) { +float Ease::InCirc(float t) { t = Math::Clamp(t, 0.0f, 1.0f); return 1 - sqrt(1 - t); } -PUBLIC STATIC float Ease::OutCirc(float t) { +float Ease::OutCirc(float t) { t = Math::Clamp(t, 0.0f, 1.0f); return sqrt(t); } -PUBLIC STATIC float Ease::InOutCirc(float t) { +float Ease::InOutCirc(float t) { t = Math::Clamp(t, 0.0f, 1.0f); if (t < 0.5) { return (1 - sqrt(1 - 2 * t)) * 0.5; @@ -132,16 +124,16 @@ PUBLIC STATIC float Ease::InOutCirc(float t) { return (1 + sqrt(2 * t - 1)) * 0.5; } } -PUBLIC STATIC float Ease::InBack(float t) { +float Ease::InBack(float t) { t = Math::Clamp(t, 0.0f, 1.0f); return t * t * (2.70158 * t - 1.70158); } -PUBLIC STATIC float Ease::OutBack(float t) { +float Ease::OutBack(float t) { t = Math::Clamp(t, 0.0f, 1.0f); t -= 1.0; return 1 + t * t * (2.70158 * t + 1.70158); } -PUBLIC STATIC float Ease::InOutBack(float t) { +float Ease::InOutBack(float t) { t = Math::Clamp(t, 0.0f, 1.0f); if (t < 0.5) { return t * t * (7 * t - 2.5) * 2; @@ -151,17 +143,17 @@ PUBLIC STATIC float Ease::InOutBack(float t) { return 1 + t * t * 2 * (7 * t + 2.5); } } -PUBLIC STATIC float Ease::InElastic(float t) { +float Ease::InElastic(float t) { t = Math::Clamp(t, 0.0f, 1.0f); float t2 = t * t; return t2 * t2 * sin(t * PI * 4.5); } -PUBLIC STATIC float Ease::OutElastic(float t) { +float Ease::OutElastic(float t) { t = Math::Clamp(t, 0.0f, 1.0f); float t2 = (t - 1) * (t - 1); return 1 - t2 * t2 * cos(t * PI * 4.5); } -PUBLIC STATIC float Ease::InOutElastic(float t) { +float Ease::InOutElastic(float t) { t = Math::Clamp(t, 0.0f, 1.0f); float t2; if (t < 0.45) { @@ -176,15 +168,15 @@ PUBLIC STATIC float Ease::InOutElastic(float t) { return 1 - 8 * t2 * t2 * sin(t * PI * 9); } } -PUBLIC STATIC float Ease::InBounce(float t) { +float Ease::InBounce(float t) { t = Math::Clamp(t, 0.0f, 1.0f); return pow(2, 6 * (t - 1)) * abs(sin(t * PI * 3.5)); } -PUBLIC STATIC float Ease::OutBounce(float t) { +float Ease::OutBounce(float t) { t = Math::Clamp(t, 0.0f, 1.0f); return 1 - pow(2, -6 * t) * abs(cos(t * PI * 3.5)); } -PUBLIC STATIC float Ease::InOutBounce(float t) { +float Ease::InOutBounce(float t) { t = Math::Clamp(t, 0.0f, 1.0f); if (t < 0.5) { return 8 * pow(2, 8 * (t - 1)) * abs(sin(t * PI * 7)); @@ -193,7 +185,7 @@ PUBLIC STATIC float Ease::InOutBounce(float t) { return 1 - 8 * pow(2, -8 * t) * abs(sin(t * PI * 7)); } } -PUBLIC STATIC float Ease::Triangle(float t) { +float Ease::Triangle(float t) { t = Math::Clamp(t, 0.0f, 1.0f); if (t < 0.5) { return t * 2.0; diff --git a/source/Engine/Math/Geometry.cpp b/source/Engine/Math/Geometry.cpp index 629bd95b..997a45b3 100644 --- a/source/Engine/Math/Geometry.cpp +++ b/source/Engine/Math/Geometry.cpp @@ -1,12 +1,3 @@ -#if INTERFACE -#include -#include - -class Geometry { -public: -}; -#endif - #include #include @@ -15,7 +6,7 @@ class Geometry { #include #include -PRIVATE STATIC bool Geometry::CheckEar(vector& input, unsigned count, unsigned prev, unsigned curr, unsigned next) { +bool Geometry::CheckEar(vector& input, unsigned count, unsigned prev, unsigned curr, unsigned next) { FVector2& a = input[prev]; FVector2& b = input[curr]; FVector2& c = input[next]; @@ -46,7 +37,7 @@ PRIVATE STATIC bool Geometry::CheckEar(vector& input, unsigned count, return true; } -PRIVATE STATIC int Geometry::GetPointForTriangulation(int point, unsigned count) { +int Geometry::GetPointForTriangulation(int point, unsigned count) { if (point < 0) return point + count; else if (point >= count) @@ -69,7 +60,7 @@ static void FreeP2TPoints(std::vector& points) { delete points[i]; } -PUBLIC STATIC vector* Geometry::Triangulate(Polygon2D& input, vector holes) { +vector* Geometry::Triangulate(Polygon2D& input, vector holes) { vector points = input.Points; unsigned count = points.size(); @@ -151,7 +142,7 @@ static Clipper2Lib::FillRule GetFillRule(unsigned fillRule) { } } -PUBLIC STATIC vector* Geometry::Intersect(unsigned clipType, unsigned fillRule, vector inputSubjects, vector inputClips) { +vector* Geometry::Intersect(unsigned clipType, unsigned fillRule, vector inputSubjects, vector inputClips) { Clipper2Lib::PathsD subjects; Clipper2Lib::PathsD clips; diff --git a/source/Engine/Math/Math.cpp b/source/Engine/Math/Math.cpp index 056232c9..d5589328 100644 --- a/source/Engine/Math/Math.cpp +++ b/source/Engine/Math/Math.cpp @@ -1,10 +1,3 @@ -#if INTERFACE -#include -class Math { -public: -}; -#endif - int Sin1024LookupTable[0x400]; int Cos1024LookupTable[0x400]; int Tan1024LookupTable[0x400]; @@ -30,42 +23,42 @@ int randSeed = 0; #include #include -PUBLIC STATIC void Math::Init() { +void Math::Init() { srand((Uint32)time(NULL)); Math::ClearTrigLookupTables(); Math::CalculateTrigAngles(); } // Trig functions -PUBLIC STATIC float Math::Cos(float n) { +float Math::Cos(float n) { return std::cos(n); } -PUBLIC STATIC float Math::Sin(float n) { +float Math::Sin(float n) { return std::sin(n); } -PUBLIC STATIC float Math::Tan(float n) { +float Math::Tan(float n) { return std::tan(n); } -PUBLIC STATIC float Math::Asin(float x) { +float Math::Asin(float x) { return std::asin(x); } -PUBLIC STATIC float Math::Acos(float x) { +float Math::Acos(float x) { return std::acos(x); } -PUBLIC STATIC float Math::Atan(float x, float y) { +float Math::Atan(float x, float y) { if (x == 0.0f && y == 0.0f) return 0.0f; return std::atan2(y, x); } -PUBLIC STATIC float Math::Distance(float x1, float y1, float x2, float y2) { +float Math::Distance(float x1, float y1, float x2, float y2) { x2 -= x1; x2 *= x2; y2 -= y1; y2 *= y2; return (float)sqrt(x2 + y2); } -PUBLIC STATIC float Math::Hypot(float a, float b, float c) { +float Math::Hypot(float a, float b, float c) { return (float)sqrt(a * a + b * b + c * c); } -PUBLIC STATIC void Math::ClearTrigLookupTables() { +void Math::ClearTrigLookupTables() { memset(Sin256LookupTable, 0, sizeof(Sin256LookupTable)); memset(Cos256LookupTable, 0, sizeof(Cos256LookupTable)); memset(Tan256LookupTable, 0, sizeof(Tan256LookupTable)); @@ -84,7 +77,7 @@ PUBLIC STATIC void Math::ClearTrigLookupTables() { memset(ArcTan256LookupTable, 0, sizeof(ArcTan256LookupTable)); randSeed = 0; } -PUBLIC STATIC void Math::CalculateTrigAngles() { +void Math::CalculateTrigAngles() { randSeed = rand(); for (int i = 0; i < 0x400; i++) { @@ -131,69 +124,69 @@ PUBLIC STATIC void Math::CalculateTrigAngles() { ACos256LookupTable[i] = (int)((acosf(i / 255.0) * 128.0) / R_PI); } } -PUBLIC STATIC int Math::Sin1024(int angle) { +int Math::Sin1024(int angle) { return Sin1024LookupTable[angle & 0x3FF]; } -PUBLIC STATIC int Math::Cos1024(int angle) { +int Math::Cos1024(int angle) { return Cos1024LookupTable[angle & 0x3FF]; } -PUBLIC STATIC int Math::Tan1024(int angle) { +int Math::Tan1024(int angle) { return Tan1024LookupTable[angle & 0x3FF]; } -PUBLIC STATIC int Math::ASin1024(int angle) { +int Math::ASin1024(int angle) { if (angle > 0x3FF) return 0; if (angle < 0) return -ASin1024LookupTable[-angle]; return ASin1024LookupTable[angle]; } -PUBLIC STATIC int Math::ACos1024(int angle) { +int Math::ACos1024(int angle) { if (angle > 0x3FF) return 0; if (angle < 0) return -ACos1024LookupTable[-angle]; return ACos1024LookupTable[angle]; } -PUBLIC STATIC int Math::Sin512(int angle) { +int Math::Sin512(int angle) { return Sin512LookupTable[angle & 0x1FF]; } -PUBLIC STATIC int Math::Cos512(int angle) { +int Math::Cos512(int angle) { return Cos512LookupTable[angle & 0x1FF]; } -PUBLIC STATIC int Math::Tan512(int angle) { +int Math::Tan512(int angle) { return Tan512LookupTable[angle & 0x1FF]; } -PUBLIC STATIC int Math::ASin512(int angle) { +int Math::ASin512(int angle) { if (angle > 0x1FF) return 0; if (angle < 0) return -ASin512LookupTable[-angle]; return ASin512LookupTable[angle]; } -PUBLIC STATIC int Math::ACos512(int angle) { +int Math::ACos512(int angle) { if (angle > 0x1FF) return 0; if (angle < 0) return -ACos512LookupTable[-angle]; return ACos512LookupTable[angle]; } -PUBLIC STATIC int Math::Sin256(int angle) { +int Math::Sin256(int angle) { return Sin256LookupTable[angle & 0XFF]; } -PUBLIC STATIC int Math::Cos256(int angle) { +int Math::Cos256(int angle) { return Cos256LookupTable[angle & 0XFF]; } -PUBLIC STATIC int Math::Tan256(int angle) { +int Math::Tan256(int angle) { return Tan256LookupTable[angle & 0xFF]; } -PUBLIC STATIC int Math::ASin256(int angle) { +int Math::ASin256(int angle) { if (angle > 0xFF) return 0; if (angle < 0) return -ASin256LookupTable[-angle]; return ASin256LookupTable[angle]; } -PUBLIC STATIC int Math::ACos256(int angle) { +int Math::ACos256(int angle) { if (angle > 0XFF) return 0; if (angle < 0) @@ -202,7 +195,7 @@ PUBLIC STATIC int Math::ACos256(int angle) { } // help -PUBLIC STATIC int Math::CeilPOT(int n) { +int Math::CeilPOT(int n) { n--; n |= n >> 1; n |= n >> 2; @@ -214,39 +207,39 @@ PUBLIC STATIC int Math::CeilPOT(int n) { } // Deterministic functions -PUBLIC STATIC float Math::Abs(float n) { +float Math::Abs(float n) { return std::abs(n); } -PUBLIC STATIC float Math::Max(float a, float b) { +float Math::Max(float a, float b) { return a > b ? a : b; } -PUBLIC STATIC float Math::Min(float a, float b) { +float Math::Min(float a, float b) { return a < b ? a : b; } -PUBLIC STATIC float Math::Clamp(float v, float a, float b) { +float Math::Clamp(float v, float a, float b) { return Math::Max(a, Math::Min(v, b)); } -PUBLIC STATIC float Math::Sign(float a) { +float Math::Sign(float a) { return a < 0.0f ? -1.0f : a > 0.0f ? 1.0f : 0.0f; } // Random functions (non-inclusive) -PUBLIC STATIC float Math::Random() { +float Math::Random() { return rand() / (float)RAND_MAX; } -PUBLIC STATIC float Math::RandomMax(float max) { +float Math::RandomMax(float max) { return Math::Random() * max; } -PUBLIC STATIC float Math::RandomRange(float min, float max) { +float Math::RandomRange(float min, float max) { return (Math::Random() * (max - min)) + min; } -PUBLIC STATIC int Math::RSDK_GetRandSeed() { +int Math::RSDK_GetRandSeed() { return randSeed; } -PUBLIC STATIC void Math::RSDK_SetRandSeed(int key) { +void Math::RSDK_SetRandSeed(int key) { randSeed = key; } -PUBLIC STATIC int Math::RSDK_RandomInteger(int min, int max) { +int Math::RSDK_RandomInteger(int min, int max) { int seed1 = 1103515245 * randSeed + 12345; int seed2 = 1103515245 * seed1 + 12345; randSeed = 1103515245 * seed2 + 12345; @@ -261,7 +254,7 @@ PUBLIC STATIC int Math::RSDK_RandomInteger(int min, int max) { else return max; } -PUBLIC STATIC int Math::RSDK_RandomIntegerSeeded(int min, int max, int seed) { +int Math::RSDK_RandomIntegerSeeded(int min, int max, int seed) { if (!randSeed) return 0; diff --git a/source/Engine/Math/Matrix4x4.cpp b/source/Engine/Math/Matrix4x4.cpp index 4bab939b..a2fb1095 100644 --- a/source/Engine/Math/Matrix4x4.cpp +++ b/source/Engine/Math/Matrix4x4.cpp @@ -1,10 +1,3 @@ -#if INTERFACE -class Matrix4x4 { -public: - float Values[16]; -}; -#endif - #include #include @@ -15,12 +8,12 @@ class Matrix4x4 { #define EPSILON 0.000001 -PUBLIC STATIC Matrix4x4* Matrix4x4::Create() { +Matrix4x4* Matrix4x4::Create() { Matrix4x4* mat4 = new Matrix4x4; Matrix4x4::Identity(mat4); return mat4; } -PUBLIC STATIC void Matrix4x4::Identity(Matrix4x4* mat4) { +void Matrix4x4::Identity(Matrix4x4* mat4) { mat4->Values[0] = 1.0f; mat4->Values[1] = 0.0f; mat4->Values[2] = 0.0f; @@ -39,7 +32,7 @@ PUBLIC STATIC void Matrix4x4::Identity(Matrix4x4* mat4) { mat4->Values[15] = 1.0f; } -PUBLIC STATIC void Matrix4x4::Perspective(Matrix4x4* out, float fovy, float aspect, float near, float far) { +void Matrix4x4::Perspective(Matrix4x4* out, float fovy, float aspect, float near, float far) { float f = 1.0f / tan(fovy / 2.0f); float nf = 1.0f / (near - far); out->Values[0] = f / aspect; @@ -59,7 +52,7 @@ PUBLIC STATIC void Matrix4x4::Perspective(Matrix4x4* out, float fovy, floa out->Values[14] = 2.0f * far * near * nf; out->Values[15] = 0.0f; } -PUBLIC STATIC void Matrix4x4::Ortho(Matrix4x4* out, float left, float right, float bottom, float top, float near, float far) { +void Matrix4x4::Ortho(Matrix4x4* out, float left, float right, float bottom, float top, float near, float far) { float lr = 1.0f / (left - right); float bt = 1.0f / (bottom - top); float nf = 1.0f / (near - far); @@ -81,17 +74,17 @@ PUBLIC STATIC void Matrix4x4::Ortho(Matrix4x4* out, float left, float righ out->Values[15] = 1.0f; } -PUBLIC STATIC void Matrix4x4::Copy(Matrix4x4* out, Matrix4x4* a) { +void Matrix4x4::Copy(Matrix4x4* out, Matrix4x4* a) { memcpy(&out->Values[0], &a->Values[0], 16 * sizeof(float)); } -PUBLIC STATIC bool Matrix4x4::Equals(Matrix4x4* a, Matrix4x4* b) { +bool Matrix4x4::Equals(Matrix4x4* a, Matrix4x4* b) { if (!a && !b) return true; if (!a || !b) return false; return memcmp(&a->Values[0], &b->Values[0], 16 * sizeof(float)) == 0; } -PUBLIC STATIC void Matrix4x4::Multiply(Matrix4x4* out, Matrix4x4* a, Matrix4x4* b) { +void Matrix4x4::Multiply(Matrix4x4* out, Matrix4x4* a, Matrix4x4* b) { float a00 = a->Values[0], a01 = a->Values[1], a02 = a->Values[2], a03 = a->Values[3]; float a10 = a->Values[4], a11 = a->Values[5], a12 = a->Values[6], a13 = a->Values[7]; float a20 = a->Values[8], a21 = a->Values[9], a22 = a->Values[10], a23 = a->Values[11]; @@ -122,7 +115,7 @@ PUBLIC STATIC void Matrix4x4::Multiply(Matrix4x4* out, Matrix4x4* a, Matri out->Values[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out->Values[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; } -PUBLIC STATIC void Matrix4x4::Multiply(Matrix4x4* mat, float* a) { +void Matrix4x4::Multiply(Matrix4x4* mat, float* a) { float a0 = a[0]; float a1 = a[1]; float a2 = a[2]; @@ -134,7 +127,7 @@ PUBLIC STATIC void Matrix4x4::Multiply(Matrix4x4* mat, float* a) { a[3] = mat->Values[3] * a0 + mat->Values[7] * a1 + mat->Values[11] * a2 + mat->Values[15] * a3; } -PUBLIC STATIC void Matrix4x4::Translate(Matrix4x4* out, Matrix4x4* a, float x, float y, float z) { +void Matrix4x4::Translate(Matrix4x4* out, Matrix4x4* a, float x, float y, float z) { float a00, a01, a02, a03; float a10, a11, a12, a13; float a20, a21, a22, a23; @@ -159,7 +152,7 @@ PUBLIC STATIC void Matrix4x4::Translate(Matrix4x4* out, Matrix4x4* a, floa out->Values[15] = a03 * x + a13 * y + a23 * z + a->Values[15]; } } -PUBLIC STATIC void Matrix4x4::Scale(Matrix4x4* out, Matrix4x4* a, float x, float y, float z) { +void Matrix4x4::Scale(Matrix4x4* out, Matrix4x4* a, float x, float y, float z) { out->Values[0] = a->Values[0] * x; out->Values[1] = a->Values[1] * x; out->Values[2] = a->Values[2] * x; @@ -177,7 +170,7 @@ PUBLIC STATIC void Matrix4x4::Scale(Matrix4x4* out, Matrix4x4* a, float x, out->Values[14] = a->Values[14]; out->Values[15] = a->Values[15]; } -PUBLIC STATIC void Matrix4x4::Rotate(Matrix4x4* out, Matrix4x4* a, float rad, float x, float y, float z) { +void Matrix4x4::Rotate(Matrix4x4* out, Matrix4x4* a, float rad, float x, float y, float z) { float len = sqrt(x * x + y * y + z * z); float s, c, t; float a00, a01, a02, a03; @@ -232,14 +225,14 @@ PUBLIC STATIC void Matrix4x4::Rotate(Matrix4x4* out, Matrix4x4* a, float r out->Values[15] = a->Values[15]; } } -PUBLIC STATIC void Matrix4x4::IdentityScale(Matrix4x4* out, float x, float y, float z) { +void Matrix4x4::IdentityScale(Matrix4x4* out, float x, float y, float z) { Matrix4x4::Identity(out); out->Values[0] = x; out->Values[5] = y; out->Values[10] = z; } -PUBLIC STATIC void Matrix4x4::IdentityRotationX(Matrix4x4* out, float x) { +void Matrix4x4::IdentityRotationX(Matrix4x4* out, float x) { Matrix4x4::Identity(out); float sinX = Math::Sin(x); @@ -249,7 +242,7 @@ PUBLIC STATIC void Matrix4x4::IdentityRotationX(Matrix4x4* out, float x) { out->Values[8] = -sinX; out->Values[9] = cosX; } -PUBLIC STATIC void Matrix4x4::IdentityRotationY(Matrix4x4* out, float y) { +void Matrix4x4::IdentityRotationY(Matrix4x4* out, float y) { Matrix4x4::Identity(out); float sinY = Math::Sin(y); @@ -259,7 +252,7 @@ PUBLIC STATIC void Matrix4x4::IdentityRotationY(Matrix4x4* out, float y) { out->Values[8] = -sinY; out->Values[10] = cosY; } -PUBLIC STATIC void Matrix4x4::IdentityRotationZ(Matrix4x4* out, float z) { +void Matrix4x4::IdentityRotationZ(Matrix4x4* out, float z) { Matrix4x4::Identity(out); float sinZ = Math::Sin(z); @@ -270,7 +263,7 @@ PUBLIC STATIC void Matrix4x4::IdentityRotationZ(Matrix4x4* out, float z) { out->Values[4] = -sinZ; out->Values[5] = cosZ; } -PUBLIC STATIC void Matrix4x4::IdentityRotationXYZ(Matrix4x4* out, float x, float y, float z) { +void Matrix4x4::IdentityRotationXYZ(Matrix4x4* out, float x, float y, float z) { float sinX = Math::Sin(x); float cosX = Math::Cos(x); float sinY = Math::Sin(y); @@ -297,7 +290,7 @@ PUBLIC STATIC void Matrix4x4::IdentityRotationXYZ(Matrix4x4* out, float x, out->Values[11] = 0.f; out->Values[15] = 1.f; } -PUBLIC STATIC void Matrix4x4::Transpose(Matrix4x4* out) { +void Matrix4x4::Transpose(Matrix4x4* out) { Matrix4x4 transposed; for (int i = 0; i < 4; i++) { @@ -307,7 +300,7 @@ PUBLIC STATIC void Matrix4x4::Transpose(Matrix4x4* out) { Matrix4x4::Copy(out, &transposed); } -PUBLIC STATIC void Matrix4x4::LookAt(Matrix4x4* out, float eyex, float eyey, float eyez, float centerx, float centery, float centerz, float upx, float upy, float upz) { +void Matrix4x4::LookAt(Matrix4x4* out, float eyex, float eyey, float eyez, float centerx, float centery, float centerz, float upx, float upy, float upz) { float x0, x1, x2, y0, y1, y2, z0, z1, z2, len; if (Math::Abs(eyex - centerx) < EPSILON && Math::Abs(eyey - centery) < EPSILON && @@ -375,7 +368,7 @@ PUBLIC STATIC void Matrix4x4::LookAt(Matrix4x4* out, float eyex, float eye return; } -PUBLIC STATIC void Matrix4x4::Invert(Matrix4x4* out, Matrix4x4* in) { +void Matrix4x4::Invert(Matrix4x4* out, Matrix4x4* in) { float *src = in->Values; float inv[16]; @@ -408,6 +401,6 @@ PUBLIC STATIC void Matrix4x4::Invert(Matrix4x4* out, Matrix4x4* in) { } } -PUBLIC STATIC void Matrix4x4::Print(Matrix4x4* out) { +void Matrix4x4::Print(Matrix4x4* out) { Log::Print(Log::LOG_INFO, "\n%6.2f %6.2f %6.2f %6.2f \n%6.2f %6.2f %6.2f %6.2f \n%6.2f %6.2f %6.2f %6.2f \n%6.2f %6.2f %6.2f %6.2f", out->Values[0], out->Values[1], out->Values[2], out->Values[3], out->Values[4], out->Values[5], out->Values[6], out->Values[7], out->Values[8], out->Values[9], out->Values[10], out->Values[11], out->Values[12], out->Values[13], out->Values[14], out->Values[15]); } diff --git a/source/Engine/Math/Random.cpp b/source/Engine/Math/Random.cpp index f3cb789d..31fe7529 100644 --- a/source/Engine/Math/Random.cpp +++ b/source/Engine/Math/Random.cpp @@ -1,34 +1,26 @@ -#if INTERFACE -#include -class Random { -public: - static Sint32 Seed; -}; -#endif - #include #define INITIAL_RANDOM_SEED 1938465012 Sint32 Random::Seed = INITIAL_RANDOM_SEED; -PUBLIC STATIC void Random::SetSeed(Sint32 seed) { +void Random::SetSeed(Sint32 seed) { if (!seed) seed = INITIAL_RANDOM_SEED; Seed = seed; } -PUBLIC STATIC float Random::Get() { +float Random::Get() { Sint32 nextSeed = (1103515245 * Seed + 12345) & 0x7FFFFFFF; Seed = nextSeed; return ((float)nextSeed) / 0x7FFFFFFF; } -PUBLIC STATIC float Random::Max(float max) { +float Random::Max(float max) { return Random::Get() * max; } -PUBLIC STATIC float Random::Range(float min, float max) { +float Random::Range(float min, float max) { return (Random::Get() * (max - min)) + min; } diff --git a/source/Engine/Math/Vector.cpp b/source/Engine/Math/Vector.cpp index ff0675e1..b63dfa62 100644 --- a/source/Engine/Math/Vector.cpp +++ b/source/Engine/Math/Vector.cpp @@ -1,17 +1,7 @@ -#if INTERFACE -#include -#include -#include - -class Vector { -public: -}; -#endif - #include #include -PUBLIC STATIC Vector4 Vector::Add(Vector4 v1, Vector4 v2) { +Vector4 Vector::Add(Vector4 v1, Vector4 v2) { Vector4 result; result.X = v1.X + v2.X; result.Y = v1.Y + v2.Y; @@ -20,7 +10,7 @@ PUBLIC STATIC Vector4 Vector::Add(Vector4 v1, Vector4 v2) { return result; } -PUBLIC STATIC Vector4 Vector::Subtract(Vector4 v1, Vector4 v2) { +Vector4 Vector::Subtract(Vector4 v1, Vector4 v2) { Vector4 result; result.X = v1.X - v2.X; result.Y = v1.Y - v2.Y; @@ -29,7 +19,7 @@ PUBLIC STATIC Vector4 Vector::Subtract(Vector4 v1, Vector4 v2) { return result; } -PUBLIC STATIC Vector4 Vector::Multiply(Vector4 v, Sint64 t) { +Vector4 Vector::Multiply(Vector4 v, Sint64 t) { Vector4 result; result.X = FP16_MULTIPLY(v.X, t); result.Y = FP16_MULTIPLY(v.Y, t); @@ -38,7 +28,7 @@ PUBLIC STATIC Vector4 Vector::Multiply(Vector4 v, Sint64 t) { return result; } -PUBLIC STATIC Vector3 Vector::Multiply(Vector3 v, Matrix4x4* m) { +Vector3 Vector::Multiply(Vector3 v, Matrix4x4* m) { Vector3 result; Sint64 mat11 = m->Values[0] * 0x10000; @@ -61,7 +51,7 @@ PUBLIC STATIC Vector3 Vector::Multiply(Vector3 v, Matrix4x4* m) { return result; } -PUBLIC STATIC Vector2 Vector::Interpolate(Vector2 v1, Vector2 v2, Sint64 t) { +Vector2 Vector::Interpolate(Vector2 v1, Vector2 v2, Sint64 t) { Vector2 result; result.X = v1.X + FP16_MULTIPLY(v2.X - v1.X, t); @@ -70,7 +60,7 @@ PUBLIC STATIC Vector2 Vector::Interpolate(Vector2 v1, Vector2 v2, Sint64 t) { return result; } -PUBLIC STATIC Vector3 Vector::Interpolate(Vector3 v1, Vector3 v2, Sint64 t) { +Vector3 Vector::Interpolate(Vector3 v1, Vector3 v2, Sint64 t) { Vector3 result; result.X = v1.X + FP16_MULTIPLY(v2.X - v1.X, t); @@ -80,7 +70,7 @@ PUBLIC STATIC Vector3 Vector::Interpolate(Vector3 v1, Vector3 v2, Sint64 t) { return result; } -PUBLIC STATIC Vector4 Vector::Interpolate(Vector4 v1, Vector4 v2, Sint64 t) { +Vector4 Vector::Interpolate(Vector4 v1, Vector4 v2, Sint64 t) { Vector4 result; result.X = v1.X + FP16_MULTIPLY(v2.X - v1.X, t); @@ -91,7 +81,7 @@ PUBLIC STATIC Vector4 Vector::Interpolate(Vector4 v1, Vector4 v2, Sint64 t) { return result; } -PUBLIC STATIC Sint64 Vector::DotProduct(Vector4 v1, Vector4 v2) { +Sint64 Vector::DotProduct(Vector4 v1, Vector4 v2) { Sint64 result = 0; result += FP16_MULTIPLY(v1.X, v2.X); result += FP16_MULTIPLY(v1.Y, v2.Y); @@ -100,13 +90,13 @@ PUBLIC STATIC Sint64 Vector::DotProduct(Vector4 v1, Vector4 v2) { return result; } -PUBLIC STATIC Sint64 Vector::Length(Vector4 v) { +Sint64 Vector::Length(Vector4 v) { float result = Vector::DotProduct(v, v); result = sqrtf(result / 0x10000); return result * 0x10000; } -PUBLIC STATIC Vector4 Vector::Normalize(Vector4 v) { +Vector4 Vector::Normalize(Vector4 v) { Vector4 result; Sint64 length = Vector::Length(v); @@ -122,7 +112,7 @@ PUBLIC STATIC Vector4 Vector::Normalize(Vector4 v) { return result; } -PUBLIC STATIC Sint64 Vector::IntersectWithPlane(Vector4 plane, Vector4 normal, Vector4 v1, Vector4 v2) { +Sint64 Vector::IntersectWithPlane(Vector4 plane, Vector4 normal, Vector4 v1, Vector4 v2) { Vector4 planeNormal = Vector::Normalize(normal); Sint64 dotProduct = Vector::DotProduct(v1, planeNormal); Sint64 t = Vector::DotProduct(planeNormal, plane) - dotProduct; @@ -133,7 +123,7 @@ PUBLIC STATIC Sint64 Vector::IntersectWithPlane(Vector4 plane, Vector4 normal, return FP16_DIVIDE(t, diff); } -PUBLIC STATIC Sint64 Vector::DistanceToPlane(Vector4 v, Vector4 plane, Vector4 normal) { +Sint64 Vector::DistanceToPlane(Vector4 v, Vector4 plane, Vector4 normal) { Sint64 dotProduct = Vector::DotProduct(normal, plane); Sint64 result = 0; diff --git a/source/Engine/Media/Decoder.cpp b/source/Engine/Media/Decoder.cpp index c4911146..ceb3ddb3 100644 --- a/source/Engine/Media/Decoder.cpp +++ b/source/Engine/Media/Decoder.cpp @@ -1,31 +1,3 @@ -#if INTERFACE -#include -#include -#include -#include -#include -#include -#include - -class Decoder { -public: - bool Successful; - int StreamIndex; - double ClockSync; - double ClockPos; - - PtrBuffer* Buffer[2]; - SDL_mutex* OutputLock; - AVCodecContext* CodecCtx; - AVFormatContext* FormatCtx; - - Uint32 Format; // SDL_Format - - int (*DecodeFunc)(void*, AVPacket*); - void (*CloseFunc)(void*); -}; -#endif - #include #include @@ -43,11 +15,11 @@ enum { typedef void (*FreePacketCallback)(void*); // void (*)(void*) -PUBLIC STATIC void Decoder::FreeInVideoPacketFunc(void* packet) { +void Decoder::FreeInVideoPacketFunc(void* packet) { av_packet_free((AVPacket**)&packet); } -PUBLIC void Decoder::Create(MediaSource* src, int stream_index, int outBufferLength, void (*freeOutFunc)(void*), int thread_count) { +void Decoder::Create(MediaSource* src, int stream_index, int outBufferLength, void (*freeOutFunc)(void*), int thread_count) { if (outBufferLength <= 0) { Log::Print(Log::LOG_ERROR, "Decoder::Create: outBufferLength <= 0"); exit(-1); @@ -160,7 +132,7 @@ PUBLIC void Decoder::Create(MediaSource* src, int stream_index, int exit_0: return; } -PUBLIC void Decoder::Close() { +void Decoder::Close() { if (CloseFunc) CloseFunc(this); @@ -171,10 +143,10 @@ PUBLIC void Decoder::Close() { avcodec_close(CodecCtx); avcodec_free_context(&CodecCtx); } -PUBLIC Decoder::~Decoder() { +Decoder::~Decoder() { Close(); } -PUBLIC int Decoder::Run() { +int Decoder::Run() { AVPacket* in_packet; int is_output_full = 1; @@ -201,48 +173,48 @@ PUBLIC int Decoder::Run() { return 0; } // ---- Information API ---- -PUBLIC int Decoder::GetCodecInfo(Codec* codec) { +int Decoder::GetCodecInfo(Codec* codec) { codec->Threads = CodecCtx->thread_count; strncpy(codec->Name, CodecCtx->codec->name, KIT_CODEC_NAME_MAX - 1); strncpy(codec->Description, CodecCtx->codec->long_name, KIT_CODEC_DESC_MAX - 1); return 0; } -PUBLIC int Decoder::GetOutputFormat(OutputFormat* output) { +int Decoder::GetOutputFormat(OutputFormat* output) { output->Format = Format; return 0; } -PUBLIC int Decoder::GetStreamIndex() { +int Decoder::GetStreamIndex() { return StreamIndex; } // ---- Clock handling ---- -PUBLIC void Decoder::SetClockSync(double sync) { +void Decoder::SetClockSync(double sync) { ClockSync = sync; } -PUBLIC void Decoder::ChangeClockSync(double sync) { +void Decoder::ChangeClockSync(double sync) { ClockSync += sync; } // ---- Input buffer handling ---- -PUBLIC int Decoder::WriteInput(AVPacket* packet) { +int Decoder::WriteInput(AVPacket* packet) { return Buffer[KIT_DEC_BUF_IN]->Write(packet); } -PUBLIC AVPacket* Decoder::PeekInput() { +AVPacket* Decoder::PeekInput() { return (AVPacket*)Buffer[KIT_DEC_BUF_IN]->Peek(); } -PUBLIC AVPacket* Decoder::ReadInput() { +AVPacket* Decoder::ReadInput() { return (AVPacket*)Buffer[KIT_DEC_BUF_IN]->Read(); } -PUBLIC bool Decoder::CanWriteInput() { +bool Decoder::CanWriteInput() { return !(Buffer[KIT_DEC_BUF_IN]->IsFull()); } -PUBLIC void Decoder::AdvanceInput() { +void Decoder::AdvanceInput() { Buffer[KIT_DEC_BUF_IN]->Advance(); } -PUBLIC void Decoder::ClearInput() { +void Decoder::ClearInput() { Buffer[KIT_DEC_BUF_IN]->Clear(); } // ---- Output buffer handling ---- // Kit_([A-z0-9_]+)Buffer([A-z0-9_]*)\((.*)\) -PUBLIC int Decoder::WriteOutput(void* packet) { +int Decoder::WriteOutput(void* packet) { int ret = 1; if (SDL_LockMutex(OutputLock) == 0) { ret = Buffer[KIT_DEC_BUF_OUT]->Write(packet); @@ -250,7 +222,7 @@ PUBLIC int Decoder::WriteOutput(void* packet) { } return ret; } -PUBLIC void* Decoder::PeekOutput() { +void* Decoder::PeekOutput() { void* ret = NULL; if (SDL_LockMutex(OutputLock) == 0) { ret = Buffer[KIT_DEC_BUF_OUT]->Peek(); @@ -258,7 +230,7 @@ PUBLIC void* Decoder::PeekOutput() { } return ret; } -PUBLIC void* Decoder::ReadOutput() { +void* Decoder::ReadOutput() { void* ret = NULL; if (SDL_LockMutex(OutputLock) == 0) { ret = Buffer[KIT_DEC_BUF_OUT]->Read(); @@ -266,7 +238,7 @@ PUBLIC void* Decoder::ReadOutput() { } return ret; } -PUBLIC bool Decoder::CanWriteOutput() { +bool Decoder::CanWriteOutput() { bool ret = false; if (SDL_LockMutex(OutputLock) == 0) { ret = !(Buffer[KIT_DEC_BUF_OUT]->IsFull()); @@ -274,29 +246,29 @@ PUBLIC bool Decoder::CanWriteOutput() { } return ret; } -PUBLIC void Decoder::AdvanceOutput() { +void Decoder::AdvanceOutput() { if (SDL_LockMutex(OutputLock) == 0) { Buffer[KIT_DEC_BUF_OUT]->Advance(); SDL_UnlockMutex(OutputLock); } } -PUBLIC void Decoder::ClearOutput() { +void Decoder::ClearOutput() { if (SDL_LockMutex(OutputLock) == 0) { Buffer[KIT_DEC_BUF_OUT]->Clear(); SDL_UnlockMutex(OutputLock); } } -PUBLIC void Decoder::ForEachOutput(void (*cb)(void*, void*), void* userdata) { +void Decoder::ForEachOutput(void (*cb)(void*, void*), void* userdata) { if (SDL_LockMutex(OutputLock) == 0) { Buffer[KIT_DEC_BUF_OUT]->ForEachItemInBuffer(cb, userdata); SDL_UnlockMutex(OutputLock); } } -PUBLIC Uint32 Decoder::GetInputLength() { +Uint32 Decoder::GetInputLength() { return Buffer[KIT_DEC_BUF_IN]->GetLength(); } -PUBLIC Uint32 Decoder::GetOutputLength() { +Uint32 Decoder::GetOutputLength() { Uint32 len = 0; if (SDL_LockMutex(OutputLock) == 0) { len = Buffer[KIT_DEC_BUF_OUT]->GetLength(); @@ -304,16 +276,16 @@ PUBLIC Uint32 Decoder::GetOutputLength() { } return len; } -PUBLIC void Decoder::ClearBuffers() { +void Decoder::ClearBuffers() { ClearInput(); ClearOutput(); avcodec_flush_buffers(CodecCtx); } -PUBLIC int Decoder::LockOutput() { +int Decoder::LockOutput() { return SDL_LockMutex(OutputLock); } -PUBLIC void Decoder::UnlockOutput() { +void Decoder::UnlockOutput() { SDL_UnlockMutex(OutputLock); } diff --git a/source/Engine/Media/Decoders/AudioDecoder.cpp b/source/Engine/Media/Decoders/AudioDecoder.cpp index e2b9b8fa..1a6a99d2 100644 --- a/source/Engine/Media/Decoders/AudioDecoder.cpp +++ b/source/Engine/Media/Decoders/AudioDecoder.cpp @@ -1,20 +1,3 @@ -#if INTERFACE -#include -#include -#include - -class AudioDecoder : public Decoder { -public: - SwrContext* SWR; - AVFrame* ScratchFrame; - - int SampleRate; - int Channels; - int Bytes; - int IsSigned; -}; -#endif - #include #include @@ -33,7 +16,7 @@ struct AudioPacket { #define KIT_AUDIO_SYNC_THRESHOLD 0.05 // Lifecycle functions -PUBLIC AudioDecoder::AudioDecoder(MediaSource* src, int stream_index) { +AudioDecoder::AudioDecoder(MediaSource* src, int stream_index) { int ret; if (stream_index < 0) { Log::Print(Log::LOG_ERROR, "stream_index < 0"); @@ -128,7 +111,7 @@ PUBLIC AudioDecoder::AudioDecoder(MediaSource* src, int st // exit_0: return; } -PUBLIC void* AudioDecoder::CreateAudioPacket(const char* data, size_t len, double pts) { +void* AudioDecoder::CreateAudioPacket(const char* data, size_t len, double pts) { AudioPacket* packet = (AudioPacket*)calloc(1, sizeof(AudioPacket)); if (!packet) { Log::Print(Log::LOG_ERROR, "Something went horribly wrong. (Ran out of memory at AudioDecoder::CreateAudioPacket \"(AudioPacket*)calloc\")"); @@ -143,14 +126,14 @@ PUBLIC void* AudioDecoder::CreateAudioPacket(const char* data, s packet->pts = pts; return packet; } -PUBLIC STATIC void AudioDecoder::FreeAudioPacket(void* p) { +void AudioDecoder::FreeAudioPacket(void* p) { AudioPacket* packet = (AudioPacket*)p; delete packet->buffer; free(packet); } // Unique format info functions -PUBLIC AVSampleFormat AudioDecoder::FindAVSampleFormat(int format) { +AVSampleFormat AudioDecoder::FindAVSampleFormat(int format) { switch (format) { case AUDIO_U8: return AV_SAMPLE_FMT_U8; @@ -164,14 +147,14 @@ PUBLIC AVSampleFormat AudioDecoder::FindAVSampleFormat(int format) { return AV_SAMPLE_FMT_NONE; } } -PUBLIC Sint64 AudioDecoder::FindAVChannelLayout(int channels) { +Sint64 AudioDecoder::FindAVChannelLayout(int channels) { switch (channels) { case 1: return AV_CH_LAYOUT_MONO; case 2: return AV_CH_LAYOUT_STEREO; default: return AV_CH_LAYOUT_STEREO_DOWNMIX; } } -PUBLIC int AudioDecoder::FindChannelLayout(uint64_t channel_layout) { +int AudioDecoder::FindChannelLayout(uint64_t channel_layout) { switch (channel_layout) { case AV_CH_LAYOUT_MONO: return 1; case AV_CH_LAYOUT_STEREO: return 2; @@ -180,7 +163,7 @@ PUBLIC int AudioDecoder::FindChannelLayout(uint64_t channel_la } return 2; } -PUBLIC int AudioDecoder::FindBytes(AVSampleFormat fmt) { +int AudioDecoder::FindBytes(AVSampleFormat fmt) { switch (fmt) { case AV_SAMPLE_FMT_U8: case AV_SAMPLE_FMT_U8P: @@ -198,7 +181,7 @@ PUBLIC int AudioDecoder::FindBytes(AVSampleFormat fmt) { return 2; } } -PUBLIC int AudioDecoder::FindSignedness(AVSampleFormat fmt) { +int AudioDecoder::FindSignedness(AVSampleFormat fmt) { switch (fmt) { case AV_SAMPLE_FMT_U8P: case AV_SAMPLE_FMT_U8: @@ -207,7 +190,7 @@ PUBLIC int AudioDecoder::FindSignedness(AVSampleFormat fmt) { return 1; } } -PUBLIC int AudioDecoder::FindSDLSampleFormat(AVSampleFormat fmt) { +int AudioDecoder::FindSDLSampleFormat(AVSampleFormat fmt) { switch (fmt) { case AV_SAMPLE_FMT_U8: case AV_SAMPLE_FMT_U8P: @@ -227,7 +210,7 @@ PUBLIC int AudioDecoder::FindSDLSampleFormat(AVSampleFormat fm } // Common format info functions -PUBLIC int AudioDecoder::GetOutputFormat(OutputFormat* output) { +int AudioDecoder::GetOutputFormat(OutputFormat* output) { output->Format = Format; output->SampleRate = SampleRate; output->Channels = Channels; @@ -237,7 +220,7 @@ PUBLIC int AudioDecoder::GetOutputFormat(OutputFormat* output) } // Unique decoding functions -PUBLIC STATIC void AudioDecoder::ReadAudio(void* ptr) { +void AudioDecoder::ReadAudio(void* ptr) { #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101) AudioDecoder* self = (AudioDecoder*)ptr; int len, dst_linesize, dst_nb_samples, dst_bufsize; @@ -291,7 +274,7 @@ PUBLIC STATIC void AudioDecoder::ReadAudio(void* ptr) { } #endif } -PUBLIC STATIC int AudioDecoder::DecodeFunction(void* ptr, AVPacket* in_packet) { +int AudioDecoder::DecodeFunction(void* ptr, AVPacket* in_packet) { if (in_packet == NULL) { return 0; } @@ -378,7 +361,7 @@ PUBLIC STATIC int AudioDecoder::DecodeFunction(void* ptr, AVPacket* i #endif return 0; } -PUBLIC STATIC void AudioDecoder::CloseFunction(void* ptr) { +void AudioDecoder::CloseFunction(void* ptr) { AudioDecoder* self = (AudioDecoder*)ptr; if (self->ScratchFrame != NULL) { @@ -390,14 +373,14 @@ PUBLIC STATIC void AudioDecoder::CloseFunction(void* ptr) { } // Data functions -PUBLIC double AudioDecoder::GetPTS() { +double AudioDecoder::GetPTS() { AudioPacket* packet = (AudioPacket*)PeekOutput(); if (packet == NULL) { return -1.0; } return packet->pts; } -PUBLIC int AudioDecoder::GetAudioDecoderData(Uint8* buf, int len) { +int AudioDecoder::GetAudioDecoderData(Uint8* buf, int len) { AudioPacket* packet = NULL; int ret = 0; int bytes_per_sample = 0; diff --git a/source/Engine/Media/Decoders/VideoDecoder.cpp b/source/Engine/Media/Decoders/VideoDecoder.cpp index 80df28ca..afd57e9d 100644 --- a/source/Engine/Media/Decoders/VideoDecoder.cpp +++ b/source/Engine/Media/Decoders/VideoDecoder.cpp @@ -1,19 +1,3 @@ -#if INTERFACE -#include -#include -#include -#include - -class VideoDecoder : public Decoder { -public: - SwsContext* SWS; - AVFrame* ScratchFrame; - - int Width; - int Height; -}; -#endif - #include #include @@ -48,7 +32,7 @@ struct VideoPacket { }; // Lifecycle functions -PUBLIC VideoDecoder::VideoDecoder(MediaSource* src, int stream_index) { + VideoDecoder::VideoDecoder(MediaSource* src, int stream_index) { if (stream_index < 0) { Log::Print(Log::LOG_ERROR, "stream_index < 0"); return; @@ -110,7 +94,7 @@ PUBLIC VideoDecoder::VideoDecoder(MediaSource* src, int st // exit_0: return; } -PUBLIC void* VideoDecoder::CreateVideoPacket(AVFrame* frame, double pts) { +void* VideoDecoder::CreateVideoPacket(AVFrame* frame, double pts) { VideoPacket* packet = (VideoPacket*)calloc(1, sizeof(VideoPacket)); if (!packet) { Log::Print(Log::LOG_ERROR, "Something went horribly wrong. (Ran out of memory at VideoDecoder::CreateVideoPacket \"(VideoPacket*)calloc\")"); @@ -120,7 +104,7 @@ PUBLIC void* VideoDecoder::CreateVideoPacket(AVFrame* frame, dou packet->pts = pts; return packet; } -PUBLIC STATIC void VideoDecoder::FreeVideoPacket(void* p) { +void VideoDecoder::FreeVideoPacket(void* p) { VideoPacket* packet = (VideoPacket*)p; av_freep(&packet->frame->data[0]); av_frame_free(&packet->frame); @@ -128,7 +112,7 @@ PUBLIC STATIC void VideoDecoder::FreeVideoPacket(void* p) { } // Unique format info functions -PUBLIC AVPixelFormat VideoDecoder::FindAVPixelFormat(Uint32 format) { +AVPixelFormat VideoDecoder::FindAVPixelFormat(Uint32 format) { switch (format) { case SDL_PIXELFORMAT_YV12: return AV_PIX_FMT_YUV420P; case SDL_PIXELFORMAT_YUY2: return AV_PIX_FMT_YUYV422; @@ -146,7 +130,7 @@ PUBLIC AVPixelFormat VideoDecoder::FindAVPixelFormat(Uint32 format) { default: return AV_PIX_FMT_NONE; } } -PUBLIC int VideoDecoder::FindSDLPixelFormat(AVPixelFormat fmt) { +int VideoDecoder::FindSDLPixelFormat(AVPixelFormat fmt) { switch (fmt) { case AV_PIX_FMT_YUV420P: return SDL_PIXELFORMAT_YV12; @@ -164,7 +148,7 @@ PUBLIC int VideoDecoder::FindSDLPixelFormat(AVPixelFormat fmt) } // Common format info functions -PUBLIC int VideoDecoder::GetOutputFormat(OutputFormat* output) { +int VideoDecoder::GetOutputFormat(OutputFormat* output) { output->Format = Format; output->Width = Width; output->Height = Height; @@ -172,7 +156,7 @@ PUBLIC int VideoDecoder::GetOutputFormat(OutputFormat* output) } // Unique decoding functions -PUBLIC STATIC void VideoDecoder::ReadVideo(void* ptr) { +void VideoDecoder::ReadVideo(void* ptr) { #if LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(57, 48, 101) VideoDecoder* self = (VideoDecoder*)ptr; AVFrame* out_frame = NULL; @@ -213,7 +197,7 @@ PUBLIC STATIC void VideoDecoder::ReadVideo(void* ptr) { } #endif } -PUBLIC STATIC int VideoDecoder::DecodeFunction(void* ptr, AVPacket* in_packet) { +int VideoDecoder::DecodeFunction(void* ptr, AVPacket* in_packet) { if (in_packet == NULL) { return 0; } @@ -283,7 +267,7 @@ PUBLIC STATIC int VideoDecoder::DecodeFunction(void* ptr, AVPacket* i #endif return 0; } -PUBLIC STATIC void VideoDecoder::CloseFunction(void* ptr) { +void VideoDecoder::CloseFunction(void* ptr) { VideoDecoder* self = (VideoDecoder*)ptr; if (self->ScratchFrame != NULL) { av_frame_free(&self->ScratchFrame); @@ -294,14 +278,14 @@ PUBLIC STATIC void VideoDecoder::CloseFunction(void* ptr) { } // Data functions -PUBLIC double VideoDecoder::GetPTS() { +double VideoDecoder::GetPTS() { VideoPacket* packet = (VideoPacket*)PeekOutput(); if (packet == NULL) { return -1.0; } return packet->pts; } -PUBLIC int VideoDecoder::GetVideoDecoderData(Texture* texture) { +int VideoDecoder::GetVideoDecoderData(Texture* texture) { double sync_ts = 0.0; Uint32 limit_rounds = 0; VideoPacket* packet = NULL; diff --git a/source/Engine/Media/MediaPlayer.cpp b/source/Engine/Media/MediaPlayer.cpp index 7a030aab..37f1cd40 100644 --- a/source/Engine/Media/MediaPlayer.cpp +++ b/source/Engine/Media/MediaPlayer.cpp @@ -1,31 +1,3 @@ -#if INTERFACE -#include -#include -#include -#include - -class MediaPlayer { -public: - enum { - KIT_WAITING_TO_BE_PLAYABLE = 0, ///< Playback stopped or has not started yet. - KIT_PLAYING, ///< Playback started & player is actively decoding. - KIT_PAUSED, ///< Playback paused; player is actively decoding but no new data is given out. - KIT_CLOSED, ///< Playback is stopped and player is closing. - KIT_STOPPED, - }; - - Uint32 State; - Decoder* Decoders[3]; - SDL_Thread* DecoderThread; - SDL_mutex* DecoderLock; - MediaSource* Source; - double PauseStarted; - double PausedPosition; - double SeekStarted; - Uint32 WaitState; -}; -#endif - #ifdef USING_LIBAV #include @@ -61,7 +33,7 @@ All of this is based on SDL_Kitchensink */ // Demux/decode running functions -PUBLIC STATIC int MediaPlayer::DemuxAllStreams(MediaPlayer* player) { +int MediaPlayer::DemuxAllStreams(MediaPlayer* player) { // Return 0 if stream is good but nothing else to do for now. // Return -1 if there may still work to be done. // Return 1 if there was an error or stream end. @@ -123,7 +95,7 @@ PUBLIC STATIC int MediaPlayer::DemuxAllStreams(MediaPlayer* player) { av_packet_free(&packet); return DEMUXER_KEEP_READING; } -PUBLIC STATIC int MediaPlayer::RunAllDecoders(MediaPlayer* player) { +int MediaPlayer::RunAllDecoders(MediaPlayer* player) { int got; bool has_room = true; @@ -161,7 +133,7 @@ PUBLIC STATIC int MediaPlayer::RunAllDecoders(MediaPlayer* player) { while (has_room); return DECODER_RUN_OKAY; } -PUBLIC STATIC int MediaPlayer::DecoderThreadFunc(void* ptr) { +int MediaPlayer::DecoderThreadFunc(void* ptr) { MediaPlayer* player = (MediaPlayer*)ptr; bool is_running = true; bool is_playing = true; @@ -212,7 +184,7 @@ PUBLIC STATIC int MediaPlayer::DecoderThreadFunc(void* ptr) { } // Lifecycle functions -PUBLIC STATIC MediaPlayer* MediaPlayer::Create(MediaSource* src, int video_stream_index, int audio_stream_index, int subtitle_stream_index, int screen_w, int screen_h) { +MediaPlayer* MediaPlayer::Create(MediaSource* src, int video_stream_index, int audio_stream_index, int subtitle_stream_index, int screen_w, int screen_h) { if (!src) { Log::Print(Log::LOG_ERROR, "MediaPlayer::Create: src == NULL"); exit(-1); @@ -336,7 +308,7 @@ PUBLIC STATIC MediaPlayer* MediaPlayer::Create(MediaSource* src, int video_strea exit_0: return NULL; } -PUBLIC void MediaPlayer::Close() { +void MediaPlayer::Close() { // Kill the decoder thread and mutex if (SDL_LockMutex(this->DecoderLock) == 0) { this->State = KIT_CLOSED; @@ -373,28 +345,28 @@ PUBLIC void MediaPlayer::Close() { } // Info functions -PUBLIC void MediaPlayer::SetScreenSize(int w, int h) { +void MediaPlayer::SetScreenSize(int w, int h) { // SubtitleDecoder* dec = (SubtitleDecoder*)Decoders[KIT_SUBTITLE_DEC]; // if (dec == NULL) // return; // dec->SetSize(w, h); } -PUBLIC int MediaPlayer::GetVideoStream() { +int MediaPlayer::GetVideoStream() { if (!Decoders[KIT_VIDEO_DEC]) return -1; return Decoders[KIT_VIDEO_DEC]->GetStreamIndex(); } -PUBLIC int MediaPlayer::GetAudioStream() { +int MediaPlayer::GetAudioStream() { if (!Decoders[KIT_AUDIO_DEC]) return -1; return Decoders[KIT_AUDIO_DEC]->GetStreamIndex(); } -PUBLIC int MediaPlayer::GetSubtitleStream() { +int MediaPlayer::GetSubtitleStream() { if (!Decoders[KIT_SUBTITLE_DEC]) return -1; return Decoders[KIT_SUBTITLE_DEC]->GetStreamIndex(); } -PUBLIC void MediaPlayer::GetInfo(PlayerInfo* info) { +void MediaPlayer::GetInfo(PlayerInfo* info) { if (!info) { Log::Print(Log::LOG_ERROR, "MediaPlayer::GetInfo: info == NULL"); exit(-1); @@ -427,11 +399,11 @@ PUBLIC void MediaPlayer::GetInfo(PlayerInfo* info) { } } } -PUBLIC double MediaPlayer::GetDuration() { +double MediaPlayer::GetDuration() { AVFormatContext* fmt_ctx = (AVFormatContext*)this->Source->FormatCtx; return (fmt_ctx->duration / AV_TIME_BASE); } -PUBLIC double MediaPlayer::GetPosition() { +double MediaPlayer::GetPosition() { if (State != KIT_PLAYING) return PausedPosition; @@ -445,7 +417,7 @@ PUBLIC double MediaPlayer::GetPosition() { } return 0; } -PUBLIC double MediaPlayer::GetBufferPosition() { +double MediaPlayer::GetBufferPosition() { double maxPTS = 0.0; for (int i = 0; i < KIT_DEC_COUNT; i++) { Decoder* dec = this->Decoders[i]; @@ -467,7 +439,7 @@ PUBLIC double MediaPlayer::GetBufferPosition() { } // Data functions -PUBLIC bool MediaPlayer::ManageWaiting() { +bool MediaPlayer::ManageWaiting() { if (IsOutputEmpty()) { return true; } @@ -502,7 +474,7 @@ PUBLIC bool MediaPlayer::ManageWaiting() { } return false; } -PUBLIC int MediaPlayer::GetVideoData(Texture* texture) { +int MediaPlayer::GetVideoData(Texture* texture) { Decoder* dec = (Decoder*)Decoders[KIT_VIDEO_DEC]; if (dec == NULL) { return 0; @@ -523,7 +495,7 @@ PUBLIC int MediaPlayer::GetVideoData(Texture* texture) { return ((VideoDecoder*)dec)->GetVideoDecoderData(texture); } -PUBLIC int MediaPlayer::GetVideoDataForPaused(Texture* texture) { +int MediaPlayer::GetVideoDataForPaused(Texture* texture) { Decoder* dec = (Decoder*)Decoders[KIT_VIDEO_DEC]; if (dec == NULL) { return 0; @@ -531,7 +503,7 @@ PUBLIC int MediaPlayer::GetVideoDataForPaused(Texture* texture) return ((VideoDecoder*)dec)->GetVideoDecoderData(texture); } -PUBLIC int MediaPlayer::GetAudioData(unsigned char* buffer, int length) { +int MediaPlayer::GetAudioData(unsigned char* buffer, int length) { if (!buffer) { Log::Print(Log::LOG_ERROR, "MediaPlayer::GetAudioData: buffer == NULL"); exit(-1); @@ -562,7 +534,7 @@ PUBLIC int MediaPlayer::GetAudioData(unsigned char* buffer, int return ((AudioDecoder*)dec)->GetAudioDecoderData(buffer, length); } -PUBLIC int MediaPlayer::GetSubtitleData(Texture* texture, SDL_Rect* sources, SDL_Rect* targets, int limit) { +int MediaPlayer::GetSubtitleData(Texture* texture, SDL_Rect* sources, SDL_Rect* targets, int limit) { /* // NOTE: All asserts need to be removed/replaced. assert(texture != NULL); @@ -600,21 +572,21 @@ PUBLIC int MediaPlayer::GetSubtitleData(Texture* texture, SDL_Re } // Clock functions -PUBLIC void MediaPlayer::SetClockSync() { +void MediaPlayer::SetClockSync() { double sync = MediaPlayerState::GetSystemTime(); for (int i = 0; i < KIT_DEC_COUNT; i++) { if (Decoders[i]) Decoders[i]->SetClockSync(sync); } } -PUBLIC void MediaPlayer::SetClockSyncOffset(double offset) { +void MediaPlayer::SetClockSyncOffset(double offset) { double sync = MediaPlayerState::GetSystemTime(); for (int i = 0; i < KIT_DEC_COUNT; i++) { if (Decoders[i]) Decoders[i]->SetClockSync(sync + offset); } } -PUBLIC void MediaPlayer::ChangeClockSync(double delta) { +void MediaPlayer::ChangeClockSync(double delta) { for (int i = 0; i < KIT_DEC_COUNT; i++) { if (Decoders[i]) Decoders[i]->ChangeClockSync(delta); @@ -622,7 +594,7 @@ PUBLIC void MediaPlayer::ChangeClockSync(double delta) { } // State functions -PUBLIC void MediaPlayer::Play() { +void MediaPlayer::Play() { double tmp; switch (this->State) { case KIT_WAITING_TO_BE_PLAYABLE: @@ -655,7 +627,7 @@ PUBLIC void MediaPlayer::Play() { break; } } -PUBLIC void MediaPlayer::Stop() { +void MediaPlayer::Stop() { MediaPlayer* player = this; if (SDL_LockMutex(player->DecoderLock) == 0) { switch (player->State) { @@ -675,7 +647,7 @@ PUBLIC void MediaPlayer::Stop() { SDL_UnlockMutex(player->DecoderLock); } } -PUBLIC void MediaPlayer::Pause() { +void MediaPlayer::Pause() { switch (this->State) { case KIT_WAITING_TO_BE_PLAYABLE: this->WaitState = KIT_PAUSED; @@ -687,7 +659,7 @@ PUBLIC void MediaPlayer::Pause() { this->State = KIT_PAUSED; this->PauseStarted = MediaPlayerState::GetSystemTime(); } -PUBLIC int MediaPlayer::Seek(double seek_set) { +int MediaPlayer::Seek(double seek_set) { MediaPlayer* player = this; double position; double duration = 1.0; @@ -760,12 +732,12 @@ PUBLIC int MediaPlayer::Seek(double seek_set) { return 0; } -PUBLIC Uint32 MediaPlayer::GetPlayerState() { +Uint32 MediaPlayer::GetPlayerState() { return this->State; } // Buffer checks -PUBLIC bool MediaPlayer::IsInputEmpty() { +bool MediaPlayer::IsInputEmpty() { for (int i = 0; i < KIT_DEC_COUNT; i++) { Decoder* dec = (Decoder*)this->Decoders[i]; if (dec == NULL) @@ -775,7 +747,7 @@ PUBLIC bool MediaPlayer::IsInputEmpty() { } return true; } -PUBLIC bool MediaPlayer::IsOutputEmpty() { +bool MediaPlayer::IsOutputEmpty() { for (int i = 0; i < KIT_DEC_COUNT; i++) { Decoder* dec = (Decoder*)this->Decoders[i]; if (dec == NULL) @@ -787,13 +759,13 @@ PUBLIC bool MediaPlayer::IsOutputEmpty() { } // ??? -PUBLIC STATIC Uint32 MediaPlayer::GetInputLength(MediaPlayer* player, int i) { +Uint32 MediaPlayer::GetInputLength(MediaPlayer* player, int i) { Decoder* dec = player->Decoders[i]; if (dec == NULL) return 0; return dec->GetInputLength(); } -PUBLIC STATIC Uint32 MediaPlayer::GetOutputLength(MediaPlayer* player, int i) { +Uint32 MediaPlayer::GetOutputLength(MediaPlayer* player, int i) { Decoder* dec = player->Decoders[i]; if (dec == NULL) return 0; diff --git a/source/Engine/Media/MediaSource.cpp b/source/Engine/Media/MediaSource.cpp index 939bd018..d20daf15 100644 --- a/source/Engine/Media/MediaSource.cpp +++ b/source/Engine/Media/MediaSource.cpp @@ -1,25 +1,3 @@ -#if INTERFACE -#include -#include -#include - -class MediaSource { -public: - enum { - STREAMTYPE_UNKNOWN, - STREAMTYPE_VIDEO, - STREAMTYPE_AUDIO, - STREAMTYPE_DATA, - STREAMTYPE_SUBTITLE, - STREAMTYPE_ATTACHMENT - }; - - void* FormatCtx; - void* AvioCtx; - Stream* StreamPtr; -} -#endif - #include #include @@ -88,7 +66,7 @@ void _AVLogCallback(void *ptr, int level, const char* fmt, va_list vargs) { #endif -PUBLIC STATIC MediaSource* MediaSource::CreateSourceFromUrl(const char* url) { +MediaSource* MediaSource::CreateSourceFromUrl(const char* url) { if (!url) return NULL; @@ -122,7 +100,7 @@ PUBLIC STATIC MediaSource* MediaSource::CreateSourceFromUrl(const char* url) { return NULL; } -PUBLIC STATIC MediaSource* MediaSource::CreateSourceFromStream(Stream* stream) { +MediaSource* MediaSource::CreateSourceFromStream(Stream* stream) { #ifdef USING_LIBAV AVIOContext* avio_ctx = NULL; Uint8* avio_ctx_buffer = NULL; @@ -196,7 +174,7 @@ PUBLIC STATIC MediaSource* MediaSource::CreateSourceFromStream(Stream* stream) { return NULL; } -PUBLIC int MediaSource::GetStreamInfo(Uint32* info, int index) { +int MediaSource::GetStreamInfo(Uint32* info, int index) { if (!info) return 1; @@ -232,13 +210,13 @@ PUBLIC int MediaSource::GetStreamInfo(Uint32* info, int index) { return 0; } -PUBLIC int MediaSource::GetStreamCount() { +int MediaSource::GetStreamCount() { #ifdef USING_LIBAV return ((AVFormatContext*)FormatCtx)->nb_streams; #endif return 0; } -PUBLIC int MediaSource::GetBestStream(Uint32 type) { +int MediaSource::GetBestStream(Uint32 type) { #ifdef USING_LIBAV int avmedia_type = 0; switch (type) { @@ -260,7 +238,7 @@ PUBLIC int MediaSource::GetBestStream(Uint32 type) { return -1; } -PUBLIC void MediaSource::Close() { +void MediaSource::Close() { #ifdef USING_LIBAV AVFormatContext* format_ctx = (AVFormatContext*)this->FormatCtx; AVIOContext* avio_ctx = (AVIOContext*)this->AvioCtx; diff --git a/source/Engine/Media/Utils/MediaPlayerState.cpp b/source/Engine/Media/Utils/MediaPlayerState.cpp index c936e973..68b491ed 100644 --- a/source/Engine/Media/Utils/MediaPlayerState.cpp +++ b/source/Engine/Media/Utils/MediaPlayerState.cpp @@ -1,19 +1,3 @@ -#if INTERFACE -#include - -class MediaPlayerState { -public: - static Uint32 InitFlags; - static Uint32 ThreadCount; - static Uint32 FontHinting; - static Uint32 VideoBufFrames; - static Uint32 AudioBufFrames; - static Uint32 SubtitleBufFrames; - static void* LibassHandle; - static void* AssSharedObjectHandle; -}; -#endif - #include #include #include @@ -39,10 +23,10 @@ const char* const font_mime[] = { #ifdef USING_LIBAV -PUBLIC STATIC double MediaPlayerState::GetSystemTime() { +double MediaPlayerState::GetSystemTime() { return (double)av_gettime() / 1000000.0; } -PUBLIC STATIC bool MediaPlayerState::AttachmentIsFont(void* p) { +bool MediaPlayerState::AttachmentIsFont(void* p) { AVStream* stream = (AVStream*)p; AVDictionaryEntry *tag = av_dict_get(stream->metadata, "mimetype", NULL, AV_DICT_MATCH_CASE); if (tag) { diff --git a/source/Engine/Media/Utils/PtrBuffer.cpp b/source/Engine/Media/Utils/PtrBuffer.cpp index 00f02f17..d25406e3 100644 --- a/source/Engine/Media/Utils/PtrBuffer.cpp +++ b/source/Engine/Media/Utils/PtrBuffer.cpp @@ -1,22 +1,8 @@ -#if INTERFACE -#include -#include - -class PtrBuffer { -public: - Uint32 ReadPtr; - Uint32 WritePtr; - Uint32 Size; - void** Data; - void (*FreeFunc)(void*); -}; -#endif - #include #include -PUBLIC PtrBuffer::PtrBuffer(Uint32 size, void (*freeFunc)(void*)) { +PtrBuffer::PtrBuffer(Uint32 size, void (*freeFunc)(void*)) { this->ReadPtr = 0; this->WritePtr = 0; this->Size = size; @@ -28,15 +14,15 @@ PUBLIC PtrBuffer::PtrBuffer(Uint32 size, void (*freeFunc)(void*)) { exit(-1); } } -PUBLIC PtrBuffer::~PtrBuffer() { +PtrBuffer::~PtrBuffer() { Clear(); free(this->Data); } -PUBLIC Uint32 PtrBuffer::GetLength() { +Uint32 PtrBuffer::GetLength() { return this->WritePtr - this->ReadPtr; } -PUBLIC void PtrBuffer::Clear() { +void PtrBuffer::Clear() { if (FreeFunc == NULL) return; @@ -45,7 +31,7 @@ PUBLIC void PtrBuffer::Clear() { FreeFunc(data); } } -PUBLIC void* PtrBuffer::Read() { +void* PtrBuffer::Read() { if (ReadPtr < WritePtr) { void* out = Data[ReadPtr % Size]; Data[ReadPtr % Size] = NULL; @@ -58,13 +44,13 @@ PUBLIC void* PtrBuffer::Read() { } return NULL; } -PUBLIC void* PtrBuffer::Peek() { +void* PtrBuffer::Peek() { if (ReadPtr < WritePtr) { return Data[ReadPtr % Size]; } return NULL; } -PUBLIC void PtrBuffer::Advance() { +void PtrBuffer::Advance() { if (ReadPtr < WritePtr) { Data[ReadPtr % Size] = NULL; ReadPtr++; @@ -74,7 +60,7 @@ PUBLIC void PtrBuffer::Advance() { } } } -PUBLIC int PtrBuffer::Write(void* ptr) { +int PtrBuffer::Write(void* ptr) { if (!ptr) { Log::Print(Log::LOG_ERROR, "PtrBuffer::Write: ptr == NULL"); exit(-1); @@ -87,7 +73,7 @@ PUBLIC int PtrBuffer::Write(void* ptr) { } return 1; } -PUBLIC void PtrBuffer::ForEachItemInBuffer(void (*callback)(void*, void*), void* userdata) { +void PtrBuffer::ForEachItemInBuffer(void (*callback)(void*, void*), void* userdata) { Uint32 read_p = ReadPtr; Uint32 write_p = WritePtr; while (read_p < write_p) { @@ -98,7 +84,7 @@ PUBLIC void PtrBuffer::ForEachItemInBuffer(void (*callback)(void*, void*), voi } } } -PUBLIC void PtrBuffer::WithEachItemInBuffer(std::function callback, void* userdata) { +void PtrBuffer::WithEachItemInBuffer(std::function callback, void* userdata) { Uint32 read_p = ReadPtr; Uint32 write_p = WritePtr; while (read_p < write_p) { @@ -109,7 +95,7 @@ PUBLIC void PtrBuffer::WithEachItemInBuffer(std::function } } } -PUBLIC int PtrBuffer::IsFull() { +int PtrBuffer::IsFull() { int len = WritePtr - ReadPtr; int k = (len >= (int)Size); return k; diff --git a/source/Engine/Media/Utils/RingBuffer.cpp b/source/Engine/Media/Utils/RingBuffer.cpp index b7850f96..6952add4 100644 --- a/source/Engine/Media/Utils/RingBuffer.cpp +++ b/source/Engine/Media/Utils/RingBuffer.cpp @@ -1,21 +1,8 @@ -#if INTERFACE -#include - -class RingBuffer { -public: - int Size; - int Length; - int WritePos; - int ReadPos; - char* Data; -}; -#endif - #include #include -PUBLIC RingBuffer::RingBuffer(Uint32 size) { +RingBuffer::RingBuffer(Uint32 size) { this->Length = 0; this->WritePos = 0; this->ReadPos = 0; @@ -27,10 +14,10 @@ PUBLIC RingBuffer::RingBuffer(Uint32 size) { exit(-1); } } -PUBLIC RingBuffer::~RingBuffer() { +RingBuffer::~RingBuffer() { free(this->Data); } -PUBLIC int RingBuffer::Write(const char* data, int len) { +int RingBuffer::Write(const char* data, int len) { int k; len = (len > (this->Size - this->Length)) ? (this->Size - this->Length) : len; if (this->Length < this->Size) { @@ -52,7 +39,7 @@ PUBLIC int RingBuffer::Write(const char* data, int len) { return 0; } -PUBLIC void RingBuffer::ReadData(char* data, const int len) { +void RingBuffer::ReadData(char* data, const int len) { int k; if (len + this->ReadPos > this->Size) { k = (len + this->ReadPos) % this->Size; @@ -63,7 +50,7 @@ PUBLIC void RingBuffer::ReadData(char* data, const int len) { memcpy(data, this->Data + this->ReadPos, len); } } -PUBLIC int RingBuffer::Read(char* data, int len) { +int RingBuffer::Read(char* data, int len) { len = (len > this->Length) ? this->Length : len; if (this->Length > 0) { ReadData(data, len); @@ -76,7 +63,7 @@ PUBLIC int RingBuffer::Read(char* data, int len) { } return 0; } -PUBLIC int RingBuffer::Peek(char *data, int len) { +int RingBuffer::Peek(char *data, int len) { len = (len > this->Length) ? this->Length : len; if (this->Length > 0) { ReadData(data, len); @@ -84,7 +71,7 @@ PUBLIC int RingBuffer::Peek(char *data, int len) { } return 0; } -PUBLIC int RingBuffer::Advance(int len) { +int RingBuffer::Advance(int len) { len = (len > this->Length) ? this->Length : len; if (this->Length > 0) { this->Length -= len; @@ -96,12 +83,12 @@ PUBLIC int RingBuffer::Advance(int len) { } return 0; } -PUBLIC int RingBuffer::GetLength() { +int RingBuffer::GetLength() { return this->Length; } -PUBLIC int RingBuffer::GetSize() { +int RingBuffer::GetSize() { return this->Size; } -PUBLIC int RingBuffer::GetFree() { +int RingBuffer::GetFree() { return this->Size - this->Length; } diff --git a/source/Engine/Network/HTTP.cpp b/source/Engine/Network/HTTP.cpp index 8ea55f53..6a93cb9c 100644 --- a/source/Engine/Network/HTTP.cpp +++ b/source/Engine/Network/HTTP.cpp @@ -1,14 +1,3 @@ -#if INTERFACE -#include -#include -#include - -class HTTP { -public: - -}; -#endif - #include #include @@ -109,7 +98,7 @@ int _GET_FromThread(void* op) { #endif -PUBLIC STATIC bool HTTP::GET(const char* url, Uint8** outBuf, size_t* outLen, ObjBoundMethod* callback) { +bool HTTP::GET(const char* url, Uint8** outBuf, size_t* outLen, ObjBoundMethod* callback) { #ifdef USING_CURL if (!curl) { diff --git a/source/Engine/Network/WebSocketClient.cpp b/source/Engine/Network/WebSocketClient.cpp index 07bfdf1e..98493333 100644 --- a/source/Engine/Network/WebSocketClient.cpp +++ b/source/Engine/Network/WebSocketClient.cpp @@ -1,29 +1,3 @@ -#if INTERFACE -#include -#include - -#include - -class WebSocketClient { -public: - enum { - CLOSING = 0, - CLOSED = 1, - CONNECTING = 2, - OPEN = 3, - }; - - std::vector rxbuf; - std::vector txbuf; - std::vector receivedData; - - socket_t socket; - int readyState; - bool useMask; - bool isRxBad; -}; -#endif - #include const char* BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; @@ -239,7 +213,7 @@ size_t socket_send_string(socket_t sockfd, const char* str, ...) { // easywsclient -PUBLIC STATIC WebSocketClient* WebSocketClient::New(const char* url) { +WebSocketClient* WebSocketClient::New(const char* url) { #ifdef _WIN32 INT rc; WSADATA wsaData; @@ -358,7 +332,7 @@ PUBLIC STATIC WebSocketClient* WebSocketClient::New(const char* url) { delete socket; return NULL; } -PUBLIC void WebSocketClient::Poll(int timeout) { +void WebSocketClient::Poll(int timeout) { if (readyState == WebSocketClient::CLOSED) { if (timeout > 0) { timeval tv = { timeout / 1000, (timeout % 1000) * 1000 }; @@ -426,7 +400,7 @@ PUBLIC void WebSocketClient::Poll(int timeout) { printf("readyState = CLOSED 2\n"); } } -PUBLIC void WebSocketClient::Dispatch(void(*callback)(void* mem, size_t size)) { +void WebSocketClient::Dispatch(void(*callback)(void* mem, size_t size)) { // TODO: consider acquiring a lock on rxbuf... if (isRxBad) { printf("bad rx\n"); @@ -541,7 +515,7 @@ PUBLIC void WebSocketClient::Dispatch(void(*callback)(void* m } } -PUBLIC size_t WebSocketClient::BytesToRead() { +size_t WebSocketClient::BytesToRead() { if (readyState == WebSocketClient::CLOSED || readyState == WebSocketClient::CLOSING) return 0; @@ -661,27 +635,27 @@ PUBLIC size_t WebSocketClient::BytesToRead() { } return 0; } -PUBLIC size_t WebSocketClient::ReadBytes(void* data, size_t n) { +size_t WebSocketClient::ReadBytes(void* data, size_t n) { memcpy(data, receivedData.data(), n); receivedData.erase(receivedData.begin(), receivedData.begin() + n); return n; } -PUBLIC Uint32 WebSocketClient::ReadUint32() { +Uint32 WebSocketClient::ReadUint32() { Uint32 data; ReadBytes(&data, sizeof(data)); return data; } -PUBLIC Sint32 WebSocketClient::ReadSint32() { +Sint32 WebSocketClient::ReadSint32() { Sint32 data; ReadBytes(&data, sizeof(data)); return data; } -PUBLIC float WebSocketClient::ReadFloat() { +float WebSocketClient::ReadFloat() { float data; ReadBytes(&data, sizeof(data)); return data; } -PUBLIC char* WebSocketClient::ReadString() { +char* WebSocketClient::ReadString() { char* data = (char*)receivedData.data(); char* dataStart = data; char* dataEnd = data + receivedData.size(); @@ -698,7 +672,7 @@ PUBLIC char* WebSocketClient::ReadString() { return output; } -PUBLIC void WebSocketClient::SendData(int type, const void* message, int64_t message_size) { +void WebSocketClient::SendData(int type, const void* message, int64_t message_size) { // TODO: // Masking key should (must) be derived from a high quality random // number generator, to mitigate attacks on non-WebSocketClient friendly @@ -759,13 +733,13 @@ PUBLIC void WebSocketClient::SendData(int type, const void* m } } } -PUBLIC void WebSocketClient::SendBinary(const void* message, int64_t message_size) { +void WebSocketClient::SendBinary(const void* message, int64_t message_size) { SendData(opcode_type::BINARY_FRAME, message, message_size); } -PUBLIC void WebSocketClient::SendText(const char* message) { +void WebSocketClient::SendText(const char* message) { SendData(opcode_type::TEXT_FRAME, message, (int64_t)strlen(message)); } -PUBLIC void WebSocketClient::Close() { +void WebSocketClient::Close() { if (readyState == WebSocketClient::CLOSING || readyState == WebSocketClient::CLOSED) return; diff --git a/source/Engine/Rendering/D3D/D3DRenderer.cpp b/source/Engine/Rendering/D3D/D3DRenderer.cpp index 40347700..1418b368 100644 --- a/source/Engine/Rendering/D3D/D3DRenderer.cpp +++ b/source/Engine/Rendering/D3D/D3DRenderer.cpp @@ -1,17 +1,3 @@ -#if INTERFACE -#include -#include -#include -#include -#include - -#include - -class D3DRenderer { -public: -}; -#endif - #ifdef USING_DIRECT3D #include @@ -669,7 +655,7 @@ void D3D_EndDrawShape(Vertex* shapeBuffer, D3DPRIMITIVETYPE prim, int tri } // Initialization and disposal functions -PUBLIC STATIC void D3DRenderer::Init() { +void D3DRenderer::Init() { Graphics::PreferredPixelFormat = SDL_PIXELFORMAT_ARGB8888; D3D_MatrixIdentity = Matrix4x4::Create(); @@ -836,13 +822,13 @@ PUBLIC STATIC void D3DRenderer::Init() { Log::Print(Log::LOG_INFO, "Graphics Card: %s", indent.Description); } -PUBLIC STATIC Uint32 D3DRenderer::GetWindowFlags() { +Uint32 D3DRenderer::GetWindowFlags() { return 0; } -PUBLIC STATIC void D3DRenderer::SetVSync(bool enabled) { +void D3DRenderer::SetVSync(bool enabled) { } -PUBLIC STATIC void D3DRenderer::SetGraphicsFunctions() { +void D3DRenderer::SetGraphicsFunctions() { Graphics::PixelOffset = 0.5f; Graphics::Internal.Init = D3DRenderer::Init; @@ -912,7 +898,7 @@ PUBLIC STATIC void D3DRenderer::SetGraphicsFunctions() { Graphics::Internal.ClearScene3D = D3DRenderer::ClearScene3D; Graphics::Internal.DrawScene3D = D3DRenderer::DrawScene3D; } -PUBLIC STATIC void D3DRenderer::Dispose() { +void D3DRenderer::Dispose() { Memory::Free(D3D_BufferCircleFill); Memory::Free(D3D_BufferCircleStroke); Memory::Free(D3D_BufferSquareFill); @@ -924,7 +910,7 @@ PUBLIC STATIC void D3DRenderer::Dispose() { } // Texture management functions -PUBLIC STATIC Texture* D3DRenderer::CreateTexture(Uint32 format, Uint32 access, Uint32 width, Uint32 height) { +Texture* D3DRenderer::CreateTexture(Uint32 format, Uint32 access, Uint32 width, Uint32 height) { Texture* texture = Texture::New(format, access, width, height); D3D_CreateTexture(texture); @@ -934,10 +920,10 @@ PUBLIC STATIC Texture* D3DRenderer::CreateTexture(Uint32 format, Uint32 access, return texture; } -PUBLIC STATIC int D3DRenderer::LockTexture(Texture* texture, void** pixels, int* pitch) { +int D3DRenderer::LockTexture(Texture* texture, void** pixels, int* pitch) { return 0; } -PUBLIC STATIC int D3DRenderer::UpdateTexture(Texture* texture, SDL_Rect* r, void* pixels, int pitch) { +int D3DRenderer::UpdateTexture(Texture* texture, SDL_Rect* r, void* pixels, int pitch) { int inputPixelsX = 0; int inputPixelsY = 0; int inputPixelsW = texture->Width; @@ -1011,10 +997,10 @@ PUBLIC STATIC int D3DRenderer::UpdateTexture(Texture* texture, SDL_Rect* r, return 0; } -PUBLIC STATIC void D3DRenderer::UnlockTexture(Texture* texture) { +void D3DRenderer::UnlockTexture(Texture* texture) { } -PUBLIC STATIC void D3DRenderer::DisposeTexture(Texture* texture) { +void D3DRenderer::DisposeTexture(Texture* texture) { D3D_TextureData* textureData = (D3D_TextureData*)texture->DriverData; if (!textureData) return; @@ -1035,15 +1021,15 @@ PUBLIC STATIC void D3DRenderer::DisposeTexture(Texture* texture) { } // Viewport and view-related functions -PUBLIC STATIC void D3DRenderer::SetRenderTarget(Texture* texture) { +void D3DRenderer::SetRenderTarget(Texture* texture) { D3D_Predraw(); D3D_SetRenderTarget(texture); } -PUBLIC STATIC void D3DRenderer::UpdateWindowSize(int width, int height) { +void D3DRenderer::UpdateWindowSize(int width, int height) { // D3D_UpdateViewport(0, 0, width, height); renderData->UpdateBackBufferSize = true; } -PUBLIC STATIC void D3DRenderer::UpdateViewport() { +void D3DRenderer::UpdateViewport() { Viewport* vp = &Graphics::CurrentViewport; D3DVIEWPORT9 viewport; @@ -1059,7 +1045,7 @@ PUBLIC STATIC void D3DRenderer::UpdateViewport() { // D3DRenderer::UpdateOrtho(vp->Width, vp->Height); D3DRenderer::UpdateProjectionMatrix(); } -PUBLIC STATIC void D3DRenderer::UpdateClipRect() { +void D3DRenderer::UpdateClipRect() { ClipArea clip = Graphics::CurrentClip; if (Graphics::CurrentClip.Enabled) { Viewport view = Graphics::CurrentViewport; @@ -1089,7 +1075,7 @@ PUBLIC STATIC void D3DRenderer::UpdateClipRect() { IDirect3DDevice9_SetRenderState(renderData->Device, D3DRS_SCISSORTESTENABLE, FALSE); } } -PUBLIC STATIC void D3DRenderer::UpdateOrtho(float left, float top, float right, float bottom) { +void D3DRenderer::UpdateOrtho(float left, float top, float right, float bottom) { if (Scene::Views[Scene::ViewCurrent].Software) Matrix4x4::Ortho(Scene::Views[Scene::ViewCurrent].BaseProjectionMatrix, left, right, bottom, top, 500.0f, -500.0f); else @@ -1101,27 +1087,27 @@ PUBLIC STATIC void D3DRenderer::UpdateOrtho(float left, float top, float rig D3D_RenderScaleY = Graphics::CurrentViewport.Height / top; } } -PUBLIC STATIC void D3DRenderer::UpdatePerspective(float fovy, float aspect, float nearv, float farv) { +void D3DRenderer::UpdatePerspective(float fovy, float aspect, float nearv, float farv) { MakePerspectiveMatrix(Scene::Views[Scene::ViewCurrent].BaseProjectionMatrix, fovy, nearv, farv, aspect); Matrix4x4::Copy(Scene::Views[Scene::ViewCurrent].ProjectionMatrix, Scene::Views[Scene::ViewCurrent].BaseProjectionMatrix); } -PUBLIC STATIC void D3DRenderer::UpdateProjectionMatrix() { +void D3DRenderer::UpdateProjectionMatrix() { D3DMATRIX matrix; memcpy(&matrix.m, Scene::Views[Scene::ViewCurrent].ProjectionMatrix->Values, sizeof(float) * 16); IDirect3DDevice9_SetTransform(renderData->Device, D3DTS_PROJECTION, &matrix); } -PUBLIC STATIC void D3DRenderer::MakePerspectiveMatrix(Matrix4x4* out, float fov, float near, float far, float aspect) { +void D3DRenderer::MakePerspectiveMatrix(Matrix4x4* out, float fov, float near, float far, float aspect) { Matrix4x4::Perspective(out, fov, aspect, near, far); } // Shader-related functions -PUBLIC STATIC void D3DRenderer::UseShader(void* shader) { +void D3DRenderer::UseShader(void* shader) { // if (D3D_CurrentShader != (D3DShader*)shader) { // D3D_CurrentShader = (D3DShader*)shader; // D3D_CurrentShader->Use(); // } } -PUBLIC STATIC void D3DRenderer::SetUniformF(int location, int count, float* values) { +void D3DRenderer::SetUniformF(int location, int count, float* values) { // switch (count) { // case 1: glUniform1f(location, values[0]); CHECK_GL(); break; // case 2: glUniform2f(location, values[0], values[1]); CHECK_GL(); break; @@ -1129,15 +1115,15 @@ PUBLIC STATIC void D3DRenderer::SetUniformF(int location, int count, float* // case 4: glUniform4f(location, values[0], values[1], values[2], values[3]); CHECK_GL(); break; // } } -PUBLIC STATIC void D3DRenderer::SetUniformI(int location, int count, int* values) { +void D3DRenderer::SetUniformI(int location, int count, int* values) { // glUniform1iv(location, count, values); } -PUBLIC STATIC void D3DRenderer::SetUniformTexture(Texture* texture, int uniform_index, int slot) { +void D3DRenderer::SetUniformTexture(Texture* texture, int uniform_index, int slot) { } // These guys -PUBLIC STATIC void D3DRenderer::Clear() { +void D3DRenderer::Clear() { DWORD color; HRESULT result; int BackBufferWidth, BackBufferHeight; @@ -1201,7 +1187,7 @@ PUBLIC STATIC void D3DRenderer::Clear() { D3D_SetError("Clear()", result); } } -PUBLIC STATIC void D3DRenderer::Present() { +void D3DRenderer::Present() { HRESULT result; if (!renderData->BeginScene) { @@ -1226,34 +1212,34 @@ PUBLIC STATIC void D3DRenderer::Present() { } // Draw mode setting functions -PUBLIC STATIC void D3DRenderer::SetBlendColor(float r, float g, float b, float a) { +void D3DRenderer::SetBlendColor(float r, float g, float b, float a) { int ha = (int)(a * 0xFF) << 24; int hr = (int)(r * 0xFF) << 16; int hg = (int)(g * 0xFF) << 8; int hb = (int)(b * 0xFF); D3D_BlendColorsAsHex = ha | hr | hg | hb; } -PUBLIC STATIC void D3DRenderer::SetBlendMode(int srcC, int dstC, int srcA, int dstA) { +void D3DRenderer::SetBlendMode(int srcC, int dstC, int srcA, int dstA) { D3D_Blend_SRC_COLOR = D3D_GetBlendFactorFromHatch(srcC); D3D_Blend_DST_COLOR = D3D_GetBlendFactorFromHatch(dstC); D3D_Blend_SRC_ALPHA = D3D_GetBlendFactorFromHatch(srcA); D3D_Blend_DST_ALPHA = D3D_GetBlendFactorFromHatch(dstA); } -PUBLIC STATIC void D3DRenderer::SetTintColor(float r, float g, float b, float a) { +void D3DRenderer::SetTintColor(float r, float g, float b, float a) { } -PUBLIC STATIC void D3DRenderer::SetTintMode(int mode) { +void D3DRenderer::SetTintMode(int mode) { } -PUBLIC STATIC void D3DRenderer::SetTintEnabled(bool enabled) { +void D3DRenderer::SetTintEnabled(bool enabled) { } -PUBLIC STATIC void D3DRenderer::SetLineWidth(float n) { +void D3DRenderer::SetLineWidth(float n) { } // Primitive drawing functions -PUBLIC STATIC void D3DRenderer::StrokeLine(float x1, float y1, float x2, float y2) { +void D3DRenderer::StrokeLine(float x1, float y1, float x2, float y2) { // UseShader(D3D_SelectedShader ? D3D_SelectedShader : D3D_ShaderShape); Graphics::Save(); @@ -1268,7 +1254,7 @@ PUBLIC STATIC void D3DRenderer::StrokeLine(float x1, float y1, float x2, flo // glDrawArrays(GL_LINES, 0, 2); Graphics::Restore(); } -PUBLIC STATIC void D3DRenderer::StrokeCircle(float x, float y, float rad, float thickness) { +void D3DRenderer::StrokeCircle(float x, float y, float rad, float thickness) { D3D_BeginDrawShape(D3D_BufferCircleStroke, 361); Graphics::Save(); @@ -1281,7 +1267,7 @@ PUBLIC STATIC void D3DRenderer::StrokeCircle(float x, float y, float rad, fl D3D_EndDrawShape(D3D_BufferCircleStroke, D3DPT_LINESTRIP, 360); } -PUBLIC STATIC void D3DRenderer::StrokeEllipse(float x, float y, float w, float h) { +void D3DRenderer::StrokeEllipse(float x, float y, float w, float h) { // UseShader(D3D_SelectedShader ? D3D_SelectedShader : D3D_ShaderShape); Graphics::Save(); @@ -1294,14 +1280,14 @@ PUBLIC STATIC void D3DRenderer::StrokeEllipse(float x, float y, float w, flo // glDrawArrays(GL_LINE_STRIP, 0, 361); Graphics::Restore(); } -PUBLIC STATIC void D3DRenderer::StrokeRectangle(float x, float y, float w, float h) { +void D3DRenderer::StrokeRectangle(float x, float y, float w, float h) { StrokeLine(x, y, x + w, y); StrokeLine(x, y + h, x + w, y + h); StrokeLine(x, y, x, y + h); StrokeLine(x + w, y, x + w, y + h); } -PUBLIC STATIC void D3DRenderer::FillCircle(float x, float y, float rad) { +void D3DRenderer::FillCircle(float x, float y, float rad) { D3D_BeginDrawShape(D3D_BufferCircleFill, 362); Graphics::Save(); @@ -1314,7 +1300,7 @@ PUBLIC STATIC void D3DRenderer::FillCircle(float x, float y, float rad) { D3D_EndDrawShape(D3D_BufferCircleFill, D3DPT_TRIANGLEFAN, 360); } -PUBLIC STATIC void D3DRenderer::FillEllipse(float x, float y, float w, float h) { +void D3DRenderer::FillEllipse(float x, float y, float w, float h) { D3D_BeginDrawShape(D3D_BufferCircleFill, 362); w *= 0.5f; @@ -1330,7 +1316,7 @@ PUBLIC STATIC void D3DRenderer::FillEllipse(float x, float y, float w, float D3D_EndDrawShape(D3D_BufferCircleFill, D3DPT_TRIANGLEFAN, 360); } -PUBLIC STATIC void D3DRenderer::FillTriangle(float x1, float y1, float x2, float y2, float x3, float y3) { +void D3DRenderer::FillTriangle(float x1, float y1, float x2, float y2, float x3, float y3) { Vertex vertices[3]; vertices[0] = Vertex { x1, y1, 0.0f, D3D_BlendColorsAsHex, 0.0f, 0.0f }; vertices[1] = Vertex { x2, y2, 0.0f, D3D_BlendColorsAsHex, 0.0f, 0.0f }; @@ -1344,7 +1330,7 @@ PUBLIC STATIC void D3DRenderer::FillTriangle(float x1, float y1, float x2, f D3D_EndDrawShape(vertices, D3DPT_TRIANGLEFAN, 1); } -PUBLIC STATIC void D3DRenderer::FillRectangle(float x, float y, float w, float h) { +void D3DRenderer::FillRectangle(float x, float y, float w, float h) { D3D_BeginDrawShape(D3D_BufferSquareFill, 4); Graphics::Save(); @@ -1359,13 +1345,13 @@ PUBLIC STATIC void D3DRenderer::FillRectangle(float x, float y, float w, flo } // Texture drawing functions -PUBLIC STATIC void D3DRenderer::DrawTexture(Texture* texture, float sx, float sy, float sw, float sh, float x, float y, float w, float h) { +void D3DRenderer::DrawTexture(Texture* texture, float sx, float sy, float sw, float sh, float x, float y, float w, float h) { // UseShader(D3D_SelectedShader ? D3D_SelectedShader : D3D_ShaderTexturedShape); if (sx < 0) sx = 0.0, sy = 0.0, sw = texture->Width, sh = texture->Height; D3D_DrawTextureRaw(texture, sx, sy, sw, sh, x, y, w, h, false, texture->Access != SDL_TEXTUREACCESS_TARGET); } -PUBLIC STATIC void D3DRenderer::DrawSprite(ISprite* sprite, int animation, int frame, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID) { +void D3DRenderer::DrawSprite(ISprite* sprite, int animation, int frame, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID) { if (Graphics::SpriteRangeCheck(sprite, animation, frame)) return; AnimFrame animframe = sprite->Animations[animation].Frames[frame]; @@ -1381,7 +1367,7 @@ PUBLIC STATIC void D3DRenderer::DrawSprite(ISprite* sprite, int animation, i D3D_DrawTextureRaw(sprite->Spritesheets[animframe.SheetNumber], animframe.X, animframe.Y, animframe.Width, animframe.Height, animframe.OffsetX, animframe.OffsetY, animframe.Width, animframe.Height, flipX, flipY); Graphics::Restore(); } -PUBLIC STATIC void D3DRenderer::DrawSpritePart(ISprite* sprite, int animation, int frame, int sx, int sy, int sw, int sh, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID) { +void D3DRenderer::DrawSpritePart(ISprite* sprite, int animation, int frame, int sx, int sy, int sw, int sh, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID) { if (Graphics::SpriteRangeCheck(sprite, animation, frame)) return; AnimFrame animframe = sprite->Animations[animation].Frames[frame]; @@ -1410,40 +1396,40 @@ PUBLIC STATIC void D3DRenderer::DrawSpritePart(ISprite* sprite, int animatio Graphics::Restore(); } // 3D drawing functions -PUBLIC STATIC void D3DRenderer::DrawPolygon3D(void* data, int vertexCount, int vertexFlag, Texture* texture, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +void D3DRenderer::DrawPolygon3D(void* data, int vertexCount, int vertexFlag, Texture* texture, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { } -PUBLIC STATIC void D3DRenderer::DrawSceneLayer3D(void* layer, int sx, int sy, int sw, int sh, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +void D3DRenderer::DrawSceneLayer3D(void* layer, int sx, int sy, int sw, int sh, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { } -PUBLIC STATIC void D3DRenderer::DrawModel(void* model, Uint16 animation, Uint32 frame, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +void D3DRenderer::DrawModel(void* model, Uint16 animation, Uint32 frame, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { } -PUBLIC STATIC void D3DRenderer::DrawModelSkinned(void* model, Uint16 armature, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +void D3DRenderer::DrawModelSkinned(void* model, Uint16 armature, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { } -PUBLIC STATIC void D3DRenderer::DrawVertexBuffer(Uint32 vertexBufferIndex, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +void D3DRenderer::DrawVertexBuffer(Uint32 vertexBufferIndex, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { } -PUBLIC STATIC void D3DRenderer::BindVertexBuffer(Uint32 vertexBufferIndex) { +void D3DRenderer::BindVertexBuffer(Uint32 vertexBufferIndex) { } -PUBLIC STATIC void D3DRenderer::UnbindVertexBuffer() { +void D3DRenderer::UnbindVertexBuffer() { } -PUBLIC STATIC void D3DRenderer::BindScene3D(Uint32 sceneIndex) { +void D3DRenderer::BindScene3D(Uint32 sceneIndex) { } -PUBLIC STATIC void D3DRenderer::ClearScene3D(Uint32 sceneIndex) { +void D3DRenderer::ClearScene3D(Uint32 sceneIndex) { } -PUBLIC STATIC void D3DRenderer::DrawScene3D(Uint32 sceneIndex, Uint32 drawMode) { +void D3DRenderer::DrawScene3D(Uint32 sceneIndex, Uint32 drawMode) { } /* // Draw buffering -PUBLIC STATIC Uint32 D3DRenderer::CreateTexturedShapeBuffer(float** data, int vertexCount) { +Uint32 D3DRenderer::CreateTexturedShapeBuffer(float** data, int vertexCount) { // x, y, z, u, v Uint32 bufferID; glGenBuffers(1, &bufferID); @@ -1455,7 +1441,7 @@ PUBLIC STATIC Uint32 D3DRenderer::CreateTexturedShapeBuffer(float** data, int return bufferID; } -PUBLIC STATIC void D3DRenderer::DrawTexturedShapeBuffer(Texture* texture, Uint32 bufferID, int vertexCount) { +void D3DRenderer::DrawTexturedShapeBuffer(Texture* texture, Uint32 bufferID, int vertexCount) { UseShader(D3D_SelectedShader ? D3D_SelectedShader : D3D_ShaderTexturedShape); GLTextureData* textureData = (GLTextureData*)texture->DriverData; diff --git a/source/Engine/Rendering/FaceInfo.cpp b/source/Engine/Rendering/FaceInfo.cpp index 306b2e95..3a14be5c 100644 --- a/source/Engine/Rendering/FaceInfo.cpp +++ b/source/Engine/Rendering/FaceInfo.cpp @@ -1,25 +1,6 @@ -#if INTERFACE -#include -#include -#include -#include - -class FaceInfo { -public: - Uint32 DrawMode; - Uint32 NumVertices; - Uint32 VerticesStartIndex; - bool UseMaterial; - FaceMaterial MaterialInfo; - BlendState Blend; - Uint8 CullMode; - int Depth; -}; -#endif - #include -PUBLIC void FaceInfo::SetMaterial(Material* material) { +void FaceInfo::SetMaterial(Material* material) { if (!material) { UseMaterial = false; return; @@ -39,7 +20,7 @@ PUBLIC void FaceInfo::SetMaterial(Material* material) { } } -PUBLIC void FaceInfo::SetMaterial(Texture* texture) { +void FaceInfo::SetMaterial(Texture* texture) { if (!texture) { UseMaterial = false; return; @@ -55,6 +36,6 @@ PUBLIC void FaceInfo::SetMaterial(Texture* texture) { } } -PUBLIC void FaceInfo::SetBlendState(BlendState blendState) { +void FaceInfo::SetBlendState(BlendState blendState) { Blend = blendState; } diff --git a/source/Engine/Rendering/GL/GLRenderer.cpp b/source/Engine/Rendering/GL/GLRenderer.cpp index d3978cc5..28d2994a 100644 --- a/source/Engine/Rendering/GL/GLRenderer.cpp +++ b/source/Engine/Rendering/GL/GLRenderer.cpp @@ -1,35 +1,3 @@ -#if INTERFACE -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class GLRenderer { -public: - static SDL_GLContext Context; - static GLShader* CurrentShader; - - static GLShaderContainer* ShaderShape; - static GLShaderContainer* ShaderShape3D; - static GLShaderContainer* ShaderFogLinear; - static GLShaderContainer* ShaderFogExp; - static GLShaderContainer* ShaderYUV; - - static GLint DefaultFramebuffer; - static GLint DefaultRenderbuffer; - - static GLuint BufferCircleFill; - static GLuint BufferCircleStroke; - static GLuint BufferSquareFill; -}; -#endif - #ifdef USING_OPENGL // #define HAVE_GL_PERFSTATS @@ -912,7 +880,7 @@ PolygonRenderer* GL_GetPolygonRenderer() { } // Initialization and disposal functions -PUBLIC STATIC void GLRenderer::Init() { +void GLRenderer::Init() { Graphics::SupportsBatching = true; Graphics::PreferredPixelFormat = SDL_PIXELFORMAT_ABGR8888; @@ -1031,7 +999,7 @@ PUBLIC STATIC void GLRenderer::Init() { glClearColor(0.0, 0.0, 0.0, 0.0); CHECK_GL(); } -PUBLIC STATIC Uint32 GLRenderer::GetWindowFlags() { +Uint32 GLRenderer::GetWindowFlags() { #ifdef GL_SUPPORTS_MULTISAMPLING if (Graphics::MultisamplingEnabled) { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); CHECK_GL(); @@ -1041,7 +1009,7 @@ PUBLIC STATIC Uint32 GLRenderer::GetWindowFlags() { return SDL_WINDOW_OPENGL; } -PUBLIC STATIC void GLRenderer::SetVSync(bool enabled) { +void GLRenderer::SetVSync(bool enabled) { if (enabled) { if (SDL_GL_SetSwapInterval(-1) < 0) { CHECK_GL(); @@ -1058,7 +1026,7 @@ PUBLIC STATIC void GLRenderer::SetVSync(bool enabled) { } Graphics::VsyncEnabled = enabled; } -PUBLIC STATIC void GLRenderer::SetGraphicsFunctions() { +void GLRenderer::SetGraphicsFunctions() { Graphics::PixelOffset = 0.0f; Graphics::Internal.Init = GLRenderer::Init; @@ -1139,7 +1107,7 @@ PUBLIC STATIC void GLRenderer::SetGraphicsFunctions() { Graphics::Internal.SetDepthTesting = GLRenderer::SetDepthTesting; } -PUBLIC STATIC void GLRenderer::Dispose() { +void GLRenderer::Dispose() { glDeleteBuffers(1, &BufferCircleFill); CHECK_GL(); glDeleteBuffers(1, &BufferCircleStroke); CHECK_GL(); glDeleteBuffers(1, &BufferSquareFill); CHECK_GL(); @@ -1154,7 +1122,7 @@ PUBLIC STATIC void GLRenderer::Dispose() { } // Texture management functions -PUBLIC STATIC Texture* GLRenderer::CreateTexture(Uint32 format, Uint32 access, Uint32 width, Uint32 height) { +Texture* GLRenderer::CreateTexture(Uint32 format, Uint32 access, Uint32 width, Uint32 height) { Texture* texture = Texture::New(format, access, width, height); texture->DriverData = Memory::TrackedCalloc("Texture::DriverData", 1, sizeof(GL_TextureData)); @@ -1277,10 +1245,10 @@ PUBLIC STATIC Texture* GLRenderer::CreateTexture(Uint32 format, Uint32 access, U return texture; } -PUBLIC STATIC int GLRenderer::LockTexture(Texture* texture, void** pixels, int* pitch) { +int GLRenderer::LockTexture(Texture* texture, void** pixels, int* pitch) { return 0; } -PUBLIC STATIC int GLRenderer::UpdateTexture(Texture* texture, SDL_Rect* src, void* pixels, int pitch) { +int GLRenderer::UpdateTexture(Texture* texture, SDL_Rect* src, void* pixels, int pitch) { Uint32 inputPixelsX = 0; Uint32 inputPixelsY = 0; Uint32 inputPixelsW = texture->Width; @@ -1311,7 +1279,7 @@ PUBLIC STATIC int GLRenderer::UpdateTexture(Texture* texture, SDL_Rect* src textureData->PixelDataFormat, textureData->PixelDataType, pixels); CHECK_GL(); return 0; } -PUBLIC STATIC int GLRenderer::UpdateTextureYUV(Texture* texture, SDL_Rect* src, void* pixelsY, int pitchY, void* pixelsU, int pitchU, void* pixelsV, int pitchV) { +int GLRenderer::UpdateTextureYUV(Texture* texture, SDL_Rect* src, void* pixelsY, int pitchY, void* pixelsU, int pitchU, void* pixelsV, int pitchV) { int inputPixelsX = 0; int inputPixelsY = 0; int inputPixelsW = texture->Width; @@ -1348,10 +1316,10 @@ PUBLIC STATIC int GLRenderer::UpdateTextureYUV(Texture* texture, SDL_Rect* textureData->PixelDataFormat, textureData->PixelDataType, pixelsV); CHECK_GL(); return 0; } -PUBLIC STATIC void GLRenderer::UnlockTexture(Texture* texture) { +void GLRenderer::UnlockTexture(Texture* texture) { } -PUBLIC STATIC void GLRenderer::DisposeTexture(Texture* texture) { +void GLRenderer::DisposeTexture(Texture* texture) { GL_TextureData* textureData = (GL_TextureData*)texture->DriverData; if (!textureData) return; @@ -1376,7 +1344,7 @@ PUBLIC STATIC void GLRenderer::DisposeTexture(Texture* texture) { } // Viewport and view-related functions -PUBLIC STATIC void GLRenderer::SetRenderTarget(Texture* texture) { +void GLRenderer::SetRenderTarget(Texture* texture) { if (texture == NULL) { glBindFramebuffer(GL_FRAMEBUFFER, DefaultFramebuffer); CHECK_GL(); @@ -1405,7 +1373,7 @@ PUBLIC STATIC void GLRenderer::SetRenderTarget(Texture* texture) { CHECK_GL(); } } -PUBLIC STATIC void GLRenderer::ReadFramebuffer(void* pixels, int width, int height) { +void GLRenderer::ReadFramebuffer(void* pixels, int width, int height) { glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels); if (Graphics::CurrentRenderTarget) @@ -1423,10 +1391,10 @@ PUBLIC STATIC void GLRenderer::ReadFramebuffer(void* pixels, int width, int delete[] temp; } -PUBLIC STATIC void GLRenderer::UpdateWindowSize(int width, int height) { +void GLRenderer::UpdateWindowSize(int width, int height) { GLRenderer::UpdateViewport(); } -PUBLIC STATIC void GLRenderer::UpdateViewport() { +void GLRenderer::UpdateViewport() { Viewport* vp = &Graphics::CurrentViewport; if (Graphics::CurrentRenderTarget) { glViewport(vp->X * RetinaScale, vp->Y * RetinaScale, vp->Width * RetinaScale, vp->Height * RetinaScale); CHECK_GL(); @@ -1440,7 +1408,7 @@ PUBLIC STATIC void GLRenderer::UpdateViewport() { // GLRenderer::UpdateOrtho(vp->Width, vp->Height); GLRenderer::UpdateProjectionMatrix(); } -PUBLIC STATIC void GLRenderer::UpdateClipRect() { +void GLRenderer::UpdateClipRect() { ClipArea clip = Graphics::CurrentClip; if (Graphics::CurrentClip.Enabled) { Viewport view = Graphics::CurrentViewport; @@ -1465,7 +1433,7 @@ PUBLIC STATIC void GLRenderer::UpdateClipRect() { glDisable(GL_SCISSOR_TEST); CHECK_GL(); } } -PUBLIC STATIC void GLRenderer::UpdateOrtho(float left, float top, float right, float bottom) { +void GLRenderer::UpdateOrtho(float left, float top, float right, float bottom) { // if (Graphics::CurrentRenderTarget) // Matrix4x4::Ortho(Scene::Views[Scene::ViewCurrent].BaseProjectionMatrix, left, right, bottom, top, -500.0f, 500.0f); // else @@ -1473,14 +1441,14 @@ PUBLIC STATIC void GLRenderer::UpdateOrtho(float left, float top, float righ Matrix4x4::Copy(Scene::Views[Scene::ViewCurrent].ProjectionMatrix, Scene::Views[Scene::ViewCurrent].BaseProjectionMatrix); } -PUBLIC STATIC void GLRenderer::UpdatePerspective(float fovy, float aspect, float nearv, float farv) { +void GLRenderer::UpdatePerspective(float fovy, float aspect, float nearv, float farv) { MakePerspectiveMatrix(Scene::Views[Scene::ViewCurrent].BaseProjectionMatrix, fovy, nearv, farv, aspect); Matrix4x4::Copy(Scene::Views[Scene::ViewCurrent].ProjectionMatrix, Scene::Views[Scene::ViewCurrent].BaseProjectionMatrix); } -PUBLIC STATIC void GLRenderer::UpdateProjectionMatrix() { +void GLRenderer::UpdateProjectionMatrix() { } -PUBLIC STATIC void GLRenderer::MakePerspectiveMatrix(Matrix4x4* out, float fov, float near, float far, float aspect) { +void GLRenderer::MakePerspectiveMatrix(Matrix4x4* out, float fov, float near, float far, float aspect) { float f = 1.0f / tanf(fov / 2.0f); float delta = far - near; @@ -1508,7 +1476,7 @@ PUBLIC STATIC void GLRenderer::MakePerspectiveMatrix(Matrix4x4* out, float f } // Shader-related functions -PUBLIC STATIC void GLRenderer::UseShader(void* shader) { +void GLRenderer::UseShader(void* shader) { if (GLRenderer::CurrentShader != (GLShader*)shader) { GLRenderer::CurrentShader = (GLShader*)shader; GLRenderer::CurrentShader->Use(); @@ -1517,7 +1485,7 @@ PUBLIC STATIC void GLRenderer::UseShader(void* shader) { glUniform1i(GLRenderer::CurrentShader->LocTexture, 0); CHECK_GL(); } } -PUBLIC STATIC void GLRenderer::SetUniformF(int location, int count, float* values) { +void GLRenderer::SetUniformF(int location, int count, float* values) { switch (count) { case 1: glUniform1f(location, values[0]); CHECK_GL(); break; case 2: glUniform2f(location, values[0], values[1]); CHECK_GL(); break; @@ -1525,10 +1493,10 @@ PUBLIC STATIC void GLRenderer::SetUniformF(int location, int count, float* v case 4: glUniform4f(location, values[0], values[1], values[2], values[3]); CHECK_GL(); break; } } -PUBLIC STATIC void GLRenderer::SetUniformI(int location, int count, int* values) { +void GLRenderer::SetUniformI(int location, int count, int* values) { glUniform1iv(location, count, values); CHECK_GL(); } -PUBLIC STATIC void GLRenderer::SetUniformTexture(Texture* texture, int uniform_index, int slot) { +void GLRenderer::SetUniformTexture(Texture* texture, int uniform_index, int slot) { GL_TextureData* textureData = (GL_TextureData*)texture->DriverData; glActiveTexture(GL_TEXTURE0 + slot); CHECK_GL(); glUniform1i(uniform_index, slot); CHECK_GL(); @@ -1536,12 +1504,12 @@ PUBLIC STATIC void GLRenderer::SetUniformTexture(Texture* texture, int unifo } // Palette-related functions -PUBLIC STATIC void GLRenderer::UpdateGlobalPalette() { +void GLRenderer::UpdateGlobalPalette() { } // These guys -PUBLIC STATIC void GLRenderer::Clear() { +void GLRenderer::Clear() { if (UseDepthTesting) { #ifdef GL_ES glClearDepthf(1.0f); CHECK_GL(); @@ -1554,34 +1522,34 @@ PUBLIC STATIC void GLRenderer::Clear() { glClear(GL_COLOR_BUFFER_BIT); CHECK_GL(); } } -PUBLIC STATIC void GLRenderer::Present() { +void GLRenderer::Present() { SDL_GL_SwapWindow(Application::Window); CHECK_GL(); } // Draw mode setting functions -PUBLIC STATIC void GLRenderer::SetBlendColor(float r, float g, float b, float a) { +void GLRenderer::SetBlendColor(float r, float g, float b, float a) { } -PUBLIC STATIC void GLRenderer::SetBlendMode(int srcC, int dstC, int srcA, int dstA) { +void GLRenderer::SetBlendMode(int srcC, int dstC, int srcA, int dstA) { glBlendFuncSeparate( GL_GetBlendFactorFromHatchEnum(srcC), GL_GetBlendFactorFromHatchEnum(dstC), GL_GetBlendFactorFromHatchEnum(srcA), GL_GetBlendFactorFromHatchEnum(dstA)); CHECK_GL(); } -PUBLIC STATIC void GLRenderer::SetTintColor(float r, float g, float b, float a) { +void GLRenderer::SetTintColor(float r, float g, float b, float a) { } -PUBLIC STATIC void GLRenderer::SetTintMode(int mode) { +void GLRenderer::SetTintMode(int mode) { } -PUBLIC STATIC void GLRenderer::SetTintEnabled(bool enabled) { +void GLRenderer::SetTintEnabled(bool enabled) { } -PUBLIC STATIC void GLRenderer::SetLineWidth(float n) { +void GLRenderer::SetLineWidth(float n) { glLineWidth(n); CHECK_GL(); } // Primitive drawing functions -PUBLIC STATIC void GLRenderer::StrokeLine(float x1, float y1, float x2, float y2) { +void GLRenderer::StrokeLine(float x1, float y1, float x2, float y2) { // Graphics::Save(); GL_Predraw(NULL); @@ -1594,7 +1562,7 @@ PUBLIC STATIC void GLRenderer::StrokeLine(float x1, float y1, float x2, floa glDrawArrays(GL_LINES, 0, 2); CHECK_GL(); // Graphics::Restore(); } -PUBLIC STATIC void GLRenderer::StrokeCircle(float x, float y, float rad, float thickness) { +void GLRenderer::StrokeCircle(float x, float y, float rad, float thickness) { Graphics::Save(); Graphics::Translate(x, y, 0.0f); Graphics::Scale(rad, rad, 1.0f); @@ -1605,7 +1573,7 @@ PUBLIC STATIC void GLRenderer::StrokeCircle(float x, float y, float rad, flo glDrawArrays(GL_LINE_STRIP, 0, 361); CHECK_GL(); Graphics::Restore(); } -PUBLIC STATIC void GLRenderer::StrokeEllipse(float x, float y, float w, float h) { +void GLRenderer::StrokeEllipse(float x, float y, float w, float h) { Graphics::Save(); Graphics::Translate(x + w / 2, y + h / 2, 0.0f); Graphics::Scale(w / 2, h / 2, 1.0f); @@ -1616,14 +1584,14 @@ PUBLIC STATIC void GLRenderer::StrokeEllipse(float x, float y, float w, floa glDrawArrays(GL_LINE_STRIP, 0, 361); CHECK_GL(); Graphics::Restore(); } -PUBLIC STATIC void GLRenderer::StrokeRectangle(float x, float y, float w, float h) { +void GLRenderer::StrokeRectangle(float x, float y, float w, float h) { StrokeLine(x, y, x + w, y); StrokeLine(x, y + h, x + w, y + h); StrokeLine(x, y, x, y + h); StrokeLine(x + w, y, x + w, y + h); } -PUBLIC STATIC void GLRenderer::FillCircle(float x, float y, float rad) { +void GLRenderer::FillCircle(float x, float y, float rad) { #ifdef GL_SUPPORTS_SMOOTHING if (Graphics::SmoothFill) { glEnable(GL_POLYGON_SMOOTH); CHECK_GL(); @@ -1646,7 +1614,7 @@ PUBLIC STATIC void GLRenderer::FillCircle(float x, float y, float rad) { } #endif } -PUBLIC STATIC void GLRenderer::FillEllipse(float x, float y, float w, float h) { +void GLRenderer::FillEllipse(float x, float y, float w, float h) { #ifdef GL_SUPPORTS_SMOOTHING if (Graphics::SmoothFill) { glEnable(GL_POLYGON_SMOOTH); CHECK_GL(); @@ -1669,7 +1637,7 @@ PUBLIC STATIC void GLRenderer::FillEllipse(float x, float y, float w, float } #endif } -PUBLIC STATIC void GLRenderer::FillTriangle(float x1, float y1, float x2, float y2, float x3, float y3) { +void GLRenderer::FillTriangle(float x1, float y1, float x2, float y2, float x3, float y3) { #ifdef GL_SUPPORTS_SMOOTHING if (Graphics::SmoothFill) { glEnable(GL_POLYGON_SMOOTH); CHECK_GL(); @@ -1692,7 +1660,7 @@ PUBLIC STATIC void GLRenderer::FillTriangle(float x1, float y1, float x2, fl } #endif } -PUBLIC STATIC void GLRenderer::FillRectangle(float x, float y, float w, float h) { +void GLRenderer::FillRectangle(float x, float y, float w, float h) { #ifdef GL_SUPPORTS_SMOOTHING if (Graphics::SmoothFill) { glEnable(GL_POLYGON_SMOOTH); CHECK_GL(); @@ -1716,7 +1684,7 @@ PUBLIC STATIC void GLRenderer::FillRectangle(float x, float y, float w, floa } #endif } -PUBLIC STATIC Uint32 GLRenderer::CreateTexturedShapeBuffer(float* data, int vertexCount) { +Uint32 GLRenderer::CreateTexturedShapeBuffer(float* data, int vertexCount) { // x, y, z, u, v Uint32 bufferID; glGenBuffers(1, &bufferID); CHECK_GL(); @@ -1724,7 +1692,7 @@ PUBLIC STATIC Uint32 GLRenderer::CreateTexturedShapeBuffer(float* data, int ve glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertexCount * 5, data, GL_STATIC_DRAW); CHECK_GL(); return bufferID; } -PUBLIC STATIC void GLRenderer::DrawTexturedShapeBuffer(Texture* texture, Uint32 bufferID, int vertexCount) { +void GLRenderer::DrawTexturedShapeBuffer(Texture* texture, Uint32 bufferID, int vertexCount) { GL_Predraw(texture); // glEnableVertexAttribArray(GLRenderer::CurrentShader->LocTexCoord); @@ -1738,14 +1706,14 @@ PUBLIC STATIC void GLRenderer::DrawTexturedShapeBuffer(Texture* texture, Uin } // Texture drawing functions -PUBLIC STATIC void GLRenderer::DrawTexture(Texture* texture, float sx, float sy, float sw, float sh, float x, float y, float w, float h) { +void GLRenderer::DrawTexture(Texture* texture, float sx, float sy, float sw, float sh, float x, float y, float w, float h) { x *= RetinaScale; y *= RetinaScale; w *= RetinaScale; h *= RetinaScale; GL_DrawTexture(texture, sx, sy, sw, sh, x, y, w, h); } -PUBLIC STATIC void GLRenderer::DrawSprite(ISprite* sprite, int animation, int frame, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID) { +void GLRenderer::DrawSprite(ISprite* sprite, int animation, int frame, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID) { if (Graphics::SpriteRangeCheck(sprite, animation, frame)) return; // /* @@ -1768,7 +1736,7 @@ PUBLIC STATIC void GLRenderer::DrawSprite(ISprite* sprite, int animation, in // x + fX * animframe.OffsetX, // y + fY * animframe.OffsetY, fX * sw, fY * sh); } -PUBLIC STATIC void GLRenderer::DrawSpritePart(ISprite* sprite, int animation, int frame, int sx, int sy, int sw, int sh, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID) { +void GLRenderer::DrawSpritePart(ISprite* sprite, int animation, int frame, int sx, int sy, int sw, int sh, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID) { if (Graphics::SpriteRangeCheck(sprite, animation, frame)) return; AnimFrame animframe = sprite->Animations[animation].Frames[frame]; @@ -1791,7 +1759,7 @@ PUBLIC STATIC void GLRenderer::DrawSpritePart(ISprite* sprite, int animation y + fY * (sy + animframe.OffsetY), fX * sw, fY * sh); } // 3D drawing functions -PUBLIC STATIC void GLRenderer::DrawPolygon3D(void* data, int vertexCount, int vertexFlag, Texture* texture, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +void GLRenderer::DrawPolygon3D(void* data, int vertexCount, int vertexFlag, Texture* texture, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { PolygonRenderer *renderer = GL_GetPolygonRenderer(); if (renderer != nullptr) { renderer->ModelMatrix = modelMatrix; @@ -1799,7 +1767,7 @@ PUBLIC STATIC void GLRenderer::DrawPolygon3D(void* data, int vertexCount, in renderer->DrawPolygon3D((VertexAttribute*)data, vertexCount, vertexFlag, texture); } } -PUBLIC STATIC void GLRenderer::DrawSceneLayer3D(void* layer, int sx, int sy, int sw, int sh, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +void GLRenderer::DrawSceneLayer3D(void* layer, int sx, int sy, int sw, int sh, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { PolygonRenderer *renderer = GL_GetPolygonRenderer(); if (renderer != nullptr) { renderer->ModelMatrix = modelMatrix; @@ -1807,7 +1775,7 @@ PUBLIC STATIC void GLRenderer::DrawSceneLayer3D(void* layer, int sx, int sy, renderer->DrawSceneLayer3D((SceneLayer*)layer, sx, sy, sw, sh); } } -PUBLIC STATIC void GLRenderer::DrawModel(void* inModel, Uint16 animation, Uint32 frame, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +void GLRenderer::DrawModel(void* inModel, Uint16 animation, Uint32 frame, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { PolygonRenderer *renderer = GL_GetPolygonRenderer(); if (renderer != nullptr) { renderer->ModelMatrix = modelMatrix; @@ -1815,7 +1783,7 @@ PUBLIC STATIC void GLRenderer::DrawModel(void* inModel, Uint16 animation, Ui renderer->DrawModel((IModel*)inModel, animation, frame); } } -PUBLIC STATIC void GLRenderer::DrawModelSkinned(void* inModel, Uint16 armature, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +void GLRenderer::DrawModelSkinned(void* inModel, Uint16 armature, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { PolygonRenderer *renderer = GL_GetPolygonRenderer(); if (renderer != nullptr) { renderer->ModelMatrix = modelMatrix; @@ -1823,7 +1791,7 @@ PUBLIC STATIC void GLRenderer::DrawModelSkinned(void* inModel, Uint16 armatu renderer->DrawModelSkinned((IModel*)inModel, armature); } } -PUBLIC STATIC void GLRenderer::DrawVertexBuffer(Uint32 vertexBufferIndex, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +void GLRenderer::DrawVertexBuffer(Uint32 vertexBufferIndex, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { if (Graphics::CurrentScene3D < 0 || vertexBufferIndex < 0 || vertexBufferIndex >= MAX_VERTEX_BUFFERS) return; @@ -1852,18 +1820,18 @@ PUBLIC STATIC void GLRenderer::DrawVertexBuffer(Uint32 vertexBufferIndex, Ma driverData = (GL_VertexBuffer*)scene->Buffer->DriverData; driverData->Changed = true; } -PUBLIC STATIC void GLRenderer::BindVertexBuffer(Uint32 vertexBufferIndex) { +void GLRenderer::BindVertexBuffer(Uint32 vertexBufferIndex) { } -PUBLIC STATIC void GLRenderer::UnbindVertexBuffer() { +void GLRenderer::UnbindVertexBuffer() { } -PUBLIC STATIC void GLRenderer::ClearScene3D(Uint32 sceneIndex) { +void GLRenderer::ClearScene3D(Uint32 sceneIndex) { Scene3D* scene = &Graphics::Scene3Ds[sceneIndex]; GL_VertexBuffer *driverData = (GL_VertexBuffer*)scene->Buffer->DriverData; driverData->Changed = true; } -PUBLIC STATIC void GLRenderer::DrawScene3D(Uint32 sceneIndex, Uint32 drawMode) { +void GLRenderer::DrawScene3D(Uint32 sceneIndex, Uint32 drawMode) { if (sceneIndex < 0 || sceneIndex >= MAX_3D_SCENES) return; @@ -2047,7 +2015,7 @@ PUBLIC STATIC void GLRenderer::DrawScene3D(Uint32 sceneIndex, Uint32 drawMod GLRenderer::SetDepthTesting(Graphics::UseDepthTesting); } -PUBLIC STATIC void* GLRenderer::CreateVertexBuffer(Uint32 maxVertices) { +void* GLRenderer::CreateVertexBuffer(Uint32 maxVertices) { VertexBuffer* vtxBuf = new VertexBuffer(maxVertices); vtxBuf->DriverData = Memory::TrackedCalloc("VertexBuffer::DriverData", 1, sizeof(GL_VertexBuffer)); @@ -2061,7 +2029,7 @@ PUBLIC STATIC void* GLRenderer::CreateVertexBuffer(Uint32 maxVertices) { return (void*)vtxBuf; } -PUBLIC STATIC void GLRenderer::DeleteVertexBuffer(void* vtxBuf) { +void GLRenderer::DeleteVertexBuffer(void* vtxBuf) { VertexBuffer* vertexBuffer = (VertexBuffer*)vtxBuf; GL_VertexBuffer* driverData = (GL_VertexBuffer*)vertexBuffer->DriverData; if (driverData) { @@ -2081,7 +2049,7 @@ PUBLIC STATIC void GLRenderer::DeleteVertexBuffer(void* vtxBuf) { delete vertexBuffer; } -PUBLIC STATIC void GLRenderer::MakeFrameBufferID(ISprite* sprite, AnimFrame* frame) { +void GLRenderer::MakeFrameBufferID(ISprite* sprite, AnimFrame* frame) { frame->ID = 0; float fX[4], fY[4]; @@ -2124,13 +2092,13 @@ PUBLIC STATIC void GLRenderer::MakeFrameBufferID(ISprite* sprite, AnimFrame* glBindBuffer(GL_ARRAY_BUFFER, frame->ID); CHECK_GL(); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); CHECK_GL(); } -PUBLIC STATIC void GLRenderer::DeleteFrameBufferID(AnimFrame* frame) { +void GLRenderer::DeleteFrameBufferID(AnimFrame* frame) { if (frame->ID) { glDeleteBuffers(1, (GLuint*)&frame->ID); CHECK_GL(); frame->ID = 0; } } -PUBLIC STATIC void GLRenderer::SetDepthTesting(bool enable) { +void GLRenderer::SetDepthTesting(bool enable) { if (UseDepthTesting) { if (enable) { glEnable(GL_DEPTH_TEST); CHECK_GL(); diff --git a/source/Engine/Rendering/GL/GLShader.cpp b/source/Engine/Rendering/GL/GLShader.cpp index 7e24ae08..415c8daa 100644 --- a/source/Engine/Rendering/GL/GLShader.cpp +++ b/source/Engine/Rendering/GL/GLShader.cpp @@ -1,42 +1,3 @@ -#if INTERFACE -#include -#include -#include - -#include - -class GLShader { -public: - GLuint ProgramID = 0; - GLuint VertexProgramID = 0; - GLuint FragmentProgramID = 0; - - GLint LocProjectionMatrix; - GLint LocModelViewMatrix; - GLint LocPosition; - GLint LocTexCoord; - GLint LocTexture; - GLint LocTextureU; - GLint LocTextureV; - GLint LocPalette; - GLint LocColor; - GLint LocVaryingColor; - GLint LocFogColor; - GLint LocFogLinearStart; - GLint LocFogLinearEnd; - GLint LocFogDensity; - GLint LocFogTable; - - char FilenameV[256]; - char FilenameF[256]; - - // Cache stuff - float CachedBlendColors[4]; - Matrix4x4* CachedProjectionMatrix = NULL; - Matrix4x4* CachedModelViewMatrix = NULL; -}; -#endif - #ifdef USING_OPENGL #include @@ -46,7 +7,7 @@ class GLShader { #define CHECK_GL() \ GLShader::CheckGLError(__LINE__) -PUBLIC GLShader::GLShader(std::string vertexShaderSource, std::string fragmentShaderSource) { +GLShader::GLShader(std::string vertexShaderSource, std::string fragmentShaderSource) { GLint compiled = GL_FALSE; ProgramID = glCreateProgram(); CHECK_GL(); @@ -76,7 +37,7 @@ PUBLIC GLShader::GLShader(std::string vertexShaderSource, std::string fra AttachAndLink(); } -PUBLIC GLShader::GLShader(Stream* streamVS, Stream* streamFS) { +GLShader::GLShader(Stream* streamVS, Stream* streamFS) { GLint compiled = GL_FALSE; ProgramID = glCreateProgram(); CHECK_GL(); @@ -150,7 +111,7 @@ PUBLIC GLShader::GLShader(Stream* streamVS, Stream* streamFS) { AttachAndLink(); } -PRIVATE void GLShader::AttachAndLink() { +void GLShader::AttachAndLink() { glAttachShader(ProgramID, VertexProgramID); CHECK_GL(); glAttachShader(ProgramID, FragmentProgramID); CHECK_GL(); @@ -189,7 +150,7 @@ PRIVATE void GLShader::AttachAndLink() { } -PUBLIC bool GLShader::CheckShaderError(GLuint shader) { +bool GLShader::CheckShaderError(GLuint shader) { int infoLogLength = 0; int maxLength = infoLogLength; @@ -205,7 +166,7 @@ PUBLIC bool GLShader::CheckShaderError(GLuint shader) { delete[] infoLog; return false; } -PUBLIC bool GLShader::CheckProgramError(GLuint prog) { +bool GLShader::CheckProgramError(GLuint prog) { int infoLogLength = 0; int maxLength = infoLogLength; @@ -222,23 +183,23 @@ PUBLIC bool GLShader::CheckProgramError(GLuint prog) { return false; } -PUBLIC GLuint GLShader::Use() { +GLuint GLShader::Use() { glUseProgram(ProgramID); CHECK_GL(); // glEnableVertexAttribArray(1); CHECK_GL(); return ProgramID; } -PUBLIC GLint GLShader::GetAttribLocation(const GLchar* identifier) { +GLint GLShader::GetAttribLocation(const GLchar* identifier) { GLint value = glGetAttribLocation(ProgramID, identifier); CHECK_GL(); return value; } -PUBLIC GLint GLShader::GetUniformLocation(const GLchar* identifier) { +GLint GLShader::GetUniformLocation(const GLchar* identifier) { GLint value = glGetUniformLocation(ProgramID, identifier); CHECK_GL(); return value; } -PUBLIC GLShader::~GLShader() { +GLShader::~GLShader() { if (CachedProjectionMatrix) { delete CachedProjectionMatrix; } @@ -256,7 +217,7 @@ PUBLIC GLShader::~GLShader() { } } -PUBLIC STATIC bool GLShader::CheckGLError(int line) { +bool GLShader::CheckGLError(int line) { const char* errstr = NULL; GLenum error = glGetError(); switch (error) { diff --git a/source/Engine/Rendering/GL/GLShaderBuilder.cpp b/source/Engine/Rendering/GL/GLShaderBuilder.cpp index 7845a986..f4a23c99 100644 --- a/source/Engine/Rendering/GL/GLShaderBuilder.cpp +++ b/source/Engine/Rendering/GL/GLShaderBuilder.cpp @@ -1,16 +1,6 @@ -#if INTERFACE -#include -#include - -class GLShaderBuilder { -public: - -}; -#endif - #include -PRIVATE STATIC void GLShaderBuilder::AddUniformsToShaderText(std::string& shaderText, GLShaderUniforms uniforms) { +void GLShaderBuilder::AddUniformsToShaderText(std::string& shaderText, GLShaderUniforms uniforms) { if (uniforms.u_matrix) { shaderText += "uniform mat4 u_projectionMatrix;\n"; shaderText += "uniform mat4 u_modelViewMatrix;\n"; @@ -41,7 +31,7 @@ PRIVATE STATIC void GLShaderBuilder::AddUniformsToShaderText(std::string& shader shaderText += "uniform float u_fogDensity;\n"; } } -PRIVATE STATIC void GLShaderBuilder::AddInputsToVertexShaderText(std::string& shaderText, GLShaderLinkage inputs) { +void GLShaderBuilder::AddInputsToVertexShaderText(std::string& shaderText, GLShaderLinkage inputs) { if (inputs.link_position) { shaderText += "attribute vec3 i_position;\n"; } @@ -52,7 +42,7 @@ PRIVATE STATIC void GLShaderBuilder::AddInputsToVertexShaderText(std::string& sh shaderText += "attribute vec4 i_color;\n"; } } -PRIVATE STATIC void GLShaderBuilder::AddOutputsToVertexShaderText(std::string& shaderText, GLShaderLinkage outputs) { +void GLShaderBuilder::AddOutputsToVertexShaderText(std::string& shaderText, GLShaderLinkage outputs) { if (outputs.link_position) { shaderText += "varying vec4 o_position;\n"; } @@ -63,10 +53,10 @@ PRIVATE STATIC void GLShaderBuilder::AddOutputsToVertexShaderText(std::string& s shaderText += "varying vec4 o_color;\n"; } } -PRIVATE STATIC void GLShaderBuilder::AddInputsToFragmentShaderText(std::string& shaderText, GLShaderLinkage& inputs) { +void GLShaderBuilder::AddInputsToFragmentShaderText(std::string& shaderText, GLShaderLinkage& inputs) { AddOutputsToVertexShaderText(shaderText, inputs); } -PRIVATE STATIC string GLShaderBuilder::BuildFragmentShaderMainFunc(GLShaderLinkage& inputs, GLShaderUniforms& uniforms) { +string GLShaderBuilder::BuildFragmentShaderMainFunc(GLShaderLinkage& inputs, GLShaderUniforms& uniforms) { std::string shaderText = ""; if (uniforms.u_fog_linear) { @@ -140,7 +130,7 @@ PRIVATE STATIC string GLShaderBuilder::BuildFragmentShaderMainFunc(GLShaderLinka return shaderText; } -PUBLIC STATIC string GLShaderBuilder::Vertex(GLShaderLinkage& inputs, GLShaderLinkage& outputs, GLShaderUniforms& uniforms) { +string GLShaderBuilder::Vertex(GLShaderLinkage& inputs, GLShaderLinkage& outputs, GLShaderUniforms& uniforms) { std::string shaderText = ""; #ifdef GL_ES @@ -166,7 +156,7 @@ PUBLIC STATIC string GLShaderBuilder::Vertex(GLShaderLinkage& inputs, GLShaderLi return shaderText; } -PUBLIC STATIC string GLShaderBuilder::Fragment(GLShaderLinkage& inputs, GLShaderUniforms& uniforms, std::string mainText) { +string GLShaderBuilder::Fragment(GLShaderLinkage& inputs, GLShaderUniforms& uniforms, std::string mainText) { std::string shaderText = ""; #ifdef GL_ES @@ -180,6 +170,6 @@ PUBLIC STATIC string GLShaderBuilder::Fragment(GLShaderLinkage& inputs, GLShader return shaderText; } -PUBLIC STATIC string GLShaderBuilder::Fragment(GLShaderLinkage& inputs, GLShaderUniforms& uniforms) { +string GLShaderBuilder::Fragment(GLShaderLinkage& inputs, GLShaderUniforms& uniforms) { return Fragment(inputs, uniforms, BuildFragmentShaderMainFunc(inputs, uniforms)); } diff --git a/source/Engine/Rendering/GL/GLShaderContainer.cpp b/source/Engine/Rendering/GL/GLShaderContainer.cpp index 39243743..dc91a4bf 100644 --- a/source/Engine/Rendering/GL/GLShaderContainer.cpp +++ b/source/Engine/Rendering/GL/GLShaderContainer.cpp @@ -1,24 +1,12 @@ -#if INTERFACE -#include -#include - -class GLShaderContainer { -public: - GLShader *Base = nullptr; - GLShader *Textured = nullptr; - GLShader *PalettizedTextured = nullptr; -}; -#endif - #include #include #include -PUBLIC GLShaderContainer::GLShaderContainer() { +GLShaderContainer::GLShaderContainer() { } -PUBLIC GLShaderContainer::GLShaderContainer(GLShaderLinkage vsIn, GLShaderLinkage vsOut, GLShaderLinkage fsIn, GLShaderUniforms vsUni, GLShaderUniforms fsUni) { +GLShaderContainer::GLShaderContainer(GLShaderLinkage vsIn, GLShaderLinkage vsOut, GLShaderLinkage fsIn, GLShaderUniforms vsUni, GLShaderUniforms fsUni) { std::string vs, fs; vsIn.link_position = true; @@ -43,7 +31,7 @@ PUBLIC GLShaderContainer::GLShaderContainer(GLShaderLinkage vsIn, GLShaderLinkag PalettizedTextured = new GLShader(vs, fs); } -PUBLIC GLShader* GLShaderContainer::Get(bool useTexturing, bool usePalette) { +GLShader* GLShaderContainer::Get(bool useTexturing, bool usePalette) { if (useTexturing) { if (usePalette) return PalettizedTextured; @@ -54,15 +42,15 @@ PUBLIC GLShader* GLShaderContainer::Get(bool useTexturing, bool usePalette) { return Base; } -PUBLIC GLShader* GLShaderContainer::Get(bool useTexturing) { +GLShader* GLShaderContainer::Get(bool useTexturing) { return Get(useTexturing, false); } -PUBLIC GLShader* GLShaderContainer::Get() { +GLShader* GLShaderContainer::Get() { return Get(false, false); } -PUBLIC STATIC GLShaderContainer* GLShaderContainer::Make(bool use_vertex_colors) { +GLShaderContainer* GLShaderContainer::Make(bool use_vertex_colors) { GLShaderLinkage vsIn = {0}; GLShaderLinkage vsOut = {0}; GLShaderLinkage fsIn = {0}; @@ -76,7 +64,7 @@ PUBLIC STATIC GLShaderContainer* GLShaderContainer::Make(bool use_vertex_colors) return new GLShaderContainer(vsIn, vsOut, fsIn, vsUni, fsUni); } -PUBLIC STATIC GLShaderContainer* GLShaderContainer::MakeFog(int fog_type) { +GLShaderContainer* GLShaderContainer::MakeFog(int fog_type) { GLShaderLinkage vsIn = {0}; GLShaderLinkage vsOut = {0}; GLShaderLinkage fsIn = {0}; @@ -97,7 +85,7 @@ PUBLIC STATIC GLShaderContainer* GLShaderContainer::MakeFog(int fog_type) { return new GLShaderContainer(vsIn, vsOut, fsIn, vsUni, fsUni); } -PUBLIC STATIC GLShaderContainer* GLShaderContainer::MakeYUV() { +GLShaderContainer* GLShaderContainer::MakeYUV() { GLShaderLinkage vsIn = {0}; GLShaderLinkage vsOut = {0}; GLShaderLinkage fsIn = {0}; @@ -140,7 +128,7 @@ PUBLIC STATIC GLShaderContainer* GLShaderContainer::MakeYUV() { return container; } -PUBLIC GLShaderContainer::~GLShaderContainer() { +GLShaderContainer::~GLShaderContainer() { if (Base) delete Base; if (Textured) diff --git a/source/Engine/Rendering/GameTexture.cpp b/source/Engine/Rendering/GameTexture.cpp index 133941e2..37b6c1fd 100644 --- a/source/Engine/Rendering/GameTexture.cpp +++ b/source/Engine/Rendering/GameTexture.cpp @@ -1,40 +1,28 @@ -#if INTERFACE -#include -#include - -class GameTexture { -public: - Texture* TexturePtr = nullptr; - int UnloadPolicy; - bool OwnsTexture = true; -}; -#endif - #include #include -PUBLIC GameTexture::GameTexture() { +GameTexture::GameTexture() { } -PUBLIC GameTexture::GameTexture(Uint32 width, Uint32 height, int unloadPolicy) { +GameTexture::GameTexture(Uint32 width, Uint32 height, int unloadPolicy) { TexturePtr = Texture::New(SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, width, height); UnloadPolicy = unloadPolicy; } -PUBLIC VIRTUAL Texture* GameTexture::GetTexture() { +Texture* GameTexture::GetTexture() { return TexturePtr; } -PUBLIC VIRTUAL int GameTexture::GetID() { +int GameTexture::GetID() { if (TexturePtr) return TexturePtr->ID; return 0; } -PUBLIC GameTexture::~GameTexture() { +GameTexture::~GameTexture() { if (TexturePtr && OwnsTexture) Graphics::DisposeTexture(TexturePtr); } diff --git a/source/Engine/Rendering/Material.cpp b/source/Engine/Rendering/Material.cpp index 522ba883..1c37596f 100644 --- a/source/Engine/Rendering/Material.cpp +++ b/source/Engine/Rendering/Material.cpp @@ -1,37 +1,8 @@ -#if INTERFACE -#include -#include - -class Material { -public: - char* Name = nullptr; - - float ColorDiffuse[4]; - float ColorSpecular[4]; - float ColorAmbient[4]; - float ColorEmissive[4]; - - float Shininess = 0.0f; - float ShininessStrength = 1.0f; - float Opacity = 1.0f; - - char* TextureDiffuseName = nullptr; - char* TextureSpecularName = nullptr; - char* TextureAmbientName = nullptr; - char* TextureEmissiveName = nullptr; - - Image* TextureDiffuse = nullptr; - Image* TextureSpecular = nullptr; - Image* TextureAmbient = nullptr; - Image* TextureEmissive = nullptr; -}; -#endif - #include #include -PUBLIC Material::Material() { +Material::Material() { for (int i = 0; i < 4; i++) { ColorDiffuse[i] = ColorSpecular[i] = @@ -40,7 +11,7 @@ PUBLIC Material::Material() { } } -PUBLIC void Material::Dispose() { +void Material::Dispose() { delete TextureDiffuse; delete TextureSpecular; delete TextureAmbient; @@ -54,6 +25,6 @@ PUBLIC void Material::Dispose() { Memory::Free(TextureEmissiveName); } -PUBLIC Material::~Material() { +Material::~Material() { Dispose(); } diff --git a/source/Engine/Rendering/Metal/MetalRenderer.cpp.unused b/source/Engine/Rendering/Metal/MetalRenderer.cpp.unused deleted file mode 100644 index b53c5933..00000000 --- a/source/Engine/Rendering/Metal/MetalRenderer.cpp.unused +++ /dev/null @@ -1,1418 +0,0 @@ -#if INTERFACE -#include -#include -#include -#include -#include - -#include - -class MetalRenderer { -public: -}; -#endif - -// Shader -// https://github.com/spurious/SDL-mirror/blob/master/src/render/metal/SDL_shaders_metal.metal -// Renderer -// https://github.com/spurious/SDL-mirror/blob/master/src/render/metal/SDL_render_metal.m - -#ifdef MACOSXAAAAAAAAAAAAAA - -#include - -#include -#include -#include - -struct Vertex { - float x, y, z; - int color; - float u, v; -}; -struct Metal_RenderData { - void* Metal_DLL; - IDirect3D9* D3D; - IDirect3DDevice9* Device; - UINT Adapter; - D3DPRESENT_PARAMETERS PresentParams; - bool UpdateBackBufferSize; - bool BeginScene; - bool EnableSeparateAlphaBlend; - IDirect3DSurface9* DefaultRenderTarget; - IDirect3DSurface9* CurrentRenderTarget; - void* D3Dx_DLL; - LPDIRECT3DPIXELSHADER9 Shaders[NUM_SHADERS]; -}; -struct Metal_TextureData { - bool Dirty; - DWORD Usage; - Uint32 Format; - D3DFORMAT D3DFormat; - IDirect3DTexture9* Texture; - IDirect3DTexture9* Staging; - D3DTEXTUREFILTERTYPE ScaleMode; -}; - -MetalShader* Metal_CurrentShader = NULL; -MetalShader* Metal_SelectedShader = NULL; -MetalShader* Metal_ShaderShape = NULL; -MetalShader* Metal_ShaderTexturedShape = NULL; - -int Metal_DefaultFramebuffer; -Vertex* Metal_BufferCircleFill; -Vertex* Metal_BufferCircleStroke; -Vertex* Metal_BufferSquareFill; - -Uint32 Metal_BlendColorsAsHex = 0; - -bool Metal_PixelPerfectScale = false; -float Metal_RenderScaleX = 1.0f; -float Metal_RenderScaleY = 1.0f; -Matrix4x4* Metal_MatrixIdentity = NULL; - -DWORD Metal_Blend_SRC_COLOR = D3DBLEND_SRCALPHA; -DWORD Metal_Blend_DST_COLOR = D3DBLEND_INVSRCALPHA; -DWORD Metal_Blend_SRC_ALPHA = D3DBLEND_SRCALPHA; -DWORD Metal_Blend_DST_ALPHA = D3DBLEND_INVSRCALPHA; - -Metal_RenderData* renderData = NULL; - -bool Metal_LoadDLL(void** pD3DDLL, IDirect3D9** pDirect3D9Interface) { - *pD3DDLL = SDL_LoadObject("D3D9.DLL"); - if (*pD3DDLL) { - typedef IDirect3D9 *(WINAPI *Direct3DCreate9_t) (UINT SDKVersion); - Direct3DCreate9_t Direct3DCreate9Func; - - #ifdef USE_D3D9EX - typedef HRESULT (WINAPI *Direct3DCreate9Ex_t)(UINT SDKVersion, IDirect3D9Ex **ppD3D); - Direct3DCreate9Ex_t Direct3DCreate9ExFunc; - - Direct3DCreate9ExFunc = (Direct3DCreate9Ex_t)SDL_LoadFunction(*pD3DDLL, "Direct3DCreate9Ex"); - if (Direct3DCreate9ExFunc) { - IDirect3D9Ex *pDirect3D9ExInterface; - HRESULT hr = Direct3DCreate9ExFunc(Metal_SDK_VERSION, &pDirect3D9ExInterface); - if (SUCCEEDED(hr)) { - const GUID IDirect3D9_GUID = { 0x81bdcbca, 0x64d4, 0x426d, { 0xae, 0x8d, 0xad, 0x1, 0x47, 0xf4, 0x27, 0x5c } }; - hr = IDirect3D9Ex_QueryInterface(pDirect3D9ExInterface, &IDirect3D9_GUID, (void**)pDirect3D9Interface); - IDirect3D9Ex_Release(pDirect3D9ExInterface); - if (SUCCEEDED(hr)) { - return true; - } - } - } - #endif /* USE_D3D9EX */ - - Direct3DCreate9Func = (Direct3DCreate9_t)SDL_LoadFunction(*pD3DDLL, "Direct3DCreate9"); - if (Direct3DCreate9Func) { - *pDirect3D9Interface = Direct3DCreate9Func(Metal_SDK_VERSION); - if (*pDirect3D9Interface) { - return true; - } - } - - SDL_UnloadObject(*pD3DDLL); - *pD3DDLL = NULL; - } - *pDirect3D9Interface = NULL; - return false; -} -void Metal_InitRenderState() { - D3DMATRIX matrix; - - IDirect3DDevice9* device = renderData->Device; - - IDirect3DDevice9_SetVertexShader(device, NULL); - IDirect3DDevice9_SetFVF(device, D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1); - // IDirect3DDevice9_SetRenderState(device, D3DRS_ZENABLE, D3DZB_FALSE); - IDirect3DDevice9_SetRenderState(device, D3DRS_ZENABLE, D3DZB_TRUE); - IDirect3DDevice9_SetRenderState(device, D3DRS_CULLMODE, D3DCULL_NONE); - IDirect3DDevice9_SetRenderState(device, D3DRS_LIGHTING, FALSE); - - /* Enable color modulation by diffuse color */ - IDirect3DDevice9_SetTextureStageState(device, 0, D3DTSS_COLOROP, D3DTOP_MODULATE); - IDirect3DDevice9_SetTextureStageState(device, 0, D3DTSS_COLORARG1, D3DTA_TEXTURE); - IDirect3DDevice9_SetTextureStageState(device, 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE); - - /* Enable alpha modulation by diffuse alpha */ - IDirect3DDevice9_SetTextureStageState(device, 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); - IDirect3DDevice9_SetTextureStageState(device, 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); - IDirect3DDevice9_SetTextureStageState(device, 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); - - /* Enable separate alpha blend function, if possible */ - if (renderData->EnableSeparateAlphaBlend) { - IDirect3DDevice9_SetRenderState(device, D3DRS_SEPARATEALPHABLENDENABLE, TRUE); - } - - /* Disable second texture stage, since we're done */ - IDirect3DDevice9_SetTextureStageState(device, 1, D3DTSS_COLOROP, D3DTOP_DISABLE); - IDirect3DDevice9_SetTextureStageState(device, 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE); - - /* Set an identity world and view matrix */ - matrix.m[0][0] = 1.0f; - matrix.m[0][1] = 0.0f; - matrix.m[0][2] = 0.0f; - matrix.m[0][3] = 0.0f; - matrix.m[1][0] = 0.0f; - matrix.m[1][1] = 1.0f; - matrix.m[1][2] = 0.0f; - matrix.m[1][3] = 0.0f; - matrix.m[2][0] = 0.0f; - matrix.m[2][1] = 0.0f; - matrix.m[2][2] = 1.0f; - matrix.m[2][3] = 0.0f; - matrix.m[3][0] = 0.0f; - matrix.m[3][1] = 0.0f; - matrix.m[3][2] = 0.0f; - matrix.m[3][3] = 1.0f; - IDirect3DDevice9_SetTransform(device, D3DTS_WORLD, &matrix); - IDirect3DDevice9_SetTransform(device, D3DTS_VIEW, &matrix); - - /* Reset our current scale mode */ - // SDL_memset(renderData->ScaleMode, 0xFF, sizeof(renderData->ScaleMode)); - - /* Start the render with BeginScene */ - renderData->BeginScene = true; -} -void Metal_MakeShaders() { - // Metal_ShaderShape = new MetalShader(vertexShaderSource, sizeof(vertexShaderSource), fragmentShaderSource_Shape, sizeof(fragmentShaderSource_Shape)); - // Metal_ShaderTexturedShape = new MetalShader(vertexShaderSource, sizeof(vertexShaderSource), fragmentShaderSource_TexturedShape, sizeof(fragmentShaderSource_TexturedShape)); - // ShaderTexturedShapeBGRA = new MetalShader(vertexShaderSource, sizeof(vertexShaderSource), fragmentShaderSource_TexturedShapeBGRA, sizeof(fragmentShaderSource_TexturedShapeBGRA)); -} -void Metal_MakeShapeBuffers() { - Vertex* buffer; - - Metal_BufferCircleFill = (Vertex*)Memory::TrackedMalloc("MetalRenderer::Metal_BufferCircleFill", 362 * sizeof(Vertex)); - buffer = Metal_BufferCircleFill; - buffer[0] = Vertex { 0.0f, 0.0f, 0.0f, 0xFFFFFFFF, 0.0f, 0.0f }; - for (int i = 0; i < 361; i++) { - buffer[i + 1] = Vertex { cos(i * M_PI / 180.0f), sin(i * M_PI / 180.0f), 0.0f, 0xFFFFFFFF, 0.0f, 0.0f }; - } - - Metal_BufferCircleStroke = (Vertex*)Memory::TrackedMalloc("MetalRenderer::Metal_BufferCircleStroke", 361 * sizeof(Vertex)); - buffer = (Vertex*)Metal_BufferCircleStroke; - for (int i = 0; i < 361; i++) { - buffer[i + 0] = Vertex { cos(i * M_PI / 180.0f), sin(i * M_PI / 180.0f), 0.0f, 0xFFFFFFFF, 0.0f, 0.0f }; - } - - Metal_BufferSquareFill = (Vertex*)Memory::TrackedMalloc("MetalRenderer::Metal_BufferSquareFill", 4 * sizeof(Vertex)); - buffer = (Vertex*)Metal_BufferSquareFill; - buffer[0] = Vertex { 0.0f, 0.0f, 0.0f, 0xFFFFFFFF, 0.0f, 0.0f }; - buffer[1] = Vertex { 1.0f, 0.0f, 0.0f, 0xFFFFFFFF, 0.0f, 0.0f }; - buffer[2] = Vertex { 1.0f, 1.0f, 0.0f, 0xFFFFFFFF, 0.0f, 0.0f }; - buffer[3] = Vertex { 0.0f, 1.0f, 0.0f, 0xFFFFFFFF, 0.0f, 0.0f }; -} -const char* Metal_GetResultString(HRESULT result) { - switch (result) { - case D3DERR_WRONGTEXTUREFORMAT: - return "WRONGTEXTUREFORMAT"; - case D3DERR_UNSUPPORTEDCOLOROPERATION: - return "UNSUPPORTEDCOLOROPERATION"; - case D3DERR_UNSUPPORTEDCOLORARG: - return "UNSUPPORTEDCOLORARG"; - case D3DERR_UNSUPPORTEDALPHAOPERATION: - return "UNSUPPORTEDALPHAOPERATION"; - case D3DERR_UNSUPPORTEDALPHAARG: - return "UNSUPPORTEDALPHAARG"; - case D3DERR_TOOMANYOPERATIONS: - return "TOOMANYOPERATIONS"; - case D3DERR_CONFLICTINGTEXTUREFILTER: - return "CONFLICTINGTEXTUREFILTER"; - case D3DERR_UNSUPPORTEDFACTORVALUE: - return "UNSUPPORTEDFACTORVALUE"; - case D3DERR_CONFLICTINGRENDERSTATE: - return "CONFLICTINGRENDERSTATE"; - case D3DERR_UNSUPPORTEDTEXTUREFILTER: - return "UNSUPPORTEDTEXTUREFILTER"; - case D3DERR_CONFLICTINGTEXTUREPALETTE: - return "CONFLICTINGTEXTUREPALETTE"; - case D3DERR_DRIVERINTERNALERROR: - return "DRIVERINTERNALERROR"; - case D3DERR_NOTFOUND: - return "NOTFOUND"; - case D3DERR_MOREDATA: - return "MOREDATA"; - case D3DERR_DEVICELOST: - return "DEVICELOST"; - case D3DERR_DEVICENOTRESET: - return "DEVICENOTRESET"; - case D3DERR_NOTAVAILABLE: - return "NOTAVAILABLE"; - case D3DERR_OUTOFVIDEOMEMORY: - return "OUTOFVIDEOMEMORY"; - case D3DERR_INVALIDDEVICE: - return "INVALIDDEVICE"; - case D3DERR_INVALIDCALL: - return "INVALIDCALL"; - case D3DERR_DRIVERINVALIDCALL: - return "DRIVERINVALIDCALL"; - case D3DERR_WASSTILLDRAWING: - return "WASSTILLDRAWING"; - default: - return "UNKNOWN"; - } - return NULL; -} -D3DFORMAT Metal_PixelFormatToD3DFORMAT(Uint32 format) { - switch (format) { - case SDL_PIXELFORMAT_RGB565: - return D3DFMT_R5G6B5; - case SDL_PIXELFORMAT_RGB888: - return D3DFMT_X8R8G8B8; - case SDL_PIXELFORMAT_ARGB8888: - return D3DFMT_A8R8G8B8; - case SDL_PIXELFORMAT_YV12: - case SDL_PIXELFORMAT_IYUV: - case SDL_PIXELFORMAT_NV12: - case SDL_PIXELFORMAT_NV21: - return D3DFMT_L8; - default: - return D3DFMT_UNKNOWN; - } -} -Uint32 Metal_D3DFORMATToPixelFormat(D3DFORMAT format) { - switch (format) { - case D3DFMT_R5G6B5: - return SDL_PIXELFORMAT_RGB565; - case D3DFMT_X8R8G8B8: - return SDL_PIXELFORMAT_RGB888; - case D3DFMT_A8R8G8B8: - return SDL_PIXELFORMAT_ARGB8888; - default: - return SDL_PIXELFORMAT_UNKNOWN; - } - return SDL_PIXELFORMAT_UNKNOWN; -} -int Metal_SetError(const char* error, HRESULT result) { - Log::Print(Log::LOG_ERROR, "D3D: %s (%s)", error, Metal_GetResultString(result)); - exit(0); - return 0; -} - -void Metal_CreateTexture(Texture* texture) { - texture->DriverData = Memory::TrackedCalloc("Texture::DriverData", 1, sizeof(Metal_TextureData)); - - Metal_TextureData* textureData = (Metal_TextureData*)texture->DriverData; - - textureData->ScaleMode = Graphics::TextureInterpolate ? D3DTEXF_LINEAR : D3DTEXF_POINT; - - DWORD usage = 0; - if (texture->Access == SDL_TEXTUREACCESS_TARGET) - usage = D3DUSAGE_RENDERTARGET; - - // Metal_CreateTextureRep - HRESULT result; - textureData->Dirty = false; - textureData->Usage = usage; - textureData->Format = texture->Format; - textureData->D3DFormat = Metal_PixelFormatToD3DFORMAT(texture->Format); - - result = IDirect3DDevice9_CreateTexture(renderData->Device, texture->Width, texture->Height, 1, usage, textureData->D3DFormat, D3DPOOL_DEFAULT, &textureData->Texture, NULL); - if (FAILED(result)) { - Log::Print(Log::LOG_ERROR, "CreateTextureD3DPOOL_DEFAULT() %s", Metal_GetResultString(result)); - Log::Print(Log::LOG_INFO, "IDirect3DDevice9_CreateTexture(%p, %u, %u, %u, %u", renderData->Device, texture->Width, texture->Height, 1, usage); - exit(0); - } -} -int Metal_RecreateTexture(Texture* texture) { - Metal_TextureData* textureData = (Metal_TextureData*)texture->DriverData; - if (!textureData) - return 0; - - if (textureData->Texture) { - IDirect3DTexture9_Release(textureData->Texture); - textureData->Texture = NULL; - } - if (textureData->Staging) { - IDirect3DTexture9_AddDirtyRect(textureData->Staging, NULL); - textureData->Dirty = true; - } - return 0; -} - -int Metal_SetRenderTarget(Texture* texture) { - HRESULT result; - /* Release the previous render target if it wasn't the default one */ - if (renderData->CurrentRenderTarget != NULL) { - IDirect3DSurface9_Release(renderData->CurrentRenderTarget); - renderData->CurrentRenderTarget = NULL; - } - - if (texture == NULL) { - IDirect3DDevice9_SetRenderTarget(renderData->Device, 0, renderData->DefaultRenderTarget); - return 0; - } - - Metal_TextureData* textureData = (Metal_TextureData*)texture->DriverData; - if (!textureData) { - SDL_SetError("Texture is not currently available"); - return -1; - } - - /* Make sure the render target is updated if it was locked and written to */ - if (textureData->Dirty && textureData->Staging) { - if (!textureData->Texture) { - result = IDirect3DDevice9_CreateTexture(renderData->Device, texture->Width, texture->Height, 1, textureData->Usage, Metal_PixelFormatToD3DFORMAT(textureData->Format), D3DPOOL_DEFAULT, &textureData->Texture, NULL); - if (FAILED(result)) { - return Metal_SetError("CreateTexture(D3DPOOL_DEFAULT)", result); - } - } - - result = IDirect3DDevice9_UpdateTexture(renderData->Device, (IDirect3DBaseTexture9*)textureData->Staging, (IDirect3DBaseTexture9*)textureData->Texture); - if (FAILED(result)) { - return Metal_SetError("UpdateTexture()", result); - } - textureData->Dirty = false; - } - - result = IDirect3DTexture9_GetSurfaceLevel(textureData->Texture, 0, &renderData->CurrentRenderTarget); - if (FAILED(result)) { - return Metal_SetError("GetSurfaceLevel()", result); - } - - result = IDirect3DDevice9_SetRenderTarget(renderData->Device, 0, renderData->CurrentRenderTarget); - if (FAILED(result)) { - return Metal_SetError("SetRenderTarget()", result); - } - - return 0; -} -void Metal_Reset() { - HRESULT result; - - /* Release the default render target before reset */ - if (renderData->DefaultRenderTarget) { - IDirect3DSurface9_Release(renderData->DefaultRenderTarget); - renderData->DefaultRenderTarget = NULL; - } - if (renderData->CurrentRenderTarget) { - IDirect3DSurface9_Release(renderData->CurrentRenderTarget); - renderData->CurrentRenderTarget = NULL; - } - - /* Release application render targets */ - for (Texture* texture = Graphics::TextureHead; texture != NULL; texture = texture->Next) { - if (texture->Access == SDL_TEXTUREACCESS_TARGET) - MetalRenderer::DisposeTexture(texture); - else - Metal_RecreateTexture(texture); - } - - result = IDirect3DDevice9_Reset(renderData->Device, &renderData->PresentParams); - if (FAILED(result)) { - if (result == D3DERR_DEVICELOST) { - /* Don't worry about it, we'll reset later... */ - return; - } - else { - Metal_SetError("Reset() %s", result); - return; - } - } - - /* Allocate application render targets */ - for (Texture* texture = Graphics::TextureHead; texture != NULL; texture = texture->Next) { - if (texture->Access == SDL_TEXTUREACCESS_TARGET) - Metal_CreateTexture(texture); - } - - IDirect3DDevice9_GetRenderTarget(renderData->Device, 0, &renderData->DefaultRenderTarget); - Metal_InitRenderState(); - Metal_SetRenderTarget(Graphics::CurrentRenderTarget); - MetalRenderer::UpdateViewport(); -} -void Metal_Predraw() { - HRESULT result; - - if (renderData->UpdateBackBufferSize) { - SDL_Window* window = Application::Window; - int w, h; - Uint32 window_flags = SDL_GetWindowFlags(window); - SDL_GetWindowSize(window, &w, &h); - - renderData->PresentParams.BackBufferWidth = w; - renderData->PresentParams.BackBufferHeight = h; - if (window_flags & SDL_WINDOW_FULLSCREEN && (window_flags & SDL_WINDOW_FULLSCREEN_DESKTOP) != SDL_WINDOW_FULLSCREEN_DESKTOP) { - SDL_DisplayMode fullscreen_mode; - SDL_GetWindowDisplayMode(window, &fullscreen_mode); - renderData->PresentParams.Windowed = FALSE; - renderData->PresentParams.BackBufferFormat = Metal_PixelFormatToD3DFORMAT(fullscreen_mode.format); - renderData->PresentParams.FullScreen_RefreshRateInHz = fullscreen_mode.refresh_rate; - } - else { - renderData->PresentParams.Windowed = TRUE; - renderData->PresentParams.BackBufferFormat = D3DFMT_UNKNOWN; - renderData->PresentParams.FullScreen_RefreshRateInHz = 0; - } - - Metal_Reset(); - // if (Metal_Reset(renderer) < 0) { - // return -1; - // } - - renderData->UpdateBackBufferSize = false; - } - if (renderData->BeginScene) { - result = IDirect3DDevice9_BeginScene(renderData->Device); - if (result == D3DERR_DEVICELOST) { - Metal_Reset(); - // if (Metal_Reset(renderer) < 0) { - // return -1; - // } - result = IDirect3DDevice9_BeginScene(renderData->Device); - } - if (FAILED(result)) { - Metal_SetError("BeginScene() %s", result); - } - renderData->BeginScene = false; - } -} - -void Metal_SetBlendMode() { - IDirect3DDevice9_SetRenderState(renderData->Device, D3DRS_ALPHABLENDENABLE, TRUE); - IDirect3DDevice9_SetRenderState(renderData->Device, D3DRS_SRCBLEND, Metal_Blend_SRC_COLOR); - IDirect3DDevice9_SetRenderState(renderData->Device, D3DRS_DESTBLEND, Metal_Blend_DST_COLOR); - if (renderData->EnableSeparateAlphaBlend) { - IDirect3DDevice9_SetRenderState(renderData->Device, D3DRS_SRCBLENDALPHA, Metal_Blend_SRC_ALPHA); - IDirect3DDevice9_SetRenderState(renderData->Device, D3DRS_DESTBLENDALPHA, Metal_Blend_DST_ALPHA); - } - - // Enable multisample - if (Graphics::MultisamplingEnabled) { - IDirect3DDevice9_SetRenderState(renderData->Device, D3DRS_MULTISAMPLEANTIALIAS, TRUE); - } -} -DWORD Metal_GetBlendFactorFromHatch(int factor) { - switch (factor) { - case BlendFactor_ZERO: - return D3DBLEND_ZERO; - case BlendFactor_ONE: - return D3DBLEND_ONE; - case BlendFactor_SRC_COLOR: - return D3DBLEND_SRCCOLOR; - case BlendFactor_INV_SRC_COLOR: - return D3DBLEND_INVSRCCOLOR; - case BlendFactor_SRC_ALPHA: - return D3DBLEND_SRCALPHA; - case BlendFactor_INV_SRC_ALPHA: - return D3DBLEND_INVSRCALPHA; - case BlendFactor_DST_COLOR: - return D3DBLEND_DESTCOLOR; - case BlendFactor_INV_DST_COLOR: - return D3DBLEND_INVDESTCOLOR; - case BlendFactor_DST_ALPHA: - return D3DBLEND_DESTALPHA; - case BlendFactor_INV_DST_ALPHA: - return D3DBLEND_INVDESTALPHA; - } - return 0; -} -void Metal_BindTexture(Texture* texture, int index) { - HRESULT result; - - if (!texture) { - result = IDirect3DDevice9_SetTexture(renderData->Device, index, NULL); - if (FAILED(result)) { - Metal_SetError("SetTexture() %s", result); - } - return; - } - - Metal_TextureData* textureData = (Metal_TextureData*)texture->DriverData; - - IDirect3DDevice9_SetSamplerState(renderData->Device, index, D3DSAMP_MINFILTER, textureData->ScaleMode); - IDirect3DDevice9_SetSamplerState(renderData->Device, index, D3DSAMP_MAGFILTER, textureData->ScaleMode); - IDirect3DDevice9_SetSamplerState(renderData->Device, index, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP); - IDirect3DDevice9_SetSamplerState(renderData->Device, index, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP); - - if (textureData->Dirty && textureData->Staging) { - if (!textureData->Texture) { - result = IDirect3DDevice9_CreateTexture(renderData->Device, texture->Width, texture->Height, 1, textureData->Usage, Metal_PixelFormatToD3DFORMAT(texture->Format), D3DPOOL_DEFAULT, &textureData->Texture, NULL); - if (FAILED(result)) { - Metal_SetError("CreateTexture(D3DPOOL_DEFAULT)", result); - } - } - - result = IDirect3DDevice9_UpdateTexture(renderData->Device, (IDirect3DBaseTexture9*)textureData->Staging, (IDirect3DBaseTexture9*)textureData->Texture); - if (FAILED(result)) { - Metal_SetError("UpdateTexture()", result); - } - textureData->Dirty = false; - } - - result = IDirect3DDevice9_SetTexture(renderData->Device, index, (IDirect3DBaseTexture9*)textureData->Texture); - if (FAILED(result)) { - Metal_SetError("SetTexture() %s", result); - } -} - -void Metal_DrawTextureRaw(Texture* texture, float sx, float sy, float sw, float sh, float x, float y, float w, float h, bool flipX, bool flipY) { - HRESULT result; - Metal_TextureData* textureData = (Metal_TextureData*)texture->DriverData; - - LPDIRECT3DPIXELSHADER9 shader = (LPDIRECT3DPIXELSHADER9)NULL; - - Metal_Predraw(); - - float minu = (sx) / texture->Width; - float maxu = (sx + sw) / texture->Width; - float minv = (sy) / texture->Height; - float maxv = (sy + sh) / texture->Height; - DWORD color = 0xFFFFFFFF; - if (Graphics::TextureBlend) - color = Metal_BlendColorsAsHex; - - float minx = x; - float maxx = x + w; - float miny = y; - float maxy = y + h; - - // NOTE: We do this because Direct3D9's origin for render targets is top-left, - // instead of the usual bottom-left. - if (texture->Access == SDL_TEXTUREACCESS_TARGET) { - // miny = y + h; - // maxy = y; - // if (Graphics::CurrentRenderTarget != NULL) - // flipY = !flipY; - maxv = (sy) / texture->Height; - minv = (sy + sh) / texture->Height; - } - - Vertex vertices[4]; - // vertices[0] = Vertex { minx, miny, 0.0f, color, minu, minv }; - // vertices[1] = Vertex { maxx, miny, 0.0f, color, maxu, minv }; - // vertices[2] = Vertex { maxx, maxy, 0.0f, color, maxu, maxv }; - // vertices[3] = Vertex { minx, maxy, 0.0f, color, minu, maxv }; - vertices[0] = Vertex { 0.0f, 0.0f, 0.0f, color, minu, minv }; - vertices[1] = Vertex { 1.0f, 0.0f, 0.0f, color, maxu, minv }; - vertices[2] = Vertex { 1.0f, 1.0f, 0.0f, color, maxu, maxv }; - vertices[3] = Vertex { 0.0f, 1.0f, 0.0f, color, minu, maxv }; - - if (Metal_PixelPerfectScale) { - Point points[4]; - for (int i = 0; i < 4; i++) { - points[i] = Graphics::ProjectToScreen(vertices[i].x, vertices[i].y, vertices[i].z); - vertices[i].x = points[i].X ; - vertices[i].y = points[i].Y; - vertices[i].z = points[i].Z; - } - } - - // NOTE: This is not necessary in D3D10 and onwards - float fx = flipX ? -1.0f : 1.0f; - float fy = flipY ? -1.0f : 1.0f; - // if (Graphics::CurrentRenderTarget) { - // for (int i = 0; i < 4; i++) { - // vertices[i].x -= 0.5f * fx; - // vertices[i].y += 0.5f * fy; // NOTE: Note the plus here, instead of minus - // } - // } - // else { - // for (int i = 0; i < 4; i++) { - // vertices[i].x -= 0.5f * fx; - // vertices[i].y -= 0.5f * fy; - // } - // } - - Metal_SetBlendMode(); - Metal_BindTexture(texture, 0); - - if (shader) { - // result = IDirect3DDevice9_SetPixelShader(renderData->Device, shader); - // if (FAILED(result)) { - // return Metal_SetError("SetShader()", result); - // } - } - - D3DMATRIX matrix; - if (Metal_PixelPerfectScale) { - memcpy(&matrix.m, Metal_MatrixIdentity->Values, sizeof(float) * 16); - } - else { - // memcpy(&matrix.m, Graphics::ModelViewMatrix->Values, sizeof(float) * 16); - Graphics::Save(); - Graphics::Translate(x, y, 0.0f); - if (texture->Access != SDL_TEXTUREACCESS_TARGET) - Graphics::Translate(-0.5f * fx, 0.5f * fy, 0.0f); - else - Graphics::Translate(-0.5f * fx, -0.5f * fy, 0.0f); - Graphics::Scale(w, h, 1.0f); - memcpy(&matrix.m, Graphics::ModelViewMatrix->Values, sizeof(float) * 16); - Graphics::Restore(); - } - IDirect3DDevice9_SetTransform(renderData->Device, D3DTS_VIEW, &matrix); - - result = IDirect3DDevice9_DrawPrimitiveUP(renderData->Device, D3DPT_TRIANGLEFAN, 2, vertices, sizeof(*vertices)); - if (FAILED(result)) { - Metal_SetError("DrawPrimitiveUP() %s", result); - } - - if (shader) { - // IDirect3DDevice9_SetPixelShader(renderData->Device, NULL); - } - // return FAILED(result) ? -1 : 0; -} - -void Metal_BeginDrawShape(Vertex* shapeBuffer, int vertexCount) { - Metal_Predraw(); - - Vertex* buffer = (Vertex*)shapeBuffer; - for (int i = 0; i < vertexCount; i++) { - buffer[i].color = Metal_BlendColorsAsHex; - } - - Metal_SetBlendMode(); - Metal_BindTexture(NULL, 0); -} -void Metal_EndDrawShape(Vertex* shapeBuffer, D3DPRIMITIVETYPE prim, int triangleCount) { - HRESULT result = IDirect3DDevice9_DrawPrimitiveUP(renderData->Device, prim, triangleCount, shapeBuffer, sizeof(Vertex)); - if (FAILED(result)) - Metal_SetError("DrawPrimitiveUP() %s", result); -} - -// Initialization and disposal functions -PUBLIC STATIC void MetalRenderer::Init() { - Graphics::PreferredPixelFormat = SDL_PIXELFORMAT_ARGB8888; - Metal_MatrixIdentity = Matrix4x4::Create(); - - renderData = (Metal_RenderData*)calloc(1, sizeof(Metal_RenderData)); - - // renderData->D3D = Direct3DCreate9(Metal_SDK_VERSION); - if (!Metal_LoadDLL(&renderData->Metal_DLL, &renderData->D3D)) { - Log::Print(Log::LOG_ERROR, "Unable to create Direct3D interface."); - return; - } - - Log::Print(Log::LOG_INFO, "Renderer: Direct3D 9"); - - D3DCAPS9 caps; - HRESULT result; - DWORD device_flags; - Uint32 window_flags; - SDL_SysWMinfo windowinfo; - IDirect3DSwapChain9* chain; - D3DPRESENT_PARAMETERS pparams; - SDL_DisplayMode fullscreen_mode; - int displayIndex, w, h, texture_max_w, texture_max_h; - - SDL_VERSION(&windowinfo.version); - SDL_GetWindowWMInfo(Application::Window, &windowinfo); - - window_flags = SDL_GetWindowFlags(Application::Window); - SDL_GetWindowSize(Application::Window, &w, &h); - SDL_GetWindowDisplayMode(Application::Window, &fullscreen_mode); - - memset(&pparams, 0, sizeof(pparams)); - pparams.hDeviceWindow = windowinfo.info.win.window; - pparams.BackBufferWidth = w; - pparams.BackBufferHeight = h; - pparams.BackBufferCount = 1; - pparams.SwapEffect = D3DSWAPEFFECT_DISCARD; - - pparams.EnableAutoDepthStencil = TRUE; - pparams.AutoDepthStencilFormat = D3DFMT_D16; - - if (window_flags & SDL_WINDOW_FULLSCREEN && (window_flags & SDL_WINDOW_FULLSCREEN_DESKTOP) != SDL_WINDOW_FULLSCREEN_DESKTOP) { - pparams.Windowed = FALSE; - pparams.BackBufferFormat = Metal_PixelFormatToD3DFORMAT(fullscreen_mode.format); - pparams.FullScreen_RefreshRateInHz = fullscreen_mode.refresh_rate; - } - else { - pparams.Windowed = TRUE; - pparams.BackBufferFormat = D3DFMT_UNKNOWN; - pparams.FullScreen_RefreshRateInHz = 0; - } - - if (Graphics::VsyncEnabled) { - pparams.PresentationInterval = D3DPRESENT_INTERVAL_ONE; - } - else { - pparams.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; - } - - displayIndex = SDL_GetWindowDisplayIndex(Application::Window); - renderData->Adapter = SDL_Direct3D9GetAdapterIndex(displayIndex); - - // Check for full-scene antialiasing - if (Graphics::MultisamplingEnabled) { - pparams.MultiSampleType = D3DMULTISAMPLE_2_SAMPLES; - if (SUCCEEDED(result = IDirect3D9_CheckDeviceMultiSampleType(renderData->D3D, renderData->Adapter, - D3DDEVTYPE_HAL, - Metal_PixelFormatToD3DFORMAT(SDL_GetWindowPixelFormat(Application::Window)), - pparams.Windowed, - pparams.MultiSampleType, NULL))) { - pparams.SwapEffect = D3DSWAPEFFECT_DISCARD; - } - else if (FAILED(result)) { - pparams.MultiSampleType = D3DMULTISAMPLE_NONE; - Graphics::MultisamplingEnabled = 0; - } - } - - IDirect3D9_GetDeviceCaps(renderData->D3D, renderData->Adapter, D3DDEVTYPE_HAL, &caps); - - device_flags = D3DCREATE_FPU_PRESERVE; - if (caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) - device_flags |= D3DCREATE_HARDWARE_VERTEXPROCESSING; - else - device_flags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING; - - if (SDL_GetHintBoolean(SDL_HINT_RENDER_DIRECT3D_THREADSAFE, SDL_FALSE)) { - device_flags |= D3DCREATE_MULTITHREADED; - } - - result = IDirect3D9_CreateDevice( - renderData->D3D, renderData->Adapter, - D3DDEVTYPE_HAL, - pparams.hDeviceWindow, - device_flags, - &pparams, &renderData->Device); - if (FAILED(result)) { - MetalRenderer::Dispose(); - Log::Print(Log::LOG_ERROR, "CreateDevice() %s", Metal_GetResultString(result)); - exit(0); - } - - /* Get presentation parameters to fill info */ - result = IDirect3DDevice9_GetSwapChain(renderData->Device, 0, &chain); - if (FAILED(result)) { - MetalRenderer::Dispose(); - Log::Print(Log::LOG_ERROR, "GetSwapChain() %d", result); - return; - } - result = IDirect3DSwapChain9_GetPresentParameters(chain, &pparams); - if (FAILED(result)) { - IDirect3DSwapChain9_Release(chain); - MetalRenderer::Dispose(); - Log::Print(Log::LOG_ERROR, "GetPresentParameters() %d", result); - return; - } - IDirect3DSwapChain9_Release(chain); - if (pparams.PresentationInterval == D3DPRESENT_INTERVAL_ONE) { - Graphics::VsyncEnabled = true; - } - renderData->PresentParams = pparams; - - IDirect3DDevice9_GetDeviceCaps(renderData->Device, &caps); - texture_max_w = caps.MaxTextureWidth; - texture_max_h = caps.MaxTextureHeight; - if (caps.NumSimultaneousRTs >= 2) { - // renderer->info.flags |= SDL_RENDERER_TARGETTEXTURE; - } - - if (caps.PrimitiveMiscCaps & D3DPMISCCAPS_SEPARATEALPHABLEND) { - renderData->EnableSeparateAlphaBlend = SDL_TRUE; - } - - /* Store the default render target */ - IDirect3DDevice9_GetRenderTarget(renderData->Device, 0, &renderData->DefaultRenderTarget); - renderData->CurrentRenderTarget = NULL; - - /* Set up parameters for rendering */ - Metal_InitRenderState(); - - if (caps.MaxSimultaneousTextures >= 3) { - // int i; - // for (i = 0; i < SDL_arraysize(MetalRenderer::shaders); ++i) { - // result = D3D9_CreatePixelShader(renderData->Device, (D3D9_Shader)i, &MetalRenderer::shaders[i]); - // if (FAILED(result)) { - // Metal_SetError("CreatePixelShader()", result); - // } - // } - // if (MetalRenderer::shaders[SHADER_YUV_JPEG] && MetalRenderer::shaders[SHADER_YUV_BT601] && MetalRenderer::shaders[SHADER_YUV_BT709]) { - // renderer->info.texture_formats[renderer->info.num_texture_formats++] = SDL_PIXELFORMAT_YV12; - // renderer->info.texture_formats[renderer->info.num_texture_formats++] = SDL_PIXELFORMAT_IYUV; - // } - } - - Metal_MakeShaders(); - Metal_MakeShapeBuffers(); - - UseShader(Metal_ShaderShape); - - Graphics::MaxTextureWidth = texture_max_w; - Graphics::MaxTextureHeight = texture_max_h; - - D3DADAPTER_IDENTIFIER9 indent; - IDirect3D9_GetAdapterIdentifier(renderData->D3D, renderData->Adapter, 0, &indent); - - Log::Print(Log::LOG_INFO, "Graphics Card: %s", indent.Description); -} -PUBLIC STATIC Uint32 MetalRenderer::GetWindowFlags() { - return SDL_WINDOW_METAL; -} -PUBLIC STATIC void MetalRenderer::SetGraphicsFunctions() { - Graphics::PixelOffset = 0.5f; - - Graphics::Internal.Init = MetalRenderer::Init; - Graphics::Internal.GetWindowFlags = MetalRenderer::GetWindowFlags; - Graphics::Internal.Dispose = MetalRenderer::Dispose; - - // Texture management functions - Graphics::Internal.CreateTexture = MetalRenderer::CreateTexture; - Graphics::Internal.LockTexture = MetalRenderer::LockTexture; - Graphics::Internal.UpdateTexture = MetalRenderer::UpdateTexture; - Graphics::Internal.UnlockTexture = MetalRenderer::UnlockTexture; - Graphics::Internal.DisposeTexture = MetalRenderer::DisposeTexture; - - // Viewport and view-related functions - Graphics::Internal.SetRenderTarget = MetalRenderer::SetRenderTarget; - Graphics::Internal.UpdateWindowSize = MetalRenderer::UpdateWindowSize; - Graphics::Internal.UpdateViewport = MetalRenderer::UpdateViewport; - Graphics::Internal.UpdateClipRect = MetalRenderer::UpdateClipRect; - Graphics::Internal.UpdateOrtho = MetalRenderer::UpdateOrtho; - Graphics::Internal.UpdatePerspective = MetalRenderer::UpdatePerspective; - Graphics::Internal.UpdateProjectionMatrix = MetalRenderer::UpdateProjectionMatrix; - - // Shader-related functions - Graphics::Internal.UseShader = MetalRenderer::UseShader; - Graphics::Internal.SetUniformF = MetalRenderer::SetUniformF; - Graphics::Internal.SetUniformI = MetalRenderer::SetUniformI; - Graphics::Internal.SetUniformTexture = MetalRenderer::SetUniformTexture; - - // These guys - Graphics::Internal.Clear = MetalRenderer::Clear; - Graphics::Internal.Present = MetalRenderer::Present; - - // Draw mode setting functions - Graphics::Internal.SetBlendColor = MetalRenderer::SetBlendColor; - Graphics::Internal.SetBlendMode = MetalRenderer::SetBlendMode; - Graphics::Internal.SetLineWidth = MetalRenderer::SetLineWidth; - - // Primitive drawing functions - Graphics::Internal.StrokeLine = MetalRenderer::StrokeLine; - Graphics::Internal.StrokeCircle = MetalRenderer::StrokeCircle; - Graphics::Internal.StrokeEllipse = MetalRenderer::StrokeEllipse; - Graphics::Internal.StrokeRectangle = MetalRenderer::StrokeRectangle; - Graphics::Internal.FillCircle = MetalRenderer::FillCircle; - Graphics::Internal.FillEllipse = MetalRenderer::FillEllipse; - Graphics::Internal.FillTriangle = MetalRenderer::FillTriangle; - Graphics::Internal.FillRectangle = MetalRenderer::FillRectangle; - - // Texture drawing functions - Graphics::Internal.DrawTexture = MetalRenderer::DrawTexture; - Graphics::Internal.DrawSprite = MetalRenderer::DrawSprite; - Graphics::Internal.DrawSpritePart = MetalRenderer::DrawSpritePart; -} -PUBLIC STATIC void MetalRenderer::Dispose() { - Memory::Free(Metal_BufferCircleFill); - Memory::Free(Metal_BufferCircleStroke); - Memory::Free(Metal_BufferSquareFill); - - // Metal_ShaderShape->Dispose(); delete Metal_ShaderShape; - // Metal_ShaderTexturedShape->Dispose(); delete Metal_ShaderTexturedShape; - // ShaderTexturedShapeYUV->Dispose(); delete ShaderTexturedShapeYUV; - // ShaderTexturedShapeBlur->Dispose(); delete ShaderTexturedShapeBlur; -} - -// Texture management functions -PUBLIC STATIC Texture* MetalRenderer::CreateTexture(Uint32 format, Uint32 access, Uint32 width, Uint32 height) { - Texture* texture = Texture::New(format, access, width, height); - - Metal_CreateTexture(texture); - - texture->ID = Graphics::TextureMap->Count + 1; - Graphics::TextureMap->Put(texture->ID, texture); - - return texture; -} -PUBLIC STATIC int MetalRenderer::LockTexture(Texture* texture, void** pixels, int* pitch) { - return 0; -} -PUBLIC STATIC int MetalRenderer::UpdateTexture(Texture* texture, SDL_Rect* r, void* pixels, int pitch) { - int inputPixelsX = 0; - int inputPixelsY = 0; - int inputPixelsW = texture->Width; - int inputPixelsH = texture->Height; - if (r) { - inputPixelsX = r->x; - inputPixelsY = r->y; - inputPixelsW = r->w; - inputPixelsH = r->h; - } - - if (Graphics::NoInternalTextures) { - if (inputPixelsW > Graphics::MaxTextureWidth) - inputPixelsW = Graphics::MaxTextureWidth; - if (inputPixelsH > Graphics::MaxTextureHeight) - inputPixelsH = Graphics::MaxTextureHeight; - } - - Metal_TextureData* textureData = (Metal_TextureData*)texture->DriverData; - - RECT d3drect; - D3DLOCKED_RECT locked; - const Uint8 *src; - Uint8 *dst; - int row, length; - HRESULT result; - - d3drect.left = inputPixelsX; - d3drect.right = inputPixelsX + inputPixelsW; - d3drect.top = inputPixelsY; - d3drect.bottom = inputPixelsY + inputPixelsH; - - if (textureData->Staging == NULL) { - result = IDirect3DDevice9_CreateTexture(renderData->Device, texture->Width, texture->Height, 1, 0, textureData->D3DFormat, D3DPOOL_SYSTEMMEM, &textureData->Staging, NULL); - if (FAILED(result)) { - return Metal_SetError("CreateTexture(D3DPOOL_SYSTEMMEM)", result); - } - } - - result = IDirect3DTexture9_LockRect(textureData->Staging, 0, &locked, &d3drect, 0); - if (FAILED(result)) { - Metal_SetError("LockRect() %s", result); - return -1; - } - - src = (const Uint8*)pixels; - dst = (Uint8*)locked.pBits; - length = inputPixelsW * SDL_BYTESPERPIXEL(texture->Format); - if (length == pitch && length == locked.Pitch) { - memcpy(dst, src, length * inputPixelsH); - } - else { - if (length > pitch) { - length = pitch; - } - if (length > locked.Pitch) { - length = locked.Pitch; - } - for (row = 0; row < inputPixelsH; ++row) { - memcpy(dst, src, length); - src += pitch; - dst += locked.Pitch; - } - } - result = IDirect3DTexture9_UnlockRect(textureData->Staging, 0); - if (FAILED(result)) { - Metal_SetError("UnlockRect() %s", result); - return -1; - } - textureData->Dirty = true; - - return 0; -} -PUBLIC STATIC void MetalRenderer::UnlockTexture(Texture* texture) { - -} -PUBLIC STATIC void MetalRenderer::DisposeTexture(Texture* texture) { - Metal_TextureData* textureData = (Metal_TextureData*)texture->DriverData; - if (!textureData) - return; - - if (textureData->Texture) { - IDirect3DTexture9_Release(textureData->Texture); - textureData->Texture = NULL; - } - if (textureData->Staging) { - IDirect3DTexture9_Release(textureData->Staging); - textureData->Staging = NULL; - } - - // free(texture->Pixels); - Memory::Free(texture->DriverData); - - texture->DriverData = NULL; -} - -// Viewport and view-related functions -PUBLIC STATIC void MetalRenderer::SetRenderTarget(Texture* texture) { - Metal_Predraw(); - Metal_SetRenderTarget(texture); -} -PUBLIC STATIC void MetalRenderer::UpdateWindowSize(int width, int height) { - // Metal_UpdateViewport(0, 0, width, height); - renderData->UpdateBackBufferSize = true; -} -PUBLIC STATIC void MetalRenderer::UpdateViewport() { - Viewport* vp = &Graphics::CurrentViewport; - - D3DVIEWPORT9 viewport; - viewport.X = vp->X; - viewport.Y = vp->Y; - viewport.Width = vp->Width; - viewport.Height = vp->Height; // * RetinaScale - viewport.MinZ = 0.0f; - viewport.MaxZ = 1.0f; - IDirect3DDevice9_SetViewport(renderData->Device, &viewport); - - // NOTE: According to SDL2 we should be setting projection matrix here. - // MetalRenderer::UpdateOrtho(vp->Width, vp->Height); - MetalRenderer::UpdateProjectionMatrix(); -} -PUBLIC STATIC void MetalRenderer::UpdateClipRect() { - ClipArea clip = Graphics::CurrentClip; - if (Graphics::CurrentClip.Enabled) { - Viewport view = Graphics::CurrentViewport; - - IDirect3DDevice9_SetRenderState(renderData->Device, D3DRS_SCISSORTESTENABLE, TRUE); - - - int w, h; - float scaleW = 1.0f, scaleH = 1.0f; - SDL_GetWindowSize(Application::Window, &w, &h); - View* currentView = &Scene::Views[Scene::ViewCurrent]; - scaleW *= w / currentView->Width; - scaleH *= h / currentView->Height; - - RECT r; - r.left = view.X + (int)((clip.X) * scaleW); - r.top = view.Y + (int)((clip.Y) * scaleH); - r.right = view.X + (int)((clip.X + clip.Width) * scaleW); - r.bottom = view.Y + (int)((clip.Y + clip.Height) * scaleH); - - HRESULT result = IDirect3DDevice9_SetScissorRect(renderData->Device, &r); - if (result != Metal_OK) { - Metal_SetError("SetScissor()", result); - } - } - else { - IDirect3DDevice9_SetRenderState(renderData->Device, D3DRS_SCISSORTESTENABLE, FALSE); - } -} -PUBLIC STATIC void MetalRenderer::UpdateOrtho(float left, float top, float right, float bottom) { - if (Scene::Views[Scene::ViewCurrent].Software) - Matrix4x4::Ortho(Scene::Views[Scene::ViewCurrent].BaseProjectionMatrix, left, right, bottom, top, 500.0f, -500.0f); - else - Matrix4x4::Ortho(Scene::Views[Scene::ViewCurrent].BaseProjectionMatrix, left, right, top, bottom, 500.0f, -500.0f); - Matrix4x4::Copy(Scene::Views[Scene::ViewCurrent].ProjectionMatrix, Scene::Views[Scene::ViewCurrent].BaseProjectionMatrix); - - if (Metal_PixelPerfectScale) { - Metal_RenderScaleX = Graphics::CurrentViewport.Width / right; - Metal_RenderScaleY = Graphics::CurrentViewport.Height / top; - } -} -PUBLIC STATIC void MetalRenderer::UpdatePerspective(float fovy, float aspect, float nearv, float farv) { - Matrix4x4::Perspective(Scene::Views[Scene::ViewCurrent].BaseProjectionMatrix, fovy, aspect, nearv, farv); - Matrix4x4::Copy(Scene::Views[Scene::ViewCurrent].ProjectionMatrix, Scene::Views[Scene::ViewCurrent].BaseProjectionMatrix); -} -PUBLIC STATIC void MetalRenderer::UpdateProjectionMatrix() { - D3DMATRIX matrix; - memcpy(&matrix.m, Scene::Views[Scene::ViewCurrent].ProjectionMatrix->Values, sizeof(float) * 16); - IDirect3DDevice9_SetTransform(renderData->Device, D3DTS_PROJECTION, &matrix); -} - -// Shader-related functions -PUBLIC STATIC void MetalRenderer::UseShader(void* shader) { - if (Metal_CurrentShader != (MetalShader*)shader) { - Metal_CurrentShader = (MetalShader*)shader; - Metal_CurrentShader->Use(); - } -} -PUBLIC STATIC void MetalRenderer::SetUniformF(int location, int count, float* values) { - // switch (count) { - // case 1: glUniform1f(location, values[0]); CHECK_GL(); break; - // case 2: glUniform2f(location, values[0], values[1]); CHECK_GL(); break; - // case 3: glUniform3f(location, values[0], values[1], values[2]); CHECK_GL(); break; - // case 4: glUniform4f(location, values[0], values[1], values[2], values[3]); CHECK_GL(); break; - // } -} -PUBLIC STATIC void MetalRenderer::SetUniformI(int location, int count, int* values) { - // glUniform1iv(location, count, values); -} -PUBLIC STATIC void MetalRenderer::SetUniformTexture(Texture* texture, int uniform_index, int slot) { - -} - -// These guys -PUBLIC STATIC void MetalRenderer::Clear() { - DWORD color; - HRESULT result; - int BackBufferWidth, BackBufferHeight; - - Metal_Predraw(); - - if (Graphics::CurrentRenderTarget) { - BackBufferWidth = Graphics::CurrentRenderTarget->Width; - BackBufferHeight = Graphics::CurrentRenderTarget->Height; - } - else { - BackBufferWidth = renderData->PresentParams.BackBufferWidth; - BackBufferHeight = renderData->PresentParams.BackBufferHeight; - } - - if (Graphics::CurrentClip.Enabled) - IDirect3DDevice9_SetRenderState(renderData->Device, D3DRS_SCISSORTESTENABLE, FALSE); - - DWORD clear_flags = D3DCLEAR_TARGET; - - clear_flags |= D3DCLEAR_ZBUFFER; - - color = 0x00000000; - - /* Don't reset the viewport if we don't have to! */ - Viewport* vp = &Graphics::CurrentViewport; - if (vp->X == 0.0 && - vp->Y == 0.0 && - vp->Width == BackBufferWidth && - vp->Height == BackBufferHeight) { - result = IDirect3DDevice9_Clear(renderData->Device, 0, NULL, clear_flags, color, 1.0f, 0); - } - else { - D3DVIEWPORT9 viewport; - - /* Clear is defined to clear the entire render target */ - viewport.X = 0.0; - viewport.Y = 0.0; - viewport.Width = BackBufferWidth; - viewport.Height = BackBufferHeight; - viewport.MinZ = 0.0f; - viewport.MaxZ = 1.0f; - IDirect3DDevice9_SetViewport(renderData->Device, &viewport); - - result = IDirect3DDevice9_Clear(renderData->Device, 0, NULL, clear_flags, color, 1.0f, 0); - - /* Reset the viewport */ - viewport.X = vp->X; - viewport.Y = vp->Y; - viewport.Width = vp->Width; - viewport.Height = vp->Height; - viewport.MinZ = 0.0f; - viewport.MaxZ = 1.0f; - IDirect3DDevice9_SetViewport(renderData->Device, &viewport); - } - - if (Graphics::CurrentClip.Enabled) - IDirect3DDevice9_SetRenderState(renderData->Device, D3DRS_SCISSORTESTENABLE, TRUE); - - if (FAILED(result)) { - Metal_SetError("Clear()", result); - } -} -PUBLIC STATIC void MetalRenderer::Present() { - HRESULT result; - - if (!renderData->BeginScene) { - IDirect3DDevice9_EndScene(renderData->Device); - renderData->BeginScene = true; - } - - result = IDirect3DDevice9_TestCooperativeLevel(renderData->Device); - if (result == D3DERR_DEVICELOST) { - /* We'll reset later */ - return; - } - if (result == D3DERR_DEVICENOTRESET) { - Metal_Reset(); - // Metal_Reset(renderer); - } - - result = IDirect3DDevice9_Present(renderData->Device, NULL, NULL, NULL, NULL); - if (FAILED(result)) { - Metal_SetError("Present()", result); - } -} - -// Draw mode setting functions -PUBLIC STATIC void MetalRenderer::SetBlendColor(float r, float g, float b, float a) { - int ha = (int)(a * 0xFF) << 24; - int hr = (int)(r * 0xFF) << 16; - int hg = (int)(g * 0xFF) << 8; - int hb = (int)(b * 0xFF); - Metal_BlendColorsAsHex = ha | hr | hg | hb; -} -PUBLIC STATIC void MetalRenderer::SetBlendMode(int srcC, int dstC, int srcA, int dstA) { - Metal_Blend_SRC_COLOR = Metal_GetBlendFactorFromHatch(srcC); - Metal_Blend_DST_COLOR = Metal_GetBlendFactorFromHatch(dstC); - Metal_Blend_SRC_ALPHA = Metal_GetBlendFactorFromHatch(srcA); - Metal_Blend_DST_ALPHA = Metal_GetBlendFactorFromHatch(dstA); -} -PUBLIC STATIC void MetalRenderer::SetLineWidth(float n) { - // glLineWidth(n); -} - -// Primitive drawing functions -PUBLIC STATIC void MetalRenderer::StrokeLine(float x1, float y1, float x2, float y2) { - UseShader(Metal_SelectedShader ? Metal_SelectedShader : Metal_ShaderShape); - - Graphics::Save(); - // glUniformMatrix4fv(Metal_CurrentShader->LocModelViewMatrix, 1, false, Graphics::ModelViewMatrix->Values); - - float v[6]; - v[0] = x1; v[1] = y1; v[2] = 0.0f; - v[3] = x2; v[4] = y2; v[5] = 0.0f; - - // glBindBuffer(GL_ARRAY_BUFFER, 0); - // glVertexAttribPointer(Metal_CurrentShader->LocPosition, 3, GL_FLOAT, GL_FALSE, 0, v); - // glDrawArrays(GL_LINES, 0, 2); - Graphics::Restore(); -} -PUBLIC STATIC void MetalRenderer::StrokeCircle(float x, float y, float rad) { - Metal_BeginDrawShape(Metal_BufferCircleStroke, 361); - - Graphics::Save(); - Graphics::Translate(x, y, 0.0f); - Graphics::Scale(rad, rad, 1.0f); - D3DMATRIX matrix; - memcpy(&matrix.m, Graphics::ModelViewMatrix->Values, sizeof(float) * 16); - IDirect3DDevice9_SetTransform(renderData->Device, D3DTS_VIEW, &matrix); - Graphics::Restore(); - - Metal_EndDrawShape(Metal_BufferCircleStroke, D3DPT_LINESTRIP, 360); -} -PUBLIC STATIC void MetalRenderer::StrokeEllipse(float x, float y, float w, float h) { - UseShader(Metal_SelectedShader ? Metal_SelectedShader : Metal_ShaderShape); - - Graphics::Save(); - Graphics::Translate(x + w / 2, y + h / 2, 0.0f); - Graphics::Scale(w / 2, h / 2, 1.0f); - // glUniformMatrix4fv(Metal_CurrentShader->LocModelViewMatrix, 1, false, Graphics::ModelViewMatrix->Values); - - // glBindBuffer(GL_ARRAY_BUFFER, Metal_BufferCircleStroke); - // glVertexAttribPointer(Metal_CurrentShader->LocPosition, 3, GL_FLOAT, GL_FALSE, 0, 0); - // glDrawArrays(GL_LINE_STRIP, 0, 361); - Graphics::Restore(); -} -PUBLIC STATIC void MetalRenderer::StrokeRectangle(float x, float y, float w, float h) { - StrokeLine(x, y, x + w, y); - StrokeLine(x, y + h, x + w, y + h); - - StrokeLine(x, y, x, y + h); - StrokeLine(x + w, y, x + w, y + h); -} -PUBLIC STATIC void MetalRenderer::FillCircle(float x, float y, float rad) { - Metal_BeginDrawShape(Metal_BufferCircleFill, 362); - - Graphics::Save(); - Graphics::Translate(x, y, 0.0f); - Graphics::Scale(rad, rad, 1.0f); - D3DMATRIX matrix; - memcpy(&matrix.m, Graphics::ModelViewMatrix->Values, sizeof(float) * 16); - IDirect3DDevice9_SetTransform(renderData->Device, D3DTS_VIEW, &matrix); - Graphics::Restore(); - - Metal_EndDrawShape(Metal_BufferCircleFill, D3DPT_TRIANGLEFAN, 360); -} -PUBLIC STATIC void MetalRenderer::FillEllipse(float x, float y, float w, float h) { - Metal_BeginDrawShape(Metal_BufferCircleFill, 362); - - w *= 0.5f; - h *= 0.5f; - - Graphics::Save(); - Graphics::Translate(x + w, y + h, 0.0f); - Graphics::Scale(w, h, 1.0f); - D3DMATRIX matrix; - memcpy(&matrix.m, Graphics::ModelViewMatrix->Values, sizeof(float) * 16); - IDirect3DDevice9_SetTransform(renderData->Device, D3DTS_VIEW, &matrix); - Graphics::Restore(); - - Metal_EndDrawShape(Metal_BufferCircleFill, D3DPT_TRIANGLEFAN, 360); -} -PUBLIC STATIC void MetalRenderer::FillTriangle(float x1, float y1, float x2, float y2, float x3, float y3) { - Vertex vertices[3]; - vertices[0] = Vertex { x1, y1, 0.0f, Metal_BlendColorsAsHex, 0.0f, 0.0f }; - vertices[1] = Vertex { x2, y2, 0.0f, Metal_BlendColorsAsHex, 0.0f, 0.0f }; - vertices[2] = Vertex { x3, y3, 0.0f, Metal_BlendColorsAsHex, 0.0f, 0.0f }; - - Metal_BeginDrawShape(vertices, 3); - - D3DMATRIX matrix; - memcpy(&matrix.m, Graphics::ModelViewMatrix->Values, sizeof(float) * 16); - IDirect3DDevice9_SetTransform(renderData->Device, D3DTS_VIEW, &matrix); - - Metal_EndDrawShape(vertices, D3DPT_TRIANGLEFAN, 1); -} -PUBLIC STATIC void MetalRenderer::FillRectangle(float x, float y, float w, float h) { - Metal_BeginDrawShape(Metal_BufferSquareFill, 4); - - Graphics::Save(); - Graphics::Translate(x, y, 0.0f); - Graphics::Scale(w, h, 1.0f); - D3DMATRIX matrix; - memcpy(&matrix.m, Graphics::ModelViewMatrix->Values, sizeof(float) * 16); - IDirect3DDevice9_SetTransform(renderData->Device, D3DTS_VIEW, &matrix); - Graphics::Restore(); - - Metal_EndDrawShape(Metal_BufferSquareFill, D3DPT_TRIANGLEFAN, 2); -} - -// Texture drawing functions -PUBLIC STATIC void MetalRenderer::DrawTexture(Texture* texture, float sx, float sy, float sw, float sh, float x, float y, float w, float h) { - UseShader(Metal_SelectedShader ? Metal_SelectedShader : Metal_ShaderTexturedShape); - if (sx < 0) - sx = 0.0, sy = 0.0, sw = texture->Width, sh = texture->Height; - Metal_DrawTextureRaw(texture, sx, sy, sw, sh, x, y, w, h, false, texture->Access != SDL_TEXTUREACCESS_TARGET); -} -PUBLIC STATIC void MetalRenderer::DrawSprite(ISprite* sprite, int animation, int frame, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation) { - if (Graphics::SpriteRangeCheck(sprite, animation, frame)) return; - - AnimFrame animframe = sprite->Animations[animation].Frames[frame]; - - float fX = flipX ? -1.0 : 1.0; - float fY = flipY ? -1.0 : 1.0; - // DrawTexture(sprite->Spritesheets[animframe.SheetNumber], animframe.X, animframe.Y, animframe.W, animframe.H, x + fX * animframe.OffX, y + fY * animframe.OffY, fX * animframe.W, fY * animframe.H); - - UseShader(Metal_SelectedShader ? Metal_SelectedShader : Metal_ShaderTexturedShape); - Graphics::Save(); - Graphics::Translate(x, y, 0.0f); - Graphics::Scale(fX, fY, 1.0f); - Metal_DrawTextureRaw(sprite->Spritesheets[animframe.SheetNumber], animframe.X, animframe.Y, animframe.Width, animframe.Height, animframe.OffsetX, animframe.OffsetY, animframe.Width, animframe.Height, flipX, flipY); - Graphics::Restore(); -} -PUBLIC STATIC void MetalRenderer::DrawSpritePart(ISprite* sprite, int animation, int frame, int sx, int sy, int sw, int sh, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation) { - if (Graphics::SpriteRangeCheck(sprite, animation, frame)) return; - - AnimFrame animframe = sprite->Animations[animation].Frames[frame]; - if (sx == animframe.Width) - return; - if (sy == animframe.Height) - return; - - float fX = flipX ? -1.0 : 1.0; - float fY = flipY ? -1.0 : 1.0; - if (sw >= animframe.Width - sx) - sw = animframe.Width - sx; - if (sh >= animframe.Height - sy) - sh = animframe.Height - sy; - - UseShader(Metal_SelectedShader ? Metal_SelectedShader : Metal_ShaderTexturedShape); - Graphics::Save(); - Graphics::Translate(x, y, 0.0f); - Graphics::Scale(fX, fY, 1.0f); - Metal_DrawTextureRaw(sprite->Spritesheets[animframe.SheetNumber], - animframe.X + sx, animframe.Y + sy, - sw, sh, - sx + animframe.OffsetX, sy + animframe.OffsetY, - sw, sh, - flipX, flipY); - Graphics::Restore(); -} - -/* -// Draw buffering -PUBLIC STATIC Uint32 MetalRenderer::CreateTexturedShapeBuffer(float** data, int vertexCount) { - // x, y, z, u, v - Uint32 bufferID; - glGenBuffers(1, &bufferID); - glBindBuffer(GL_ARRAY_BUFFER, bufferID); - glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertexCount * 5, data, GL_STATIC_DRAW); - - *data = NULL; - - return bufferID; -} - -PUBLIC STATIC void MetalRenderer::DrawTexturedShapeBuffer(Texture* texture, Uint32 bufferID, int vertexCount) { - UseShader(Metal_SelectedShader ? Metal_SelectedShader : Metal_ShaderTexturedShape); - - GLTextureData* textureData = (GLTextureData*)texture->DriverData; - glUniformMatrix4fv(MetalRenderer::Metal_CurrentShader->LocModelViewMatrix, 1, false, MetalRenderer::Graphics::ModelViewMatrix->Values); - - glActiveTexture(GL_TEXTURE0); - glUniform1i(MetalRenderer::Metal_CurrentShader->LocTexture, 0); - glBindTexture(GL_TEXTURE_2D, textureData->TextureID); - - glEnableVertexAttribArray(MetalRenderer::Metal_CurrentShader->LocTexCoord); - - glBindBuffer(GL_ARRAY_BUFFER, bufferID); - glVertexAttribPointer(MetalRenderer::Metal_CurrentShader->LocPosition, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 5, (GLvoid*)0); - glVertexAttribPointer(MetalRenderer::Metal_CurrentShader->LocTexCoord, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 5, (GLvoid*)12); - glDrawArrays(GL_TRIANGLES, 0, vertexCount); - - glDisableVertexAttribArray(MetalRenderer::Metal_CurrentShader->LocTexCoord); -} -//*/ - -#endif diff --git a/source/Engine/Rendering/Metal/MetalRenderer.mm.unused b/source/Engine/Rendering/Metal/MetalRenderer.mm.unused deleted file mode 100644 index 4bcdbefc..00000000 --- a/source/Engine/Rendering/Metal/MetalRenderer.mm.unused +++ /dev/null @@ -1,443 +0,0 @@ - -#include - -#import -#import - -#ifdef __MACOSX__ - #import -#endif - -/* Regenerate these with build-metal-shaders.sh */ -// #ifdef __MACOSX__ -// #include "SDL_shaders_metal_osx.h" -// #elif defined(__TVOS__) -// #if TARGET_OS_SIMULATOR -// #include "SDL_shaders_metal_tvsimulator.h" -// #else -// #include "SDL_shaders_metal_tvos.h" -// #endif -// #else -// #if TARGET_OS_SIMULATOR -// #include "SDL_shaders_metal_iphonesimulator.h" -// #else -// #include "SDL_shaders_metal_ios.h" -// #endif -// #endif - -#include - -@interface METAL_TextureData : NSObject - @property (nonatomic, retain) id mtltexture; - @property (nonatomic, retain) id mtltexture_uv; - @property (nonatomic, retain) id mtlsampler; - @property (nonatomic, assign) SDL_MetalFragmentFunction fragmentFunction; - @property (nonatomic, assign) BOOL yuv; - @property (nonatomic, assign) BOOL nv12; - @property (nonatomic, assign) size_t conversionBufferOffset; - @property (nonatomic, assign) BOOL hasdata; - - @property (nonatomic, retain) id lockedbuffer; - @property (nonatomic, assign) SDL_Rect lockedrect; -@end - -@implementation METAL_TextureData -#if !__has_feature(objc_arc) - - (void)dealloc { - [_mtltexture release]; - [_mtltexture_uv release]; - [_mtlsampler release]; - [_lockedbuffer release]; - [super dealloc]; - } -#endif -@end - -static int IsMetalAvailable(const SDL_SysWMinfo* syswm) { - if (syswm->subsystem != SDL_SYSWM_COCOA && syswm->subsystem != SDL_SYSWM_UIKIT) { - Log::Print(Log::LOG_ERROR, "Metal render target only supports Cocoa and UIKit video targets at the moment."); - return -1; - } - // this checks a weak symbol. - #if (defined(__MACOSX__) && (MAC_OS_X_VERSION_MIN_REQUIRED < 101100)) - if (MTLCreateSystemDefaultDevice == NULL) { // probably on 10.10 or lower. - Log::Print(Log::LOG_ERROR, "Metal framework not available on this system"); - return -1; - } - #endif - - return 0; -} - -void METAL_Init() { - @autoreleasepool { - Graphics::PreferredPixelFormat = SDL_PIXELFORMAT_ARGB8888; - Metal_MatrixIdentity = Matrix4x4::Create(); - - // renderData = (Metal_RenderData*)calloc(1, sizeof(Metal_RenderData)); - - Log::Print(Log::LOG_INFO, "Renderer: Metal"); - - SDL_SysWMinfo windowinfo; - SDL_DisplayMode fullscreen_mode; - int displayIndex, w, h, texture_max_w, texture_max_h; - - SDL_VERSION(&windowinfo.version); - SDL_GetWindowWMInfo(Application::Window, &windowinfo); - - SDL_GetWindowSize(Application::Window, &w, &h); - SDL_GetWindowDisplayMode(Application::Window, &fullscreen_mode); - - mtldevice = MTLCreateSystemDefaultDevice(); - - if (mtldevice == nil) { - SDL_free(renderer); - SDL_SetError("Failed to obtain Metal device"); - if (changed_window) { - SDL_RecreateWindow(window, window_flags); - } - return NULL; - } - - view = SDL_Metal_CreateView(window); - - if (view == NULL) { - #if !__has_feature(objc_arc) - [mtldevice release]; - #endif - - SDL_free(renderer); - if (changed_window) { - SDL_RecreateWindow(window, window_flags); - } - return NULL; - } - - // !!! FIXME: error checking on all of this. - data = [[METAL_RenderData alloc] init]; - - if (data == nil) { - #if !__has_feature(objc_arc) - [mtldevice release]; - #endif - SDL_Metal_DestroyView(view); - SDL_free(renderer); - if (changed_window) { - SDL_RecreateWindow(window, window_flags); - } - return NULL; - } - - driverdata = (void*)CFBridgingRetain(data); - - data.mtlview = view; - - #ifdef __MACOSX__ - layer = (CAMetalLayer *)[(NSView *)view layer]; - #else - layer = (CAMetalLayer *)[(__bridge UIView *)view layer]; - #endif - - layer.device = mtldevice; - - /* Necessary for RenderReadPixels. */ - layer.framebufferOnly = NO; - - data.mtldevice = layer.device; - data.mtllayer = layer; - id mtlcmdqueue = [data.mtldevice newCommandQueue]; - data.mtlcmdqueue = mtlcmdqueue; - data.mtlcmdqueue.label = @"SDL Metal Renderer"; - data.mtlpassdesc = [MTLRenderPassDescriptor renderPassDescriptor]; - - NSError *err = nil; - - // The compiled .metallib is embedded in a static array in a header file - // but the original shader source code is in SDL_shaders_metal.metal. - dispatch_data_t mtllibdata = dispatch_data_create(sdl_metallib, sdl_metallib_len, dispatch_get_global_queue(0, 0), ^{}); - id mtllibrary = [data.mtldevice newLibraryWithData:mtllibdata error:&err]; - data.mtllibrary = mtllibrary; - SDL_assert(err == nil); - #if !__has_feature(objc_arc) - dispatch_release(mtllibdata); - #endif - data.mtllibrary.label = @"SDL Metal renderer shader library"; - - /* Do some shader pipeline state loading up-front rather than on demand. */ - data.pipelinescount = 0; - data.allpipelines = NULL; - ChooseShaderPipelines(data, MTLPixelFormatBGRA8Unorm); - - MTLSamplerDescriptor *samplerdesc = [[MTLSamplerDescriptor alloc] init]; - - samplerdesc.minFilter = MTLSamplerMinMagFilterNearest; - samplerdesc.magFilter = MTLSamplerMinMagFilterNearest; - id mtlsamplernearest = [data.mtldevice newSamplerStateWithDescriptor:samplerdesc]; - data.mtlsamplernearest = mtlsamplernearest; - - samplerdesc.minFilter = MTLSamplerMinMagFilterLinear; - samplerdesc.magFilter = MTLSamplerMinMagFilterLinear; - id mtlsamplerlinear = [data.mtldevice newSamplerStateWithDescriptor:samplerdesc]; - data.mtlsamplerlinear = mtlsamplerlinear; - - /* Note: matrices are column major. */ - float identitytransform[16] = { - 1.000000000f, 0.000000000f, 0.000000000f, 0.000000000f, - 0.000000000f, 1.000000000f, 0.000000000f, 0.000000000f, - 0.000000000f, 0.000000000f, 1.000000000f, 0.000000000f, - 0.000000000f, 0.000000000f, 0.000000000f, 1.000000000f, - }; - float halfpixeltransform[16] = { - 1.000000000f, 0.000000000f, 0.000000000f, 0.000000000f, - 0.000000000f, 1.000000000f, 0.000000000f, 0.000000000f, - 0.000000000f, 0.000000000f, 1.000000000f, 0.000000000f, - 0.500000000f, 0.500000000f, 0.000000000f, 1.000000000f, - }; - /* Metal pads float3s to 16 bytes. */ - float decodetransformJPEG[4*4] = { - 0.000000000, -0.501960814, -0.501960814, 0.000000000, /* offset */ - 1.000000000, 0.000000000, 1.402000000, 0.000000000, /* Rcoeff */ - 1.000000000, -0.344100000, -0.714100000, 0.000000000, /* Gcoeff */ - 1.000000000, 1.772000000, 0.000000000, 0.000000000, /* Bcoeff */ - }; - float decodetransformBT601[4*4] = { - -0.0627451017, -0.501960814, -0.501960814, 0.000000000, /* offset */ - 1.1644000000, 0.000000000, 1.596000000, 0.000000000, /* Rcoeff */ - 1.1644000000, -0.391800000, -0.813000000, 0.000000000, /* Gcoeff */ - 1.1644000000, 2.017200000, 0.000000000, 0.000000000, /* Bcoeff */ - }; - float decodetransformBT709[4*4] = { - 0.000000000, -0.501960814, -0.501960814, 0.000000000, /* offset */ - 1.000000000, 0.000000000, 1.402000000, 0.000000000, /* Rcoeff */ - 1.000000000, -0.344100000, -0.714100000, 0.000000000, /* Gcoeff */ - 1.000000000, 1.772000000, 0.000000000, 0.000000000, /* Bcoeff */ - }; - - id mtlbufconstantstaging = [data.mtldevice newBufferWithLength:CONSTANTS_LENGTH options:MTLResourceStorageModeShared]; - #if !__has_feature(objc_arc) - [mtlbufconstantstaging autorelease]; - #endif - - char *constantdata = [mtlbufconstantstaging contents]; - SDL_memcpy(constantdata + CONSTANTS_OFFSET_IDENTITY, identitytransform, sizeof(identitytransform)); - SDL_memcpy(constantdata + CONSTANTS_OFFSET_HALF_PIXEL_TRANSFORM, halfpixeltransform, sizeof(halfpixeltransform)); - SDL_memcpy(constantdata + CONSTANTS_OFFSET_DECODE_JPEG, decodetransformJPEG, sizeof(decodetransformJPEG)); - SDL_memcpy(constantdata + CONSTANTS_OFFSET_DECODE_BT601, decodetransformBT601, sizeof(decodetransformBT601)); - SDL_memcpy(constantdata + CONSTANTS_OFFSET_DECODE_BT709, decodetransformBT709, sizeof(decodetransformBT709)); - - int quadcount = UINT16_MAX / 4; - size_t indicessize = sizeof(UInt16) * quadcount * 6; - id mtlbufquadindicesstaging = [data.mtldevice newBufferWithLength:indicessize options:MTLResourceStorageModeShared]; - #if !__has_feature(objc_arc) - [mtlbufquadindicesstaging autorelease]; - #endif - - /* Quads in the following vertex order (matches the FillRects vertices): - * 1---3 - * | \ | - * 0---2 - */ - UInt16 *indexdata = [mtlbufquadindicesstaging contents]; - for (int i = 0; i < quadcount; i++) { - indexdata[i * 6 + 0] = i * 4 + 0; - indexdata[i * 6 + 1] = i * 4 + 1; - indexdata[i * 6 + 2] = i * 4 + 2; - - indexdata[i * 6 + 3] = i * 4 + 2; - indexdata[i * 6 + 4] = i * 4 + 1; - indexdata[i * 6 + 5] = i * 4 + 3; - } - - id mtlbufconstants = [data.mtldevice newBufferWithLength:CONSTANTS_LENGTH options:MTLResourceStorageModePrivate]; - data.mtlbufconstants = mtlbufconstants; - data.mtlbufconstants.label = @"SDL constant data"; - - id mtlbufquadindices = [data.mtldevice newBufferWithLength:indicessize options:MTLResourceStorageModePrivate]; - data.mtlbufquadindices = mtlbufquadindices; - data.mtlbufquadindices.label = @"SDL quad index buffer"; - - id cmdbuffer = [data.mtlcmdqueue commandBuffer]; - id blitcmd = [cmdbuffer blitCommandEncoder]; - - [blitcmd copyFromBuffer:mtlbufconstantstaging sourceOffset:0 toBuffer:mtlbufconstants destinationOffset:0 size:CONSTANTS_LENGTH]; - [blitcmd copyFromBuffer:mtlbufquadindicesstaging sourceOffset:0 toBuffer:mtlbufquadindices destinationOffset:0 size:indicessize]; - - [blitcmd endEncoding]; - [cmdbuffer commit]; - - // !!! FIXME: force more clears here so all the drawables are sane to start, and our static buffers are definitely flushed. - - // renderer->WindowEvent = METAL_WindowEvent; - // renderer->GetOutputSize = METAL_GetOutputSize; - // renderer->SupportsBlendMode = METAL_SupportsBlendMode; - // renderer->CreateTexture = METAL_CreateTexture; - // renderer->UpdateTexture = METAL_UpdateTexture; - // #if SDL_HAVE_YUV - // renderer->UpdateTextureYUV = METAL_UpdateTextureYUV; - // renderer->UpdateTextureNV = METAL_UpdateTextureNV; - // #endif - // renderer->LockTexture = METAL_LockTexture; - // renderer->UnlockTexture = METAL_UnlockTexture; - // renderer->SetTextureScaleMode = METAL_SetTextureScaleMode; - // renderer->SetRenderTarget = METAL_SetRenderTarget; - // renderer->QueueSetViewport = METAL_QueueSetViewport; - // renderer->QueueSetDrawColor = METAL_QueueSetDrawColor; - // renderer->QueueDrawPoints = METAL_QueueDrawPoints; - // renderer->QueueDrawLines = METAL_QueueDrawLines; - // renderer->QueueFillRects = METAL_QueueFillRects; - // renderer->QueueCopy = METAL_QueueCopy; - // renderer->QueueCopyEx = METAL_QueueCopyEx; - // renderer->RunCommandQueue = METAL_RunCommandQueue; - // renderer->RenderReadPixels = METAL_RenderReadPixels; - // renderer->RenderPresent = METAL_RenderPresent; - // renderer->DestroyTexture = METAL_DestroyTexture; - // renderer->DestroyRenderer = METAL_DestroyRenderer; - // renderer->GetMetalLayer = METAL_GetMetalLayer; - // renderer->GetMetalCommandEncoder = METAL_GetMetalCommandEncoder; - // - // renderer->info = METAL_RenderDriver.info; - // renderer->info.flags = (SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE); - // - // renderer->always_batch = SDL_TRUE; - - #if (defined(__MACOSX__) && defined(MAC_OS_X_VERSION_10_13)) || TARGET_OS_MACCATALYST - if (@available(macOS 10.13, *)) { - data.mtllayer.displaySyncEnabled = (flags & SDL_RENDERER_PRESENTVSYNC) != 0; - if (data.mtllayer.displaySyncEnabled) { - renderer->info.flags |= SDL_RENDERER_PRESENTVSYNC; - } - } else - #endif - { - renderer->info.flags |= SDL_RENDERER_PRESENTVSYNC; - } - - /* https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf */ - int maxtexsize = 4096; - #if defined(__MACOSX__) || TARGET_OS_MACCATALYST - maxtexsize = 16384; - #elif defined(__TVOS__) - maxtexsize = 8192; - #ifdef __TVOS_11_0 - if (@available(tvOS 11.0, *)) { - if ([mtldevice supportsFeatureSet:MTLFeatureSet_tvOS_GPUFamily2_v1]) { - maxtexsize = 16384; - } - } - #endif - #else - #ifdef __IPHONE_11_0 - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wunguarded-availability-new" - if ([mtldevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily4_v1]) { - maxtexsize = 16384; - } else - #pragma clang diagnostic pop - #endif - #ifdef __IPHONE_10_0 - if ([mtldevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily3_v1]) { - maxtexsize = 16384; - } else - #endif - if ([mtldevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily2_v2] || [mtldevice supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily1_v2]) { - maxtexsize = 8192; - } - else { - maxtexsize = 4096; - } - #endif - - renderer->info.max_texture_width = maxtexsize; - renderer->info.max_texture_height = maxtexsize; - - #if !__has_feature(objc_arc) - [mtlcmdqueue release]; - [mtllibrary release]; - [samplerdesc release]; - [mtlsamplernearest release]; - [mtlsamplerlinear release]; - [mtlbufconstants release]; - [mtlbufquadindices release]; - [data release]; - [mtldevice release]; - #endif - } -} -void METAL_Dispose() { - -} -Texture* METAL_CreateTexture(Uint32 format, Uint32 access, Uint32 width, Uint32 height) { - -} -int METAL_LockTexture(Texture* texture, void** pixels, int* pitch) { - -} -int METAL_UpdateTexture(Texture* texture, SDL_Rect* r, void* pixels, int pitch) { - -} -void METAL_UnlockTexture(Texture* texture) { - -} -void METAL_DisposeTexture(Texture* texture) { - -} -void METAL_SetRenderTarget(Texture* texture) { - -} -void METAL_UpdateWindowSize(int width, int height) { - -} -void METAL_UpdateViewport() { - -} -void METAL_UpdateClipRect() { - -} -void METAL_UpdateOrtho(float left, float top, float right, float bottom) { - -} -void METAL_UpdatePerspective(float fovy, float aspect, float nearv, float farv) { - -} -void METAL_UpdateProjectionMatrix() { - -} -void METAL_Clear() { - -} -void METAL_Present() { - -} -void METAL_SetBlendColor(float r, float g, float b, float a) { - -} -void METAL_SetBlendMode(int srcC, int dstC, int srcA, int dstA) { - -} -void METAL_StrokeLine(float x1, float y1, float x2, float y2) { - -} -void METAL_StrokeCircle(float x, float y, float rad) { - -} -void METAL_StrokeEllipse(float x, float y, float w, float h) { - -} -void METAL_StrokeRectangle(float x, float y, float w, float h) { - -} -void METAL_FillCircle(float x, float y, float rad) { - -} -void METAL_FillEllipse(float x, float y, float w, float h) { - -} -void METAL_FillTriangle(float x1, float y1, float x2, float y2, float x3, float y3) { - -} -void METAL_FillRectangle(float x, float y, float w, float h) { - -} -void METAL_DrawTexture(Texture* texture, float sx, float sy, float sw, float sh, float x, float y, float w, float h) { - -} diff --git a/source/Engine/Rendering/ModelRenderer.cpp b/source/Engine/Rendering/ModelRenderer.cpp index cf183117..30ea31c7 100644 --- a/source/Engine/Rendering/ModelRenderer.cpp +++ b/source/Engine/Rendering/ModelRenderer.cpp @@ -1,43 +1,8 @@ -#if INTERFACE -#include -#include -#include -#include -#include -#include -#include - -class ModelRenderer { -public: - PolygonRenderer* PolyRenderer; - VertexBuffer* Buffer; - - VertexAttribute* AttribBuffer; - VertexAttribute* Vertex; - FaceInfo* FaceItem; - - Matrix4x4* ModelMatrix; - Matrix4x4* ViewMatrix; - Matrix4x4* ProjectionMatrix; - Matrix4x4* NormalMatrix; - - Matrix4x4 MVPMatrix; - - bool DoProjection; - bool ClipFaces; - Armature* ArmaturePtr; - - Uint32 DrawMode; - Uint8 FaceCullMode; - Uint32 CurrentColor; -}; -#endif - #include #include #include -PRIVATE void ModelRenderer::Init() { +void ModelRenderer::Init() { FaceItem = &Buffer->FaceInfoBuffer[Buffer->FaceCount]; AttribBuffer = Vertex = &Buffer->Vertices[Buffer->VertexCount]; @@ -45,28 +10,28 @@ PRIVATE void ModelRenderer::Init() { ArmaturePtr = nullptr; } -PUBLIC ModelRenderer::ModelRenderer(PolygonRenderer* polyRenderer) { +ModelRenderer::ModelRenderer(PolygonRenderer* polyRenderer) { PolyRenderer = polyRenderer; Buffer = PolyRenderer->VertexBuf; Init(); } -PUBLIC ModelRenderer::ModelRenderer(VertexBuffer* buffer) { +ModelRenderer::ModelRenderer(VertexBuffer* buffer) { PolyRenderer = nullptr; Buffer = buffer; Init(); } -PUBLIC void ModelRenderer::SetMatrices(Matrix4x4* model, Matrix4x4* view, Matrix4x4* projection, Matrix4x4* normal) { +void ModelRenderer::SetMatrices(Matrix4x4* model, Matrix4x4* view, Matrix4x4* projection, Matrix4x4* normal) { ModelMatrix = model; ViewMatrix = view; ProjectionMatrix = projection; NormalMatrix = normal; } -PRIVATE void ModelRenderer::AddFace(int faceVertexCount, Material* material) { +void ModelRenderer::AddFace(int faceVertexCount, Material* material) { FaceItem->DrawMode = DrawMode; FaceItem->CullMode = FaceCullMode; FaceItem->NumVertices = faceVertexCount; @@ -83,7 +48,7 @@ PRIVATE void ModelRenderer::AddFace(int faceVertexCount, Material* material) { Buffer->VertexCount += faceVertexCount; } -PRIVATE int ModelRenderer::ClipFace(int faceVertexCount) { +int ModelRenderer::ClipFace(int faceVertexCount) { if (!ClipFaces) return faceVertexCount; @@ -114,7 +79,7 @@ PRIVATE int ModelRenderer::ClipFace(int faceVertexCount) { return faceVertexCount; } -PRIVATE void ModelRenderer::DrawMesh(IModel* model, Mesh* mesh, Skeleton* skeleton, Matrix4x4& mvpMatrix) { +void ModelRenderer::DrawMesh(IModel* model, Mesh* mesh, Skeleton* skeleton, Matrix4x4& mvpMatrix) { Vector3* positionBuffer = mesh->PositionBuffer; Vector3* normalBuffer = mesh->NormalBuffer; Vector2* uvBuffer = mesh->UVBuffer; @@ -127,7 +92,7 @@ PRIVATE void ModelRenderer::DrawMesh(IModel* model, Mesh* mesh, Skeleton* skelet DrawMesh(model, mesh, positionBuffer, normalBuffer, uvBuffer, mvpMatrix); } -PRIVATE void ModelRenderer::DrawMesh(IModel* model, Mesh* mesh, Uint16 animation, Uint32 frame, Matrix4x4& mvpMatrix) { +void ModelRenderer::DrawMesh(IModel* model, Mesh* mesh, Uint16 animation, Uint32 frame, Matrix4x4& mvpMatrix) { Vector3* positionBuffer = mesh->PositionBuffer; Vector3* normalBuffer = mesh->NormalBuffer; Vector2* uvBuffer = mesh->UVBuffer; @@ -143,7 +108,7 @@ PRIVATE void ModelRenderer::DrawMesh(IModel* model, Mesh* mesh, Uint16 animation DrawMesh(model, mesh, positionBuffer, normalBuffer, uvBuffer, mvpMatrix); } -PRIVATE void ModelRenderer::DrawMesh(IModel* model, Mesh* mesh, Vector3* positionBuffer, Vector3* normalBuffer, Vector2* uvBuffer, Matrix4x4& mvpMatrix) { +void ModelRenderer::DrawMesh(IModel* model, Mesh* mesh, Vector3* positionBuffer, Vector3* normalBuffer, Vector2* uvBuffer, Matrix4x4& mvpMatrix) { Material* material = mesh->MaterialIndex != -1 ? model->Materials[mesh->MaterialIndex] : nullptr; Sint32* modelVertexIndexPtr = mesh->VertexIndexBuffer; @@ -370,7 +335,7 @@ PRIVATE void ModelRenderer::DrawMesh(IModel* model, Mesh* mesh, Vector3* positio } } -PRIVATE void ModelRenderer::DrawNode(IModel* model, ModelNode* node, Matrix4x4* world) { +void ModelRenderer::DrawNode(IModel* model, ModelNode* node, Matrix4x4* world) { size_t numMeshes = node->Meshes.size(); size_t numChildren = node->Children.size(); @@ -403,7 +368,7 @@ PRIVATE void ModelRenderer::DrawNode(IModel* model, ModelNode* node, Matrix4x4* DrawNode(model, node->Children[i], world); } -PRIVATE void ModelRenderer::DrawModelInternal(IModel* model, Uint16 animation, Uint32 frame) { +void ModelRenderer::DrawModelInternal(IModel* model, Uint16 animation, Uint32 frame) { if (DoProjection) Graphics::CalculateMVPMatrix(&MVPMatrix, ModelMatrix, ViewMatrix, ProjectionMatrix); else @@ -422,7 +387,7 @@ PRIVATE void ModelRenderer::DrawModelInternal(IModel* model, Uint16 animation, U } } -PUBLIC void ModelRenderer::DrawModel(IModel* model, Uint16 animation, Uint32 frame) { +void ModelRenderer::DrawModel(IModel* model, Uint16 animation, Uint32 frame) { Uint16 numAnims = model->AnimationCount; if (numAnims > 0) { if (animation >= numAnims) diff --git a/source/Engine/Rendering/PolygonRenderer.cpp b/source/Engine/Rendering/PolygonRenderer.cpp index 2014b164..6e305395 100644 --- a/source/Engine/Rendering/PolygonRenderer.cpp +++ b/source/Engine/Rendering/PolygonRenderer.cpp @@ -1,34 +1,3 @@ -#if INTERFACE -#include -#include -#include -#include -#include -#include -#include -#include - -class PolygonRenderer { -public: - Scene3D* ScenePtr = nullptr; - VertexBuffer* VertexBuf = nullptr; - Matrix4x4* ModelMatrix = nullptr; - Matrix4x4* NormalMatrix = nullptr; - Matrix4x4* ViewMatrix = nullptr; - Matrix4x4* ProjectionMatrix = nullptr; - - Uint32 DrawMode = 0; - Uint8 FaceCullMode = 0; - Uint32 CurrentColor = 0; - - bool DoProjection = false; - bool DoClipping = false; - bool ClipPolygonsByFrustum = false; - int NumFrustumPlanes = 0; - Frustum ViewFrustum[NUM_FRUSTUM_PLANES]; -}; -#endif - #include #include #include @@ -36,13 +5,13 @@ class PolygonRenderer { #include #include -PUBLIC STATIC int PolygonRenderer::FaceSortFunction(const void *a, const void *b) { +int PolygonRenderer::FaceSortFunction(const void *a, const void *b) { const FaceInfo* faceA = (const FaceInfo *)a; const FaceInfo* faceB = (const FaceInfo *)b; return faceB->Depth - faceA->Depth; } -PUBLIC void PolygonRenderer::BuildFrustumPlanes(float nearClippingPlane, float farClippingPlane) { +void PolygonRenderer::BuildFrustumPlanes(float nearClippingPlane, float farClippingPlane) { // Near ViewFrustum[0].Plane.Z = nearClippingPlane * 0x10000; ViewFrustum[0].Normal.Z = 0x10000; @@ -54,7 +23,7 @@ PUBLIC void PolygonRenderer::BuildFrustumPlanes(float nearClippingPlane, float f NumFrustumPlanes = 2; } -PUBLIC bool PolygonRenderer::SetBuffers() { +bool PolygonRenderer::SetBuffers() { VertexBuf = nullptr; ScenePtr = nullptr; ViewMatrix = nullptr; @@ -82,7 +51,7 @@ PUBLIC bool PolygonRenderer::SetBuffers() { return true; } -PUBLIC void PolygonRenderer::DrawPolygon3D(VertexAttribute* data, int vertexCount, int vertexFlag, Texture* texture) { +void PolygonRenderer::DrawPolygon3D(VertexAttribute* data, int vertexCount, int vertexFlag, Texture* texture) { VertexBuffer* vertexBuffer = VertexBuf; Uint32 colRGB = CurrentColor; @@ -167,7 +136,7 @@ PUBLIC void PolygonRenderer::DrawPolygon3D(VertexAttribute* data, int vertexCoun vertexBuffer->VertexCount += vertexCount; vertexBuffer->FaceCount++; } -PUBLIC void PolygonRenderer::DrawSceneLayer3D(SceneLayer* layer, int sx, int sy, int sw, int sh) { +void PolygonRenderer::DrawSceneLayer3D(SceneLayer* layer, int sx, int sy, int sw, int sh) { int vertexCountPerFace = 4; int tileWidth = Scene::TileWidth; int tileHeight = Scene::TileHeight; @@ -340,7 +309,7 @@ PUBLIC void PolygonRenderer::DrawSceneLayer3D(SceneLayer* layer, int sx, int sy, vertexBuffer->VertexCount = arrayVertexCount; vertexBuffer->FaceCount = arrayFaceCount; } -PUBLIC void PolygonRenderer::DrawModel(IModel* model, Uint16 animation, Uint32 frame) { +void PolygonRenderer::DrawModel(IModel* model, Uint16 animation, Uint32 frame) { if (animation < 0 || frame < 0) return; else if (model->AnimationCount > 0 && animation >= model->AnimationCount) @@ -360,7 +329,7 @@ PUBLIC void PolygonRenderer::DrawModel(IModel* model, Uint16 animation, Uint32 f rend.SetMatrices(ModelMatrix, ViewMatrix, ProjectionMatrix, NormalMatrix); rend.DrawModel(model, animation, frame); } -PUBLIC void PolygonRenderer::DrawModelSkinned(IModel* model, Uint16 armature) { +void PolygonRenderer::DrawModelSkinned(IModel* model, Uint16 armature) { if (model->UseVertexAnimation) { DrawModel(model, 0, 0); return; @@ -384,7 +353,7 @@ PUBLIC void PolygonRenderer::DrawModelSkinned(IModel* model, Uint16 armature) { rend.SetMatrices(ModelMatrix, ViewMatrix, ProjectionMatrix, NormalMatrix); rend.DrawModel(model, 0, 0); } -PUBLIC void PolygonRenderer::DrawVertexBuffer() { +void PolygonRenderer::DrawVertexBuffer() { Matrix4x4 mvpMatrix; if (DoProjection) Graphics::CalculateMVPMatrix(&mvpMatrix, ModelMatrix, ViewMatrix, ProjectionMatrix); @@ -473,7 +442,7 @@ PUBLIC void PolygonRenderer::DrawVertexBuffer() { destVertexBuffer->VertexCount = arrayVertexCount; destVertexBuffer->FaceCount = arrayFaceCount; } -PUBLIC int PolygonRenderer::ClipPolygon(PolygonClipBuffer& clipper, VertexAttribute* input, int numVertices) { +int PolygonRenderer::ClipPolygon(PolygonClipBuffer& clipper, VertexAttribute* input, int numVertices) { clipper.NumPoints = 0; clipper.MaxPoints = MAX_POLYGON_VERTICES; @@ -483,7 +452,7 @@ PUBLIC int PolygonRenderer::ClipPolygon(PolygonClipBuffer& clipper, VertexAttrib return numOutVertices; } -PUBLIC STATIC bool PolygonRenderer::CheckPolygonVisible(VertexAttribute* vertex, int vertexCount) { +bool PolygonRenderer::CheckPolygonVisible(VertexAttribute* vertex, int vertexCount) { int numBehind[3] = { 0, 0, 0 }; int numVertices = vertexCount; while (numVertices--) { @@ -502,7 +471,7 @@ PUBLIC STATIC bool PolygonRenderer::CheckPolygonVisible(VertexAttribute* vertex, return true; } -PUBLIC STATIC void PolygonRenderer::CopyVertices(VertexAttribute* buffer, VertexAttribute* output, int numVertices) { +void PolygonRenderer::CopyVertices(VertexAttribute* buffer, VertexAttribute* output, int numVertices) { while (numVertices--) { COPY_VECTOR(output->Position, buffer->Position); COPY_NORMAL(output->Normal, buffer->Normal); diff --git a/source/Engine/Rendering/SDL2/SDL2Renderer.cpp b/source/Engine/Rendering/SDL2/SDL2Renderer.cpp index 55262179..ded9034e 100644 --- a/source/Engine/Rendering/SDL2/SDL2Renderer.cpp +++ b/source/Engine/Rendering/SDL2/SDL2Renderer.cpp @@ -1,17 +1,3 @@ -#if INTERFACE -#include -#include -#include -#include -#include -#include - -class SDL2Renderer { -public: - static float RenderScale; -}; -#endif - #include #include @@ -48,7 +34,7 @@ void FindTextureID(Texture* texture) { } // Initialization and disposal functions -PUBLIC STATIC void SDL2Renderer::Init() { +void SDL2Renderer::Init() { Log::Print(Log::LOG_INFO, "Renderer: SDL2"); Uint32 flags = SDL_RENDERER_ACCELERATED; @@ -74,14 +60,14 @@ PUBLIC STATIC void SDL2Renderer::Init() { if (h > wh) RenderScale = h / wh; } -PUBLIC STATIC Uint32 SDL2Renderer::GetWindowFlags() { +Uint32 SDL2Renderer::GetWindowFlags() { return 0; } -PUBLIC STATIC void SDL2Renderer::SetVSync(bool enabled) { +void SDL2Renderer::SetVSync(bool enabled) { Graphics::VsyncEnabled = enabled; SDL_RenderSetVSync(Renderer, enabled); } -PUBLIC STATIC void SDL2Renderer::SetGraphicsFunctions() { +void SDL2Renderer::SetGraphicsFunctions() { Graphics::PixelOffset = 0.0f; Graphics::Internal.Init = SDL2Renderer::Init; @@ -142,12 +128,12 @@ PUBLIC STATIC void SDL2Renderer::SetGraphicsFunctions() { Graphics::Internal.MakeFrameBufferID = SDL2Renderer::MakeFrameBufferID; } -PUBLIC STATIC void SDL2Renderer::Dispose() { +void SDL2Renderer::Dispose() { SDL_DestroyRenderer(Renderer); } // Texture management functions -PUBLIC STATIC Texture* SDL2Renderer::CreateTexture(Uint32 format, Uint32 access, Uint32 width, Uint32 height) { +Texture* SDL2Renderer::CreateTexture(Uint32 format, Uint32 access, Uint32 width, Uint32 height) { Texture* texture = Texture::New(format, access, width, height); texture->DriverData = Memory::TrackedCalloc("Texture::DriverData", 1, sizeof(SDL_Texture*)); @@ -161,21 +147,21 @@ PUBLIC STATIC Texture* SDL2Renderer::CreateTexture(Uint32 format, Uint32 access, return texture; } -PUBLIC STATIC int SDL2Renderer::LockTexture(Texture* texture, void** pixels, int* pitch) { +int SDL2Renderer::LockTexture(Texture* texture, void** pixels, int* pitch) { return 0; } -PUBLIC STATIC int SDL2Renderer::UpdateTexture(Texture* texture, SDL_Rect* src, void* pixels, int pitch) { +int SDL2Renderer::UpdateTexture(Texture* texture, SDL_Rect* src, void* pixels, int pitch) { SDL_Texture* textureData = *(SDL_Texture**)texture->DriverData; return SDL_UpdateTexture(textureData, src, pixels, pitch); } -PUBLIC STATIC int SDL2Renderer::UpdateTextureYUV(Texture* texture, SDL_Rect* src, void* pixelsY, int pitchY, void* pixelsU, int pitchU, void* pixelsV, int pitchV) { +int SDL2Renderer::UpdateTextureYUV(Texture* texture, SDL_Rect* src, void* pixelsY, int pitchY, void* pixelsU, int pitchU, void* pixelsV, int pitchV) { // SDL_Texture* textureData = *(SDL_Texture**)texture->DriverData; return 0; } -PUBLIC STATIC void SDL2Renderer::UnlockTexture(Texture* texture) { +void SDL2Renderer::UnlockTexture(Texture* texture) { } -PUBLIC STATIC void SDL2Renderer::DisposeTexture(Texture* texture) { +void SDL2Renderer::DisposeTexture(Texture* texture) { SDL_Texture** textureData = (SDL_Texture**)texture->DriverData; if (!textureData) return; @@ -189,7 +175,7 @@ PUBLIC STATIC void SDL2Renderer::DisposeTexture(Texture* texture) { } // Viewport and view-related functions -PUBLIC STATIC void SDL2Renderer::SetRenderTarget(Texture* texture) { +void SDL2Renderer::SetRenderTarget(Texture* texture) { if (texture == NULL) { SDL_SetRenderTarget(Renderer, NULL); } @@ -197,7 +183,7 @@ PUBLIC STATIC void SDL2Renderer::SetRenderTarget(Texture* texture) { SDL_SetRenderTarget(Renderer, *(SDL_Texture**)texture->DriverData); } } -PUBLIC STATIC void SDL2Renderer::CopyScreen(void* pixels, int width, int height) { +void SDL2Renderer::CopyScreen(void* pixels, int width, int height) { Viewport* vp = &Graphics::CurrentViewport; SDL_Rect r = { @@ -209,10 +195,10 @@ PUBLIC STATIC void SDL2Renderer::CopyScreen(void* pixels, int width, int hei SDL_RenderReadPixels(Renderer, &r, Graphics::PreferredPixelFormat, pixels, width * SDL_BYTESPERPIXEL(Graphics::PreferredPixelFormat)); } -PUBLIC STATIC void SDL2Renderer::UpdateWindowSize(int width, int height) { +void SDL2Renderer::UpdateWindowSize(int width, int height) { SDL2Renderer::UpdateViewport(); } -PUBLIC STATIC void SDL2Renderer::UpdateViewport() { +void SDL2Renderer::UpdateViewport() { Viewport* vp = &Graphics::CurrentViewport; SDL_Rect r = { (int)(vp->X * RenderScale), @@ -224,7 +210,7 @@ PUBLIC STATIC void SDL2Renderer::UpdateViewport() { SDL2Renderer::UpdateProjectionMatrix(); } -PUBLIC STATIC void SDL2Renderer::UpdateClipRect() { +void SDL2Renderer::UpdateClipRect() { ClipArea clip = Graphics::CurrentClip; if (Graphics::CurrentClip.Enabled) { SDL_Rect r = { @@ -239,20 +225,20 @@ PUBLIC STATIC void SDL2Renderer::UpdateClipRect() { SDL_RenderSetClipRect(Renderer, NULL); } } -PUBLIC STATIC void SDL2Renderer::UpdateOrtho(float left, float top, float right, float bottom) { +void SDL2Renderer::UpdateOrtho(float left, float top, float right, float bottom) { } -PUBLIC STATIC void SDL2Renderer::UpdatePerspective(float fovy, float aspect, float nearv, float farv) { +void SDL2Renderer::UpdatePerspective(float fovy, float aspect, float nearv, float farv) { } -PUBLIC STATIC void SDL2Renderer::UpdateProjectionMatrix() { +void SDL2Renderer::UpdateProjectionMatrix() { } -PUBLIC STATIC void SDL2Renderer::MakePerspectiveMatrix(Matrix4x4* out, float fov, float near, float far, float aspect) { +void SDL2Renderer::MakePerspectiveMatrix(Matrix4x4* out, float fov, float near, float far, float aspect) { Matrix4x4::Perspective(out, fov, aspect, near, far); } -PUBLIC STATIC void SDL2Renderer::GetMetalSize(int* width, int* height) { +void SDL2Renderer::GetMetalSize(int* width, int* height) { // #ifdef IOS // SDL2MetalFunc_GetMetalSize(width, height, Renderer); // #endif @@ -260,21 +246,21 @@ PUBLIC STATIC void SDL2Renderer::GetMetalSize(int* width, int* height) { } // Shader-related functions -PUBLIC STATIC void SDL2Renderer::UseShader(void* shader) { +void SDL2Renderer::UseShader(void* shader) { } -PUBLIC STATIC void SDL2Renderer::SetUniformF(int location, int count, float* values) { +void SDL2Renderer::SetUniformF(int location, int count, float* values) { } -PUBLIC STATIC void SDL2Renderer::SetUniformI(int location, int count, int* values) { +void SDL2Renderer::SetUniformI(int location, int count, int* values) { } -PUBLIC STATIC void SDL2Renderer::SetUniformTexture(Texture* texture, int uniform_index, int slot) { +void SDL2Renderer::SetUniformTexture(Texture* texture, int uniform_index, int slot) { } // These guys -PUBLIC STATIC void SDL2Renderer::Clear() { +void SDL2Renderer::Clear() { SDL_RenderClear(Renderer); int w, h, ww, wh; @@ -285,15 +271,15 @@ PUBLIC STATIC void SDL2Renderer::Clear() { if (h > wh) RenderScale = h / wh; } -PUBLIC STATIC void SDL2Renderer::Present() { +void SDL2Renderer::Present() { SDL_RenderPresent(Renderer); } // Draw mode setting functions -PUBLIC STATIC void SDL2Renderer::SetBlendColor(float r, float g, float b, float a) { +void SDL2Renderer::SetBlendColor(float r, float g, float b, float a) { SDL_SetRenderDrawColor(Renderer, r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f); } -PRIVATE STATIC SDL_BlendMode SDL2Renderer::GetCustomBlendMode(int srcC, int dstC, int srcA, int dstA) { +SDL_BlendMode SDL2Renderer::GetCustomBlendMode(int srcC, int dstC, int srcA, int dstA) { SDL_BlendFactor blendFactorToSDL[] = { SDL_BLENDFACTOR_ZERO, SDL_BLENDFACTOR_ONE, @@ -312,7 +298,7 @@ PRIVATE STATIC SDL_BlendMode SDL2Renderer::GetCustomBlendMode(int srcC, int dstC blendFactorToSDL[srcA], blendFactorToSDL[srcA], SDL_BLENDOPERATION_ADD ); } -PUBLIC STATIC void SDL2Renderer::SetBlendMode(int srcC, int dstC, int srcA, int dstA) { +void SDL2Renderer::SetBlendMode(int srcC, int dstC, int srcA, int dstA) { SDL_BlendMode customBlendMode = GetCustomBlendMode(srcC, dstC, srcA, dstA); if (SDL_SetRenderDrawBlendMode(Renderer, customBlendMode) == 0) return; @@ -329,46 +315,46 @@ PUBLIC STATIC void SDL2Renderer::SetBlendMode(int srcC, int dstC, int srcA, SDL_SetRenderDrawBlendMode(Renderer, SDL_BLENDMODE_NONE); } } -PUBLIC STATIC void SDL2Renderer::SetTintColor(float r, float g, float b, float a) { +void SDL2Renderer::SetTintColor(float r, float g, float b, float a) { } -PUBLIC STATIC void SDL2Renderer::SetTintMode(int mode) { +void SDL2Renderer::SetTintMode(int mode) { } -PUBLIC STATIC void SDL2Renderer::SetTintEnabled(bool enabled) { +void SDL2Renderer::SetTintEnabled(bool enabled) { } -PUBLIC STATIC void SDL2Renderer::SetLineWidth(float n) { +void SDL2Renderer::SetLineWidth(float n) { } // Primitive drawing functions -PUBLIC STATIC void SDL2Renderer::StrokeLine(float x1, float y1, float x2, float y2) { +void SDL2Renderer::StrokeLine(float x1, float y1, float x2, float y2) { } -PUBLIC STATIC void SDL2Renderer::StrokeCircle(float x, float y, float rad, float thickness) { +void SDL2Renderer::StrokeCircle(float x, float y, float rad, float thickness) { } -PUBLIC STATIC void SDL2Renderer::StrokeEllipse(float x, float y, float w, float h) { +void SDL2Renderer::StrokeEllipse(float x, float y, float w, float h) { } -PUBLIC STATIC void SDL2Renderer::StrokeRectangle(float x, float y, float w, float h) { +void SDL2Renderer::StrokeRectangle(float x, float y, float w, float h) { } -PUBLIC STATIC void SDL2Renderer::FillCircle(float x, float y, float rad) { +void SDL2Renderer::FillCircle(float x, float y, float rad) { } -PUBLIC STATIC void SDL2Renderer::FillEllipse(float x, float y, float w, float h) { +void SDL2Renderer::FillEllipse(float x, float y, float w, float h) { } -PUBLIC STATIC void SDL2Renderer::FillTriangle(float x1, float y1, float x2, float y2, float x3, float y3) { +void SDL2Renderer::FillTriangle(float x1, float y1, float x2, float y2, float x3, float y3) { } -PUBLIC STATIC void SDL2Renderer::FillRectangle(float x, float y, float w, float h) { +void SDL2Renderer::FillRectangle(float x, float y, float w, float h) { } // Texture drawing functions -PUBLIC STATIC void SDL2Renderer::DrawTexture(Texture* texture, float sx, float sy, float sw, float sh, float x, float y, float w, float h) { +void SDL2Renderer::DrawTexture(Texture* texture, float sx, float sy, float sw, float sh, float x, float y, float w, float h) { x *= RenderScale; y *= RenderScale; w *= RenderScale; @@ -397,7 +383,7 @@ PUBLIC STATIC void SDL2Renderer::DrawTexture(Texture* texture, float sx, flo } SDL_RenderCopyEx(Renderer, *textureData, &src, &dst, 0.0, NULL, (SDL_RendererFlip)flip); } -PUBLIC STATIC void SDL2Renderer::DrawSprite(ISprite* sprite, int animation, int frame, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID) { +void SDL2Renderer::DrawSprite(ISprite* sprite, int animation, int frame, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID) { if (Graphics::SpriteRangeCheck(sprite, animation, frame)) return; AnimFrame animframe = sprite->Animations[animation].Frames[frame]; @@ -411,7 +397,7 @@ PUBLIC STATIC void SDL2Renderer::DrawSprite(ISprite* sprite, int animation, x + fX * animframe.OffsetX, y + fY * animframe.OffsetY, fX * sw, fY * sh); } -PUBLIC STATIC void SDL2Renderer::DrawSpritePart(ISprite* sprite, int animation, int frame, int sx, int sy, int sw, int sh, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID) { +void SDL2Renderer::DrawSpritePart(ISprite* sprite, int animation, int frame, int sx, int sy, int sw, int sh, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID) { if (Graphics::SpriteRangeCheck(sprite, animation, frame)) return; AnimFrame animframe = sprite->Animations[animation].Frames[frame]; @@ -434,6 +420,6 @@ PUBLIC STATIC void SDL2Renderer::DrawSpritePart(ISprite* sprite, int animati y + fY * (sy + animframe.OffsetY), fX * sw, fY * sh); } -PUBLIC STATIC void SDL2Renderer::MakeFrameBufferID(ISprite* sprite, AnimFrame* frame) { +void SDL2Renderer::MakeFrameBufferID(ISprite* sprite, AnimFrame* frame) { frame->ID = 0; } diff --git a/source/Engine/Rendering/Shader.cpp b/source/Engine/Rendering/Shader.cpp index 0dff11be..2e73bfb6 100644 --- a/source/Engine/Rendering/Shader.cpp +++ b/source/Engine/Rendering/Shader.cpp @@ -1,15 +1,7 @@ -#if INTERFACE -#include -class Shader { -public: - -}; -#endif - #include #include -PUBLIC STATIC Shader* Shader::New() { +Shader* Shader::New() { Shader* texture = (Shader*)Memory::TrackedCalloc("Shader::Shader", 1, sizeof(Shader)); return texture; } diff --git a/source/Engine/Rendering/Software/PolygonRasterizer.cpp b/source/Engine/Rendering/Software/PolygonRasterizer.cpp index 3169fc79..4c0a0b87 100644 --- a/source/Engine/Rendering/Software/PolygonRasterizer.cpp +++ b/source/Engine/Rendering/Software/PolygonRasterizer.cpp @@ -1,26 +1,3 @@ -#if INTERFACE -#include -#include -#include -#include - -class PolygonRasterizer { -public: - static bool DepthTest; - static size_t DepthBufferSize; - static Uint32* DepthBuffer; - - static bool UseDepthBuffer; - - static bool UseFog; - static float FogStart; - static float FogEnd; - static float FogDensity; - static int FogColor; - static Uint16 FogTable[0x100 + 1]; -}; -#endif - #include #include #include @@ -210,7 +187,7 @@ static void GetPolygonBounds(T* positions, int count, int& minVal, int& maxVal) return // Draws a polygon -PUBLIC STATIC void PolygonRasterizer::DrawBasic(Vector2* positions, Uint32 color, int count, BlendState blendState) { +void PolygonRasterizer::DrawBasic(Vector2* positions, Uint32 color, int count, BlendState blendState) { if (!Graphics::CurrentRenderTarget) return; @@ -277,7 +254,7 @@ PUBLIC STATIC void PolygonRasterizer::DrawBasic(Vector2* positions, Uint32 color } } // Draws a blended polygon -PUBLIC STATIC void PolygonRasterizer::DrawBasicBlend(Vector2* positions, int* colors, int count, BlendState blendState) { +void PolygonRasterizer::DrawBasicBlend(Vector2* positions, int* colors, int count, BlendState blendState) { if (!Graphics::CurrentRenderTarget) return; @@ -345,7 +322,7 @@ PUBLIC STATIC void PolygonRasterizer::DrawBasicBlend(Vector2* positions, int* co } } // Draws a polygon with lighting -PUBLIC STATIC void PolygonRasterizer::DrawShaded(Vector3* positions, Uint32 color, int count, BlendState blendState) { +void PolygonRasterizer::DrawShaded(Vector3* positions, Uint32 color, int count, BlendState blendState) { if (!Graphics::CurrentRenderTarget) return; @@ -443,7 +420,7 @@ PUBLIC STATIC void PolygonRasterizer::DrawShaded(Vector3* positions, Uint32 colo #undef DRAW_POLYGONSHADED_FOG } // Draws a blended polygon with lighting -PUBLIC STATIC void PolygonRasterizer::DrawBlendShaded(Vector3* positions, int* colors, int count, BlendState blendState) { +void PolygonRasterizer::DrawBlendShaded(Vector3* positions, int* colors, int count, BlendState blendState) { if (!Graphics::CurrentRenderTarget) return; @@ -536,7 +513,7 @@ PUBLIC STATIC void PolygonRasterizer::DrawBlendShaded(Vector3* positions, int* c #undef DRAW_POLYGONBLENDSHADED } // Draws an affine texture mapped polygon -PUBLIC STATIC void PolygonRasterizer::DrawAffine(Texture* texture, Vector3* positions, Vector2* uvs, Uint32 color, int count, BlendState blendState) { +void PolygonRasterizer::DrawAffine(Texture* texture, Vector3* positions, Vector2* uvs, Uint32 color, int count, BlendState blendState) { if (!Graphics::CurrentRenderTarget) return; @@ -672,7 +649,7 @@ PUBLIC STATIC void PolygonRasterizer::DrawAffine(Texture* texture, Vector3* posi #undef DRAW_POLYGONAFFINE } // Draws an affine texture mapped polygon with blending -PUBLIC STATIC void PolygonRasterizer::DrawBlendAffine(Texture* texture, Vector3* positions, Vector2* uvs, int* colors, int count, BlendState blendState) { +void PolygonRasterizer::DrawBlendAffine(Texture* texture, Vector3* positions, Vector2* uvs, int* colors, int count, BlendState blendState) { if (!Graphics::CurrentRenderTarget) return; @@ -890,7 +867,7 @@ PUBLIC STATIC void PolygonRasterizer::DrawBlendAffine(Texture* texture, Vector3* DRAW_PERSP_STEP(); \ } #endif -PUBLIC STATIC void PolygonRasterizer::DrawPerspective(Texture* texture, Vector3* positions, Vector2* uvs, Uint32 color, int count, BlendState blendState) { +void PolygonRasterizer::DrawPerspective(Texture* texture, Vector3* positions, Vector2* uvs, Uint32 color, int count, BlendState blendState) { if (!Graphics::CurrentRenderTarget) return; @@ -1012,7 +989,7 @@ PUBLIC STATIC void PolygonRasterizer::DrawPerspective(Texture* texture, Vector3* #undef DRAW_POLYGONPERSP } // Draws a perspective-correct texture mapped polygon with blending -PUBLIC STATIC void PolygonRasterizer::DrawBlendPerspective(Texture* texture, Vector3* positions, Vector2* uvs, int* colors, int count, BlendState blendState) { +void PolygonRasterizer::DrawBlendPerspective(Texture* texture, Vector3* positions, Vector2* uvs, int* colors, int count, BlendState blendState) { if (!Graphics::CurrentRenderTarget) return; @@ -1143,7 +1120,7 @@ PUBLIC STATIC void PolygonRasterizer::DrawBlendPerspective(Texture* texture, Vec #undef DRAW_POLYGONBLENDPERSP } // Draws a polygon with depth testing -PUBLIC STATIC void PolygonRasterizer::DrawDepth(Vector3* positions, Uint32 color, int count, BlendState blendState) { +void PolygonRasterizer::DrawDepth(Vector3* positions, Uint32 color, int count, BlendState blendState) { if (!Graphics::CurrentRenderTarget) return; @@ -1237,7 +1214,7 @@ PUBLIC STATIC void PolygonRasterizer::DrawDepth(Vector3* positions, Uint32 color #undef DRAW_POLYGONDEPTH } // Draws a blended polygon with depth testing -PUBLIC STATIC void PolygonRasterizer::DrawBlendDepth(Vector3* positions, int* colors, int count, BlendState blendState) { +void PolygonRasterizer::DrawBlendDepth(Vector3* positions, int* colors, int count, BlendState blendState) { if (!Graphics::CurrentRenderTarget) return; @@ -1340,7 +1317,7 @@ PUBLIC STATIC void PolygonRasterizer::DrawBlendDepth(Vector3* positions, int* co #undef DRAW_POLYGONBLENDDEPTH } -PUBLIC STATIC void PolygonRasterizer::SetDepthTest(bool enabled) { +void PolygonRasterizer::SetDepthTest(bool enabled) { DepthTest = enabled; if (!DepthTest) return; @@ -1353,19 +1330,19 @@ PUBLIC STATIC void PolygonRasterizer::SetDepthTest(bool enabled) { memset(DepthBuffer, 0xFF, dpSize * sizeof(*DepthBuffer)); } -PUBLIC STATIC void PolygonRasterizer::FreeDepthBuffer(void) { +void PolygonRasterizer::FreeDepthBuffer(void) { Memory::Free(DepthBuffer); DepthBuffer = NULL; } -PUBLIC STATIC void PolygonRasterizer::SetUseDepthBuffer(bool enabled) { +void PolygonRasterizer::SetUseDepthBuffer(bool enabled) { UseDepthBuffer = enabled; } -PUBLIC STATIC void PolygonRasterizer::SetUseFog(bool enabled) { +void PolygonRasterizer::SetUseFog(bool enabled) { UseFog = enabled; } -PUBLIC STATIC void PolygonRasterizer::SetFogEquation(FogEquation equation) { +void PolygonRasterizer::SetFogEquation(FogEquation equation) { switch (equation) { case FogEquation_Exp: FogEquationFunc = FogEquationFunc_Exp; @@ -1375,16 +1352,16 @@ PUBLIC STATIC void PolygonRasterizer::SetFogEquation(FogEquation equation) { break; } } -PUBLIC STATIC void PolygonRasterizer::SetFogStart(float start) { +void PolygonRasterizer::SetFogStart(float start) { FogStart = start; } -PUBLIC STATIC void PolygonRasterizer::SetFogEnd(float end) { +void PolygonRasterizer::SetFogEnd(float end) { FogEnd = end; } -PUBLIC STATIC void PolygonRasterizer::SetFogDensity(float density) { +void PolygonRasterizer::SetFogDensity(float density) { FogDensity = density; } -PUBLIC STATIC void PolygonRasterizer::SetFogColor(float r, float g, float b) { +void PolygonRasterizer::SetFogColor(float r, float g, float b) { Uint8 colorR = (Uint32)(r * 0xFF); Uint8 colorG = (Uint32)(g * 0xFF); Uint8 colorB = (Uint32)(b * 0xFF); @@ -1392,7 +1369,7 @@ PUBLIC STATIC void PolygonRasterizer::SetFogColor(float r, float g, float b) Graphics::ConvertFromARGBtoNative(&result, 1); FogColor = result; } -PUBLIC STATIC void PolygonRasterizer::SetFogSmoothness(float smoothness) { +void PolygonRasterizer::SetFogSmoothness(float smoothness) { float value = Math::Clamp(1.0f - smoothness, 0.0f, 1.0f); if (value <= 0.0) { for (size_t i = 0; i <= 0x100; i++) diff --git a/source/Engine/Rendering/Software/Scanline.cpp b/source/Engine/Rendering/Software/Scanline.cpp index 46546938..005d61ae 100644 --- a/source/Engine/Rendering/Software/Scanline.cpp +++ b/source/Engine/Rendering/Software/Scanline.cpp @@ -1,15 +1,3 @@ -#if INTERFACE -#include -#include -#include -#include - -class Scanline { -public: - -}; -#endif - #include #include #include @@ -38,7 +26,7 @@ class Scanline { y2 = (int)Graphics::CurrentRenderTarget->Height; \ } -PUBLIC STATIC void Scanline::Prepare(int y1, int y2) { +void Scanline::Prepare(int y1, int y2) { int scanLineCount = y2 - y1; Contour* contourPtr = &SoftwareRenderer::ContourBuffer[y1]; while (scanLineCount--) { @@ -49,7 +37,7 @@ PUBLIC STATIC void Scanline::Prepare(int y1, int y2) { } // Simple -PUBLIC STATIC void Scanline::Process(int x1, int y1, int x2, int y2) { +void Scanline::Process(int x1, int y1, int x2, int y2) { int xStart = x1 / 0x10000; int xEnd = x2 / 0x10000; int yStart = y1 / 0x10000; @@ -107,7 +95,7 @@ PUBLIC STATIC void Scanline::Process(int x1, int y1, int x2, int y2) { } // Blended -PUBLIC STATIC void Scanline::Process(int color1, int color2, int x1, int y1, int x2, int y2) { +void Scanline::Process(int color1, int color2, int x1, int y1, int x2, int y2) { int xStart = x1 / 0x10000; int xEnd = x2 / 0x10000; int yStart = y1 / 0x10000; @@ -209,7 +197,7 @@ PUBLIC STATIC void Scanline::Process(int color1, int color2, int x1, int y1, int } // With depth -PUBLIC STATIC void Scanline::ProcessDepth(int x1, int y1, int z1, int x2, int y2, int z2) { +void Scanline::ProcessDepth(int x1, int y1, int z1, int x2, int y2, int z2) { int xStart = x1 / 0x10000; int xEnd = x2 / 0x10000; int yStart = y1 / 0x10000; @@ -291,7 +279,7 @@ PUBLIC STATIC void Scanline::ProcessDepth(int x1, int y1, int z1, int x2, int y2 } // With depth and blending -PUBLIC STATIC void Scanline::ProcessDepth(int color1, int color2, int x1, int y1, int z1, int x2, int y2, int z2) { +void Scanline::ProcessDepth(int color1, int color2, int x1, int y1, int z1, int x2, int y2, int z2) { int xStart = x1 / 0x10000; int xEnd = x2 / 0x10000; int yStart = y1 / 0x10000; @@ -408,7 +396,7 @@ PUBLIC STATIC void Scanline::ProcessDepth(int color1, int color2, int x1, int y1 } // Textured affine -PUBLIC STATIC void Scanline::ProcessUVAffine(Vector2 uv1, Vector2 uv2, int x1, int y1, int z1, int x2, int y2, int z2) { +void Scanline::ProcessUVAffine(Vector2 uv1, Vector2 uv2, int x1, int y1, int z1, int x2, int y2, int z2) { int xStart = x1 / 0x10000; int xEnd = x2 / 0x10000; int yStart = y1 / 0x10000; @@ -516,7 +504,7 @@ PUBLIC STATIC void Scanline::ProcessUVAffine(Vector2 uv1, Vector2 uv2, int x1, i } // Textured affine with blending -PUBLIC STATIC void Scanline::ProcessUVAffine(int color1, int color2, Vector2 uv1, Vector2 uv2, int x1, int y1, int z1, int x2, int y2, int z2) { +void Scanline::ProcessUVAffine(int color1, int color2, Vector2 uv1, Vector2 uv2, int x1, int y1, int z1, int x2, int y2, int z2) { int xStart = x1 / 0x10000; int xEnd = x2 / 0x10000; int yStart = y1 / 0x10000; @@ -662,7 +650,7 @@ PUBLIC STATIC void Scanline::ProcessUVAffine(int color1, int color2, Vector2 uv1 } // Perspective correct -PUBLIC STATIC void Scanline::ProcessUV(Vector2 uv1, Vector2 uv2, int x1, int y1, int z1, int x2, int y2, int z2) { +void Scanline::ProcessUV(Vector2 uv1, Vector2 uv2, int x1, int y1, int z1, int x2, int y2, int z2) { int xStart = x1 / 0x10000; int xEnd = x2 / 0x10000; int yStart = y1 / 0x10000; @@ -776,7 +764,7 @@ PUBLIC STATIC void Scanline::ProcessUV(Vector2 uv1, Vector2 uv2, int x1, int y1, } // Perspective correct with blending -PUBLIC STATIC void Scanline::ProcessUV(int color1, int color2, Vector2 uv1, Vector2 uv2, int x1, int y1, int z1, int x2, int y2, int z2) { +void Scanline::ProcessUV(int color1, int color2, Vector2 uv1, Vector2 uv2, int x1, int y1, int z1, int x2, int y2, int z2) { int xStart = x1 / 0x10000; int xEnd = x2 / 0x10000; int yStart = y1 / 0x10000; diff --git a/source/Engine/Rendering/Software/SoftwareRenderer.cpp b/source/Engine/Rendering/Software/SoftwareRenderer.cpp index af3e3908..60ee9c8b 100644 --- a/source/Engine/Rendering/Software/SoftwareRenderer.cpp +++ b/source/Engine/Rendering/Software/SoftwareRenderer.cpp @@ -1,31 +1,3 @@ -#if INTERFACE -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class SoftwareRenderer { -public: - static GraphicsFunctions BackendFunctions; - static Uint32 CompareColor; - static TileScanLine TileScanLineBuffer[MAX_FRAMEBUFFER_HEIGHT]; - static Sint32 SpriteDeformBuffer[MAX_FRAMEBUFFER_HEIGHT]; - static bool UseSpriteDeform; - static Contour ContourBuffer[MAX_FRAMEBUFFER_HEIGHT]; - static int MultTable[0x10000]; - static int MultTableInv[0x10000]; - static int MultSubTable[0x10000]; -}; -#endif - #include #include #include @@ -112,7 +84,7 @@ int FilterInvert[0x8000]; int FilterBlackAndWhite[0x8000]; // Initialization and disposal functions -PUBLIC STATIC void SoftwareRenderer::Init() { +void SoftwareRenderer::Init() { SoftwareRenderer::BackendFunctions.Init(); UseStencil = false; @@ -122,10 +94,10 @@ PUBLIC STATIC void SoftwareRenderer::Init() { SetDotMaskOffsetH(0); SetDotMaskOffsetV(0); } -PUBLIC STATIC Uint32 SoftwareRenderer::GetWindowFlags() { +Uint32 SoftwareRenderer::GetWindowFlags() { return Graphics::Internal.GetWindowFlags(); } -PUBLIC STATIC void SoftwareRenderer::SetGraphicsFunctions() { +void SoftwareRenderer::SetGraphicsFunctions() { for (int alpha = 0; alpha < 0x100; alpha++) { for (int color = 0; color < 0x100; color++) { MultTable[alpha << 8 | color] = (alpha * color) >> 8; @@ -231,64 +203,64 @@ PUBLIC STATIC void SoftwareRenderer::SetGraphicsFunctions() { SoftwareRenderer::BackendFunctions.MakeFrameBufferID = SoftwareRenderer::MakeFrameBufferID; } -PUBLIC STATIC void SoftwareRenderer::Dispose() { +void SoftwareRenderer::Dispose() { } -PUBLIC STATIC void SoftwareRenderer::RenderStart() { +void SoftwareRenderer::RenderStart() { for (int i = 0; i < MAX_PALETTE_COUNT; i++) Graphics::PaletteColors[i][0] &= 0xFFFFFF; } -PUBLIC STATIC void SoftwareRenderer::RenderEnd() { +void SoftwareRenderer::RenderEnd() { } // Texture management functions -PUBLIC STATIC Texture* SoftwareRenderer::CreateTexture(Uint32 format, Uint32 access, Uint32 width, Uint32 height) { +Texture* SoftwareRenderer::CreateTexture(Uint32 format, Uint32 access, Uint32 width, Uint32 height) { Texture* texture = NULL; // Texture::New(format, access, width, height); return texture; } -PUBLIC STATIC int SoftwareRenderer::LockTexture(Texture* texture, void** pixels, int* pitch) { +int SoftwareRenderer::LockTexture(Texture* texture, void** pixels, int* pitch) { return 0; } -PUBLIC STATIC int SoftwareRenderer::UpdateTexture(Texture* texture, SDL_Rect* src, void* pixels, int pitch) { +int SoftwareRenderer::UpdateTexture(Texture* texture, SDL_Rect* src, void* pixels, int pitch) { return 0; } -PUBLIC STATIC void SoftwareRenderer::UnlockTexture(Texture* texture) { +void SoftwareRenderer::UnlockTexture(Texture* texture) { } -PUBLIC STATIC void SoftwareRenderer::DisposeTexture(Texture* texture) { +void SoftwareRenderer::DisposeTexture(Texture* texture) { } // Viewport and view-related functions -PUBLIC STATIC void SoftwareRenderer::SetRenderTarget(Texture* texture) { +void SoftwareRenderer::SetRenderTarget(Texture* texture) { } -PUBLIC STATIC void SoftwareRenderer::ReadFramebuffer(void* pixels, int width, int height) { +void SoftwareRenderer::ReadFramebuffer(void* pixels, int width, int height) { if (Graphics::Internal.ReadFramebuffer) Graphics::Internal.ReadFramebuffer(pixels, width, height); } -PUBLIC STATIC void SoftwareRenderer::UpdateWindowSize(int width, int height) { +void SoftwareRenderer::UpdateWindowSize(int width, int height) { Graphics::Internal.UpdateWindowSize(width, height); } -PUBLIC STATIC void SoftwareRenderer::UpdateViewport() { +void SoftwareRenderer::UpdateViewport() { Graphics::Internal.UpdateViewport(); } -PUBLIC STATIC void SoftwareRenderer::UpdateClipRect() { +void SoftwareRenderer::UpdateClipRect() { Graphics::Internal.UpdateClipRect(); } -PUBLIC STATIC void SoftwareRenderer::UpdateOrtho(float left, float top, float right, float bottom) { +void SoftwareRenderer::UpdateOrtho(float left, float top, float right, float bottom) { Graphics::Internal.UpdateOrtho(left, top, right, bottom); } -PUBLIC STATIC void SoftwareRenderer::UpdatePerspective(float fovy, float aspect, float nearv, float farv) { +void SoftwareRenderer::UpdatePerspective(float fovy, float aspect, float nearv, float farv) { Graphics::Internal.UpdatePerspective(fovy, aspect, nearv, farv); } -PUBLIC STATIC void SoftwareRenderer::UpdateProjectionMatrix() { +void SoftwareRenderer::UpdateProjectionMatrix() { Graphics::Internal.UpdateProjectionMatrix(); } -PUBLIC STATIC void SoftwareRenderer::MakePerspectiveMatrix(Matrix4x4* out, float fov, float near, float far, float aspect) { +void SoftwareRenderer::MakePerspectiveMatrix(Matrix4x4* out, float fov, float near, float far, float aspect) { float f = 1.0f / tanf(fov / 2.0f); float diff = near - far; @@ -343,7 +315,7 @@ bool CheckClipRegion(int clip_x1, int clip_y1, int clip_x2, int clip_y2) { } // Shader-related functions -PUBLIC STATIC void SoftwareRenderer::UseShader(void* shader) { +void SoftwareRenderer::UseShader(void* shader) { if (!shader) { CurrentBlendState.FilterTable = nullptr; return; @@ -367,17 +339,17 @@ PUBLIC STATIC void SoftwareRenderer::UseShader(void* shader) { } CurrentBlendState.FilterTable = &FilterCurrent[0]; } -PUBLIC STATIC void SoftwareRenderer::SetUniformF(int location, int count, float* values) { +void SoftwareRenderer::SetUniformF(int location, int count, float* values) { } -PUBLIC STATIC void SoftwareRenderer::SetUniformI(int location, int count, int* values) { +void SoftwareRenderer::SetUniformI(int location, int count, int* values) { } -PUBLIC STATIC void SoftwareRenderer::SetUniformTexture(Texture* texture, int uniform_index, int slot) { +void SoftwareRenderer::SetUniformTexture(Texture* texture, int uniform_index, int slot) { } -PUBLIC STATIC void SoftwareRenderer::SetFilter(int filter) { +void SoftwareRenderer::SetFilter(int filter) { switch (filter) { case Filter_NONE: CurrentBlendState.FilterTable = nullptr; @@ -392,12 +364,12 @@ PUBLIC STATIC void SoftwareRenderer::SetFilter(int filter) { } // These guys -PUBLIC STATIC void SoftwareRenderer::Clear() { +void SoftwareRenderer::Clear() { Uint32* dstPx = (Uint32*)Graphics::CurrentRenderTarget->Pixels; Uint32 dstStride = Graphics::CurrentRenderTarget->Width; memset(dstPx, 0, dstStride * Graphics::CurrentRenderTarget->Height * 4); } -PUBLIC STATIC void SoftwareRenderer::Present() { +void SoftwareRenderer::Present() { } @@ -405,14 +377,14 @@ PUBLIC STATIC void SoftwareRenderer::Present() { #define GET_R(color) ((color >> 16) & 0xFF) #define GET_G(color) ((color >> 8) & 0xFF) #define GET_B(color) ((color) & 0xFF) -PRIVATE STATIC void SoftwareRenderer::SetColor(Uint32 color) { +void SoftwareRenderer::SetColor(Uint32 color) { ColRGB = color; ColR = GET_R(color); ColG = GET_G(color); ColB = GET_B(color); Graphics::ConvertFromARGBtoNative(&ColRGB, 1); } -PUBLIC STATIC void SoftwareRenderer::SetBlendColor(float r, float g, float b, float a) { +void SoftwareRenderer::SetBlendColor(float r, float g, float b, float a) { ColR = (Uint8)(r * 0xFF); ColG = (Uint8)(g * 0xFF); ColB = (Uint8)(b * 0xFF); @@ -423,10 +395,10 @@ PUBLIC STATIC void SoftwareRenderer::SetBlendColor(float r, float g, float b CLAMP_VAL(opacity, 0x00, 0xFF); CurrentBlendState.Opacity = opacity; } -PUBLIC STATIC void SoftwareRenderer::SetBlendMode(int srcC, int dstC, int srcA, int dstA) { +void SoftwareRenderer::SetBlendMode(int srcC, int dstC, int srcA, int dstA) { CurrentBlendState.Mode = Graphics::BlendMode; } -PUBLIC STATIC void SoftwareRenderer::SetTintColor(float r, float g, float b, float a) { +void SoftwareRenderer::SetTintColor(float r, float g, float b, float a) { int red = (int)(r * 0xFF); int green = (int)(g * 0xFF); int blue = (int)(b * 0xFF); @@ -442,45 +414,45 @@ PUBLIC STATIC void SoftwareRenderer::SetTintColor(float r, float g, float b, Graphics::ConvertFromARGBtoNative(&CurrentBlendState.Tint.Color, 1); } -PUBLIC STATIC void SoftwareRenderer::SetTintMode(int mode) { +void SoftwareRenderer::SetTintMode(int mode) { CurrentBlendState.Tint.Mode = mode; } -PUBLIC STATIC void SoftwareRenderer::SetTintEnabled(bool enabled) { +void SoftwareRenderer::SetTintEnabled(bool enabled) { CurrentBlendState.Tint.Enabled = enabled; } -PUBLIC STATIC void SoftwareRenderer::Resize(int width, int height) { +void SoftwareRenderer::Resize(int width, int height) { } -PUBLIC STATIC void SoftwareRenderer::SetClip(float x, float y, float width, float height) { +void SoftwareRenderer::SetClip(float x, float y, float width, float height) { } -PUBLIC STATIC void SoftwareRenderer::ClearClip() { +void SoftwareRenderer::ClearClip() { } -PUBLIC STATIC void SoftwareRenderer::Save() { +void SoftwareRenderer::Save() { } -PUBLIC STATIC void SoftwareRenderer::Translate(float x, float y, float z) { +void SoftwareRenderer::Translate(float x, float y, float z) { } -PUBLIC STATIC void SoftwareRenderer::Rotate(float x, float y, float z) { +void SoftwareRenderer::Rotate(float x, float y, float z) { } -PUBLIC STATIC void SoftwareRenderer::Scale(float x, float y, float z) { +void SoftwareRenderer::Scale(float x, float y, float z) { } -PUBLIC STATIC void SoftwareRenderer::Restore() { +void SoftwareRenderer::Restore() { } -PRIVATE STATIC Uint32 SoftwareRenderer::GetBlendColor() { +Uint32 SoftwareRenderer::GetBlendColor() { return ColorUtils::ToRGB(ColR, ColG, ColB); } -PUBLIC STATIC int SoftwareRenderer::ConvertBlendMode(int blendMode) { +int SoftwareRenderer::ConvertBlendMode(int blendMode) { switch (blendMode) { case BlendMode_NORMAL: return BlendFlag_TRANSPARENT; @@ -495,10 +467,10 @@ PUBLIC STATIC int SoftwareRenderer::ConvertBlendMode(int blendMode) { } return BlendFlag_OPAQUE; } -PUBLIC STATIC BlendState SoftwareRenderer::GetBlendState() { +BlendState SoftwareRenderer::GetBlendState() { return CurrentBlendState; } -PUBLIC STATIC bool SoftwareRenderer::AlterBlendState(BlendState& state) { +bool SoftwareRenderer::AlterBlendState(BlendState& state) { int blendMode = ConvertBlendMode(state.Mode); int opacity = state.Opacity; @@ -528,17 +500,17 @@ PUBLIC STATIC bool SoftwareRenderer::AlterBlendState(BlendState& state) { #define ISOLATE_G(color) (color & 0x00FF00) #define ISOLATE_B(color) (color & 0x0000FF) -PUBLIC STATIC void SoftwareRenderer::PixelNoFiltSetOpaque(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { +void SoftwareRenderer::PixelNoFiltSetOpaque(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { *dst = *src; } -PUBLIC STATIC void SoftwareRenderer::PixelNoFiltSetTransparent(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { +void SoftwareRenderer::PixelNoFiltSetTransparent(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { int* multInvTableAt = &MultTableInv[state.Opacity << 8]; *dst = 0xFF000000U | (multTableAt[GET_R(*src)] + multInvTableAt[GET_R(*dst)]) << 16 | (multTableAt[GET_G(*src)] + multInvTableAt[GET_G(*dst)]) << 8 | (multTableAt[GET_B(*src)] + multInvTableAt[GET_B(*dst)]); } -PUBLIC STATIC void SoftwareRenderer::PixelNoFiltSetAdditive(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { +void SoftwareRenderer::PixelNoFiltSetAdditive(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { Uint32 R = (multTableAt[GET_R(*src)] << 16) + ISOLATE_R(*dst); Uint32 G = (multTableAt[GET_G(*src)] << 8) + ISOLATE_G(*dst); Uint32 B = (multTableAt[GET_B(*src)]) + ISOLATE_B(*dst); @@ -547,7 +519,7 @@ PUBLIC STATIC void SoftwareRenderer::PixelNoFiltSetAdditive(Uint32* src, Uint32* if (B > 0x0000FF) B = 0x0000FF; *dst = 0xFF000000U | R | G | B; } -PUBLIC STATIC void SoftwareRenderer::PixelNoFiltSetSubtract(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { +void SoftwareRenderer::PixelNoFiltSetSubtract(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { Sint32 R = (multSubTableAt[GET_R(*src)] << 16) + ISOLATE_R(*dst); Sint32 G = (multSubTableAt[GET_G(*src)] << 8) + ISOLATE_G(*dst); Sint32 B = (multSubTableAt[GET_B(*src)]) + ISOLATE_B(*dst); @@ -556,11 +528,11 @@ PUBLIC STATIC void SoftwareRenderer::PixelNoFiltSetSubtract(Uint32* src, Uint32* if (B < 0) B = 0; *dst = 0xFF000000U | R | G | B; } -PUBLIC STATIC void SoftwareRenderer::PixelNoFiltSetMatchEqual(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { +void SoftwareRenderer::PixelNoFiltSetMatchEqual(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { if ((*dst & 0xFCFCFC) == (SoftwareRenderer::CompareColor & 0xFCFCFC)) *dst = *src; } -PUBLIC STATIC void SoftwareRenderer::PixelNoFiltSetMatchNotEqual(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { +void SoftwareRenderer::PixelNoFiltSetMatchNotEqual(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { if ((*dst & 0xFCFCFC) != (SoftwareRenderer::CompareColor & 0xFCFCFC)) *dst = *src; } @@ -575,26 +547,26 @@ static PixelFunction PixelNoFiltFunctions[] = { }; // Tinted versions -PUBLIC STATIC void SoftwareRenderer::PixelTintSetOpaque(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { +void SoftwareRenderer::PixelTintSetOpaque(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { *dst = 0xFF000000 | CurrentTintFunction(src, dst, state.Tint.Color, state.Tint.Amount); } -PUBLIC STATIC void SoftwareRenderer::PixelTintSetTransparent(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { +void SoftwareRenderer::PixelTintSetTransparent(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { Uint32 col = 0xFF000000 | CurrentTintFunction(src, dst, state.Tint.Color, state.Tint.Amount); PixelNoFiltSetTransparent(&col, dst, state, multTableAt, multSubTableAt); } -PUBLIC STATIC void SoftwareRenderer::PixelTintSetAdditive(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { +void SoftwareRenderer::PixelTintSetAdditive(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { Uint32 col = 0xFF000000 | CurrentTintFunction(src, dst, state.Tint.Color, state.Tint.Amount); PixelNoFiltSetAdditive(&col, dst, state, multTableAt, multSubTableAt); } -PUBLIC STATIC void SoftwareRenderer::PixelTintSetSubtract(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { +void SoftwareRenderer::PixelTintSetSubtract(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { Uint32 col = 0xFF000000 | CurrentTintFunction(src, dst, state.Tint.Color, state.Tint.Amount); PixelNoFiltSetSubtract(&col, dst, state, multTableAt, multSubTableAt); } -PUBLIC STATIC void SoftwareRenderer::PixelTintSetMatchEqual(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { +void SoftwareRenderer::PixelTintSetMatchEqual(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { if ((*dst & 0xFCFCFC) == (SoftwareRenderer::CompareColor & 0xFCFCFC)) *dst = 0xFF000000 | CurrentTintFunction(src, dst, state.Tint.Color, state.Tint.Amount); } -PUBLIC STATIC void SoftwareRenderer::PixelTintSetMatchNotEqual(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { +void SoftwareRenderer::PixelTintSetMatchNotEqual(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { if ((*dst & 0xFCFCFC) != (SoftwareRenderer::CompareColor & 0xFCFCFC)) *dst = 0xFF000000 | CurrentTintFunction(src, dst, state.Tint.Color, state.Tint.Amount); } @@ -629,7 +601,7 @@ static Uint32 TintFilterDest(Uint32* src, Uint32* dst, Uint32 tintColor, Uint32 return CurrentBlendState.FilterTable[GET_FILTER_COLOR(*dst)]; } -PUBLIC STATIC void SoftwareRenderer::SetTintFunction(int blendFlags) { +void SoftwareRenderer::SetTintFunction(int blendFlags) { TintFunction tintFunctions[] = { TintNormalSource, TintNormalDest, @@ -727,16 +699,16 @@ StencilTestFunction StencilFuncTest = StencilTestAlways; StencilOpFunction StencilFuncPass = StencilOpKeep; StencilOpFunction StencilFuncFail = StencilOpKeep; -PUBLIC STATIC void SoftwareRenderer::SetStencilEnabled(bool enabled) { +void SoftwareRenderer::SetStencilEnabled(bool enabled) { if (Scene::ViewCurrent >= 0) { UseStencil = enabled; Scene::Views[Scene::ViewCurrent].SetStencilEnabled(enabled); } } -PUBLIC STATIC bool SoftwareRenderer::IsStencilEnabled() { +bool SoftwareRenderer::IsStencilEnabled() { return UseStencil; } -PUBLIC STATIC void SoftwareRenderer::SetStencilTestFunc(int stencilTest) { +void SoftwareRenderer::SetStencilTestFunc(int stencilTest) { StencilTestFunction funcList[] = { StencilTestNever, StencilTestAlways, @@ -751,26 +723,26 @@ PUBLIC STATIC void SoftwareRenderer::SetStencilTestFunc(int stencilTest) { if (stencilTest >= StencilTest_Never && stencilTest <= StencilTest_GEqual) StencilFuncTest = funcList[stencilTest]; } -PUBLIC STATIC void SoftwareRenderer::SetStencilPassFunc(int stencilOp) { +void SoftwareRenderer::SetStencilPassFunc(int stencilOp) { if (stencilOp >= StencilOp_Keep && stencilOp <= StencilOp_DecrWrap) StencilFuncPass = StencilOpFunctionList[stencilOp]; } -PUBLIC STATIC void SoftwareRenderer::SetStencilFailFunc(int stencilOp) { +void SoftwareRenderer::SetStencilFailFunc(int stencilOp) { if (stencilOp >= StencilOp_Keep && stencilOp <= StencilOp_DecrWrap) StencilFuncFail = StencilOpFunctionList[stencilOp]; } -PUBLIC STATIC void SoftwareRenderer::SetStencilValue(int value) { +void SoftwareRenderer::SetStencilValue(int value) { StencilValue = value; } -PUBLIC STATIC void SoftwareRenderer::SetStencilMask(int mask) { +void SoftwareRenderer::SetStencilMask(int mask) { StencilMask = mask; } -PUBLIC STATIC void SoftwareRenderer::ClearStencil() { +void SoftwareRenderer::ClearStencil() { if (UseStencil && Graphics::CurrentView) Graphics::CurrentView->ClearStencil(); } -PUBLIC STATIC void SoftwareRenderer::PixelStencil(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { +void SoftwareRenderer::PixelStencil(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { size_t pos = dst - (Uint32*)Graphics::CurrentRenderTarget->Pixels; View* currentView = Graphics::CurrentView; @@ -783,11 +755,11 @@ PUBLIC STATIC void SoftwareRenderer::PixelStencil(Uint32* src, Uint32* dst, Blen StencilFuncFail(buffer, StencilValue); } -PUBLIC STATIC void SoftwareRenderer::SetDotMask(int mask) { +void SoftwareRenderer::SetDotMask(int mask) { SetDotMaskH(mask); SetDotMaskV(mask); } -PUBLIC STATIC void SoftwareRenderer::SetDotMaskH(int mask) { +void SoftwareRenderer::SetDotMaskH(int mask) { if (mask < 0) mask = 0; else if (mask > 255) @@ -795,7 +767,7 @@ PUBLIC STATIC void SoftwareRenderer::SetDotMaskH(int mask) { DotMaskH = mask; } -PUBLIC STATIC void SoftwareRenderer::SetDotMaskV(int mask) { +void SoftwareRenderer::SetDotMaskV(int mask) { if (mask < 0) mask = 0; else if (mask > 255) @@ -803,14 +775,14 @@ PUBLIC STATIC void SoftwareRenderer::SetDotMaskV(int mask) { DotMaskV = mask; } -PUBLIC STATIC void SoftwareRenderer::SetDotMaskOffsetH(int offset) { +void SoftwareRenderer::SetDotMaskOffsetH(int offset) { DotMaskOffsetH = offset; } -PUBLIC STATIC void SoftwareRenderer::SetDotMaskOffsetV(int offset) { +void SoftwareRenderer::SetDotMaskOffsetV(int offset) { DotMaskOffsetV = offset; } -PUBLIC STATIC void SoftwareRenderer::PixelDotMaskH(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { +void SoftwareRenderer::PixelDotMaskH(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { size_t pos = dst - (Uint32*)Graphics::CurrentRenderTarget->Pixels; int x = (pos % Graphics::CurrentRenderTarget->Width) + DotMaskOffsetH; @@ -822,7 +794,7 @@ PUBLIC STATIC void SoftwareRenderer::PixelDotMaskH(Uint32* src, Uint32* dst, Ble else CurrentPixelFunction(src, dst, state, multTableAt, multSubTableAt); } -PUBLIC STATIC void SoftwareRenderer::PixelDotMaskV(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { +void SoftwareRenderer::PixelDotMaskV(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { size_t pos = dst - (Uint32*)Graphics::CurrentRenderTarget->Pixels; int y = (pos / Graphics::CurrentRenderTarget->Width) + DotMaskOffsetV; @@ -834,7 +806,7 @@ PUBLIC STATIC void SoftwareRenderer::PixelDotMaskV(Uint32* src, Uint32* dst, Ble else CurrentPixelFunction(src, dst, state, multTableAt, multSubTableAt); } -PUBLIC STATIC void SoftwareRenderer::PixelDotMaskHV(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { +void SoftwareRenderer::PixelDotMaskHV(Uint32* src, Uint32* dst, BlendState& state, int* multTableAt, int* multSubTableAt) { size_t pos = dst - (Uint32*)Graphics::CurrentRenderTarget->Pixels; int x = (pos % Graphics::CurrentRenderTarget->Width) + DotMaskOffsetH; @@ -914,13 +886,13 @@ static int CalcVertexColor(Scene3D* scene, VertexAttribute *vertex, int normalY) } // Drawing 3D -PUBLIC STATIC void SoftwareRenderer::BindVertexBuffer(Uint32 vertexBufferIndex) { +void SoftwareRenderer::BindVertexBuffer(Uint32 vertexBufferIndex) { } -PUBLIC STATIC void SoftwareRenderer::UnbindVertexBuffer() { +void SoftwareRenderer::UnbindVertexBuffer() { } -PUBLIC STATIC void SoftwareRenderer::BindScene3D(Uint32 sceneIndex) { +void SoftwareRenderer::BindScene3D(Uint32 sceneIndex) { if (sceneIndex < 0 || sceneIndex >= MAX_3D_SCENES) return; @@ -932,7 +904,7 @@ PUBLIC STATIC void SoftwareRenderer::BindScene3D(Uint32 sceneIndex) { else polygonRenderer.ClipPolygonsByFrustum = false; } -PUBLIC STATIC void SoftwareRenderer::DrawScene3D(Uint32 sceneIndex, Uint32 drawMode) { +void SoftwareRenderer::DrawScene3D(Uint32 sceneIndex, Uint32 drawMode) { if (sceneIndex < 0 || sceneIndex >= MAX_3D_SCENES) return; @@ -1373,7 +1345,7 @@ PUBLIC STATIC void SoftwareRenderer::DrawScene3D(Uint32 sceneIndex, Uint32 d #undef ORTHO_Y } -PRIVATE STATIC bool SoftwareRenderer::SetupPolygonRenderer(Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +bool SoftwareRenderer::SetupPolygonRenderer(Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { if (!polygonRenderer.SetBuffers()) return false; @@ -1387,23 +1359,23 @@ PRIVATE STATIC bool SoftwareRenderer::SetupPolygonRenderer(Matrix4x4* modelM return true; } -PUBLIC STATIC void SoftwareRenderer::DrawPolygon3D(void* data, int vertexCount, int vertexFlag, Texture* texture, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +void SoftwareRenderer::DrawPolygon3D(void* data, int vertexCount, int vertexFlag, Texture* texture, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { if (SetupPolygonRenderer(modelMatrix, normalMatrix)) polygonRenderer.DrawPolygon3D((VertexAttribute*)data, vertexCount, vertexFlag, texture); } -PUBLIC STATIC void SoftwareRenderer::DrawSceneLayer3D(void* layer, int sx, int sy, int sw, int sh, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +void SoftwareRenderer::DrawSceneLayer3D(void* layer, int sx, int sy, int sw, int sh, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { if (SetupPolygonRenderer(modelMatrix, normalMatrix)) polygonRenderer.DrawSceneLayer3D((SceneLayer*)layer, sx, sy, sw, sh); } -PUBLIC STATIC void SoftwareRenderer::DrawModel(void* model, Uint16 animation, Uint32 frame, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +void SoftwareRenderer::DrawModel(void* model, Uint16 animation, Uint32 frame, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { if (SetupPolygonRenderer(modelMatrix, normalMatrix)) polygonRenderer.DrawModel((IModel*)model, animation, frame); } -PUBLIC STATIC void SoftwareRenderer::DrawModelSkinned(void* model, Uint16 armature, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +void SoftwareRenderer::DrawModelSkinned(void* model, Uint16 armature, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { if (SetupPolygonRenderer(modelMatrix, normalMatrix)) polygonRenderer.DrawModelSkinned((IModel*)model, armature); } -PUBLIC STATIC void SoftwareRenderer::DrawVertexBuffer(Uint32 vertexBufferIndex, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { +void SoftwareRenderer::DrawVertexBuffer(Uint32 vertexBufferIndex, Matrix4x4* modelMatrix, Matrix4x4* normalMatrix) { if (Graphics::CurrentScene3D < 0 || vertexBufferIndex < 0 || vertexBufferIndex >= MAX_VERTEX_BUFFERS) return; @@ -1429,7 +1401,7 @@ PUBLIC STATIC void SoftwareRenderer::DrawVertexBuffer(Uint32 vertexBufferInd rend.DrawVertexBuffer(); } -PUBLIC STATIC PixelFunction SoftwareRenderer::GetPixelFunction(int blendFlag) { +PixelFunction SoftwareRenderer::GetPixelFunction(int blendFlag) { if (blendFlag & BlendFlag_TINT_BIT) CurrentPixelFunction = PixelTintFunctions[blendFlag & BlendFlag_MODE_MASK]; else @@ -1495,10 +1467,10 @@ static void DoLineStrokeBounded(int dst_x1, int dst_y1, int dst_x2, int dst_y2, } } -PUBLIC STATIC void SoftwareRenderer::SetLineWidth(float n) { +void SoftwareRenderer::SetLineWidth(float n) { } -PUBLIC STATIC void SoftwareRenderer::StrokeLine(float x1, float y1, float x2, float y2) { +void SoftwareRenderer::StrokeLine(float x1, float y1, float x2, float y2) { int x = 0, y = 0; Uint32* dstPx = (Uint32*)Graphics::CurrentRenderTarget->Pixels; Uint32 dstStride = Graphics::CurrentRenderTarget->Width; @@ -1543,7 +1515,7 @@ PUBLIC STATIC void SoftwareRenderer::StrokeLine(float x1, float y1, float x2 DoLineStrokeBounded(dst_x1, dst_y1, dst_x2, dst_y2, minX, maxX, minY, maxY, pixelFunction, ColRGB, blendState, multTableAt, multSubTableAt, dstPx, dstStride); } -PUBLIC STATIC void SoftwareRenderer::StrokeCircle(float x, float y, float rad, float thickness) { +void SoftwareRenderer::StrokeCircle(float x, float y, float rad, float thickness) { Uint32* dstPx = (Uint32*)Graphics::CurrentRenderTarget->Pixels; Uint32 dstStride = Graphics::CurrentRenderTarget->Width; @@ -1636,7 +1608,7 @@ PUBLIC STATIC void SoftwareRenderer::StrokeCircle(float x, float y, float ra #undef DRAW_POINT } -PRIVATE STATIC void SoftwareRenderer::InitContour(Contour *contourBuffer, int dst_y1, int scanLineCount) { +void SoftwareRenderer::InitContour(Contour *contourBuffer, int dst_y1, int scanLineCount) { Contour* contourPtr = &contourBuffer[dst_y1]; while (scanLineCount--) { contourPtr->MinX = 0x7FFFFFFF; @@ -1644,7 +1616,7 @@ PRIVATE STATIC void SoftwareRenderer::InitContour(Contour *contourBuffer, in contourPtr++; } } -PRIVATE STATIC void SoftwareRenderer::RasterizeCircle(int ccx, int ccy, int dst_x1, int dst_y1, int dst_x2, int dst_y2, float rad, Contour *contourBuffer) { +void SoftwareRenderer::RasterizeCircle(int ccx, int ccy, int dst_x1, int dst_y1, int dst_x2, int dst_y2, float rad, Contour *contourBuffer) { #define SEEK_MIN(our_x, our_y) if (our_y >= dst_y1 && our_y < dst_y2 && our_x < (cont = &contourBuffer[our_y])->MinX) \ cont->MinX = our_x < dst_x1 ? dst_x1 : our_x > (dst_x2 - 1) ? dst_x2 - 1 : our_x; #define SEEK_MAX(our_x, our_y) if (our_y >= dst_y1 && our_y < dst_y2 && our_x > (cont = &contourBuffer[our_y])->MaxX) \ @@ -1677,7 +1649,7 @@ PRIVATE STATIC void SoftwareRenderer::RasterizeCircle(int ccx, int ccy, int #undef SEEK_MIN #undef SEEK_MAX } -PRIVATE STATIC void SoftwareRenderer::StrokeThickCircle(float x, float y, float rad, float thickness) { +void SoftwareRenderer::StrokeThickCircle(float x, float y, float rad, float thickness) { Uint32* dstPx = (Uint32*)Graphics::CurrentRenderTarget->Pixels; Uint32 dstStride = Graphics::CurrentRenderTarget->Width; @@ -1828,10 +1800,10 @@ PRIVATE STATIC void SoftwareRenderer::StrokeThickCircle(float x, float y, fl } } } -PUBLIC STATIC void SoftwareRenderer::StrokeEllipse(float x, float y, float w, float h) { +void SoftwareRenderer::StrokeEllipse(float x, float y, float w, float h) { } -PUBLIC STATIC void SoftwareRenderer::StrokeRectangle(float x, float y, float w, float h) { +void SoftwareRenderer::StrokeRectangle(float x, float y, float w, float h) { Uint32* dstPx = (Uint32*)Graphics::CurrentRenderTarget->Pixels; Uint32 dstStride = Graphics::CurrentRenderTarget->Width; @@ -1899,7 +1871,7 @@ PUBLIC STATIC void SoftwareRenderer::StrokeRectangle(float x, float y, float DoLineStroke(dst_x2 - 1, dst_y1 + 1, dst_x2 - 1, dst_y2 - 1, pixelFunction, col, blendState, multTableAt, multSubTableAt, dstPx, dstStride); } -PUBLIC STATIC void SoftwareRenderer::FillCircle(float x, float y, float rad) { +void SoftwareRenderer::FillCircle(float x, float y, float rad) { // just checks to see if the pixel is within a radius range, uses a bounding box constructed by the diameter Uint32* dstPx = (Uint32*)Graphics::CurrentRenderTarget->Pixels; @@ -2002,10 +1974,10 @@ PUBLIC STATIC void SoftwareRenderer::FillCircle(float x, float y, float rad) #undef SEEK_MIN #undef SEEK_MAX } -PUBLIC STATIC void SoftwareRenderer::FillEllipse(float x, float y, float w, float h) { +void SoftwareRenderer::FillEllipse(float x, float y, float w, float h) { } -PUBLIC STATIC void SoftwareRenderer::FillRectangle(float x, float y, float w, float h) { +void SoftwareRenderer::FillRectangle(float x, float y, float w, float h) { Uint32* dstPx = (Uint32*)Graphics::CurrentRenderTarget->Pixels; Uint32 dstStride = Graphics::CurrentRenderTarget->Width; @@ -2076,7 +2048,7 @@ PUBLIC STATIC void SoftwareRenderer::FillRectangle(float x, float y, float w } } } -PUBLIC STATIC void SoftwareRenderer::FillTriangle(float x1, float y1, float x2, float y2, float x3, float y3) { +void SoftwareRenderer::FillTriangle(float x1, float y1, float x2, float y2, float x3, float y3) { View* currentView = Graphics::CurrentView; if (!currentView) return; @@ -2102,7 +2074,7 @@ PUBLIC STATIC void SoftwareRenderer::FillTriangle(float x1, float y1, float vectors[2].X = ((int)x3 + x) << 16; vectors[2].Y = ((int)y3 + y) << 16; PolygonRasterizer::DrawBasic(vectors, ColRGB, 3, blendState); } -PUBLIC STATIC void SoftwareRenderer::FillTriangleBlend(float x1, float y1, float x2, float y2, float x3, float y3, int c1, int c2, int c3) { +void SoftwareRenderer::FillTriangleBlend(float x1, float y1, float x2, float y2, float x3, float y3, int c1, int c2, int c3) { View* currentView = Graphics::CurrentView; if (!currentView) return; @@ -2129,7 +2101,7 @@ PUBLIC STATIC void SoftwareRenderer::FillTriangleBlend(float x1, float y1, f vectors[2].X = ((int)x3 + x) << 16; vectors[2].Y = ((int)y3 + y) << 16; colors[2] = ColorUtils::Multiply(c3, GetBlendColor()); PolygonRasterizer::DrawBasicBlend(vectors, colors, 3, blendState); } -PUBLIC STATIC void SoftwareRenderer::FillQuad(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { +void SoftwareRenderer::FillQuad(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { View* currentView = Graphics::CurrentView; if (!currentView) return; @@ -2156,7 +2128,7 @@ PUBLIC STATIC void SoftwareRenderer::FillQuad(float x1, float y1, float x2, vectors[3].X = ((int)x4 + x) << 16; vectors[3].Y = ((int)y4 + y) << 16; PolygonRasterizer::DrawBasic(vectors, ColRGB, 4, blendState); } -PUBLIC STATIC void SoftwareRenderer::FillQuadBlend(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, int c1, int c2, int c3, int c4) { +void SoftwareRenderer::FillQuadBlend(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, int c1, int c2, int c3, int c4) { View* currentView = Graphics::CurrentView; if (!currentView) return; @@ -2184,7 +2156,7 @@ PUBLIC STATIC void SoftwareRenderer::FillQuadBlend(float x1, float y1, float vectors[3].X = ((int)x4 + x) << 16; vectors[3].Y = ((int)y4 + y) << 16; colors[3] = ColorUtils::Multiply(c4, GetBlendColor()); PolygonRasterizer::DrawBasicBlend(vectors, colors, 4, blendState); } -PRIVATE STATIC void SoftwareRenderer::DrawShapeTextured(Texture* texturePtr, unsigned numPoints, float* px, float* py, int* pc, float* pu, float* pv) { +void SoftwareRenderer::DrawShapeTextured(Texture* texturePtr, unsigned numPoints, float* px, float* py, int* pc, float* pu, float* pv) { View* currentView = Graphics::CurrentView; if (!currentView) return; @@ -2222,7 +2194,7 @@ PRIVATE STATIC void SoftwareRenderer::DrawShapeTextured(Texture* texturePtr, PolygonRasterizer::DrawBlendPerspective(texturePtr, vectors, uv, colors, numPoints, blendState); } -PUBLIC STATIC void SoftwareRenderer::DrawTriangleTextured(Texture* texturePtr, float x1, float y1, float x2, float y2, float x3, float y3, int c1, int c2, int c3, float u1, float v1, float u2, float v2, float u3, float v3) { +void SoftwareRenderer::DrawTriangleTextured(Texture* texturePtr, float x1, float y1, float x2, float y2, float x3, float y3, int c1, int c2, int c3, float u1, float v1, float u2, float v2, float u3, float v3) { float px[3]; float py[3]; float pu[3]; @@ -2249,7 +2221,7 @@ PUBLIC STATIC void SoftwareRenderer::DrawTriangleTextured(Texture* texturePt DrawShapeTextured(texturePtr, 3, px, py, pc, pu, pv); } -PUBLIC STATIC void SoftwareRenderer::DrawQuadTextured(Texture* texturePtr, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, int c1, int c2, int c3, int c4, float u1, float v1, float u2, float v2, float u3, float v3, float u4, float v4) { +void SoftwareRenderer::DrawQuadTextured(Texture* texturePtr, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, int c1, int c2, int c3, int c4, float u1, float v1, float u2, float v2, float u3, float v3, float u4, float v4) { float px[4]; float py[4]; float pu[4]; @@ -2820,7 +2792,7 @@ void DrawSpriteImageTransformed(Texture* texture, int x, int y, int offx, int of #undef DRAW_FLIPXY } -PUBLIC STATIC void SoftwareRenderer::DrawTexture(Texture* texture, float sx, float sy, float sw, float sh, float x, float y, float w, float h) { +void SoftwareRenderer::DrawTexture(Texture* texture, float sx, float sy, float sw, float sh, float x, float y, float w, float h) { View* currentView = Graphics::CurrentView; if (!currentView) return; @@ -2848,7 +2820,7 @@ PUBLIC STATIC void SoftwareRenderer::DrawTexture(Texture* texture, float sx, else DrawSpriteImage(texture, x, y, sw, sh, sx, sy, 0, 0, blendState); } -PUBLIC STATIC void SoftwareRenderer::DrawSprite(ISprite* sprite, int animation, int frame, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID) { +void SoftwareRenderer::DrawSprite(ISprite* sprite, int animation, int frame, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID) { if (Graphics::SpriteRangeCheck(sprite, animation, frame)) return; View* currentView = Graphics::CurrentView; @@ -2909,7 +2881,7 @@ PUBLIC STATIC void SoftwareRenderer::DrawSprite(ISprite* sprite, int animati break; } } -PUBLIC STATIC void SoftwareRenderer::DrawSpritePart(ISprite* sprite, int animation, int frame, int sx, int sy, int sw, int sh, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID) { +void SoftwareRenderer::DrawSpritePart(ISprite* sprite, int animation, int frame, int sx, int sy, int sw, int sh, int x, int y, bool flipX, bool flipY, float scaleW, float scaleH, float rotation, unsigned paletteID) { if (Graphics::SpriteRangeCheck(sprite, animation, frame)) return; View* currentView = Graphics::CurrentView; @@ -2977,10 +2949,10 @@ PUBLIC STATIC void SoftwareRenderer::DrawSpritePart(ISprite* sprite, int ani } // Default Tile Display Line setup -PUBLIC STATIC void SoftwareRenderer::DrawTile(int tile, int x, int y, bool flipX, bool flipY) { +void SoftwareRenderer::DrawTile(int tile, int x, int y, bool flipX, bool flipY) { } -PUBLIC STATIC void SoftwareRenderer::DrawSceneLayer_InitTileScanLines(SceneLayer* layer, View* currentView) { +void SoftwareRenderer::DrawSceneLayer_InitTileScanLines(SceneLayer* layer, View* currentView) { switch (layer->DrawBehavior) { case DrawBehavior_PGZ1_BG: case DrawBehavior_HorizontalParallax: { @@ -3107,7 +3079,7 @@ PUBLIC STATIC void SoftwareRenderer::DrawSceneLayer_InitTileScanLines(SceneL } } -PUBLIC STATIC void SoftwareRenderer::DrawSceneLayer_HorizontalParallax(SceneLayer* layer, View* currentView) { +void SoftwareRenderer::DrawSceneLayer_HorizontalParallax(SceneLayer* layer, View* currentView) { int dst_x1 = 0; int dst_y1 = 0; int dst_x2 = (int)Graphics::CurrentRenderTarget->Width; @@ -3578,10 +3550,10 @@ PUBLIC STATIC void SoftwareRenderer::DrawSceneLayer_HorizontalParallax(Scene } } } -PUBLIC STATIC void SoftwareRenderer::DrawSceneLayer_VerticalParallax(SceneLayer* layer, View* currentView) { +void SoftwareRenderer::DrawSceneLayer_VerticalParallax(SceneLayer* layer, View* currentView) { } -PUBLIC STATIC void SoftwareRenderer::DrawSceneLayer_CustomTileScanLines(SceneLayer* layer, View* currentView) { +void SoftwareRenderer::DrawSceneLayer_CustomTileScanLines(SceneLayer* layer, View* currentView) { int dst_x1 = 0; int dst_y1 = 0; int dst_x2 = (int)Graphics::CurrentRenderTarget->Width; @@ -3736,7 +3708,7 @@ PUBLIC STATIC void SoftwareRenderer::DrawSceneLayer_CustomTileScanLines(Scen dst_strideY += dstStride; } } -PUBLIC STATIC void SoftwareRenderer::DrawSceneLayer(SceneLayer* layer, View* currentView, int layerIndex, bool useCustomFunction) { +void SoftwareRenderer::DrawSceneLayer(SceneLayer* layer, View* currentView, int layerIndex, bool useCustomFunction) { if (layer->UsingCustomRenderFunction && useCustomFunction) { Graphics::RunCustomSceneLayerFunction(&layer->CustomRenderFunction, layerIndex); return; @@ -3763,6 +3735,6 @@ PUBLIC STATIC void SoftwareRenderer::DrawSceneLayer(SceneLayer* layer, View* } } -PUBLIC STATIC void SoftwareRenderer::MakeFrameBufferID(ISprite* sprite, AnimFrame* frame) { +void SoftwareRenderer::MakeFrameBufferID(ISprite* sprite, AnimFrame* frame) { frame->ID = 0; } diff --git a/source/Engine/Rendering/Texture.cpp b/source/Engine/Rendering/Texture.cpp index 5e4df7f2..f161262b 100644 --- a/source/Engine/Rendering/Texture.cpp +++ b/source/Engine/Rendering/Texture.cpp @@ -1,36 +1,9 @@ -#if INTERFACE -#include - -need_t Texture; - -class Texture { -public: - Uint32 Format; - Uint32 Access; - Uint32 Width; - Uint32 Height; - - void* Pixels; - int Pitch; - - Uint32 ID; - void* DriverData; - - Texture* Prev; - Texture* Next; - - bool Paletted; - Uint32* PaletteColors; - unsigned NumPaletteColors; -}; -#endif - #include #include #include #include -PUBLIC STATIC Texture* Texture::New(Uint32 format, Uint32 access, Uint32 width, Uint32 height) { +Texture* Texture::New(Uint32 format, Uint32 access, Uint32 width, Uint32 height) { Texture* texture = (Texture*)Memory::TrackedCalloc("Texture::Texture", 1, sizeof(Texture)); texture->Format = format; texture->Access = access; @@ -40,7 +13,7 @@ PUBLIC STATIC Texture* Texture::New(Uint32 format, Uint32 access, Uint32 width, return texture; } -PUBLIC void Texture::SetPalette(Uint32* palette, unsigned numPaletteColors) { +void Texture::SetPalette(Uint32* palette, unsigned numPaletteColors) { Memory::Free(PaletteColors); if (palette && numPaletteColors) { @@ -55,7 +28,7 @@ PUBLIC void Texture::SetPalette(Uint32* palette, unsigned numPaletteC } } -PUBLIC bool Texture::ConvertToRGBA() { + bool Texture::ConvertToRGBA() { if (!Paletted) return false; @@ -70,7 +43,7 @@ PUBLIC bool Texture::ConvertToRGBA() { return true; } -PUBLIC bool Texture::ConvertToPalette(Uint32 *palColors, unsigned numPaletteColors) { + bool Texture::ConvertToPalette(Uint32 *palColors, unsigned numPaletteColors) { ConvertToRGBA(); Uint32 *pixels = (Uint32*)Pixels; @@ -101,7 +74,7 @@ PUBLIC bool Texture::ConvertToPalette(Uint32 *palColors, unsigned numPa return true; } -PUBLIC void Texture::Copy(Texture* source) { +void Texture::Copy(Texture* source) { if (!Pixels || !source || !source->Pixels) return; @@ -117,7 +90,7 @@ PUBLIC void Texture::Copy(Texture* source) { } } -PUBLIC void Texture::Dispose() { +void Texture::Dispose() { Memory::Free(PaletteColors); Memory::Free(Pixels); diff --git a/source/Engine/Rendering/TextureReference.cpp b/source/Engine/Rendering/TextureReference.cpp index 745e0477..d12bea0e 100644 --- a/source/Engine/Rendering/TextureReference.cpp +++ b/source/Engine/Rendering/TextureReference.cpp @@ -1,29 +1,16 @@ -#if INTERFACE -#include - -need_t Texture; - -class TextureReference { -public: - Texture* TexturePtr; - - unsigned References; -}; -#endif - #include -PUBLIC TextureReference::TextureReference(Texture *ptr) { +TextureReference::TextureReference(Texture *ptr) { TexturePtr = ptr; References = 0; AddRef(); } -PUBLIC void TextureReference::AddRef() { +void TextureReference::AddRef() { References++; } -PUBLIC bool TextureReference::TakeRef() { +bool TextureReference::TakeRef() { if (References == 0) abort(); diff --git a/source/Engine/Rendering/VertexBuffer.cpp b/source/Engine/Rendering/VertexBuffer.cpp index 2b3bf5db..f39db1da 100644 --- a/source/Engine/Rendering/VertexBuffer.cpp +++ b/source/Engine/Rendering/VertexBuffer.cpp @@ -1,45 +1,28 @@ -#if INTERFACE -#include -#include -#include - -class VertexBuffer { -public: - VertexAttribute* Vertices = nullptr; // count = max vertex count - FaceInfo* FaceInfoBuffer = nullptr; // count = max face count - void* DriverData = nullptr; - Uint32 Capacity = 0; - Uint32 VertexCount = 0; - Uint32 FaceCount = 0; - Uint32 UnloadPolicy; -}; -#endif - #include #include -PUBLIC VertexBuffer::VertexBuffer() { +VertexBuffer::VertexBuffer() { } -PUBLIC VertexBuffer::VertexBuffer(Uint32 numVertices) { +VertexBuffer::VertexBuffer(Uint32 numVertices) { Init(numVertices); Clear(); } -PUBLIC void VertexBuffer::Init(Uint32 numVertices) { +void VertexBuffer::Init(Uint32 numVertices) { if (!numVertices) numVertices = 192; if (Capacity != numVertices) Resize(numVertices); } -PUBLIC void VertexBuffer::Clear() { +void VertexBuffer::Clear() { VertexCount = 0; FaceCount = 0; // Not sure why we do this memset(Vertices, 0x00, Capacity * sizeof(VertexAttribute)); } -PUBLIC void VertexBuffer::Resize(Uint32 numVertices) { +void VertexBuffer::Resize(Uint32 numVertices) { if (!numVertices) numVertices = 192; @@ -47,7 +30,7 @@ PUBLIC void VertexBuffer::Resize(Uint32 numVertices) { Vertices = (VertexAttribute*)Memory::Realloc(Vertices, numVertices * sizeof(VertexAttribute)); FaceInfoBuffer = (FaceInfo*)Memory::Realloc(FaceInfoBuffer, ((numVertices / 3) + 1) * sizeof(FaceInfo)); } -PUBLIC VertexBuffer::~VertexBuffer() { +VertexBuffer::~VertexBuffer() { Memory::Free(Vertices); Memory::Free(FaceInfoBuffer); } diff --git a/source/Engine/Rendering/ViewTexture.cpp b/source/Engine/Rendering/ViewTexture.cpp index 2e0bd4b6..aac65b1c 100644 --- a/source/Engine/Rendering/ViewTexture.cpp +++ b/source/Engine/Rendering/ViewTexture.cpp @@ -1,23 +1,13 @@ -#if INTERFACE -#include -#include - -class ViewTexture : public GameTexture { -public: - int ViewIndex; -}; -#endif - #include #include -PUBLIC ViewTexture::ViewTexture(int viewIndex) { +ViewTexture::ViewTexture(int viewIndex) { ViewIndex = viewIndex; UnloadPolicy = SCOPE_GAME; OwnsTexture = false; } -PUBLIC VIRTUAL Texture* ViewTexture::GetTexture() { +Texture* ViewTexture::GetTexture() { if (ViewIndex < 0 || ViewIndex >= MAX_SCENE_VIEWS) return nullptr; @@ -27,7 +17,7 @@ PUBLIC VIRTUAL Texture* ViewTexture::GetTexture() { return nullptr; } -PUBLIC VIRTUAL int ViewTexture::GetID() { +int ViewTexture::GetID() { // Using negative IDs makes sure they don't collide with other textures return -(ViewIndex + 1); } diff --git a/source/Engine/ResourceTypes/IModel.cpp b/source/Engine/ResourceTypes/IModel.cpp index e5790989..50bff03b 100644 --- a/source/Engine/ResourceTypes/IModel.cpp +++ b/source/Engine/ResourceTypes/IModel.cpp @@ -1,37 +1,3 @@ -#if INTERFACE -#include -#include -#include -#include -#include -#include - -class IModel { -public: - Mesh** Meshes; - size_t MeshCount; - - size_t VertexCount; - size_t VertexIndexCount; - - Uint8 VertexPerFace; - - Material** Materials; - size_t MaterialCount; - - ModelAnim** Animations; - size_t AnimationCount; - - Armature** ArmatureList; - size_t ArmatureCount; - - bool UseVertexAnimation; - - Armature* BaseArmature; - Matrix4x4* GlobalInverseMatrix; -}; -#endif - #include #include #include @@ -47,7 +13,7 @@ class IModel { #include #include -PUBLIC IModel::IModel() { +IModel::IModel() { VertexCount = 0; Meshes = nullptr; @@ -69,7 +35,7 @@ PUBLIC IModel::IModel() { GlobalInverseMatrix = nullptr; UseVertexAnimation = false; } -PUBLIC IModel::IModel(const char* filename) { +IModel::IModel(const char* filename) { ResourceStream* resourceStream = ResourceStream::New(filename); if (!resourceStream) return; @@ -77,7 +43,7 @@ PUBLIC IModel::IModel(const char* filename) { if (resourceStream) resourceStream->Close(); } -PUBLIC bool IModel::Load(Stream* stream, const char* filename) { +bool IModel::Load(Stream* stream, const char* filename) { if (!stream) return false; if (!filename) return false; @@ -104,11 +70,11 @@ PUBLIC bool IModel::Load(Stream* stream, const char* filename) { return false; } -PUBLIC bool IModel::HasMaterials() { +bool IModel::HasMaterials() { return MaterialCount > 0; } -PRIVATE STATIC Image* IModel::TryLoadMaterialImage(std::string imagePath, const char *parentDirectory) { +Image* IModel::TryLoadMaterialImage(std::string imagePath, const char *parentDirectory) { std::string filename = imagePath; if (parentDirectory) { @@ -130,7 +96,7 @@ PRIVATE STATIC Image* IModel::TryLoadMaterialImage(std::string imagePath, const return nullptr; } -PUBLIC STATIC Image* IModel::LoadMaterialImage(string imagePath, const char *parentDirectory) { +Image* IModel::LoadMaterialImage(string imagePath, const char *parentDirectory) { // Try possible combinations Image* image = nullptr; @@ -148,18 +114,18 @@ PUBLIC STATIC Image* IModel::LoadMaterialImage(string imagePath, const char *par return nullptr; } -PUBLIC STATIC Image* IModel::LoadMaterialImage(const char *imagePath, const char *parentDirectory) { +Image* IModel::LoadMaterialImage(const char *imagePath, const char *parentDirectory) { return LoadMaterialImage(std::string(imagePath), parentDirectory); } -PUBLIC bool IModel::HasBones() { +bool IModel::HasBones() { if (BaseArmature == nullptr) return false; return BaseArmature->NumSkeletons > 0; } -PUBLIC void IModel::AnimateNode(ModelNode* node, SkeletalAnim* animation, Uint32 frame, Matrix4x4* parentMatrix) { +void IModel::AnimateNode(ModelNode* node, SkeletalAnim* animation, Uint32 frame, Matrix4x4* parentMatrix) { NodeAnim* nodeAnim = animation->NodeLookup->Get(node->Name); if (nodeAnim) UpdateChannel(node->LocalTransform, nodeAnim, frame); @@ -170,11 +136,11 @@ PUBLIC void IModel::AnimateNode(ModelNode* node, SkeletalAnim* animation, Uint32 AnimateNode(node->Children[i], animation, frame, node->GlobalTransform); } -PUBLIC void IModel::Pose() { +void IModel::Pose() { BaseArmature->RootNode->Transform(); } -PUBLIC void IModel::Pose(Armature* armature, SkeletalAnim* animation, Uint32 frame) { +void IModel::Pose(Armature* armature, SkeletalAnim* animation, Uint32 frame) { Matrix4x4 identity; Matrix4x4::Identity(&identity); @@ -268,11 +234,11 @@ static Vector4 InterpolateQuaternions(Vector4 q1, Vector4 q2, Sint64 t) { return result; } -PUBLIC Uint32 IModel::GetKeyFrame(Uint32 frame) { +Uint32 IModel::GetKeyFrame(Uint32 frame) { return (frame >> 8) & 0xFFFFFF; } -PUBLIC Sint64 IModel::GetInBetween(Uint32 frame) { +Sint64 IModel::GetInBetween(Uint32 frame) { float interp = (float)(frame & 0xFF) / 0xFF; Sint64 inbetween = (Sint64)(interp * 0x10000); @@ -284,7 +250,7 @@ PUBLIC Sint64 IModel::GetInBetween(Uint32 frame) { return inbetween; } -PUBLIC void IModel::DoVertexFrameInterpolation(Mesh* mesh, ModelAnim* animation, Uint32 frame, Vector3** positionBuffer, Vector3** normalBuffer, Vector2** uvBuffer) { +void IModel::DoVertexFrameInterpolation(Mesh* mesh, ModelAnim* animation, Uint32 frame, Vector3** positionBuffer, Vector3** normalBuffer, Vector2** uvBuffer) { Uint32 startFrame = 0; Uint32 animLength; @@ -339,7 +305,7 @@ PUBLIC void IModel::DoVertexFrameInterpolation(Mesh* mesh, ModelAnim* animation, } } -PRIVATE void IModel::UpdateChannel(Matrix4x4* out, NodeAnim* channel, Uint32 frame) { +void IModel::UpdateChannel(Matrix4x4* out, NodeAnim* channel, Uint32 frame) { Uint32 keyframe = GetKeyFrame(frame); Sint64 inbetween = GetInBetween(frame); @@ -376,7 +342,7 @@ PRIVATE void IModel::UpdateChannel(Matrix4x4* out, NodeAnim* channel, Uint32 fra } } -PUBLIC void IModel::Animate(Armature* armature, ModelAnim* animation, Uint32 frame) { +void IModel::Animate(Armature* armature, ModelAnim* animation, Uint32 frame) { if (animation->Skeletal == nullptr) return; @@ -388,7 +354,7 @@ PUBLIC void IModel::Animate(Armature* armature, ModelAnim* animation, Uint32 fra armature->UpdateSkeletons(); } -PUBLIC void IModel::Animate(Uint16 animation, Uint32 frame) { +void IModel::Animate(Uint16 animation, Uint32 frame) { if (AnimationCount > 0) { if (animation >= AnimationCount) animation = AnimationCount - 1; @@ -397,7 +363,7 @@ PUBLIC void IModel::Animate(Uint16 animation, Uint32 frame) { } } -PUBLIC int IModel::GetAnimationIndex(const char* animationName) { +int IModel::GetAnimationIndex(const char* animationName) { if (!AnimationCount) return -1; @@ -408,7 +374,7 @@ PUBLIC int IModel::GetAnimationIndex(const char* animationName) { return -1; } -PUBLIC int IModel::NewArmature() { +int IModel::NewArmature() { if (UseVertexAnimation) return -1; @@ -439,7 +405,7 @@ PUBLIC int IModel::NewArmature() { return ArmatureCount - 1; } -PUBLIC void IModel::DeleteArmature(size_t index) { +void IModel::DeleteArmature(size_t index) { if (ArmatureList == nullptr) return; @@ -447,7 +413,7 @@ PUBLIC void IModel::DeleteArmature(size_t index) { ArmatureList[index] = nullptr; } -PUBLIC void IModel::Dispose() { +void IModel::Dispose() { for (size_t i = 0; i < MeshCount; i++) delete Meshes[i]; delete[] Meshes; @@ -483,6 +449,6 @@ PUBLIC void IModel::Dispose() { GlobalInverseMatrix = nullptr; } -PUBLIC IModel::~IModel() { +IModel::~IModel() { Dispose(); } diff --git a/source/Engine/ResourceTypes/ISound.cpp b/source/Engine/ResourceTypes/ISound.cpp index 7a8f6189..23274161 100644 --- a/source/Engine/ResourceTypes/ISound.cpp +++ b/source/Engine/ResourceTypes/ISound.cpp @@ -1,24 +1,3 @@ -#if INTERFACE -#include -#include -#include - -#include -#include - -class ISound { -public: - SDL_AudioSpec Format; - int BytesPerSample; - - SoundFormat* SoundData = NULL; - - char Filename[256]; - bool LoadFailed = false; - bool StreamFromFile = false; -}; -#endif - #include #include #include @@ -29,14 +8,14 @@ class ISound { #include #include -PUBLIC ISound::ISound(const char* filename) { +ISound::ISound(const char* filename) { ISound::Load(filename, true); } -PUBLIC ISound::ISound(const char* filename, bool streamFromFile) { +ISound::ISound(const char* filename, bool streamFromFile) { ISound::Load(filename, streamFromFile); } -PUBLIC void ISound::Load(const char* filename, bool streamFromFile) { +void ISound::Load(const char* filename, bool streamFromFile) { LoadFailed = true; StreamFromFile = streamFromFile; strcpy(Filename, filename); @@ -87,7 +66,7 @@ PUBLIC void ISound::Load(const char* filename, bool streamFromFile) { LoadFailed = false; } -PUBLIC AudioPlayback* ISound::CreatePlayer() { +AudioPlayback* ISound::CreatePlayer() { int requiredSamples = AudioManager::DeviceFormat.samples * AUDIO_FIRST_LOAD_SAMPLE_BOOST; AudioPlayback* playback = new AudioPlayback(Format, requiredSamples, BytesPerSample, AudioManager::BytesPerSample); @@ -97,7 +76,7 @@ PUBLIC AudioPlayback* ISound::CreatePlayer() { return playback; } -PUBLIC void ISound::Dispose() { +void ISound::Dispose() { if (SoundData) { SoundData->Dispose(); delete SoundData; diff --git a/source/Engine/ResourceTypes/ISprite.cpp b/source/Engine/ResourceTypes/ISprite.cpp index c36ab635..1123617c 100644 --- a/source/Engine/ResourceTypes/ISprite.cpp +++ b/source/Engine/ResourceTypes/ISprite.cpp @@ -1,22 +1,3 @@ -#if INTERFACE -#include -#include -#include - -class ISprite { -public: - char* Filename = nullptr; - - bool LoadFailed = true; - - vector Spritesheets; - vector SpritesheetFilenames; - int CollisionBoxCount = 0; - - vector Animations; -}; -#endif - #include #include @@ -35,7 +16,7 @@ class ISprite { #include -PUBLIC ISprite::ISprite() { +ISprite::ISprite() { Spritesheets.clear(); Spritesheets.shrink_to_fit(); SpritesheetFilenames.clear(); @@ -43,7 +24,7 @@ PUBLIC ISprite::ISprite() { LoadFailed = true; Filename = nullptr; } -PUBLIC ISprite::ISprite(const char* filename) { +ISprite::ISprite(const char* filename) { Spritesheets.clear(); Spritesheets.shrink_to_fit(); SpritesheetFilenames.clear(); @@ -52,7 +33,7 @@ PUBLIC ISprite::ISprite(const char* filename) { LoadFailed = !LoadAnimation(Filename); } -PUBLIC Texture* ISprite::AddSpriteSheet(const char* filename) { +Texture* ISprite::AddSpriteSheet(const char* filename) { Texture* texture = NULL; Uint32* data = NULL; Uint32 width = 0; @@ -170,10 +151,10 @@ PUBLIC Texture* ISprite::AddSpriteSheet(const char* filename) { return texture; } -PUBLIC void ISprite::ReserveAnimationCount(int count) { +void ISprite::ReserveAnimationCount(int count) { Animations.reserve(count); } -PUBLIC void ISprite::AddAnimation(const char* name, int animationSpeed, int frameToLoop) { +void ISprite::AddAnimation(const char* name, int animationSpeed, int frameToLoop) { size_t strl = strlen(name); Animation an; @@ -185,17 +166,17 @@ PUBLIC void ISprite::AddAnimation(const char* name, int animationSpeed, int fram an.Flags = 0; Animations.push_back(an); } -PUBLIC void ISprite::AddAnimation(const char* name, int animationSpeed, int frameToLoop, int frmAlloc) { +void ISprite::AddAnimation(const char* name, int animationSpeed, int frameToLoop, int frmAlloc) { AddAnimation(name, animationSpeed, frameToLoop); Animations.back().Frames.reserve(frmAlloc); } -PUBLIC void ISprite::AddFrame(int duration, int left, int top, int width, int height, int pivotX, int pivotY) { +void ISprite::AddFrame(int duration, int left, int top, int width, int height, int pivotX, int pivotY) { ISprite::AddFrame(duration, left, top, width, height, pivotX, pivotY, 0); } -PUBLIC void ISprite::AddFrame(int duration, int left, int top, int width, int height, int pivotX, int pivotY, int id) { +void ISprite::AddFrame(int duration, int left, int top, int width, int height, int pivotX, int pivotY, int id) { AddFrame(Animations.size() - 1, duration, left, top, width, height, pivotX, pivotY, id); } -PUBLIC void ISprite::AddFrame(int animID, int duration, int left, int top, int width, int height, int pivotX, int pivotY, int id) { +void ISprite::AddFrame(int animID, int duration, int left, int top, int width, int height, int pivotX, int pivotY, int id) { AnimFrame anfrm; anfrm.Advance = id; anfrm.Duration = duration; @@ -213,24 +194,24 @@ PUBLIC void ISprite::AddFrame(int animID, int duration, int left, int top, int w Animations[animID].Frames.push_back(anfrm); } -PUBLIC void ISprite::RemoveFrames(int animID) { +void ISprite::RemoveFrames(int animID) { for (size_t i = 0; i < Animations[animID].Frames.size(); i++) Graphics::DeleteFrameBufferID(&Animations[animID].Frames[i]); Animations[animID].Frames.clear(); } -PUBLIC void ISprite::ConvertToRGBA() { +void ISprite::ConvertToRGBA() { for (int a = 0; a < Spritesheets.size(); a++) { Graphics::ConvertTextureToRGBA(Spritesheets[a]); } } -PUBLIC void ISprite::ConvertToPalette(unsigned paletteNumber) { +void ISprite::ConvertToPalette(unsigned paletteNumber) { for (int a = 0; a < Spritesheets.size(); a++) { Graphics::ConvertTextureToPalette(Spritesheets[a], paletteNumber); } } -PUBLIC bool ISprite::LoadAnimation(const char* filename) { +bool ISprite::LoadAnimation(const char* filename) { char* str; int animationCount, previousAnimationCount; @@ -388,17 +369,17 @@ PUBLIC bool ISprite::LoadAnimation(const char* filename) { return true; } -PUBLIC int ISprite::FindAnimation(const char* animname) { +int ISprite::FindAnimation(const char* animname) { for (Uint32 a = 0; a < Animations.size(); a++) if (Animations[a].Name[0] == animname[0] && !strcmp(Animations[a].Name, animname)) return a; return -1; } -PUBLIC void ISprite::LinkAnimation(vector ani) { +void ISprite::LinkAnimation(vector ani) { Animations = ani; } -PUBLIC bool ISprite::SaveAnimation(const char* filename) { +bool ISprite::SaveAnimation(const char* filename) { Stream* stream = FileStream::New(filename, FileStream::WRITE_ACCESS); if (!stream) { Log::Print(Log::LOG_ERROR, "Couldn't open file '%s'!", filename); @@ -479,7 +460,7 @@ PUBLIC bool ISprite::SaveAnimation(const char* filename) { return true; } -PUBLIC void ISprite::Dispose() { +void ISprite::Dispose() { for (size_t a = 0; a < Animations.size(); a++) { for (size_t i = 0; i < Animations[a].Frames.size(); i++) { AnimFrame* anfrm = &Animations[a].Frames[i]; @@ -516,6 +497,6 @@ PUBLIC void ISprite::Dispose() { Filename = nullptr; } -PUBLIC ISprite::~ISprite() { +ISprite::~ISprite() { Dispose(); } diff --git a/source/Engine/ResourceTypes/Image.cpp b/source/Engine/ResourceTypes/Image.cpp index 97c4c6d7..ee67c2e2 100644 --- a/source/Engine/ResourceTypes/Image.cpp +++ b/source/Engine/ResourceTypes/Image.cpp @@ -1,14 +1,3 @@ -#if INTERFACE -#include -#include - -class Image { -public: - char Filename[256]; - Texture* TexturePtr = NULL; -}; -#endif - #include #include @@ -25,23 +14,23 @@ class Image { #include #include -PUBLIC Image::Image(const char* filename) { +Image::Image(const char* filename) { strncpy(Filename, filename, 255); TexturePtr = Image::LoadTextureFromResource(Filename); } -PUBLIC void Image::Dispose() { +void Image::Dispose() { if (TexturePtr) { Graphics::DisposeTexture(TexturePtr); TexturePtr = NULL; } } -PUBLIC Image::~Image() { +Image::~Image() { Dispose(); } -PUBLIC STATIC Texture* Image::LoadTextureFromResource(const char* filename) { +Texture* Image::LoadTextureFromResource(const char* filename) { Texture* texture = NULL; Uint32* data = NULL; Uint32 width = 0; diff --git a/source/Engine/ResourceTypes/ImageFormats/GIF.cpp b/source/Engine/ResourceTypes/ImageFormats/GIF.cpp index ba9979cc..bd32368c 100644 --- a/source/Engine/ResourceTypes/ImageFormats/GIF.cpp +++ b/source/Engine/ResourceTypes/ImageFormats/GIF.cpp @@ -1,14 +1,3 @@ -#if INTERFACE -#include -#include -#include - -class GIF : public ImageFormat { -public: - vector Frames; -}; -#endif - #include #include @@ -34,7 +23,7 @@ struct Entry { Uint8 Suffix; }; -PRIVATE STATIC inline Uint32 GIF::ReadCode(Stream* stream, int codeSize, int* blockLength, int* bitCache, int* bitCacheLength) { +inline Uint32 GIF::ReadCode(Stream* stream, int codeSize, int* blockLength, int* bitCache, int* bitCacheLength) { if (*blockLength == 0) *blockLength = stream->ReadByte(); @@ -54,7 +43,7 @@ PRIVATE STATIC inline Uint32 GIF::ReadCode(Stream* stream, int codeSize, int* bl return result; } -PRIVATE STATIC inline void GIF::WriteCode(Stream* stream, int* offset, int* partial, Uint8* buffer, uint16_t key, int key_size) { +inline void GIF::WriteCode(Stream* stream, int* offset, int* partial, Uint8* buffer, uint16_t key, int key_size) { int byte_offset, bit_offset, bits_to_write; byte_offset = *offset >> 3; bit_offset = *offset & 0x7; @@ -72,7 +61,7 @@ PRIVATE STATIC inline void GIF::WriteCode(Stream* stream, int* offset, int* pa } *offset = (*offset + key_size) % (0xFF * 8); } -PRIVATE inline void GIF::WriteFrame(Stream* stream, Uint32* data) { +inline void GIF::WriteFrame(Stream* stream, Uint32* data) { int depth = 8; // Put Image Node* node; @@ -143,19 +132,19 @@ PRIVATE inline void GIF::WriteFrame(Stream* stream, Uint32* data) { FreeTree(root, degree); } -PRIVATE STATIC void* GIF::NewNode(Uint16 key, int degree) { +void* GIF::NewNode(Uint16 key, int degree) { Node* node = (Node*)Memory::Calloc(1, sizeof(*node) + degree * sizeof(Node*)); if (node) node->Key = key; return node; } -PRIVATE STATIC void* GIF::NewTree(int degree, int* nkeys) { +void* GIF::NewTree(int degree, int* nkeys) { Node *root = (Node*)GIF::NewNode(0, degree); for (*nkeys = 0; *nkeys < degree; (*nkeys)++) root->Children[*nkeys] = (Node*)GIF::NewNode(*nkeys, degree); *nkeys += 2; return root; } -PRIVATE STATIC void GIF::FreeTree(void* root, int degree) { +void GIF::FreeTree(void* root, int degree) { if (!root) return; for (int i = 0; i < degree; i++) FreeTree(((Node*)root)->Children[i], degree); Memory::Free(root); @@ -172,7 +161,7 @@ Log::Print(Log::LOG_VERBOSE, "- Mark '%s' took %.3f ms to reach.", label, delta) Clock::Start(); \ } -PUBLIC STATIC GIF* GIF::Load(const char* filename) { +GIF* GIF::Load(const char* filename) { bool loadPalette = Graphics::UsePalettes; Entry* codeTable = (Entry*)Memory::Malloc(0x1000 * sizeof(Entry)); @@ -513,11 +502,11 @@ PUBLIC STATIC GIF* GIF::Load(const char* filename) { return gif; } -PUBLIC STATIC bool GIF::Save(GIF* gif, const char* filename) { +bool GIF::Save(GIF* gif, const char* filename) { return gif->Save(filename); } -PUBLIC bool GIF::Save(const char* filename) { +bool GIF::Save(const char* filename) { Stream* stream = FileStream::New(filename, FileStream::WRITE_ACCESS); if (!stream) return false; @@ -575,6 +564,6 @@ PUBLIC bool GIF::Save(const char* filename) { return true; } -PUBLIC GIF::~GIF() { +GIF::~GIF() { } diff --git a/source/Engine/ResourceTypes/ImageFormats/ImageFormat.cpp b/source/Engine/ResourceTypes/ImageFormats/ImageFormat.cpp index e49b7616..ae7cdf1a 100644 --- a/source/Engine/ResourceTypes/ImageFormats/ImageFormat.cpp +++ b/source/Engine/ResourceTypes/ImageFormats/ImageFormat.cpp @@ -1,21 +1,7 @@ -#if INTERFACE -#include - -class ImageFormat { -public: - Uint32* Colors = NULL; - Uint32* Data = NULL; - Uint32 Width = 0; - Uint32 Height = 0; - bool Paletted = false; - Uint16 NumPaletteColors = 0; -}; -#endif - #include #include -PUBLIC Uint32* ImageFormat::GetPalette() { +Uint32* ImageFormat::GetPalette() { if (!Colors) return nullptr; @@ -24,10 +10,10 @@ PUBLIC Uint32* ImageFormat::GetPalette() { return colors; } -PUBLIC VIRTUAL bool ImageFormat::Save(const char* filename) { +bool ImageFormat::Save(const char* filename) { return false; } -PUBLIC VIRTUAL ImageFormat::~ImageFormat() { +ImageFormat::~ImageFormat() { Memory::Free(Colors); Colors = nullptr; } diff --git a/source/Engine/ResourceTypes/ImageFormats/JPEG.cpp b/source/Engine/ResourceTypes/ImageFormats/JPEG.cpp index 4b85e263..774cf9bd 100644 --- a/source/Engine/ResourceTypes/ImageFormats/JPEG.cpp +++ b/source/Engine/ResourceTypes/ImageFormats/JPEG.cpp @@ -1,14 +1,3 @@ -#if INTERFACE -#include -#include -#include - -class JPEG : public ImageFormat { -public: - -}; -#endif - #include #include @@ -105,7 +94,7 @@ static void jpeg_Hatch_IO_src(j_decompress_ptr cinfo, Stream* stream) { } #endif -PUBLIC STATIC JPEG* JPEG::Load(const char* filename) { +JPEG* JPEG::Load(const char* filename) { #ifdef USING_LIBJPEG JPEG* jpeg = new JPEG; Stream* stream = NULL; @@ -265,11 +254,11 @@ PUBLIC STATIC JPEG* JPEG::Load(const char* filename) { #endif return NULL; } -PUBLIC STATIC bool JPEG::Save(JPEG* jpeg, const char* filename) { +bool JPEG::Save(JPEG* jpeg, const char* filename) { return jpeg->Save(filename); } -PUBLIC bool JPEG::Save(const char* filename) { +bool JPEG::Save(const char* filename) { Stream* stream = FileStream::New(filename, FileStream::WRITE_ACCESS); if (!stream) return false; @@ -278,6 +267,6 @@ PUBLIC bool JPEG::Save(const char* filename) { return true; } -PUBLIC JPEG::~JPEG() { +JPEG::~JPEG() { } diff --git a/source/Engine/ResourceTypes/ImageFormats/PNG.cpp b/source/Engine/ResourceTypes/ImageFormats/PNG.cpp index 30eb9b88..fcfa0075 100644 --- a/source/Engine/ResourceTypes/ImageFormats/PNG.cpp +++ b/source/Engine/ResourceTypes/ImageFormats/PNG.cpp @@ -1,14 +1,3 @@ -#if INTERFACE -#include -#include -#include - -class PNG : public ImageFormat { -public: - -}; -#endif - #include #include @@ -48,7 +37,7 @@ void png_read_fn(png_structp ctx, png_bytep area, png_size_t size) { #include #endif -PUBLIC STATIC PNG* PNG::Load(const char* filename) { +PNG* PNG::Load(const char* filename) { #ifdef USING_LIBPNG PNG* png = new PNG; Stream* stream = NULL; @@ -351,7 +340,7 @@ PUBLIC STATIC PNG* PNG::Load(const char* filename) { #endif return NULL; } -PUBLIC void PNG::ReadPixelDataARGB(Uint32* pixelData, int num_channels) { + void PNG::ReadPixelDataARGB(Uint32* pixelData, int num_channels) { Uint32 Rmask, Gmask, Bmask, Amask; bool doConvert = false; @@ -399,7 +388,7 @@ PUBLIC void PNG::ReadPixelDataARGB(Uint32* pixelData, int num_channels memcpy(Data, pixelData, Width * Height * sizeof(Uint32)); } } -PUBLIC void PNG::ReadPixelBitstream(Uint8* pixelData, size_t bit_depth) { + void PNG::ReadPixelBitstream(Uint8* pixelData, size_t bit_depth) { size_t scanline_width = (((bit_depth * Width) + 15) / 8) - 1; Uint8 mask = (1 << bit_depth) - 1; @@ -426,11 +415,11 @@ PUBLIC void PNG::ReadPixelBitstream(Uint8* pixelData, size_t bit_depth } } -PUBLIC STATIC bool PNG::Save(PNG* png, const char* filename) { +bool PNG::Save(PNG* png, const char* filename) { return png->Save(filename); } -PUBLIC bool PNG::Save(const char* filename) { +bool PNG::Save(const char* filename) { Stream* stream = FileStream::New(filename, FileStream::WRITE_ACCESS); if (!stream) return false; @@ -439,6 +428,6 @@ PUBLIC bool PNG::Save(const char* filename) { return true; } -PUBLIC PNG::~PNG() { +PNG::~PNG() { } diff --git a/source/Engine/ResourceTypes/ModelFormats/HatchModel.cpp b/source/Engine/ResourceTypes/ModelFormats/HatchModel.cpp index 107a57d3..9082da02 100644 --- a/source/Engine/ResourceTypes/ModelFormats/HatchModel.cpp +++ b/source/Engine/ResourceTypes/ModelFormats/HatchModel.cpp @@ -1,22 +1,3 @@ -#if INTERFACE -#include -#include -class HatchModel { -public: - static Sint32 Version; - - static Uint32 NumVertexStore; - static Uint32 NumNormalStore; - static Uint32 NumTexCoordStore; - static Uint32 NumColorStore; - - static Vector3* VertexStore; - static Vector3* NormalStore; - static Vector2* TexCoordStore; - static Uint32* ColorStore; -}; -#endif - #include #include #include @@ -40,7 +21,7 @@ Vector3* HatchModel::NormalStore; Vector2* HatchModel::TexCoordStore; Uint32* HatchModel::ColorStore; -PUBLIC STATIC bool HatchModel::IsMagic(Stream* stream) { +bool HatchModel::IsMagic(Stream* stream) { Uint32 magic = stream->ReadUInt32BE(); stream->Skip(-4); @@ -48,7 +29,7 @@ PUBLIC STATIC bool HatchModel::IsMagic(Stream* stream) { return magic == HATCH_MODEL_MAGIC; } -PUBLIC STATIC void HatchModel::ReadMaterialInfo(Stream* stream, Uint8 *destColors, char **texName) { +void HatchModel::ReadMaterialInfo(Stream* stream, Uint8 *destColors, char **texName) { *texName = stream->ReadString(); Uint32 colorIndex = stream->ReadUInt32(); @@ -58,7 +39,7 @@ PUBLIC STATIC void HatchModel::ReadMaterialInfo(Stream* stream, Uint8 *destColor ColorUtils::Separate(color, destColors); } -PRIVATE STATIC Material* HatchModel::ReadMaterial(Stream* stream, const char *parentDirectory) { +Material* HatchModel::ReadMaterial(Stream* stream, const char *parentDirectory) { Material* material = new Material(); material->Name = stream->ReadString(); @@ -146,7 +127,7 @@ PRIVATE STATIC Material* HatchModel::ReadMaterial(Stream* stream, const char *pa return material; } -PRIVATE STATIC void HatchModel::ReadVertexStore(Stream* stream) { +void HatchModel::ReadVertexStore(Stream* stream) { NumVertexStore = stream->ReadUInt32(); if (!NumVertexStore) return; @@ -162,7 +143,7 @@ PRIVATE STATIC void HatchModel::ReadVertexStore(Stream* stream) { } } -PRIVATE STATIC void HatchModel::ReadNormalStore(Stream* stream) { +void HatchModel::ReadNormalStore(Stream* stream) { NumNormalStore = stream->ReadUInt32(); if (!NumNormalStore) return; @@ -178,7 +159,7 @@ PRIVATE STATIC void HatchModel::ReadNormalStore(Stream* stream) { } } -PRIVATE STATIC void HatchModel::ReadTexCoordStore(Stream* stream) { +void HatchModel::ReadTexCoordStore(Stream* stream) { NumTexCoordStore = stream->ReadUInt32(); if (!NumTexCoordStore) return; @@ -193,7 +174,7 @@ PRIVATE STATIC void HatchModel::ReadTexCoordStore(Stream* stream) { } } -PRIVATE STATIC void HatchModel::ReadColorStore(Stream* stream) { +void HatchModel::ReadColorStore(Stream* stream) { NumColorStore = stream->ReadUInt32(); if (!NumColorStore) return; @@ -211,35 +192,35 @@ PRIVATE STATIC void HatchModel::ReadColorStore(Stream* stream) { } } -PRIVATE STATIC Vector3 HatchModel::GetStoredVertex(Uint32 idx) { +Vector3 HatchModel::GetStoredVertex(Uint32 idx) { if (idx < 0 || idx >= NumVertexStore) return {}; return VertexStore[idx]; } -PRIVATE STATIC Vector3 HatchModel::GetStoredNormal(Uint32 idx) { +Vector3 HatchModel::GetStoredNormal(Uint32 idx) { if (idx < 0 || idx >= NumNormalStore) return {}; return NormalStore[idx]; } -PRIVATE STATIC Vector2 HatchModel::GetStoredTexCoord(Uint32 idx) { +Vector2 HatchModel::GetStoredTexCoord(Uint32 idx) { if (idx < 0 || idx >= NumTexCoordStore) return {}; return TexCoordStore[idx]; } -PRIVATE STATIC Uint32 HatchModel::GetStoredColor(Uint32 idx) { +Uint32 HatchModel::GetStoredColor(Uint32 idx) { if (idx < 0 || idx >= NumColorStore) return 0; return ColorStore[idx]; } -PRIVATE STATIC void HatchModel::ReadVertexIndices(Sint32* indices, Uint32 triangleCount, Stream* stream) { +void HatchModel::ReadVertexIndices(Sint32* indices, Uint32 triangleCount, Stream* stream) { for (Uint32 i = 0; i < triangleCount; i++) { *indices++ = stream->ReadUInt32(); *indices++ = stream->ReadUInt32(); @@ -249,7 +230,7 @@ PRIVATE STATIC void HatchModel::ReadVertexIndices(Sint32* indices, Uint32 triang *indices = -1; } -PRIVATE STATIC Mesh* HatchModel::ReadMesh(IModel* model, Stream* stream) { +Mesh* HatchModel::ReadMesh(IModel* model, Stream* stream) { // Read mesh data Mesh* mesh = new Mesh; mesh->Name = stream->ReadString(); @@ -336,7 +317,7 @@ PRIVATE STATIC Mesh* HatchModel::ReadMesh(IModel* model, Stream* stream) { return mesh; } -PUBLIC STATIC bool HatchModel::Convert(IModel* model, Stream* stream, const char* path) { +bool HatchModel::Convert(IModel* model, Stream* stream, const char* path) { bool success = false; if (stream->ReadUInt32BE() != HATCH_MODEL_MAGIC) { @@ -483,7 +464,7 @@ static vector normalList; static vector texCoordList; static vector colorList; -PRIVATE STATIC void HatchModel::WriteMesh(Mesh* mesh, Stream* stream) { +void HatchModel::WriteMesh(Mesh* mesh, Stream* stream) { Uint8 flags = 0; if (mesh->VertexFlag & VertexType_Normal) flags |= 1; @@ -575,7 +556,7 @@ PRIVATE STATIC void HatchModel::WriteMesh(Mesh* mesh, Stream* stream) { stream->WriteUInt32(mesh->VertexIndexBuffer[j]); } -PRIVATE STATIC char* HatchModel::GetMaterialTextureName(const char* name, const char* parentDirectory) { +char* HatchModel::GetMaterialTextureName(const char* name, const char* parentDirectory) { const char* result = strstr(name, parentDirectory); if (result) { size_t offset = strlen(parentDirectory); @@ -587,7 +568,7 @@ PRIVATE STATIC char* HatchModel::GetMaterialTextureName(const char* name, const return StringUtils::Duplicate(name); } -PRIVATE STATIC void HatchModel::WriteColorIndex(Uint32* color, Stream* stream) { +void HatchModel::WriteColorIndex(Uint32* color, Stream* stream) { Uint32 key = colorIDs->HashFunction(color, sizeof(*color)); if (colorIDs->Exists(key)) stream->WriteUInt32(colorIDs->Get(key)); @@ -598,7 +579,7 @@ PRIVATE STATIC void HatchModel::WriteColorIndex(Uint32* color, Stream* stream) { } } -PRIVATE STATIC void HatchModel::WriteMaterial(Material* material, Stream* stream, const char* parentDirectory) { +void HatchModel::WriteMaterial(Material* material, Stream* stream, const char* parentDirectory) { stream->WriteString(material->Name); Uint8 flags = 0; @@ -759,7 +740,7 @@ PRIVATE STATIC void HatchModel::WriteMaterial(Material* material, Stream* stream } } -PUBLIC STATIC bool HatchModel::Save(IModel* model, const char* filename) { +bool HatchModel::Save(IModel* model, const char* filename) { Stream* stream = FileStream::New(filename, FileStream::WRITE_ACCESS); if (!stream) { Log::Print(Log::LOG_ERROR, "Couldn't open \"%s\"!", filename); diff --git a/source/Engine/ResourceTypes/ModelFormats/Importer.cpp b/source/Engine/ResourceTypes/ModelFormats/Importer.cpp index 979e7521..174f3cb6 100644 --- a/source/Engine/ResourceTypes/ModelFormats/Importer.cpp +++ b/source/Engine/ResourceTypes/ModelFormats/Importer.cpp @@ -1,14 +1,3 @@ -#if INTERFACE -#include -#include -#include -class ModelImporter { -public: - static vector MeshIDs; - static char* ParentDirectory; -}; -#endif - #include #include #include @@ -102,7 +91,7 @@ static AnimQuaternionKey GetQuatKey(struct aiQuatKey* quatKey) { return key; } -PRIVATE STATIC Mesh* ModelImporter::LoadMesh(IModel* imodel, struct aiMesh* amesh) { +Mesh* ModelImporter::LoadMesh(IModel* imodel, struct aiMesh* amesh) { size_t numFaces = amesh->mNumFaces; size_t numVertices = amesh->mNumVertices; @@ -185,7 +174,7 @@ PRIVATE STATIC Mesh* ModelImporter::LoadMesh(IModel* imodel, struct aiMesh* ames return mesh; } -PRIVATE STATIC Material* ModelImporter::LoadMaterial(IModel* imodel, struct aiMaterial* mat, unsigned i) { +Material* ModelImporter::LoadMaterial(IModel* imodel, struct aiMaterial* mat, unsigned i) { Material* material = new Material(); aiString matName; @@ -242,7 +231,7 @@ PRIVATE STATIC Material* ModelImporter::LoadMaterial(IModel* imodel, struct aiMa return material; } -PRIVATE STATIC ModelNode* ModelImporter::LoadNode(IModel* imodel, ModelNode* parent, const struct aiNode* anode) { +ModelNode* ModelImporter::LoadNode(IModel* imodel, ModelNode* parent, const struct aiNode* anode) { ModelNode* node = new ModelNode; node->Name = GetString(anode->mName); @@ -266,7 +255,7 @@ PRIVATE STATIC ModelNode* ModelImporter::LoadNode(IModel* imodel, ModelNode* par return node; } -PRIVATE STATIC Skeleton* ModelImporter::LoadBones(IModel* imodel, Mesh* mesh, struct aiMesh* amesh) { +Skeleton* ModelImporter::LoadBones(IModel* imodel, Mesh* mesh, struct aiMesh* amesh) { Skeleton* skeleton = new Skeleton; skeleton->NumBones = amesh->mNumBones; @@ -311,7 +300,7 @@ PRIVATE STATIC Skeleton* ModelImporter::LoadBones(IModel* imodel, Mesh* mesh, st return skeleton; } -PRIVATE STATIC SkeletalAnim* ModelImporter::LoadAnimation(IModel* imodel, ModelAnim* parentAnim, struct aiAnimation* aanim) { +SkeletalAnim* ModelImporter::LoadAnimation(IModel* imodel, ModelAnim* parentAnim, struct aiAnimation* aanim) { SkeletalAnim* anim = new SkeletalAnim; anim->Channels.resize(aanim->mNumChannels); anim->NodeLookup = new HashMap(NULL, 256); // Might be enough @@ -360,7 +349,7 @@ PRIVATE STATIC SkeletalAnim* ModelImporter::LoadAnimation(IModel* imodel, ModelA return anim; } -PRIVATE STATIC bool ModelImporter::DoConversion(const struct aiScene* scene, IModel* imodel) { +bool ModelImporter::DoConversion(const struct aiScene* scene, IModel* imodel) { if (!scene->mNumMeshes) return false; @@ -482,7 +471,7 @@ PRIVATE STATIC bool ModelImporter::DoConversion(const struct aiScene* scene, IMo } #endif -PUBLIC STATIC bool ModelImporter::Convert(IModel* model, Stream* stream, const char* path) { +bool ModelImporter::Convert(IModel* model, Stream* stream, const char* path) { #ifdef USING_ASSIMP size_t size = stream->Length(); void* data = Memory::Malloc(size); diff --git a/source/Engine/ResourceTypes/ModelFormats/MD3Model.cpp b/source/Engine/ResourceTypes/ModelFormats/MD3Model.cpp index 55aa91c5..a2f6ca49 100644 --- a/source/Engine/ResourceTypes/ModelFormats/MD3Model.cpp +++ b/source/Engine/ResourceTypes/ModelFormats/MD3Model.cpp @@ -1,15 +1,3 @@ -#if INTERFACE -#include -#include -class MD3Model { -public: - static Sint32 Version; - static bool UseUVKeyframes; - static Sint32 DataEndOffset; - static vector MaterialNames; -}; -#endif - #include #include #include @@ -35,7 +23,7 @@ bool MD3Model::UseUVKeyframes; Sint32 MD3Model::DataEndOffset; vector MD3Model::MaterialNames; -PUBLIC STATIC bool MD3Model::IsMagic(Stream* stream) { +bool MD3Model::IsMagic(Stream* stream) { Uint32 magic = stream->ReadUInt32BE(); stream->Skip(-4); @@ -43,7 +31,7 @@ PUBLIC STATIC bool MD3Model::IsMagic(Stream* stream) { return magic == MD3_MODEL_MAGIC; } -PRIVATE STATIC void MD3Model::DecodeNormal(Uint16 index, float& x, float& y, float& z) { +void MD3Model::DecodeNormal(Uint16 index, float& x, float& y, float& z) { unsigned latIdx = (index >> 8) & 0xFF; unsigned lngIdx = index & 0xFF; @@ -55,7 +43,7 @@ PRIVATE STATIC void MD3Model::DecodeNormal(Uint16 index, float& x, float& y, flo z = cosf(lng); } -PRIVATE STATIC void MD3Model::ReadShader(Stream* stream) { +void MD3Model::ReadShader(Stream* stream) { char name[MAX_QPATH + 1]; memset(name, '\0', sizeof name); stream->ReadBytes(name, MAX_QPATH); @@ -65,7 +53,7 @@ PRIVATE STATIC void MD3Model::ReadShader(Stream* stream) { MaterialNames.push_back(shaderName); } -PRIVATE STATIC void MD3Model::ReadVerticesAndNormals(Vector3* vert, Vector3* norm, Sint32 vertexCount, Stream* stream) { +void MD3Model::ReadVerticesAndNormals(Vector3* vert, Vector3* norm, Sint32 vertexCount, Stream* stream) { for (Sint32 i = 0; i < vertexCount; i++) { // MD3 coordinate system is usually Z up and Y forward (I think.) vert->X = stream->ReadInt16() * FP16_TO(MD3_XYZ_SCALE); @@ -83,7 +71,7 @@ PRIVATE STATIC void MD3Model::ReadVerticesAndNormals(Vector3* vert, Vector3* nor } } -PRIVATE STATIC void MD3Model::ReadUVs(Vector2* uvs, Sint32 vertexCount, Stream* stream) { +void MD3Model::ReadUVs(Vector2* uvs, Sint32 vertexCount, Stream* stream) { for (Sint32 i = 0; i < vertexCount; i++) { uvs->X = (int)(stream->ReadFloat() * 0x10000); uvs->Y = (int)(stream->ReadFloat() * 0x10000); @@ -91,7 +79,7 @@ PRIVATE STATIC void MD3Model::ReadUVs(Vector2* uvs, Sint32 vertexCount, Stream* } } -PRIVATE STATIC void MD3Model::ReadVertexIndices(Sint32* indices, Sint32 triangleCount, Stream* stream) { +void MD3Model::ReadVertexIndices(Sint32* indices, Sint32 triangleCount, Stream* stream) { for (Sint32 i = 0; i < triangleCount; i++) { *indices++ = stream->ReadUInt32(); *indices++ = stream->ReadUInt32(); @@ -101,7 +89,7 @@ PRIVATE STATIC void MD3Model::ReadVertexIndices(Sint32* indices, Sint32 triangle *indices = -1; } -PRIVATE STATIC Mesh* MD3Model::ReadSurface(IModel* model, Stream* stream, size_t surfaceDataOffset) { +Mesh* MD3Model::ReadSurface(IModel* model, Stream* stream, size_t surfaceDataOffset) { Sint32 magic = stream->ReadUInt32BE(); if (magic != MD3_MODEL_MAGIC) { Log::Print(Log::LOG_ERROR, "Invalid magic for MD3 surface!"); @@ -212,7 +200,7 @@ PRIVATE STATIC Mesh* MD3Model::ReadSurface(IModel* model, Stream* stream, size_t return mesh; } -PUBLIC STATIC bool MD3Model::Convert(IModel* model, Stream* stream, const char* path) { +bool MD3Model::Convert(IModel* model, Stream* stream, const char* path) { if (stream->ReadUInt32BE() != MD3_MODEL_MAGIC) { Log::Print(Log::LOG_ERROR, "Model not of MD3 (Quake III) type!"); return false; diff --git a/source/Engine/ResourceTypes/ModelFormats/RSDKModel.cpp b/source/Engine/ResourceTypes/ModelFormats/RSDKModel.cpp index accd781f..b0ccc74f 100644 --- a/source/Engine/ResourceTypes/ModelFormats/RSDKModel.cpp +++ b/source/Engine/ResourceTypes/ModelFormats/RSDKModel.cpp @@ -1,12 +1,3 @@ -#if INTERFACE -#include -#include -class RSDKModel { -public: - -}; -#endif - #include #include #include @@ -16,7 +7,7 @@ class RSDKModel { #define RSDK_MODEL_MAGIC 0x4D444C00 // MDL0 -PUBLIC STATIC bool RSDKModel::IsMagic(Stream* stream) { +bool RSDKModel::IsMagic(Stream* stream) { Uint32 magic = stream->ReadUInt32BE(); stream->Skip(-4); @@ -24,7 +15,7 @@ PUBLIC STATIC bool RSDKModel::IsMagic(Stream* stream) { return magic == RSDK_MODEL_MAGIC; } -PUBLIC STATIC bool RSDKModel::Convert(IModel* model, Stream* stream) { +bool RSDKModel::Convert(IModel* model, Stream* stream) { if (stream->ReadUInt32BE() != RSDK_MODEL_MAGIC) { Log::Print(Log::LOG_ERROR, "Model not of RSDK type!"); return false; diff --git a/source/Engine/ResourceTypes/ResourceManager.cpp b/source/Engine/ResourceTypes/ResourceManager.cpp index eda7fc1c..c0332601 100644 --- a/source/Engine/ResourceTypes/ResourceManager.cpp +++ b/source/Engine/ResourceTypes/ResourceManager.cpp @@ -1,14 +1,3 @@ -#if INTERFACE -#include -#include - -class ResourceManager { -public: - static bool UsingDataFolder; - static bool UsingModPack; -}; -#endif - #include #include @@ -42,10 +31,10 @@ HashMap* ResourceRegistry = NULL; bool ResourceManager::UsingDataFolder = true; bool ResourceManager::UsingModPack = false; -PUBLIC STATIC void ResourceManager::PrefixResourcePath(char* out, size_t outSize, const char* path) { +void ResourceManager::PrefixResourcePath(char* out, size_t outSize, const char* path) { snprintf(out, outSize, "Resources/%s", path); } -PUBLIC STATIC void ResourceManager::PrefixParentPath(char* out, size_t outSize, const char* path) { +void ResourceManager::PrefixParentPath(char* out, size_t outSize, const char* path) { #if defined(SWITCH_ROMFS) snprintf(out, outSize, "romfs:/%s", path); #else @@ -53,7 +42,7 @@ PUBLIC STATIC void ResourceManager::PrefixParentPath(char* out, size_t outSize #endif } -PUBLIC STATIC void ResourceManager::Init(const char* filename) { +void ResourceManager::Init(const char* filename) { StreamNodeHead = NULL; ResourceRegistry = new HashMap(CRC32::EncryptData, 16); @@ -80,7 +69,7 @@ PUBLIC STATIC void ResourceManager::Init(const char* filename) { } } } -PUBLIC STATIC void ResourceManager::Load(const char* filename) { +void ResourceManager::Load(const char* filename) { if (!ResourceRegistry) return; @@ -128,7 +117,7 @@ PUBLIC STATIC void ResourceManager::Load(const char* filename) { // Log::Print(Log::LOG_VERBOSE, "%08X: Offset: %08llX Size: %08llX Comp Size: %08llX Data Flag: %08X", crc32, offset, size, compressedSize, dataFlag); } } -PUBLIC STATIC bool ResourceManager::LoadResource(const char* filename, Uint8** out, size_t* size) { +bool ResourceManager::LoadResource(const char* filename, Uint8** out, size_t* size) { Uint8* memory; char resourcePath[4096]; char *pathToLoad = StringUtils::ReplacePathSeparators(filename); @@ -264,7 +253,7 @@ PUBLIC STATIC bool ResourceManager::LoadResource(const char* filename, Uint8** *size = rwSize; return true; } -PUBLIC STATIC bool ResourceManager::ResourceExists(const char* filename) { +bool ResourceManager::ResourceExists(const char* filename) { char *pathToLoad = StringUtils::ReplacePathSeparators(filename); char resourcePath[4096]; @@ -293,7 +282,7 @@ PUBLIC STATIC bool ResourceManager::ResourceExists(const char* filename) { SDL_RWclose(rw); return true; } -PUBLIC STATIC void ResourceManager::Dispose() { +void ResourceManager::Dispose() { if (StreamNodeHead) { for (StreamNode *old, *streamNode = StreamNodeHead; streamNode; ) { old = streamNode; diff --git a/source/Engine/ResourceTypes/SceneFormats/HatchSceneReader.cpp b/source/Engine/ResourceTypes/SceneFormats/HatchSceneReader.cpp index 19b0f43f..3a749e1e 100644 --- a/source/Engine/ResourceTypes/SceneFormats/HatchSceneReader.cpp +++ b/source/Engine/ResourceTypes/SceneFormats/HatchSceneReader.cpp @@ -1,14 +1,3 @@ -#if INTERFACE -#include -#include -#include - -class HatchSceneReader { -public: - static Uint32 Magic; -}; -#endif - #include #include @@ -39,7 +28,7 @@ Uint32 HatchSceneReader::Magic = 0x4E435348; // HSCN #define HSCN_FLIPY_MASK 0x00002000U #define HSCN_FXYID_MASK 0x00003FFFU // Max. 4096 tiles -PUBLIC STATIC bool HatchSceneReader::Read(const char* filename, const char* parentFolder) { +bool HatchSceneReader::Read(const char* filename, const char* parentFolder) { Stream* r = ResourceStream::New(filename); if (!r) { Log::Print(Log::LOG_ERROR, "Couldn't open file '%s'!", filename); @@ -49,7 +38,7 @@ PUBLIC STATIC bool HatchSceneReader::Read(const char* filename, const char* pare return HatchSceneReader::Read(r, parentFolder); } -PUBLIC STATIC bool HatchSceneReader::Read(Stream* r, const char* parentFolder) { +bool HatchSceneReader::Read(Stream* r, const char* parentFolder) { // Start reading if (r->ReadUInt32() != HatchSceneReader::Magic) { Log::Print(Log::LOG_ERROR, "Not a Hatch scene!"); @@ -107,7 +96,7 @@ PUBLIC STATIC bool HatchSceneReader::Read(Stream* r, const char* parentFolder) { return true; } -PRIVATE STATIC SceneLayer HatchSceneReader::ReadLayer(Stream* r) { +SceneLayer HatchSceneReader::ReadLayer(Stream* r) { char* name = r->ReadHeaderedString(); Uint8 drawBehavior = r->ReadByte(); Uint8 drawGroup = r->ReadByte(); @@ -161,7 +150,7 @@ PRIVATE STATIC SceneLayer HatchSceneReader::ReadLayer(Stream* r) { return layer; } -PRIVATE STATIC void HatchSceneReader::ReadTileData(Stream* r, SceneLayer layer) { +void HatchSceneReader::ReadTileData(Stream* r, SceneLayer layer) { size_t streamPos = r->Position(); r->ReadUInt32(); // compressed size @@ -176,7 +165,7 @@ PRIVATE STATIC void HatchSceneReader::ReadTileData(Stream* r, SceneLayer layer) r->ReadCompressed(layer.Tiles, dataSize); } -PRIVATE STATIC void HatchSceneReader::ConvertTileData(SceneLayer* layer) { +void HatchSceneReader::ConvertTileData(SceneLayer* layer) { for (size_t i = 0; i < (size_t)layer->Width * layer->Height; i++) { if (layer->Tiles[i] == HSCN_EMPTY_TILE) { layer->Tiles[i] = Scene::EmptyTile; @@ -205,7 +194,7 @@ PRIVATE STATIC void HatchSceneReader::ConvertTileData(SceneLayer* layer) { } } -PRIVATE STATIC void HatchSceneReader::ReadScrollData(Stream* r, SceneLayer layer) { +void HatchSceneReader::ReadScrollData(Stream* r, SceneLayer layer) { for (Uint16 i = 0; i < layer.ScrollInfoCount; i++) { ScrollingInfo* info = &layer.ScrollInfos[i]; @@ -235,7 +224,7 @@ PRIVATE STATIC void HatchSceneReader::ReadScrollData(Stream* r, SceneLayer layer static vector SceneClasses; -PRIVATE STATIC SceneClass* HatchSceneReader::FindClass(SceneHash hash) { +SceneClass* HatchSceneReader::FindClass(SceneHash hash) { for (size_t i = 0; i < SceneClasses.size(); i++) { if (SceneClasses[i].Hash == hash) return &SceneClasses[i]; @@ -244,7 +233,7 @@ PRIVATE STATIC SceneClass* HatchSceneReader::FindClass(SceneHash hash) { return NULL; } -PRIVATE STATIC SceneClassProperty* HatchSceneReader::FindProperty(SceneClass* scnClass, SceneHash hash) { +SceneClassProperty* HatchSceneReader::FindProperty(SceneClass* scnClass, SceneHash hash) { for (size_t i = 0; i < scnClass->Properties.size(); i++) { if (scnClass->Properties[i].Hash == hash) return &scnClass->Properties[i]; @@ -253,7 +242,7 @@ PRIVATE STATIC SceneClassProperty* HatchSceneReader::FindProperty(SceneClass* sc return NULL; } -PRIVATE STATIC void HatchSceneReader::HashString(char* string, SceneHash* hash) { +void HatchSceneReader::HashString(char* string, SceneHash* hash) { Uint8 final[16]; MD5::EncryptString(final, string); @@ -264,7 +253,7 @@ PRIVATE STATIC void HatchSceneReader::HashString(char* string, SceneHash* hash) hash->D = final[12] + (final[13] << 8) + (final[14] << 16) + (final[15] << 24); } -PRIVATE STATIC void HatchSceneReader::ReadClasses(Stream *r) { +void HatchSceneReader::ReadClasses(Stream *r) { Uint16 numClasses = r->ReadUInt16(); SceneClasses.clear(); @@ -317,7 +306,7 @@ PRIVATE STATIC void HatchSceneReader::ReadClasses(Stream *r) { } } -PRIVATE STATIC void HatchSceneReader::FreeClasses() { +void HatchSceneReader::FreeClasses() { for (size_t i = 0; i < SceneClasses.size(); i++) { SceneClass* scnClass = &SceneClasses[i]; Memory::Free(scnClass->Name); @@ -328,7 +317,7 @@ PRIVATE STATIC void HatchSceneReader::FreeClasses() { SceneClasses.clear(); } -PRIVATE STATIC bool HatchSceneReader::LoadTileset(const char* parentFolder) { +bool HatchSceneReader::LoadTileset(const char* parentFolder) { int curTileCount = (int)Scene::TileSpriteInfos.size(); char tilesetFile[4096]; @@ -379,7 +368,7 @@ PRIVATE STATIC bool HatchSceneReader::LoadTileset(const char* parentFolder) { return true; } -PRIVATE STATIC void HatchSceneReader::ReadEntities(Stream *r) { +void HatchSceneReader::ReadEntities(Stream *r) { Uint16 numEntities = r->ReadUInt16(); for (Uint16 i = 0; i < numEntities; i++) { @@ -532,7 +521,7 @@ PRIVATE STATIC void HatchSceneReader::ReadEntities(Stream *r) { } } -PRIVATE STATIC void HatchSceneReader::SkipEntityProperties(Stream *r, Uint8 numProps) { +void HatchSceneReader::SkipEntityProperties(Stream *r, Uint8 numProps) { for (Uint8 j = 0; j < numProps; j++) { r->ReadUInt32(); r->ReadUInt32(); @@ -542,7 +531,7 @@ PRIVATE STATIC void HatchSceneReader::SkipEntityProperties(Stream *r, Uint8 numP } } -PRIVATE STATIC void HatchSceneReader::SkipProperty(Stream *r, Uint8 varType) { +void HatchSceneReader::SkipProperty(Stream *r, Uint8 varType) { switch (varType) { case HSCN_VAR_INT8: case HSCN_VAR_UINT8: diff --git a/source/Engine/ResourceTypes/SceneFormats/RSDKSceneReader.cpp b/source/Engine/ResourceTypes/SceneFormats/RSDKSceneReader.cpp index 4be7a5b4..fbf3ba9b 100644 --- a/source/Engine/ResourceTypes/SceneFormats/RSDKSceneReader.cpp +++ b/source/Engine/ResourceTypes/SceneFormats/RSDKSceneReader.cpp @@ -1,13 +1,3 @@ -#if INTERFACE -#include -#include -class RSDKSceneReader { -public: - static Uint32 Magic; - static bool Initialized; -}; -#endif - #include #include @@ -49,7 +39,7 @@ static HashMap* PropertyHashes = NULL; static Uint32 HACK_PlayerNameHash = 0; -PUBLIC STATIC void RSDKSceneReader::StageConfig_GetColors(const char* filename) { +void RSDKSceneReader::StageConfig_GetColors(const char* filename) { MemoryStream* memoryReader; ResourceStream* stageConfigReader; if ((stageConfigReader = ResourceStream::New(filename))) { @@ -95,7 +85,7 @@ PUBLIC STATIC void RSDKSceneReader::StageConfig_GetColors(const char* filename) stageConfigReader->Close(); } } -PUBLIC STATIC void RSDKSceneReader::GameConfig_GetColors(const char* filename) { +void RSDKSceneReader::GameConfig_GetColors(const char* filename) { MemoryStream* memoryReader; ResourceStream* gameConfigReader; if ((gameConfigReader = ResourceStream::New(filename))) { @@ -147,7 +137,7 @@ PUBLIC STATIC void RSDKSceneReader::GameConfig_GetColors(const char* filename) { gameConfigReader->Close(); } } -PRIVATE STATIC void RSDKSceneReader::LoadObjectList() { +void RSDKSceneReader::LoadObjectList() { // Object names Stream* r = ResourceStream::New("ObjectList.txt"); if (!r) return; @@ -187,7 +177,7 @@ PRIVATE STATIC void RSDKSceneReader::LoadObjectList() { r->Close(); } -PRIVATE STATIC void RSDKSceneReader::LoadPropertyList() { +void RSDKSceneReader::LoadPropertyList() { // Property Names Stream* r = ResourceStream::New("PropertyList.txt"); if (!r) return; @@ -219,7 +209,7 @@ PRIVATE STATIC void RSDKSceneReader::LoadPropertyList() { r->Close(); } -PUBLIC STATIC bool RSDKSceneReader::Read(const char* filename, const char* parentFolder) { +bool RSDKSceneReader::Read(const char* filename, const char* parentFolder) { Stream* r = ResourceStream::New(filename); if (!r) { Log::Print(Log::LOG_ERROR, "Couldn't open file '%s'!", filename); @@ -228,7 +218,7 @@ PUBLIC STATIC bool RSDKSceneReader::Read(const char* filename, const char* paren return RSDKSceneReader::Read(r, parentFolder); } -PRIVATE STATIC SceneLayer RSDKSceneReader::ReadLayer(Stream* r) { +SceneLayer RSDKSceneReader::ReadLayer(Stream* r) { r->ReadByte(); // Ignored Byte char* Name = r->ReadHeaderedString(); @@ -303,7 +293,7 @@ PRIVATE STATIC SceneLayer RSDKSceneReader::ReadLayer(Stream* r) { return layer; } -PUBLIC STATIC bool RSDKSceneReader::ReadObjectDefinition(Stream* r, Entity** objSlots, const int maxObjSlots) { +bool RSDKSceneReader::ReadObjectDefinition(Stream* r, Entity** objSlots, const int maxObjSlots) { Uint8 hashTemp[16]; r->ReadBytes(hashTemp, 16); @@ -471,7 +461,7 @@ PUBLIC STATIC bool RSDKSceneReader::ReadObjectDefinition(Stream* r, Entity** obj return true; } -PUBLIC STATIC bool RSDKSceneReader::Read(Stream* r, const char* parentFolder) { +bool RSDKSceneReader::Read(Stream* r, const char* parentFolder) { // Load PropertyList and ObjectList and others // (use regular malloc and calloc as this is technically a hack outside the scope of the engine) if (!RSDKSceneReader::Initialized) { @@ -572,7 +562,7 @@ PUBLIC STATIC bool RSDKSceneReader::Read(Stream* r, const char* parentFolder) { return true; } -PRIVATE STATIC bool RSDKSceneReader::LoadTileset(const char* parentFolder) { +bool RSDKSceneReader::LoadTileset(const char* parentFolder) { Graphics::UsePalettes = true; char filename16x16Tiles[4096]; diff --git a/source/Engine/ResourceTypes/SceneFormats/TiledMapReader.cpp b/source/Engine/ResourceTypes/SceneFormats/TiledMapReader.cpp index f5a5ec85..2485f453 100644 --- a/source/Engine/ResourceTypes/SceneFormats/TiledMapReader.cpp +++ b/source/Engine/ResourceTypes/SceneFormats/TiledMapReader.cpp @@ -1,11 +1,3 @@ -#if INTERFACE -#include -#include -class TiledMapReader { -public: -}; -#endif - #include #include @@ -104,7 +96,7 @@ int base64_decode_block(const char* code_in, const int length_in, char* plaint return (int)(plainchar - (int8_t*)plaintext_out); } -PRIVATE STATIC VMValue TiledMapReader::ParseProperty(XMLNode* property) { +VMValue TiledMapReader::ParseProperty(XMLNode* property) { // If the property has no value (for example, a multiline string), // the value is assumed to be in the content if (!property->attributes.Exists("value")) { @@ -179,7 +171,7 @@ PRIVATE STATIC VMValue TiledMapReader::ParseProperty(XMLNode* property) { return val; } -PRIVATE STATIC void TiledMapReader::ParsePropertyNode(XMLNode* node, HashMap* properties) { +void TiledMapReader::ParsePropertyNode(XMLNode* node, HashMap* properties) { if (!node->attributes.Exists("name")) return; @@ -188,7 +180,7 @@ PRIVATE STATIC void TiledMapReader::ParsePropertyNode(XMLNode* node, HashMapPut(property_name.ToString().c_str(), TiledMapReader::ParseProperty(node)); } -PRIVATE STATIC ObjArray* TiledMapReader::ParsePolyPoints(XMLNode* node) { +ObjArray* TiledMapReader::ParsePolyPoints(XMLNode* node) { if (!node->attributes.Exists("points")) return nullptr; @@ -216,7 +208,7 @@ PRIVATE STATIC ObjArray* TiledMapReader::ParsePolyPoints(XMLNode* node) { return array; } -PRIVATE STATIC Tileset* TiledMapReader::ParseTilesetImage(XMLNode* node, int firstgid, const char* parentFolder) { +Tileset* TiledMapReader::ParseTilesetImage(XMLNode* node, int firstgid, const char* parentFolder) { char imagePath[4096]; Token image_source = node->attributes.Get("source"); @@ -274,7 +266,7 @@ PRIVATE STATIC Tileset* TiledMapReader::ParseTilesetImage(XMLNode* node, int fir return &Scene::Tilesets.back(); } -PRIVATE STATIC void TiledMapReader::ParseTileAnimation(int tileID, int firstgid, Tileset* tilesetPtr, XMLNode* node) { +void TiledMapReader::ParseTileAnimation(int tileID, int firstgid, Tileset* tilesetPtr, XMLNode* node) { vector tileIDs; vector frameDurations; @@ -293,7 +285,7 @@ PRIVATE STATIC void TiledMapReader::ParseTileAnimation(int tileID, int firstgid, tilesetPtr->AddTileAnimSequence(tileID, &Scene::TileSpriteInfos[tileID], tileIDs, frameDurations); } -PRIVATE STATIC void TiledMapReader::ParseTile(Tileset* tilesetPtr, XMLNode* node) { +void TiledMapReader::ParseTile(Tileset* tilesetPtr, XMLNode* node) { if (!tilesetPtr) return; @@ -307,7 +299,7 @@ PRIVATE STATIC void TiledMapReader::ParseTile(Tileset* tilesetPtr, XMLNode* node } } -PRIVATE STATIC void TiledMapReader::LoadTileset(XMLNode* tileset, const char* parentFolder) { +void TiledMapReader::LoadTileset(XMLNode* tileset, const char* parentFolder) { int firstgid = (int)XMLParser::TokenToNumber(tileset->attributes.Get("firstgid")); XMLNode* tilesetXML = NULL; @@ -344,7 +336,7 @@ PRIVATE STATIC void TiledMapReader::LoadTileset(XMLNode* tileset, const char* pa XMLParser::Free(tilesetXML); } -PRIVATE STATIC bool TiledMapReader::ParseLayer(XMLNode* layer) { +bool TiledMapReader::ParseLayer(XMLNode* layer) { int layer_width = (int)XMLParser::TokenToNumber(layer->attributes.Get("width")); int layer_height = (int)XMLParser::TokenToNumber(layer->attributes.Get("height")); @@ -457,7 +449,7 @@ PRIVATE STATIC bool TiledMapReader::ParseLayer(XMLNode* layer) { return true; } -PRIVATE STATIC bool TiledMapReader::ParseObjectGroup(XMLNode* objectgroup) { +bool TiledMapReader::ParseObjectGroup(XMLNode* objectgroup) { for (size_t o = 0; o < objectgroup->children.size(); o++) { XMLNode* object = objectgroup->children[o]; Token object_type = object->attributes.Get("name"); @@ -522,7 +514,7 @@ PRIVATE STATIC bool TiledMapReader::ParseObjectGroup(XMLNode* objectgroup) { return true; } -PRIVATE STATIC bool TiledMapReader::ParseGroupable(XMLNode* node) { +bool TiledMapReader::ParseGroupable(XMLNode* node) { if (XMLParser::MatchToken(node->name, "layer")) { if (!ParseLayer(node)) return false; @@ -539,7 +531,7 @@ PRIVATE STATIC bool TiledMapReader::ParseGroupable(XMLNode* node) { return true; } -PRIVATE STATIC bool TiledMapReader::ParseGroup(XMLNode* group) { +bool TiledMapReader::ParseGroup(XMLNode* group) { // TODO: Read and store these groups if they can be relevant. for (size_t i = 0; i < group->children.size(); i++) { if (!ParseGroupable(group->children[i])) { @@ -550,7 +542,7 @@ PRIVATE STATIC bool TiledMapReader::ParseGroup(XMLNode* group) { return true; } -PUBLIC STATIC void TiledMapReader::Read(const char* sourceF, const char* parentFolder) { +void TiledMapReader::Read(const char* sourceF, const char* parentFolder) { XMLNode* tileMapXML = XMLParser::ParseFromResource(sourceF); if (!tileMapXML) { Log::Print(Log::LOG_ERROR, "Could not parse from resource \"%s\"", sourceF); diff --git a/source/Engine/ResourceTypes/SoundFormats/OGG.cpp b/source/Engine/ResourceTypes/SoundFormats/OGG.cpp index cf1f6bda..4449937b 100644 --- a/source/Engine/ResourceTypes/SoundFormats/OGG.cpp +++ b/source/Engine/ResourceTypes/SoundFormats/OGG.cpp @@ -1,16 +1,3 @@ -#if INTERFACE -#include -#include - -#include - -class OGG : public SoundFormat { -private: - // OGG Specific - char Vorbis[0x800]; -}; -#endif - #include #include @@ -45,11 +32,11 @@ struct VorbisGroup { }; #endif -PRIVATE STATIC size_t OGG::StaticRead(void* mem, size_t size, size_t nmemb, void* ptr) { +size_t OGG::StaticRead(void* mem, size_t size, size_t nmemb, void* ptr) { class Stream* stream = (class Stream*)ptr; return stream->ReadBytes(mem, size * nmemb); } -PRIVATE STATIC Sint32 OGG::StaticSeek(void* ptr, Sint64 offset, int whence) { +Sint32 OGG::StaticSeek(void* ptr, Sint64 offset, int whence) { class Stream* stream = (class Stream*)ptr; if (whence == SEEK_CUR) { stream->Skip((Sint64)offset); @@ -68,17 +55,17 @@ PRIVATE STATIC Sint32 OGG::StaticSeek(void* ptr, Sint64 offset, int whence) return -1; } } -PRIVATE STATIC Sint32 OGG::StaticCloseFree(void* ptr) { +Sint32 OGG::StaticCloseFree(void* ptr) { return 0; } -PRIVATE STATIC Sint32 OGG::StaticCloseNoFree(void* ptr) { +Sint32 OGG::StaticCloseNoFree(void* ptr) { return 0; } -PRIVATE STATIC long OGG::StaticTell(void* ptr) { +long OGG::StaticTell(void* ptr) { return ((class Stream*)ptr)->Position(); } -PUBLIC STATIC SoundFormat* OGG::Load(const char* filename) { +SoundFormat* OGG::Load(const char* filename) { VorbisGroup* vorbis; OGG* ogg = NULL; @@ -268,7 +255,7 @@ PUBLIC STATIC SoundFormat* OGG::Load(const char* filename) { return ogg; } -PUBLIC size_t OGG::SeekSample(int index) { +size_t OGG::SeekSample(int index) { VorbisGroup* vorbis = (VorbisGroup*)this->Vorbis; #ifdef USING_LIBOGG ov_pcm_seek(&vorbis->File, index); @@ -279,7 +266,7 @@ PUBLIC size_t OGG::SeekSample(int index) { SampleIndex = (size_t)index; return SampleIndex; } -PUBLIC int OGG::LoadSamples(size_t count) { +int OGG::LoadSamples(size_t count) { if (SampleBuffer == NULL) { SampleBuffer = (Uint8*)Memory::TrackedMalloc("SoundData::SampleBuffer", TotalPossibleSamples * SampleSize); Samples.reserve(TotalPossibleSamples); @@ -287,7 +274,7 @@ PUBLIC int OGG::LoadSamples(size_t count) { return GetSamples(SampleBuffer, count, -1); } -PUBLIC int OGG::GetSamples(Uint8* buffer, size_t count, Sint32 loopIndex) { +int OGG::GetSamples(Uint8* buffer, size_t count, Sint32 loopIndex) { #ifdef USING_LIBOGG int read; Uint32 total = 0, @@ -379,7 +366,7 @@ PUBLIC int OGG::GetSamples(Uint8* buffer, size_t count, Sint32 l #endif return 0; } -PUBLIC VIRTUAL void OGG::LoadAllSamples() { +void OGG::LoadAllSamples() { if (SampleBuffer == nullptr) { SampleBuffer = (Uint8*)Memory::TrackedMalloc("SoundData::SampleBuffer", TotalPossibleSamples * SampleSize); Samples.reserve(TotalPossibleSamples); @@ -402,7 +389,7 @@ PUBLIC VIRTUAL void OGG::LoadAllSamples() { } } -PUBLIC void OGG::Dispose() { +void OGG::Dispose() { #ifdef USING_LIBOGG // OGG specific clean up functions VorbisGroup* vorbis = (VorbisGroup*)this->Vorbis; diff --git a/source/Engine/ResourceTypes/SoundFormats/SoundFormat.cpp b/source/Engine/ResourceTypes/SoundFormats/SoundFormat.cpp index 3b61a709..f5f882a0 100644 --- a/source/Engine/ResourceTypes/SoundFormats/SoundFormat.cpp +++ b/source/Engine/ResourceTypes/SoundFormats/SoundFormat.cpp @@ -1,33 +1,13 @@ -#if INTERFACE -#include -#include -#include - -class SoundFormat { -public: - // Common - Stream* StreamPtr = NULL; - SDL_AudioSpec InputFormat; - - vector Samples; - size_t SampleSize; - size_t SampleIndex = 0; - - int TotalPossibleSamples; - Uint8* SampleBuffer = NULL; -}; -#endif - #include #include #include #include -PUBLIC VIRTUAL int SoundFormat::LoadSamples(size_t count) { +int SoundFormat::LoadSamples(size_t count) { return 0; } -PUBLIC VIRTUAL int SoundFormat::GetSamples(Uint8* buffer, size_t count, Sint32 loopIndex) { +int SoundFormat::GetSamples(Uint8* buffer, size_t count, Sint32 loopIndex) { if (SampleIndex >= Samples.size()) { if (LoadSamples(count) == 0) // If we've reached end of file return 0; @@ -45,18 +25,18 @@ PUBLIC VIRTUAL int SoundFormat::GetSamples(Uint8* buffer, size_t count, Sint3 SampleIndex += samplecount; return (int)samplecount; } -PUBLIC VIRTUAL size_t SoundFormat::SeekSample(int index) { +size_t SoundFormat::SeekSample(int index) { SampleIndex = (size_t)index; return SampleIndex; } -PUBLIC VIRTUAL size_t SoundFormat::TellSample() { +size_t SoundFormat::TellSample() { return SampleIndex; } -PUBLIC VIRTUAL void SoundFormat::LoadAllSamples() { +void SoundFormat::LoadAllSamples() { LoadSamples(TotalPossibleSamples - Samples.size()); } -PUBLIC void SoundFormat::CopySamples(SoundFormat* dest) { +void SoundFormat::CopySamples(SoundFormat* dest) { // Load the entire sound if (Samples.size() < TotalPossibleSamples) { LoadAllSamples(); @@ -73,34 +53,34 @@ PUBLIC void SoundFormat::CopySamples(SoundFormat* dest) { dest->InputFormat = InputFormat; } -PUBLIC VIRTUAL double SoundFormat::GetPosition() { +double SoundFormat::GetPosition() { return (double)SampleIndex / InputFormat.freq; } -PUBLIC VIRTUAL double SoundFormat::SetPosition(double seconds) { +double SoundFormat::SetPosition(double seconds) { SampleIndex = (size_t)(seconds * InputFormat.freq); return GetPosition(); } -PUBLIC VIRTUAL double SoundFormat::GetDuration() { +double SoundFormat::GetDuration() { return (double)TotalPossibleSamples / InputFormat.freq; } -PROTECTED void SoundFormat::LoadFinish() { +void SoundFormat::LoadFinish() { SampleIndex = 0; SampleSize = ((InputFormat.format & 0xFF) >> 3) * InputFormat.channels; SampleBuffer = NULL; } -PUBLIC VIRTUAL SoundFormat::~SoundFormat() { +SoundFormat::~SoundFormat() { // Do not add anything to a base class' destructor. } -PUBLIC VIRTUAL void SoundFormat::Close() { +void SoundFormat::Close() { if (StreamPtr) { StreamPtr->Close(); StreamPtr = NULL; } } -PUBLIC VIRTUAL void SoundFormat::Dispose() { +void SoundFormat::Dispose() { Samples.clear(); Samples.shrink_to_fit(); diff --git a/source/Engine/ResourceTypes/SoundFormats/WAV.cpp b/source/Engine/ResourceTypes/SoundFormats/WAV.cpp index 6c6d2730..8c4c0ee6 100644 --- a/source/Engine/ResourceTypes/SoundFormats/WAV.cpp +++ b/source/Engine/ResourceTypes/SoundFormats/WAV.cpp @@ -1,16 +1,3 @@ -#if INTERFACE -#include -#include - -#include - -class WAV : public SoundFormat { -private: - // WAV Specific - int DataStart = 0; -}; -#endif - #include #include @@ -48,7 +35,7 @@ struct WAVheader { Uint8 OverflowBuffer[64]; }; -PUBLIC STATIC SoundFormat* WAV::Load(const char* filename) { +SoundFormat* WAV::Load(const char* filename) { WAV* wav = NULL; class Stream* stream = ResourceStream::New(filename); if (!stream) { @@ -111,7 +98,7 @@ PUBLIC STATIC SoundFormat* WAV::Load(const char* filename) { return wav; } -PUBLIC int WAV::LoadSamples(size_t count) { +int WAV::LoadSamples(size_t count) { size_t read, bytesForSample = 0, total = 0; @@ -146,7 +133,7 @@ PUBLIC int WAV::LoadSamples(size_t count) { return (int)total; } -PUBLIC void WAV::Dispose() { +void WAV::Dispose() { // WAV specific clean up functions // Common cleanup SoundFormat::Dispose(); diff --git a/source/Engine/Scene.cpp b/source/Engine/Scene.cpp index 318fbb4c..62da3673 100644 --- a/source/Engine/Scene.cpp +++ b/source/Engine/Scene.cpp @@ -1,138 +1,3 @@ -#if INTERFACE -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -need_t Entity; - -class Scene { -public: - static int ShowTileCollisionFlag; - static int ShowObjectRegions; - - static HashMap* Properties; - - static HashMap* ObjectLists; - static HashMap* ObjectRegistries; - - static HashMap* StaticObjectLists; - - static int StaticObjectCount; - static Entity* StaticObjectFirst; - static Entity* StaticObjectLast; - static int DynamicObjectCount; - static Entity* DynamicObjectFirst; - static Entity* DynamicObjectLast; - - static int ObjectCount; - static Entity* ObjectFirst; - static Entity* ObjectLast; - - static int BasePriorityPerLayer; - static int PriorityPerLayer; - static DrawGroupList* PriorityLists; - - static vector Tilesets; - static vector TileSpriteInfos; - static Uint16 EmptyTile; - - static vector Layers; - static bool AnyLayerTileChange; - - static int TileCount; - static int TileWidth; - static int TileHeight; - static int BaseTileCount; - static int BaseTilesetCount; - static bool TileCfgLoaded; - static vector TileCfg; - - static vector SpriteList; - static vector ImageList; - static vector SoundList; - static vector MusicList; - static vector ModelList; - static vector MediaList; - static vector TextureList; - static vector AnimatorList; - - static int Frame; - static bool Paused; - static bool Loaded; - static int TileAnimationEnabled; - - static View Views[MAX_SCENE_VIEWS]; - static int ViewCurrent; - static int ViewsActive; - - static int CurrentDrawGroup; - - static int ObjectViewRenderFlag; - static int TileViewRenderFlag; - - static Perf_ViewRender PERF_ViewRender[MAX_SCENE_VIEWS]; - - static char NextScene[256]; - static char CurrentScene[256]; - static bool DoRestart; - static bool NoPersistency; - - static int TimeEnabled; - static int TimeCounter; - static int Minutes; - static int Seconds; - static int Milliseconds; - - static int Filter; - - static int CurrentSceneInList; - static char CurrentFolder[256]; - static char CurrentID[256]; - static char CurrentResourceFolder[256]; - static char CurrentCategory[256]; - static int ActiveCategory; - - static int DebugMode; - - static float CollisionTolerance; - static bool UseCollisionOffset; - static float CollisionMaskAir; - static CollisionBox CollisionOuter; - static CollisionBox CollisionInner; - static Entity* CollisionEntity; - static CollisionSensor Sensors[6]; - static float CollisionMinimumDistance; - static float LowCollisionTolerance; - static float HighCollisionTolerance; - static int FloorAngleTolerance; - static int WallAngleTolerance; - static int RoofAngleTolerance; - static bool ShowHitboxes; - static int DebugHitboxCount; - static DebugHitboxInfo DebugHitboxList[DEBUG_HITBOX_COUNT]; -}; -#endif - #include #include @@ -503,7 +368,7 @@ void UpdateObject(Entity* ent) { } // Double linked-list functions -PUBLIC STATIC void Scene::Add(Entity** first, Entity** last, int* count, Entity* obj) { +void Scene::Add(Entity** first, Entity** last, int* count, Entity* obj) { // Set "prev" of obj to last obj->PrevEntity = (*last); obj->NextEntity = NULL; @@ -529,7 +394,7 @@ PUBLIC STATIC void Scene::Add(Entity** first, Entity** last, int* count, Entity* Scene::AddToScene(obj); } -PUBLIC STATIC void Scene::Remove(Entity** first, Entity** last, int* count, Entity* obj) { +void Scene::Remove(Entity** first, Entity** last, int* count, Entity* obj) { if (obj == NULL) return; if (obj->Removed) return; @@ -549,7 +414,7 @@ PUBLIC STATIC void Scene::Remove(Entity** first, Entity** last, int* count, Enti Scene::RemoveObject(obj); } -PUBLIC STATIC void Scene::AddToScene(Entity* obj) { +void Scene::AddToScene(Entity* obj) { obj->PrevSceneEntity = Scene::ObjectLast; obj->NextSceneEntity = NULL; @@ -561,7 +426,7 @@ PUBLIC STATIC void Scene::AddToScene(Entity* obj) { Scene::ObjectLast = obj; Scene::ObjectCount++; } -PUBLIC STATIC void Scene::RemoveFromScene(Entity* obj) { +void Scene::RemoveFromScene(Entity* obj) { if (Scene::ObjectFirst == obj) Scene::ObjectFirst = obj->NextSceneEntity; if (Scene::ObjectLast == obj) @@ -576,7 +441,7 @@ PUBLIC STATIC void Scene::RemoveFromScene(Entity* obj) { Scene::ObjectCount--; } -PRIVATE STATIC void Scene::RemoveObject(Entity* obj) { +void Scene::RemoveObject(Entity* obj) { // Remove from proper list if (obj->List) obj->List->Remove(obj); @@ -604,20 +469,20 @@ PRIVATE STATIC void Scene::RemoveObject(Entity* obj) { // won't be in any object list or draw groups at this point. obj->Remove(); } -PUBLIC STATIC void Scene::Clear(Entity** first, Entity** last, int* count) { +void Scene::Clear(Entity** first, Entity** last, int* count) { (*first) = NULL; (*last) = NULL; (*count) = 0; } // Object management -PUBLIC STATIC void Scene::AddStatic(ObjectList* objectList, Entity* obj) { +void Scene::AddStatic(ObjectList* objectList, Entity* obj) { Scene::Add(&Scene::StaticObjectFirst, &Scene::StaticObjectLast, &Scene::StaticObjectCount, obj); } -PUBLIC STATIC void Scene::AddDynamic(ObjectList* objectList, Entity* obj) { +void Scene::AddDynamic(ObjectList* objectList, Entity* obj) { Scene::Add(&Scene::DynamicObjectFirst, &Scene::DynamicObjectLast, &Scene::DynamicObjectCount, obj); } -PUBLIC STATIC void Scene::DeleteRemoved(Entity* obj) { +void Scene::DeleteRemoved(Entity* obj) { if (!obj->Removed) return; @@ -625,7 +490,7 @@ PUBLIC STATIC void Scene::DeleteRemoved(Entity* obj) { delete obj; } -PUBLIC STATIC void Scene::OnEvent(Uint32 event) { +void Scene::OnEvent(Uint32 event) { switch (event) { case SDL_APP_TERMINATING: case SDL_APP_LOWMEMORY: @@ -641,7 +506,7 @@ PUBLIC STATIC void Scene::OnEvent(Uint32 event) { } // Scene List Functions -PUBLIC STATIC void Scene::SetCurrent(const char* categoryName, const char* sceneName) { +void Scene::SetCurrent(const char* categoryName, const char* sceneName) { int categoryID = SceneInfo::GetCategoryID(categoryName); if (categoryID < 0) return; @@ -658,7 +523,7 @@ PUBLIC STATIC void Scene::SetCurrent(const char* categoryName, const char* scene else Scene::CurrentSceneInList = category.OffsetStart; } -PUBLIC STATIC void Scene::SetInfoFromCurrentID() { +void Scene::SetInfoFromCurrentID() { if (!SceneInfo::IsCategoryValid(Scene::ActiveCategory)) return; @@ -678,7 +543,7 @@ PUBLIC STATIC void Scene::SetInfoFromCurrentID() { } // Scene Lifecycle -PUBLIC STATIC void Scene::Init() { +void Scene::Init() { Scene::NextScene[0] = '\0'; Scene::CurrentScene[0] = '\0'; @@ -731,7 +596,7 @@ PUBLIC STATIC void Scene::Init() { if (ScriptManager::LoadAllClasses) ScriptManager::LoadClasses(); } -PUBLIC STATIC void Scene::InitObjectListsAndRegistries() { +void Scene::InitObjectListsAndRegistries() { if (Scene::ObjectLists == NULL) Scene::ObjectLists = new HashMap(CombinedHash::EncryptData, 4); if (Scene::ObjectRegistries == NULL) @@ -740,14 +605,14 @@ PUBLIC STATIC void Scene::InitObjectListsAndRegistries() { Scene::StaticObjectLists = new HashMap(CombinedHash::EncryptData, 4); } -PUBLIC STATIC void Scene::ResetPerf() { +void Scene::ResetPerf() { if (Scene::ObjectLists) { Scene::ObjectLists->ForAll([](Uint32, ObjectList* list) -> void { list->ResetPerf(); }); } } -PUBLIC STATIC void Scene::Update() { +void Scene::Update() { // Animate tiles Scene::RunTileAnimations(); @@ -819,20 +684,20 @@ PUBLIC STATIC void Scene::Update() { Scene::ProcessSceneTimer(); } } -PRIVATE STATIC void Scene::RunTileAnimations() { +void Scene::RunTileAnimations() { if ((Scene::TileAnimationEnabled == 1 && !Scene::Paused) || Scene::TileAnimationEnabled == 2) { for (Tileset& tileset : Scene::Tilesets) tileset.RunAnimations(); } } -PUBLIC STATIC Tileset* Scene::GetTileset(int tileID) { +Tileset* Scene::GetTileset(int tileID) { for (Tileset& tileset : Scene::Tilesets) { if (tileID >= tileset.StartTile) return &tileset; } return nullptr; } -PUBLIC STATIC TileAnimator* Scene::GetTileAnimator(int tileID) { +TileAnimator* Scene::GetTileAnimator(int tileID) { for (Tileset& tileset : Scene::Tilesets) { TileAnimator* animator = tileset.GetTileAnimSequence(tileID); if (animator) @@ -840,7 +705,7 @@ PUBLIC STATIC TileAnimator* Scene::GetTileAnimator(int tileID) { } return nullptr; } -PUBLIC STATIC void Scene::SetViewActive(int viewIndex, bool active) { +void Scene::SetViewActive(int viewIndex, bool active) { if (Scene::Views[viewIndex].Active == active) return; @@ -852,12 +717,12 @@ PUBLIC STATIC void Scene::SetViewActive(int viewIndex, bool active) { Scene::SortViews(); } -PUBLIC STATIC void Scene::SetViewPriority(int viewIndex, int priority) { +void Scene::SetViewPriority(int viewIndex, int priority) { Scene::Views[viewIndex].Priority = priority; Scene::SortViews(); } -PRIVATE STATIC void Scene::ResetViews() { +void Scene::ResetViews() { Scene::ViewsActive = 0; // Deactivate extra views @@ -869,7 +734,7 @@ PRIVATE STATIC void Scene::ResetViews() { Scene::SetViewActive(0, true); } -PUBLIC STATIC void Scene::SortViews() { +void Scene::SortViews() { int count = 0; for (int i = 0; i < MAX_SCENE_VIEWS; i++) { @@ -886,7 +751,7 @@ PUBLIC STATIC void Scene::SortViews() { } } -PUBLIC STATIC void Scene::SetView(int viewIndex) { +void Scene::SetView(int viewIndex) { View* currentView = &Scene::Views[viewIndex]; Graphics::CurrentView = currentView; @@ -915,7 +780,7 @@ PUBLIC STATIC void Scene::SetView(int viewIndex) { Scene::ViewCurrent = viewIndex; } -PUBLIC STATIC bool Scene::CheckPosOnScreen(float posX, float posY, float rangeX, float rangeY) { +bool Scene::CheckPosOnScreen(float posX, float posY, float rangeX, float rangeY) { if (!posX || !posY || !rangeX || !rangeY) return false; @@ -935,7 +800,7 @@ PUBLIC STATIC bool Scene::CheckPosOnScreen(float posX, float posY, float rangeX, #define PERF_START(n) if (viewPerf) viewPerf->n = Clock::GetTicks() #define PERF_END(n) if (viewPerf) viewPerf->n = Clock::GetTicks() - viewPerf->n -PUBLIC STATIC void Scene::RenderView(int viewIndex, bool doPerf) { +void Scene::RenderView(int viewIndex, bool doPerf) { View* currentView = &Scene::Views[viewIndex]; Perf_ViewRender* viewPerf = doPerf ? &Scene::PERF_ViewRender[viewIndex] : NULL; @@ -1185,7 +1050,7 @@ PUBLIC STATIC void Scene::RenderView(int viewIndex, bool doPerf) { PERF_END(RenderFinishTime); } -PUBLIC STATIC void Scene::Render() { +void Scene::Render() { if (!Scene::PriorityLists) return; @@ -1287,7 +1152,7 @@ PUBLIC STATIC void Scene::Render() { Scene::ViewCurrent = -1; } -PUBLIC STATIC void Scene::AfterScene() { +void Scene::AfterScene() { ScriptManager::ResetStack(); ScriptManager::RequestGarbageCollection(); @@ -1310,29 +1175,29 @@ PUBLIC STATIC void Scene::AfterScene() { } } -PRIVATE STATIC void Scene::Iterate(Entity* first, std::function func) { +void Scene::Iterate(Entity* first, std::function func) { for (Entity* ent = first, *next; ent; ent = next) { next = ent->NextEntity; func(ent); } } -PRIVATE STATIC void Scene::IterateAll(Entity* first, std::function func) { +void Scene::IterateAll(Entity* first, std::function func) { for (Entity* ent = first, *next; ent; ent = next) { next = ent->NextSceneEntity; func(ent); } } -PRIVATE STATIC void Scene::ResetPriorityListIndex(Entity* first) { +void Scene::ResetPriorityListIndex(Entity* first) { Scene::Iterate(first, [](Entity* ent) -> void { ent->PriorityListIndex = -1; }); } -PRIVATE STATIC int Scene::GetPersistenceScopeForObjectDeletion() { +int Scene::GetPersistenceScopeForObjectDeletion() { return Scene::NoPersistency ? Persistence_SCENE : Persistence_NONE; } -PUBLIC STATIC void Scene::Restart() { +void Scene::Restart() { Scene::ViewCurrent = 0; Graphics::CurrentView = NULL; @@ -1470,7 +1335,7 @@ PUBLIC STATIC void Scene::Restart() { ScriptManager::ResetStack(); ScriptManager::RequestGarbageCollection(); } -PRIVATE STATIC void Scene::ClearPriorityLists() { +void Scene::ClearPriorityLists() { if (!Scene::PriorityLists) return; @@ -1482,14 +1347,14 @@ PRIVATE STATIC void Scene::ClearPriorityLists() { ResetPriorityListIndex(Scene::StaticObjectFirst); ResetPriorityListIndex(Scene::DynamicObjectFirst); } -PRIVATE STATIC void Scene::DeleteObjects(Entity** first, Entity** last, int* count) { +void Scene::DeleteObjects(Entity** first, Entity** last, int* count) { Scene::Iterate(*first, [](Entity* ent) -> void { // Garbage collection will take care of it later. Scene::RemoveObject(ent); }); Scene::Clear(first, last, count); } -PRIVATE STATIC void Scene::RemoveNonPersistentObjects(Entity** first, Entity** last, int* count) { +void Scene::RemoveNonPersistentObjects(Entity** first, Entity** last, int* count) { int persistencyScope = Scene::GetPersistenceScopeForObjectDeletion(); for (Entity* ent = *first, *next; ent; ent = next) { next = ent->NextEntity; @@ -1497,7 +1362,7 @@ PRIVATE STATIC void Scene::RemoveNonPersistentObjects(Entity** first, Entity** l Scene::Remove(first, last, count, ent); } } -PRIVATE STATIC void Scene::DeleteAllObjects() { +void Scene::DeleteAllObjects() { // Dispose and clear Static objects Scene::DeleteObjects(&Scene::StaticObjectFirst, &Scene::StaticObjectLast, &Scene::StaticObjectCount); @@ -1518,7 +1383,7 @@ PRIVATE STATIC void Scene::DeleteAllObjects() { }); } } -PUBLIC STATIC void Scene::LoadScene(const char* filename) { +void Scene::LoadScene(const char* filename) { // Remove non-persistent objects from lists if (Scene::ObjectLists) { Scene::ObjectLists->ForAll([](Uint32, ObjectList* list) -> void { @@ -1651,7 +1516,7 @@ PUBLIC STATIC void Scene::LoadScene(const char* filename) { Scene::Loaded = false; } -PUBLIC STATIC void Scene::ProcessSceneTimer() { +void Scene::ProcessSceneTimer() { if (Scene::TimeEnabled) { Scene::TimeCounter += 100; @@ -1672,13 +1537,13 @@ PUBLIC STATIC void Scene::ProcessSceneTimer() { } } -PUBLIC STATIC ObjectList* Scene::NewObjectList(const char* objectName) { +ObjectList* Scene::NewObjectList(const char* objectName) { ObjectList* objectList = new (std::nothrow) ObjectList(objectName); if (objectList && ScriptManager::LoadObjectClass(objectName, true)) objectList->SpawnFunction = ScriptManager::ObjectSpawnFunction; return objectList; } -PRIVATE STATIC void Scene::AddStaticClass() { +void Scene::AddStaticClass() { StaticObjectList = Scene::NewObjectList("Static"); if (!StaticObjectList->SpawnFunction) return; @@ -1697,11 +1562,11 @@ PRIVATE STATIC void Scene::AddStaticClass() { StaticObject = obj; } -PRIVATE STATIC void Scene::CallGameStart() { +void Scene::CallGameStart() { if (StaticObject) StaticObject->GameStart(); } -PUBLIC STATIC ObjectList* Scene::GetObjectList(const char* objectName, bool callListLoadFunction) { +ObjectList* Scene::GetObjectList(const char* objectName, bool callListLoadFunction) { Uint32 objectNameHash = Scene::ObjectLists->HashFunction(objectName, strlen(objectName)); ObjectList* objectList; @@ -1717,10 +1582,10 @@ PUBLIC STATIC ObjectList* Scene::GetObjectList(const char* objectName, bool call return objectList; } -PUBLIC STATIC ObjectList* Scene::GetObjectList(const char* objectName) { +ObjectList* Scene::GetObjectList(const char* objectName) { return GetObjectList(objectName, true); } -PUBLIC STATIC ObjectList* Scene::GetStaticObjectList(const char* objectName) { +ObjectList* Scene::GetStaticObjectList(const char* objectName) { ObjectList* objectList; if (Scene::StaticObjectLists->Exists(objectName)) { @@ -1743,7 +1608,7 @@ PUBLIC STATIC ObjectList* Scene::GetStaticObjectList(const char* objectName) { return objectList; } -PRIVATE STATIC void Scene::SpawnStaticObject(const char* objectName) { +void Scene::SpawnStaticObject(const char* objectName) { ObjectList* objectList = Scene::GetObjectList(objectName, false); if (objectList->SpawnFunction) { Entity* obj = objectList->Spawn(); @@ -1757,13 +1622,13 @@ PRIVATE STATIC void Scene::SpawnStaticObject(const char* objectName) { Scene::AddStatic(objectList, obj); } } -PUBLIC STATIC void Scene::AddManagers() { +void Scene::AddManagers() { Scene::SpawnStaticObject("WindowManager"); Scene::SpawnStaticObject("InputManager"); Scene::SpawnStaticObject("FadeManager"); } -PUBLIC STATIC void Scene::FreePriorityLists() { +void Scene::FreePriorityLists() { if (Scene::PriorityLists) { for (int i = Scene::PriorityPerLayer - 1; i >= 0; i--) { Scene::PriorityLists[i].Dispose(); @@ -1773,7 +1638,7 @@ PUBLIC STATIC void Scene::FreePriorityLists() { Scene::PriorityLists = NULL; Scene::PriorityPerLayer = 0; } -PUBLIC STATIC void Scene::InitPriorityLists() { +void Scene::InitPriorityLists() { if (Scene::PriorityPerLayer == 0) Scene::PriorityPerLayer = Scene::BasePriorityPerLayer; @@ -1792,7 +1657,7 @@ PUBLIC STATIC void Scene::InitPriorityLists() { for (int i = Scene::PriorityPerLayer - 1; i >= 0; i--) Scene::PriorityLists[i].Init(); } -PUBLIC STATIC void Scene::SetPriorityPerLayer(int count) { +void Scene::SetPriorityPerLayer(int count) { if (count < 1) count = 1; else if (count > 256) @@ -1814,7 +1679,7 @@ PUBLIC STATIC void Scene::SetPriorityPerLayer(int count) { Scene::PriorityPerLayer = count; } -PRIVATE STATIC void Scene::ReadRSDKTile(TileConfig* tile, Uint8* line) { +void Scene::ReadRSDKTile(TileConfig* tile, Uint8* line) { int bufferPos = 0; Uint8 collisionHeights[16]; @@ -1999,7 +1864,7 @@ PRIVATE STATIC void Scene::ReadRSDKTile(TileConfig* tile, Uint8* line) { tileDest->CollisionBottom[xD] = tile->CollisionTop[xS] ^ 15; } } -PRIVATE STATIC void Scene::LoadRSDKTileConfig(int tilesetID, Stream* tileColReader) { +void Scene::LoadRSDKTileConfig(int tilesetID, Stream* tileColReader) { Uint32 tileCount = 0x400; Uint8* tileData = (Uint8*)Memory::Calloc(1, tileCount * 2 * 0x26); @@ -2033,7 +1898,7 @@ PRIVATE STATIC void Scene::LoadRSDKTileConfig(int tilesetID, Stream* tileColRead Memory::Free(tileData); } -PRIVATE STATIC void Scene::LoadHCOLTileConfig(size_t tilesetID, Stream* tileColReader) { +void Scene::LoadHCOLTileConfig(size_t tilesetID, Stream* tileColReader) { if (!Scene::Tilesets.size() || tilesetID >= Scene::Tilesets.size()) return; @@ -2240,7 +2105,7 @@ PRIVATE STATIC void Scene::LoadHCOLTileConfig(size_t tilesetID, Stream* tileColR } } } -PRIVATE STATIC void Scene::InitTileCollisions() { +void Scene::InitTileCollisions() { if (Scene::TileCount == 0) { size_t tileCount = 0x400; @@ -2265,7 +2130,7 @@ PRIVATE STATIC void Scene::InitTileCollisions() { Scene::TileCfg.push_back(tileCfgA); Scene::TileCfg.push_back(tileCfgB); } -PRIVATE STATIC void Scene::ClearTileCollisions(TileConfig* cfg, size_t numTiles) { +void Scene::ClearTileCollisions(TileConfig* cfg, size_t numTiles) { for (size_t i = 0; i < numTiles; i++) { TileConfig* tile = &cfg[i]; memset(tile->CollisionTop, 16, 16); @@ -2274,7 +2139,7 @@ PRIVATE STATIC void Scene::ClearTileCollisions(TileConfig* cfg, size_t numTiles) memset(tile->CollisionRight, 16, 16); } } -PUBLIC STATIC bool Scene::AddTileset(char* path) { +bool Scene::AddTileset(char* path) { ISprite* tileSprite = new ISprite(); Texture* spriteSheet = tileSprite->AddSpriteSheet(path); if (!spriteSheet) { @@ -2310,7 +2175,7 @@ PUBLIC STATIC bool Scene::AddTileset(char* path) { return true; } -PRIVATE STATIC void Scene::SetTileCount(size_t tileCount) { +void Scene::SetTileCount(size_t tileCount) { vector configFlipX; vector configFlipY; vector configFlipXY; @@ -2357,7 +2222,7 @@ PRIVATE STATIC void Scene::SetTileCount(size_t tileCount) { Scene::TileCount = tileCount; } -PUBLIC STATIC void Scene::LoadTileCollisions(const char* filename, size_t tilesetID) { +void Scene::LoadTileCollisions(const char* filename, size_t tilesetID) { if (!ResourceManager::ResourceExists(filename)) { Log::Print(Log::LOG_WARN, "Could not find tile collision file \"%s\"!", filename); return; @@ -2382,7 +2247,7 @@ PUBLIC STATIC void Scene::LoadTileCollisions(const char* filename, size_t tilese tileColReader->Close(); } -PUBLIC STATIC void Scene::UnloadTileCollisions() { +void Scene::UnloadTileCollisions() { for (size_t i = 0; i < Scene::TileCfg.size(); i++) Memory::Free(Scene::TileCfg[i]); @@ -2393,7 +2258,7 @@ PUBLIC STATIC void Scene::UnloadTileCollisions() { // Resource Management // return true if we found it in the list -PUBLIC STATIC bool Scene::GetResourceListSpace(vector* list, ResourceType* resource, size_t& index, bool& foundEmpty) { +bool Scene::GetResourceListSpace(vector* list, ResourceType* resource, size_t& index, bool& foundEmpty) { foundEmpty = false; index = list->size(); for (size_t i = 0, listSz = list->size(); i < listSz; i++) { @@ -2413,7 +2278,7 @@ PUBLIC STATIC bool Scene::GetResourceListSpace(vector* list, Reso return false; } -PUBLIC STATIC bool Scene::GetResource(vector* list, ResourceType* resource, size_t& index) { +bool Scene::GetResource(vector* list, ResourceType* resource, size_t& index) { bool foundEmpty = false; if (GetResourceListSpace(list, resource, index, foundEmpty)) return true; @@ -2424,7 +2289,7 @@ PUBLIC STATIC bool Scene::GetResource(vector* list, ResourceType* return false; } -PUBLIC STATIC ISprite* Scene::GetSpriteResource(int index) { +ISprite* Scene::GetSpriteResource(int index) { if (index < 0 || index >= (int)Scene::SpriteList.size()) return NULL; @@ -2433,7 +2298,7 @@ PUBLIC STATIC ISprite* Scene::GetSpriteResource(int index) { return Scene::SpriteList[index]->AsSprite; } -PUBLIC STATIC void Scene::DisposeInScope(Uint32 scope) { +void Scene::DisposeInScope(Uint32 scope) { // Images for (size_t i = 0, i_sz = Scene::ImageList.size(); i < i_sz; i++) { if (!Scene::ImageList[i]) continue; @@ -2520,7 +2385,7 @@ PUBLIC STATIC void Scene::DisposeInScope(Uint32 scope) { Scene::AnimatorList[i] = NULL; } } -PUBLIC STATIC void Scene::Dispose() { +void Scene::Dispose() { for (int i = 0; i < MAX_SCENE_VIEWS; i++) { if (Scene::Views[i].DrawTarget) { Graphics::DisposeTexture(Scene::Views[i].DrawTarget); @@ -2615,7 +2480,7 @@ PUBLIC STATIC void Scene::Dispose() { Compiler::Dispose(); } -PUBLIC STATIC void Scene::UnloadTilesets() { +void Scene::UnloadTilesets() { for (size_t i = 0; i < Scene::Tilesets.size(); i++) { if (Scene::Tilesets[i].Sprite) delete Scene::Tilesets[i].Sprite; @@ -2627,7 +2492,7 @@ PUBLIC STATIC void Scene::UnloadTilesets() { } // Tile Batching -PUBLIC STATIC void Scene::SetTile(int layer, int x, int y, int tileID, int flip_x, int flip_y, int collA, int collB) { +void Scene::SetTile(int layer, int x, int y, int tileID, int flip_x, int flip_y, int collA, int collB) { Uint32* tile = &Scene::Layers[layer].Tiles[x + (y << Scene::Layers[layer].WidthInBits)]; *tile = tileID & TILE_IDENT_MASK; @@ -2640,7 +2505,7 @@ PUBLIC STATIC void Scene::SetTile(int layer, int x, int y, int tileID, int flip_ } // Tile Collision -PUBLIC STATIC int Scene::CollisionAt(int x, int y, int collisionField, int collideSide, int* angle) { +int Scene::CollisionAt(int x, int y, int collisionField, int collideSide, int* angle) { if (collisionField < 0 || collisionField >= Scene::TileCfg.size()) return -1; @@ -2743,7 +2608,7 @@ PUBLIC STATIC int Scene::CollisionAt(int x, int y, int collisionField, int coll return -1; } -PUBLIC STATIC int Scene::CollisionInLine(int x, int y, int angleMode, int checkLen, int collisionField, bool compareAngle, Sensor* sensor) { +int Scene::CollisionInLine(int x, int y, int angleMode, int checkLen, int collisionField, bool compareAngle, Sensor* sensor) { if (checkLen < 0 || collisionField < 0 || collisionField >= Scene::TileCfg.size()) return -1; @@ -2929,7 +2794,7 @@ PUBLIC STATIC int Scene::CollisionInLine(int x, int y, int angleMode, int checkL return -1; } -PUBLIC STATIC void Scene::SetupCollisionConfig(float minDistance, float lowTolerance, float highTolerance, int floorAngleTolerance, int wallAngleTolerance, int roofAngleTolerance) { +void Scene::SetupCollisionConfig(float minDistance, float lowTolerance, float highTolerance, int floorAngleTolerance, int wallAngleTolerance, int roofAngleTolerance) { CollisionMinimumDistance = minDistance; LowCollisionTolerance = lowTolerance; HighCollisionTolerance = highTolerance; @@ -2938,7 +2803,7 @@ PUBLIC STATIC void Scene::SetupCollisionConfig(float minDistance, float lowToler RoofAngleTolerance = roofAngleTolerance; } -PUBLIC STATIC int Scene::AddDebugHitbox(int type, int dir, Entity* entity, CollisionBox* hitbox) { +int Scene::AddDebugHitbox(int type, int dir, Entity* entity, CollisionBox* hitbox) { int i = 0; for (; i < DebugHitboxCount; ++i) { if (DebugHitboxList[i].hitbox.Left == hitbox->Left && DebugHitboxList[i].hitbox.Top == hitbox->Top @@ -2979,7 +2844,7 @@ PUBLIC STATIC int Scene::AddDebugHitbox(int type, int dir, Entity* entity, Colli return -1; } -PUBLIC STATIC bool Scene::CheckObjectCollisionTouch(Entity* thisEntity, CollisionBox* thisHitbox, Entity* otherEntity, CollisionBox* otherHitbox) { +bool Scene::CheckObjectCollisionTouch(Entity* thisEntity, CollisionBox* thisHitbox, Entity* otherEntity, CollisionBox* otherHitbox) { int store = 0; if (!thisEntity || !otherEntity || !thisHitbox || !otherHitbox) return false; @@ -3038,7 +2903,7 @@ PUBLIC STATIC bool Scene::CheckObjectCollisionTouch(Entity* thisEntity, Collisio return collided; } -PUBLIC STATIC bool Scene::CheckObjectCollisionCircle(Entity* thisEntity, float thisRadius, Entity* otherEntity, float otherRadius) { +bool Scene::CheckObjectCollisionCircle(Entity* thisEntity, float thisRadius, Entity* otherEntity, float otherRadius) { float x = thisEntity->X - otherEntity->X; float y = thisEntity->Y - otherEntity->Y; float r = thisRadius + otherRadius; @@ -3062,7 +2927,7 @@ PUBLIC STATIC bool Scene::CheckObjectCollisionCircle(Entity* thisEntity, float t return x * x + y * y < r * r; } -PUBLIC STATIC bool Scene::CheckObjectCollisionBox(Entity* thisEntity, CollisionBox* thisHitbox, Entity* otherEntity, CollisionBox* otherHitbox, bool setValues) { +bool Scene::CheckObjectCollisionBox(Entity* thisEntity, CollisionBox* thisHitbox, Entity* otherEntity, CollisionBox* otherHitbox, bool setValues) { if (!thisEntity || !otherEntity || !thisHitbox || !otherHitbox) return C_NONE; @@ -3255,7 +3120,7 @@ PUBLIC STATIC bool Scene::CheckObjectCollisionBox(Entity* thisEntity, CollisionB return side; } -PUBLIC STATIC bool Scene::CheckObjectCollisionPlatform(Entity* thisEntity, CollisionBox* thisHitbox, Entity* otherEntity, CollisionBox* otherHitbox, bool setValues) { +bool Scene::CheckObjectCollisionPlatform(Entity* thisEntity, CollisionBox* thisHitbox, Entity* otherEntity, CollisionBox* otherHitbox, bool setValues) { int store = 0; bool collided = false; @@ -3363,7 +3228,7 @@ PUBLIC STATIC bool Scene::CheckObjectCollisionPlatform(Entity* thisEntity, Colli return collided; } -PUBLIC STATIC bool Scene::ObjectTileCollision(Entity* entity, int cLayers, int cMode, int cPlane, int xOffset, int yOffset, bool setPos) { +bool Scene::ObjectTileCollision(Entity* entity, int cLayers, int cMode, int cPlane, int xOffset, int yOffset, bool setPos) { int layerID = 1; bool collided = false; int posX = xOffset + entity->X; @@ -3569,7 +3434,7 @@ PUBLIC STATIC bool Scene::ObjectTileCollision(Entity* entity, int cLayers, int c } } -PUBLIC STATIC bool Scene::ObjectTileGrip(Entity* entity, int cLayers, int cMode, int cPlane, float xOffset, float yOffset, float tolerance) { +bool Scene::ObjectTileGrip(Entity* entity, int cLayers, int cMode, int cPlane, float xOffset, float yOffset, float tolerance) { int layerID = 1; bool collided = false; int posX = xOffset + entity->X; @@ -3787,7 +3652,7 @@ PUBLIC STATIC bool Scene::ObjectTileGrip(Entity* entity, int cLayers, int cMode, } } -PUBLIC STATIC void Scene::ProcessObjectMovement(Entity* entity, CollisionBox* outerBox, CollisionBox* innerBox) { +void Scene::ProcessObjectMovement(Entity* entity, CollisionBox* outerBox, CollisionBox* innerBox) { if (entity && outerBox && innerBox) { if (entity->TileCollisions) { entity->Angle &= 0xFF; @@ -3844,7 +3709,7 @@ PUBLIC STATIC void Scene::ProcessObjectMovement(Entity* entity, CollisionBox* ou } } -PUBLIC STATIC void Scene::ProcessPathGrip() { +void Scene::ProcessPathGrip() { float xVel = 0.0; float yVel = 0.0; @@ -4320,7 +4185,7 @@ PUBLIC STATIC void Scene::ProcessPathGrip() { } } -PUBLIC STATIC void Scene::ProcessAirCollision_Down() { +void Scene::ProcessAirCollision_Down() { int movingDown = 0; int movingUp = 0; int movingLeft = 0; @@ -4585,7 +4450,7 @@ PUBLIC STATIC void Scene::ProcessAirCollision_Down() { } } -PUBLIC STATIC void Scene::ProcessAirCollision_Up() { +void Scene::ProcessAirCollision_Up() { int movingDown = 0; int movingUp = 0; int movingLeft = 0; @@ -4850,7 +4715,7 @@ PUBLIC STATIC void Scene::ProcessAirCollision_Up() { } } -PUBLIC STATIC void Scene::SetPathGripSensors(CollisionSensor* sensors) { +void Scene::SetPathGripSensors(CollisionSensor* sensors) { int offset = UseCollisionOffset ? COLLISION_OFFSET : 0.0; switch (CollisionEntity->CollisionMode) { @@ -4918,7 +4783,7 @@ PUBLIC STATIC void Scene::SetPathGripSensors(CollisionSensor* sensors) { } } -PUBLIC STATIC void Scene::FindFloorPosition(CollisionSensor* sensor) { +void Scene::FindFloorPosition(CollisionSensor* sensor) { int x = sensor->X; int y = sensor->Y; int temp; @@ -5018,7 +4883,7 @@ PUBLIC STATIC void Scene::FindFloorPosition(CollisionSensor* sensor) { } } -PUBLIC STATIC void Scene::FindLWallPosition(CollisionSensor* sensor) { +void Scene::FindLWallPosition(CollisionSensor* sensor) { int posX = sensor->X; int posY = sensor->Y; int OGX = sensor->X; @@ -5088,7 +4953,7 @@ PUBLIC STATIC void Scene::FindLWallPosition(CollisionSensor* sensor) { } } -PUBLIC STATIC void Scene::FindRoofPosition(CollisionSensor* sensor) { +void Scene::FindRoofPosition(CollisionSensor* sensor) { int posX = sensor->X; int posY = sensor->Y; int OGX = sensor->X; @@ -5157,7 +5022,7 @@ PUBLIC STATIC void Scene::FindRoofPosition(CollisionSensor* sensor) { } } -PUBLIC STATIC void Scene::FindRWallPosition(CollisionSensor* sensor) { +void Scene::FindRWallPosition(CollisionSensor* sensor) { int posX = sensor->X; int posY = sensor->Y; int OGX = sensor->X; @@ -5227,7 +5092,7 @@ PUBLIC STATIC void Scene::FindRWallPosition(CollisionSensor* sensor) { } } -PUBLIC STATIC void Scene::FloorCollision(CollisionSensor* sensor) { +void Scene::FloorCollision(CollisionSensor* sensor) { int posX = sensor->X; int posY = sensor->Y; int OGX = sensor->X; @@ -5305,7 +5170,7 @@ PUBLIC STATIC void Scene::FloorCollision(CollisionSensor* sensor) { } } -PUBLIC STATIC void Scene::LWallCollision(CollisionSensor* sensor) { +void Scene::LWallCollision(CollisionSensor* sensor) { int posX = sensor->X; int posY = sensor->Y; int OGX = sensor->X; @@ -5366,7 +5231,7 @@ PUBLIC STATIC void Scene::LWallCollision(CollisionSensor* sensor) { } } -PUBLIC STATIC void Scene::RoofCollision(CollisionSensor* sensor) { +void Scene::RoofCollision(CollisionSensor* sensor) { int posX = sensor->X; int posY = sensor->Y; int OGX = sensor->X; @@ -5441,7 +5306,7 @@ PUBLIC STATIC void Scene::RoofCollision(CollisionSensor* sensor) { } } -PUBLIC STATIC void Scene::RWallCollision(CollisionSensor* sensor) { +void Scene::RWallCollision(CollisionSensor* sensor) { int posX = sensor->X; int posY = sensor->Y; int OGX = sensor->X; diff --git a/source/Engine/Scene/SceneInfo.cpp b/source/Engine/Scene/SceneInfo.cpp index b0aa6ab1..c4f8c2c5 100644 --- a/source/Engine/Scene/SceneInfo.cpp +++ b/source/Engine/Scene/SceneInfo.cpp @@ -1,23 +1,10 @@ -#if INTERFACE -#include -#include -#include -#include - -class SceneInfo { -public: - static vector Entries; - static vector Categories; -}; -#endif - #include #include vector SceneInfo::Entries; vector SceneInfo::Categories; -PUBLIC STATIC void SceneInfo::Dispose() { +void SceneInfo::Dispose() { for (size_t i = 0; i < Categories.size(); i++) { Categories[i].Properties->WithAll([](Uint32 hash, char* string) -> void { Memory::Free(string); @@ -39,22 +26,22 @@ PUBLIC STATIC void SceneInfo::Dispose() { Entries.shrink_to_fit(); } -PUBLIC STATIC bool SceneInfo::IsCategoryValid(int categoryID) { +bool SceneInfo::IsCategoryValid(int categoryID) { return categoryID >= 0 && categoryID < (int)Categories.size(); } -PUBLIC STATIC bool SceneInfo::IsEntryValid(int entryID) { +bool SceneInfo::IsEntryValid(int entryID) { return entryID >= 0 && entryID < (int)Entries.size(); } -PUBLIC STATIC bool SceneInfo::IsEntryValidInCategory(size_t categoryID, size_t entryID) { +bool SceneInfo::IsEntryValidInCategory(size_t categoryID, size_t entryID) { if (!IsCategoryValid((int)categoryID)) return false; return entryID >= Categories[categoryID].OffsetStart && entryID < Categories[categoryID].OffsetEnd; } -PUBLIC STATIC int SceneInfo::GetCategoryID(const char* categoryName) { +int SceneInfo::GetCategoryID(const char* categoryName) { for (size_t i = 0; i < Categories.size(); i++) { if (!strcmp(Categories[i].Name, categoryName)) return i; @@ -63,7 +50,7 @@ PUBLIC STATIC int SceneInfo::GetCategoryID(const char* categoryName) { return -1; } -PUBLIC STATIC int SceneInfo::GetEntryID(const char* categoryName, const char* entryName) { +int SceneInfo::GetEntryID(const char* categoryName, const char* entryName) { int categoryID = GetCategoryID(categoryName); if (categoryID < 0) return -1; @@ -72,7 +59,7 @@ PUBLIC STATIC int SceneInfo::GetEntryID(const char* categoryName, const char* en return GetEntryIDWithinRange(category.OffsetStart, category.OffsetEnd, entryName); } -PUBLIC STATIC int SceneInfo::GetEntryID(const char* categoryName, size_t entryID) { +int SceneInfo::GetEntryID(const char* categoryName, size_t entryID) { int categoryID = GetCategoryID(categoryName); if (categoryID < 0) return -1; @@ -80,7 +67,7 @@ PUBLIC STATIC int SceneInfo::GetEntryID(const char* categoryName, size_t entryID return GetEntryID((size_t)categoryID, (size_t)entryID); } -PUBLIC STATIC int SceneInfo::GetEntryID(size_t categoryID, size_t entryID) { +int SceneInfo::GetEntryID(size_t categoryID, size_t entryID) { if (!SceneInfo::IsCategoryValid((int)categoryID)) return -1; @@ -92,7 +79,7 @@ PUBLIC STATIC int SceneInfo::GetEntryID(size_t categoryID, size_t entryID) { return (int)actualEntryID; } -PUBLIC STATIC int SceneInfo::GetEntryPosInCategory(const char *categoryName, const char* entryName) { +int SceneInfo::GetEntryPosInCategory(const char *categoryName, const char* entryName) { int categoryID = GetCategoryID(categoryName); if (categoryID < 0) return -1; @@ -100,7 +87,7 @@ PUBLIC STATIC int SceneInfo::GetEntryPosInCategory(const char *categoryName, con return GetEntryPosInCategory((size_t)categoryID, entryName); } -PUBLIC STATIC int SceneInfo::GetEntryPosInCategory(size_t categoryID, const char* entryName) { +int SceneInfo::GetEntryPosInCategory(size_t categoryID, const char* entryName) { if (!SceneInfo::IsCategoryValid((int)categoryID)) return -1; @@ -112,7 +99,7 @@ PUBLIC STATIC int SceneInfo::GetEntryPosInCategory(size_t categoryID, const char return actualEntryID - (int)category.OffsetStart; } -PUBLIC STATIC int SceneInfo::GetEntryIDWithinRange(size_t start, size_t end, const char* entryName) { +int SceneInfo::GetEntryIDWithinRange(size_t start, size_t end, const char* entryName) { for (size_t i = start; i < end; i++) { if (!strcmp(Entries[i].Name, entryName)) return (int)i; @@ -121,7 +108,7 @@ PUBLIC STATIC int SceneInfo::GetEntryIDWithinRange(size_t start, size_t end, con return -1; } -PUBLIC STATIC string SceneInfo::GetParentPath(int entryID) { +string SceneInfo::GetParentPath(int entryID) { SceneListEntry& entry = Entries[entryID]; char filePath[4096]; @@ -138,7 +125,7 @@ PUBLIC STATIC string SceneInfo::GetParentPath(int entryID) { return std::string(filePath); } -PUBLIC STATIC string SceneInfo::GetFilename(int entryID) { +string SceneInfo::GetFilename(int entryID) { SceneListEntry scene = Entries[entryID]; std::string parentPath = GetParentPath(entryID); @@ -174,11 +161,11 @@ PUBLIC STATIC string SceneInfo::GetFilename(int entryID) { return parentPath; } -PUBLIC STATIC string SceneInfo::GetTileConfigFilename(int entryID) { +string SceneInfo::GetTileConfigFilename(int entryID) { return GetParentPath(entryID) + "TileConfig.bin"; } -PUBLIC STATIC char* SceneInfo::GetEntryProperty(int entryID, char* property) { +char* SceneInfo::GetEntryProperty(int entryID, char* property) { if (IsEntryValid(entryID)) { SceneListEntry& entry = Entries[entryID]; if (entry.Properties->Exists(property)) @@ -186,7 +173,7 @@ PUBLIC STATIC char* SceneInfo::GetEntryProperty(int entryID, char* property) { } return nullptr; } -PUBLIC STATIC char* SceneInfo::GetCategoryProperty(int categoryID, char* property) { +char* SceneInfo::GetCategoryProperty(int categoryID, char* property) { if (IsCategoryValid(categoryID)) { SceneListCategory& category = Categories[categoryID]; if (category.Properties->Exists(property)) @@ -195,18 +182,18 @@ PUBLIC STATIC char* SceneInfo::GetCategoryProperty(int categoryID, char* propert return nullptr; } -PUBLIC STATIC bool SceneInfo::HasEntryProperty(int entryID, char* property) { +bool SceneInfo::HasEntryProperty(int entryID, char* property) { if (IsEntryValid(entryID)) return Entries[entryID].Properties->Exists(property); return false; } -PUBLIC STATIC bool SceneInfo::HasCategoryProperty(int categoryID, char* property) { +bool SceneInfo::HasCategoryProperty(int categoryID, char* property) { if (IsCategoryValid(categoryID)) return Categories[categoryID].Properties->Exists(property); return false; } -PRIVATE STATIC void SceneInfo::FillAttributesHashMap(XMLAttributes* attr, HashMap* map) { +void SceneInfo::FillAttributesHashMap(XMLAttributes* attr, HashMap* map) { for (size_t i = 0; i < attr->KeyVector.size(); i++) { char *key = attr->KeyVector[i]; char *value = XMLParser::TokenToString(attr->ValueMap.Get(key)); @@ -215,7 +202,7 @@ PRIVATE STATIC void SceneInfo::FillAttributesHashMap(XMLAttributes* attr, HashMa } } -PUBLIC STATIC bool SceneInfo::Load(XMLNode* node) { +bool SceneInfo::Load(XMLNode* node) { for (size_t i = 0; i < node->children.size(); i++) { XMLNode* listElement = node->children[i]; if (XMLParser::MatchToken(listElement->name, "category")) { diff --git a/source/Engine/Scene/SceneLayer.cpp b/source/Engine/Scene/SceneLayer.cpp index a38d8add..23448a14 100644 --- a/source/Engine/Scene/SceneLayer.cpp +++ b/source/Engine/Scene/SceneLayer.cpp @@ -1,85 +1,11 @@ -#if INTERFACE - -#include -#include -#include -#include - -class SceneLayer { -public: - char Name[50]; - bool Visible = true; - - int Width = 0; - int Height = 0; - Uint32 WidthMask = 0; - Uint32 HeightMask = 0; - Uint32 WidthInBits = 0; - Uint32 HeightInBits = 0; - Uint32 WidthData = 0; - Uint32 HeightData = 0; - Uint32 DataSize = 0; - Uint32 ScrollIndexCount = 0; - - int RelativeY = 0x0100; - int ConstantY = 0x0000; - int OffsetX = 0x0000; - int OffsetY = 0x0000; - - Uint32* Tiles = NULL; - Uint32* TilesBackup = NULL; - Uint16* TileOffsetY = NULL; - - int DeformOffsetA = 0; - int DeformOffsetB = 0; - int DeformSetA[MAX_DEFORM_LINES]; - int DeformSetB[MAX_DEFORM_LINES]; - int DeformSplitLine = 0; - - int Flags = 0x0000; - int DrawGroup = 0; - Uint8 DrawBehavior = 0; - - HashMap* Properties = NULL; - - bool Blending = false; - Uint8 BlendMode = 0; // BlendMode_NORMAL - float Opacity = 1.0f; - - bool UsePaletteIndexLines = false; - - bool UsingCustomScanlineFunction = false; - ObjFunction CustomScanlineFunction; - - bool UsingCustomRenderFunction = false; - ObjFunction CustomRenderFunction; - - int ScrollInfoCount = 0; - ScrollingInfo* ScrollInfos = NULL; - int ScrollInfosSplitIndexesCount = 0; - Uint16* ScrollInfosSplitIndexes = NULL; - Uint8* ScrollIndexes = NULL; - - Uint32 BufferID = 0; - int VertexCount = 0; - void* TileBatches = NULL; - - enum { - FLAGS_COLLIDEABLE = 1, - FLAGS_REPEAT_X = 2, - FLAGS_REPEAT_Y = 4, - }; -}; -#endif - #include #include #include -PUBLIC SceneLayer::SceneLayer() { +SceneLayer::SceneLayer() { } -PUBLIC SceneLayer::SceneLayer(int w, int h) { +SceneLayer::SceneLayer(int w, int h) { Width = w; Height = h; @@ -110,15 +36,15 @@ PUBLIC SceneLayer::SceneLayer(int w, int h) { TilesBackup = (Uint32*)Memory::TrackedCalloc("SceneLayer::TilesBackup", w * h, sizeof(Uint32)); ScrollIndexes = (Uint8*)Memory::Calloc(ScrollIndexCount * 16, sizeof(Uint8)); } -PUBLIC bool SceneLayer::PropertyExists(char* property) { +bool SceneLayer::PropertyExists(char* property) { return Properties && Properties->Exists(property); } -PUBLIC VMValue SceneLayer::PropertyGet(char* property) { +VMValue SceneLayer::PropertyGet(char* property) { if (!PropertyExists(property)) return NULL_VAL; return Properties->Get(property); } -PUBLIC void SceneLayer::Dispose() { +void SceneLayer::Dispose() { if (Properties) delete Properties; if (ScrollInfos) diff --git a/source/Engine/Scene/ScrollingIndex.cpp b/source/Engine/Scene/ScrollingIndex.cpp deleted file mode 100644 index c4112f54..00000000 --- a/source/Engine/Scene/ScrollingIndex.cpp +++ /dev/null @@ -1,8 +0,0 @@ -#if INTERFACE -class ScrollingIndex { -public: - int Index; - int Size; - int* TileBuffers = NULL; -}; -#endif diff --git a/source/Engine/Scene/TileSpriteInfo.cpp b/source/Engine/Scene/TileSpriteInfo.cpp deleted file mode 100644 index a4b6057c..00000000 --- a/source/Engine/Scene/TileSpriteInfo.cpp +++ /dev/null @@ -1,9 +0,0 @@ -#if INTERFACE -class TileSpriteInfo { -public: - ISprite* Sprite; - int AnimationIndex; - int FrameIndex; - size_t TilesetID; -}; -#endif diff --git a/source/Engine/Scene/View.cpp b/source/Engine/Scene/View.cpp index f59175aa..44d923d8 100644 --- a/source/Engine/Scene/View.cpp +++ b/source/Engine/Scene/View.cpp @@ -1,46 +1,8 @@ -#if INTERFACE -#include -#include -#include - -class View { -public: - bool Active = false; - bool Visible = true; - bool Software = false; - int Priority = 0; - float X = 0.0f; - float Y = 0.0f; - float Z = 0.0f; - float RotateX = 0.0f; - float RotateY = 0.0f; - float RotateZ = 0.0f; - float Width = 1.0f; - float Height = 1.0f; - float OutputX = 0.0f; - float OutputY = 0.0f; - float OutputWidth = 1.0f; - float OutputHeight = 1.0f; - int Stride = 1; - float FOV = 45.0f; - float NearPlane = 0.1f; - float FarPlane = 1000.f; - bool UsePerspective = false; - bool UseDrawTarget = false; - bool UseStencil = false; - Texture* DrawTarget = NULL; - Uint8* StencilBuffer = NULL; - size_t StencilBufferSize = 0; - Matrix4x4* ProjectionMatrix = NULL; - Matrix4x4* BaseProjectionMatrix = NULL; -}; -#endif - #include #include #include -PUBLIC void View::SetSize(float w, float h) { +void View::SetSize(float w, float h) { Width = w; Height = h; Stride = Math::CeilPOT(w); @@ -49,14 +11,14 @@ PUBLIC void View::SetSize(float w, float h) { ReallocStencil(); } -PUBLIC void View::SetStencilEnabled(bool enabled) { +void View::SetStencilEnabled(bool enabled) { UseStencil = enabled; if (!UseStencil) return; ReallocStencil(); } -PUBLIC void View::ReallocStencil() { +void View::ReallocStencil() { if (DrawTarget == nullptr) return; @@ -67,11 +29,11 @@ PUBLIC void View::ReallocStencil() { ClearStencil(); } } -PUBLIC void View::ClearStencil() { +void View::ClearStencil() { if (StencilBuffer) memset(StencilBuffer, 0x00, StencilBufferSize * sizeof(*StencilBuffer)); } -PUBLIC void View::DeleteStencil() { +void View::DeleteStencil() { Memory::Free(StencilBuffer); StencilBuffer = NULL; StencilBufferSize = 0; diff --git a/source/Engine/TextFormats/INI/INI.cpp b/source/Engine/TextFormats/INI/INI.cpp index 3da22189..485f1abb 100644 --- a/source/Engine/TextFormats/INI/INI.cpp +++ b/source/Engine/TextFormats/INI/INI.cpp @@ -1,26 +1,10 @@ -#if INTERFACE -#include -#include -#include - -#include - -class INI { -public: - char* Filename = nullptr; - vector Sections; -}; -#endif - #include #include #include #include #include -#define INI_IMPLEMENTATION - -PUBLIC STATIC INI* INI::New(const char* filename) { +INI* INI::New(const char* filename) { INI* ini = new INI; ini->SetFilename(filename); @@ -28,7 +12,7 @@ PUBLIC STATIC INI* INI::New(const char* filename) { return ini; } -PUBLIC STATIC INI* INI::Load(const char* filename) { +INI* INI::Load(const char* filename) { INI* ini = INI::New(filename); SDLStream* stream = SDLStream::New(filename, SDLStream::READ_ACCESS); @@ -49,7 +33,7 @@ PUBLIC STATIC INI* INI::Load(const char* filename) { return ini; } -PUBLIC bool INI::Reload() { +bool INI::Reload() { SDLStream* stream = SDLStream::New(Filename, SDLStream::READ_ACCESS); if (!stream) { Log::Print(Log::LOG_ERROR, "Couldn't open file '%s'!", Filename); @@ -66,7 +50,7 @@ PUBLIC bool INI::Reload() { return true; } -PUBLIC bool INI::Save(const char* filename) { +bool INI::Save(const char* filename) { SDLStream* stream = SDLStream::New(filename, SDLStream::WRITE_ACCESS); if (!stream) { Log::Print(Log::LOG_ERROR, "Couldn't open file '%s'!", filename); @@ -82,15 +66,15 @@ PUBLIC bool INI::Save(const char* filename) { stream->Close(); return true; } -PUBLIC bool INI::Save() { +bool INI::Save() { return Save(Filename); } -PUBLIC void INI::SetFilename(const char* filename) { +void INI::SetFilename(const char* filename) { Memory::Free(Filename); Filename = StringUtils::Duplicate(filename); } -PUBLIC bool INI::Read(Stream* stream) { +bool INI::Read(Stream* stream) { INISection* section = nullptr; size_t length = stream->Length(); @@ -180,7 +164,7 @@ PUBLIC bool INI::Read(Stream* stream) { return true; } -PUBLIC bool INI::Write(Stream* stream) { +bool INI::Write(Stream* stream) { for (INISection* section: Sections) { if (!section->Name && section->Properties.size() == 0) continue; @@ -208,7 +192,7 @@ PUBLIC bool INI::Write(Stream* stream) { return true; } -PUBLIC INISection* INI::FindSection(const char* name) { +INISection* INI::FindSection(const char* name) { if (name == nullptr) return Sections[0]; @@ -220,7 +204,7 @@ PUBLIC INISection* INI::FindSection(const char* name) { return nullptr; } -PUBLIC bool INI::GetString(const char* sectionName, const char* key, char* dest, size_t destSize) { +bool INI::GetString(const char* sectionName, const char* key, char* dest, size_t destSize) { if (!dest || !destSize) return false; @@ -235,7 +219,7 @@ PUBLIC bool INI::GetString(const char* sectionName, const char* key, char* dest, StringUtils::Copy(dest, property->Value, destSize); return true; } -PUBLIC bool INI::GetInteger(const char* sectionName, const char* key, int* dest) { +bool INI::GetInteger(const char* sectionName, const char* key, int* dest) { if (!dest) return false; @@ -249,7 +233,7 @@ PUBLIC bool INI::GetInteger(const char* sectionName, const char* key, int* dest) return StringUtils::ToNumber(dest, property->Value); } -PUBLIC bool INI::GetDecimal(const char* sectionName, const char* key, double* dest) { +bool INI::GetDecimal(const char* sectionName, const char* key, double* dest) { if (!dest) return false; @@ -263,7 +247,7 @@ PUBLIC bool INI::GetDecimal(const char* sectionName, const char* key, double* de return StringUtils::ToDecimal(dest, property->Value); } -PUBLIC bool INI::GetBool(const char* sectionName, const char* key, bool* dest) { +bool INI::GetBool(const char* sectionName, const char* key, bool* dest) { if (!dest) return false; @@ -279,7 +263,7 @@ PUBLIC bool INI::GetBool(const char* sectionName, const char* key, bool* dest) { return true; } -PUBLIC bool INI::SetString(const char* sectionName, const char* key, const char* value) { +bool INI::SetString(const char* sectionName, const char* key, const char* value) { INISection* section = FindSection(sectionName); if (section == nullptr) section = AddSection(sectionName); @@ -293,27 +277,27 @@ PUBLIC bool INI::SetString(const char* sectionName, const char* key, const char* property->SetValue(value); return true; } -PUBLIC bool INI::SetInteger(const char* section, const char* key, int value) { +bool INI::SetInteger(const char* section, const char* key, int value) { char toStr[21]; snprintf(toStr, sizeof toStr, "%d", value); return SetString(section, key, toStr); } -PUBLIC bool INI::SetDecimal(const char* section, const char* key, double value) { +bool INI::SetDecimal(const char* section, const char* key, double value) { char toStr[512]; snprintf(toStr, sizeof toStr, "%lf", value); return SetString(section, key, toStr); } -PUBLIC bool INI::SetBool(const char* section, const char* key, bool value) { +bool INI::SetBool(const char* section, const char* key, bool value) { const char* toStr = value ? "true" : "false"; return SetString(section, key, toStr); } -PUBLIC INISection* INI::AddSection(const char* name) { +INISection* INI::AddSection(const char* name) { INISection* sec = new INISection(name); Sections.push_back(sec); return sec; } -PUBLIC bool INI::RemoveSection(const char* sectionName) { +bool INI::RemoveSection(const char* sectionName) { if (sectionName == nullptr) { Sections[0]->Properties.clear(); return true; @@ -330,14 +314,14 @@ PUBLIC bool INI::RemoveSection(const char* sectionName) { return false; } -PUBLIC bool INI::SectionExists(const char* sectionName) { +bool INI::SectionExists(const char* sectionName) { return FindSection(sectionName) != nullptr; } -PUBLIC int INI::GetSectionCount() { +int INI::GetSectionCount() { return Sections.size() - 1; } -PUBLIC char* INI::GetProperty(const char* sectionName, const char* key) { +char* INI::GetProperty(const char* sectionName, const char* key) { INISection* section = FindSection(sectionName); if (section == nullptr) return nullptr; @@ -348,21 +332,21 @@ PUBLIC char* INI::GetProperty(const char* sectionName, const char* key) { return property->Value; } -PUBLIC bool INI::PropertyExists(const char* sectionName, const char* key) { +bool INI::PropertyExists(const char* sectionName, const char* key) { INISection* section = FindSection(sectionName); if (section == nullptr) return false; return section->FindProperty(key) != nullptr; } -PUBLIC bool INI::RemoveProperty(const char* sectionName, const char* key) { +bool INI::RemoveProperty(const char* sectionName, const char* key) { INISection* section = FindSection(sectionName); if (section == nullptr) return false; return section->RemoveProperty(key); } -PUBLIC int INI::GetPropertyCount(const char* sectionName) { +int INI::GetPropertyCount(const char* sectionName) { INISection* section = FindSection(sectionName); if (section == nullptr) return 0; @@ -370,7 +354,7 @@ PUBLIC int INI::GetPropertyCount(const char* sectionName) { return section->Properties.size(); } -PUBLIC void INI::Dispose() { +void INI::Dispose() { Memory::Free(Filename); for (size_t i = 0; i < Sections.size(); i++) diff --git a/source/Engine/TextFormats/XML/XMLParser.cpp b/source/Engine/TextFormats/XML/XMLParser.cpp index df0d9835..d08d38f0 100644 --- a/source/Engine/TextFormats/XML/XMLParser.cpp +++ b/source/Engine/TextFormats/XML/XMLParser.cpp @@ -1,17 +1,3 @@ -#if INTERFACE -#include -#include -#include -#include -#include -#include - -class XMLParser { -public: - -}; -#endif - #include #include @@ -386,16 +372,16 @@ void GetInstruction() { ConsumeToken(TOKEN_RIGHT_BRACE, "Missing '>' after instruction."); } -PUBLIC STATIC bool XMLParser::MatchToken(Token tok, const char* string) { +bool XMLParser::MatchToken(Token tok, const char* string) { if (tok.Length == 0) return false; return memcmp(string, tok.Start, tok.Length) == 0; } -PUBLIC STATIC float XMLParser::TokenToNumber(Token tok) { +float XMLParser::TokenToNumber(Token tok) { return atof(tok.ToString().c_str()); } -PUBLIC STATIC XMLNode* XMLParser::Parse() { +XMLNode* XMLParser::Parse() { XMLNode* XMLRoot = new (std::nothrow) XMLNode; if (!XMLRoot) return NULL; @@ -476,7 +462,7 @@ PUBLIC STATIC XMLNode* XMLParser::Parse() { return XMLRoot; } -PUBLIC STATIC XMLNode* XMLParser::ParseFromStream(MemoryStream* stream) { +XMLNode* XMLParser::ParseFromStream(MemoryStream* stream) { // NOTE: This fixes the XML overread bug (unterminated string caused bad access/read) stream->SeekEnd(0); stream->WriteByte(0); @@ -495,12 +481,12 @@ PUBLIC STATIC XMLNode* XMLParser::ParseFromStream(MemoryStream* stream) { xml->base_stream = stream; return xml; } -PUBLIC STATIC XMLNode* XMLParser::ParseFromStream(Stream* streamSrc) { +XMLNode* XMLParser::ParseFromStream(Stream* streamSrc) { MemoryStream* stream = MemoryStream::New(streamSrc); if (!stream) return NULL; return XMLParser::ParseFromStream(stream); } -PUBLIC STATIC XMLNode* XMLParser::ParseFromResource(const char* filename) { +XMLNode* XMLParser::ParseFromResource(const char* filename) { ResourceStream* res = ResourceStream::New(filename); if (!res) { Log::Print(Log::LOG_ERROR, "Could not open ResourceStream from \"%s\"", filename); @@ -512,7 +498,7 @@ PUBLIC STATIC XMLNode* XMLParser::ParseFromResource(const char* filename) { return node; } -PUBLIC STATIC char* XMLParser::TokenToString(Token tok) { +char* XMLParser::TokenToString(Token tok) { char* string = StringUtils::Create(tok); if (!string) { Log::Print(Log::LOG_ERROR, "Out of memory converting XML token to string!"); @@ -521,7 +507,7 @@ PUBLIC STATIC char* XMLParser::TokenToString(Token tok) { return string; } -PUBLIC STATIC void XMLParser::CopyTokenToString(Token tok, char* buffer, size_t size) { +void XMLParser::CopyTokenToString(Token tok, char* buffer, size_t size) { size_t length = tok.Length; if (length >= size) length = size - 1; @@ -529,7 +515,7 @@ PUBLIC STATIC void XMLParser::CopyTokenToString(Token tok, char* buffer, siz buffer[length] = '\0'; } -PUBLIC STATIC XMLNode* XMLParser::SearchNode(XMLNode* root, const char* search) { +XMLNode* XMLParser::SearchNode(XMLNode* root, const char* search) { for (size_t i = 0; i < root->children.size(); i++) { XMLNode* node = root->children[i]; if (XMLParser::MatchToken(node->name, search)) @@ -546,7 +532,7 @@ void FreeNode(XMLNode* root) { delete root; } -PUBLIC STATIC void XMLParser::Free(XMLNode* root) { +void XMLParser::Free(XMLNode* root) { if (root->base_stream) root->base_stream->Close(); diff --git a/source/Engine/Types/DrawGroupList.cpp b/source/Engine/Types/DrawGroupList.cpp index 9408a5f2..c7d2a0aa 100644 --- a/source/Engine/Types/DrawGroupList.cpp +++ b/source/Engine/Types/DrawGroupList.cpp @@ -1,43 +1,29 @@ -#if INTERFACE - -#include - -#include - -class DrawGroupList { -public: - vector* Entities = nullptr; - bool EntityDepthSortingEnabled = false; - bool NeedsSorting = false; -}; -#endif - #include #include -PUBLIC DrawGroupList::DrawGroupList() { +DrawGroupList::DrawGroupList() { Init(); } // Double linked-list functions -PUBLIC int DrawGroupList::Add(Entity* obj) { +int DrawGroupList::Add(Entity* obj) { Entities->push_back(obj); if (EntityDepthSortingEnabled) NeedsSorting = true; return Entities->size() - 1; } -PUBLIC bool DrawGroupList::Contains(Entity* obj) { +bool DrawGroupList::Contains(Entity* obj) { return GetEntityIndex(obj) == -1 ? false : true; } -PUBLIC int DrawGroupList::GetEntityIndex(Entity* obj) { +int DrawGroupList::GetEntityIndex(Entity* obj) { for (size_t i = 0, iSz = Entities->size(); i < iSz; i++) { if ((*Entities)[i] == obj) return (int)i; } return -1; } -PUBLIC void DrawGroupList::Remove(Entity* obj) { +void DrawGroupList::Remove(Entity* obj) { for (size_t i = 0, iSz = Entities->size(); i < iSz; i++) { if ((*Entities)[i] == obj) { Entities->erase(Entities->begin() + i); @@ -45,29 +31,29 @@ PUBLIC void DrawGroupList::Remove(Entity* obj) { } } } -PUBLIC void DrawGroupList::Clear() { +void DrawGroupList::Clear() { Entities->clear(); NeedsSorting = false; } -PUBLIC void DrawGroupList::Sort() { +void DrawGroupList::Sort() { std::stable_sort(Entities->begin(), Entities->end(), [](const Entity* entA, const Entity* entB) { return entA->Depth < entB->Depth; }); NeedsSorting = false; } -PUBLIC void DrawGroupList::Init() { +void DrawGroupList::Init() { Entities = new vector(); } -PUBLIC void DrawGroupList::Dispose() { +void DrawGroupList::Dispose() { delete Entities; Entities = nullptr; } -PUBLIC DrawGroupList::~DrawGroupList() { + DrawGroupList::~DrawGroupList() { // Dispose(); } -PUBLIC int DrawGroupList::Count() { +int DrawGroupList::Count() { return Entities->size(); } diff --git a/source/Engine/Types/Entity.cpp b/source/Engine/Types/Entity.cpp index 525e1f62..ccf8e2d5 100644 --- a/source/Engine/Types/Entity.cpp +++ b/source/Engine/Types/Entity.cpp @@ -1,129 +1,11 @@ -#if INTERFACE -#include -#include -#include -#include -#include - -#include -#include - -need_t ObjectList; -need_t ObjectRegistry; -need_t DrawGroupList; - -class Entity { -public: - float InitialX = 0; - float InitialY = 0; - int Active = true; - int Pauseable = true; - int Interactable = true; - int Persistence = Persistence_NONE; - int Activity = ACTIVE_BOUNDS; - int InRange = false; - bool Created = false; - bool PostCreated = false; - - float X = 0.0f; - float Y = 0.0f; - float Z = 0.0f; - - float XSpeed = 0.0f; - float YSpeed = 0.0f; - float GroundSpeed = 0.0f; - float Gravity = 0.0f; - int Ground = false; - - int WasOffScreen = false; - int OnScreen = true; - float OnScreenHitboxW = 0.0f; - float OnScreenHitboxH = 0.0f; - float OnScreenRegionTop = 0.0f; - float OnScreenRegionLeft = 0.0f; - float OnScreenRegionRight = 0.0f; - float OnScreenRegionBottom = 0.0f; - int ViewRenderFlag = 0xFFFFFFFF; - int ViewOverrideFlag = 0; - float RenderRegionW = 0.0f; - float RenderRegionH = 0.0f; - float RenderRegionTop = 0.0f; - float RenderRegionLeft = 0.0f; - float RenderRegionRight = 0.0f; - float RenderRegionBottom = 0.0f; - - int Angle = 0; - int AngleMode = 0; - float ScaleX = 1.0; - float ScaleY = 1.0; - float Rotation = 0.0; - float Alpha = 1.0; - int AutoPhysics = false; - - int Priority = 0; - int PriorityListIndex = -1; - int PriorityOld = -1; - - float Depth = 0.0f; - float OldDepth = 0.0f; - float ZDepth = 0.0; - - int Sprite = -1; - int CurrentAnimation = -1; - int CurrentFrame = -1; - int CurrentFrameCount = 0; - float AnimationSpeedMult = 1.0; - int AnimationSpeedAdd = 0; - int AutoAnimate = true; - float AnimationSpeed = 0.0; - float AnimationTimer = 0.0; - int AnimationFrameDuration = 0; - int AnimationLoopIndex = 0; - - EntityHitbox Hitbox; - int FlipFlag = 0; - - float SensorX = 0.0f; - float SensorY = 0.0f; - int SensorCollided = false; - int SensorAngle = 0; - - float VelocityX = 0.0f; - float VelocityY = 0.0f; - float GroundVel = 0.0f; - float GravityStrength = 0.0f; - int OnGround = false; - int Direction = 0; - - int TileCollisions = false; - int CollisionLayers = 0; - int CollisionPlane = 0; - int CollisionMode = 0; - - int SlotID = -1; - - bool Removed = false; - - Entity* PrevEntity = NULL; - Entity* NextEntity = NULL; - - ObjectList* List = NULL; - Entity* PrevEntityInList = NULL; - Entity* NextEntityInList = NULL; - - Entity* PrevSceneEntity = NULL; - Entity* NextSceneEntity = NULL; -}; -#endif - #include -PUBLIC void Entity::ApplyMotion() { +void Entity::ApplyMotion() { YSpeed += Gravity; X += XSpeed; Y += YSpeed; } -PUBLIC void Entity::Animate() { +void Entity::Animate() { ISprite* sprite = Scene::GetSpriteResource(Sprite); if (!sprite || CurrentAnimation < 0 || (size_t)CurrentAnimation >= sprite->Animations.size()) @@ -173,11 +55,11 @@ PUBLIC void Entity::Animate() { } #endif } -PUBLIC void Entity::SetAnimation(int animation, int frame) { +void Entity::SetAnimation(int animation, int frame) { if (CurrentAnimation != animation) ResetAnimation(animation, frame); } -PUBLIC void Entity::ResetAnimation(int animation, int frame) { +void Entity::ResetAnimation(int animation, int frame) { ISprite* sprite = Scene::GetSpriteResource(Sprite); if (!sprite || animation < 0 || (size_t)animation >= sprite->Animations.size()) @@ -194,7 +76,7 @@ PUBLIC void Entity::ResetAnimation(int animation, int frame) { AnimationSpeed = sprite->Animations[CurrentAnimation].AnimationSpeed; AnimationLoopIndex = sprite->Animations[CurrentAnimation].FrameToLoop; } -PUBLIC bool Entity::BasicCollideWithObject(Entity* other) { +bool Entity::BasicCollideWithObject(Entity* other) { float otherHitboxW = other->Hitbox.Width; float otherHitboxH = other->Hitbox.Height; @@ -207,7 +89,7 @@ PUBLIC bool Entity::BasicCollideWithObject(Entity* other) { other->X + other->Hitbox.GetRight() < X + Hitbox.GetRight() && other->Y + other->Hitbox.GetBottom() < Y + Hitbox.GetBottom(); } -PUBLIC bool Entity::CollideWithObject(Entity* other) { +bool Entity::CollideWithObject(Entity* other) { float sourceFlipX = (this->FlipFlag & 1) ? -1.0 : 1.0; float sourceFlipY = (this->FlipFlag & 2) ? -1.0 : 1.0; float otherFlipX = (other->FlipFlag & 1) ? -1.0 : 1.0; @@ -228,7 +110,7 @@ PUBLIC bool Entity::CollideWithObject(Entity* other) { sourceX - sourceHitboxW > otherX + otherHitboxW || sourceX + sourceHitboxW < otherX - otherHitboxW); } -PUBLIC int Entity::SolidCollideWithObject(Entity* other, int flag) { +int Entity::SolidCollideWithObject(Entity* other, int flag) { // NOTE: "flag" is setValues float initialOtherX = (other->X); float initialOtherY = (other->Y); @@ -378,7 +260,7 @@ PUBLIC int Entity::SolidCollideWithObject(Entity* other, int flag) { } return 0; } -PUBLIC bool Entity::TopSolidCollideWithObject(Entity* other, int flag) { +bool Entity::TopSolidCollideWithObject(Entity* other, int flag) { // NOTE: "flag" might be "UseGroundSpeed" float initialOtherX = (other->X); float initialOtherY = (other->Y); @@ -417,7 +299,7 @@ PUBLIC bool Entity::TopSolidCollideWithObject(Entity* other, int flag) { return true; } -PUBLIC void Entity::Copy(Entity* other) { +void Entity::Copy(Entity* other) { // Add the other entity to this object's list if (other->List != List) { other->List->Remove(other); @@ -440,7 +322,7 @@ PUBLIC void Entity::Copy(Entity* other) { CopyFields(other); } -PUBLIC void Entity::CopyFields(Entity* other) { +void Entity::CopyFields(Entity* other) { #define COPY(which) other->which = which COPY(InitialX); COPY(InitialY); @@ -529,59 +411,59 @@ PUBLIC void Entity::CopyFields(Entity* other) { #undef COPY } -PUBLIC void Entity::ApplyPhysics() { +void Entity::ApplyPhysics() { } -PUBLIC VIRTUAL void Entity::Initialize() { +void Entity::Initialize() { } -PUBLIC VIRTUAL void Entity::Create() { +void Entity::Create() { } -PUBLIC VIRTUAL void Entity::PostCreate() { +void Entity::PostCreate() { } -PUBLIC VIRTUAL void Entity::UpdateEarly() { +void Entity::UpdateEarly() { } -PUBLIC VIRTUAL void Entity::Update() { +void Entity::Update() { } -PUBLIC VIRTUAL void Entity::UpdateLate() { +void Entity::UpdateLate() { } -PUBLIC VIRTUAL void Entity::OnAnimationFinish() { +void Entity::OnAnimationFinish() { } -PUBLIC VIRTUAL void Entity::OnSceneLoad() { +void Entity::OnSceneLoad() { } -PUBLIC VIRTUAL void Entity::OnSceneRestart() { +void Entity::OnSceneRestart() { } -PUBLIC VIRTUAL void Entity::GameStart() { +void Entity::GameStart() { } -PUBLIC VIRTUAL void Entity::RenderEarly() { +void Entity::RenderEarly() { } -PUBLIC VIRTUAL void Entity::Render(int CamX, int CamY) { +void Entity::Render(int CamX, int CamY) { } -PUBLIC VIRTUAL void Entity::RenderLate() { +void Entity::RenderLate() { } -PUBLIC VIRTUAL void Entity::Remove() { +void Entity::Remove() { } -PUBLIC VIRTUAL void Entity::Dispose() { +void Entity::Dispose() { } diff --git a/source/Engine/Types/ObjectList.cpp b/source/Engine/Types/ObjectList.cpp index 3cda52a2..dcb3173e 100644 --- a/source/Engine/Types/ObjectList.cpp +++ b/source/Engine/Types/ObjectList.cpp @@ -1,29 +1,8 @@ -#if INTERFACE -#include -#include - -class ObjectList { -public: - int EntityCount = 0; - int Activity = ACTIVE_NORMAL; - Entity* EntityFirst = nullptr; - Entity* EntityLast = nullptr; - - char* ObjectName; - char* LoadFunctionName; - char* GlobalUpdateFunctionName; - - ObjectListPerformance Performance; - - Entity* (*SpawnFunction)(ObjectList*) = nullptr; -}; -#endif - #include #include -PUBLIC ObjectList::ObjectList(const char* name) { +ObjectList::ObjectList(const char* name) { ObjectName = StringUtils::Duplicate(name); std::string loadFunctionName = std::string(name) + "_Load"; @@ -32,14 +11,14 @@ PUBLIC ObjectList::ObjectList(const char* name) { LoadFunctionName = StringUtils::Create(loadFunctionName); GlobalUpdateFunctionName = StringUtils::Create(globalUpdateFunctionName); } -PUBLIC ObjectList::~ObjectList() { +ObjectList::~ObjectList() { Memory::Free(ObjectName); Memory::Free(LoadFunctionName); Memory::Free(GlobalUpdateFunctionName); } // Double linked-list functions -PUBLIC void ObjectList::Add(Entity* obj) { +void ObjectList::Add(Entity* obj) { // Set "prev" of obj to last obj->PrevEntityInList = EntityLast; obj->NextEntityInList = NULL; @@ -56,7 +35,7 @@ PUBLIC void ObjectList::Add(Entity* obj) { EntityCount++; } -PUBLIC bool ObjectList::Contains(Entity* obj) { +bool ObjectList::Contains(Entity* obj) { for (Entity* search = EntityFirst; search != NULL; search = search->NextEntityInList) { if (search == obj) return true; @@ -64,7 +43,7 @@ PUBLIC bool ObjectList::Contains(Entity* obj) { return false; } -PUBLIC void ObjectList::Remove(Entity* obj) { +void ObjectList::Remove(Entity* obj) { if (obj == NULL) return; obj->List = NULL; @@ -86,7 +65,7 @@ PUBLIC void ObjectList::Remove(Entity* obj) { EntityCount--; } -PUBLIC void ObjectList::Clear() { +void ObjectList::Clear() { EntityCount = 0; EntityFirst = NULL; EntityLast = NULL; @@ -95,14 +74,14 @@ PUBLIC void ObjectList::Clear() { } // ObjectList functions -PUBLIC Entity* ObjectList::Spawn() { +Entity* ObjectList::Spawn() { return SpawnFunction(this); } -PUBLIC void ObjectList::Iterate(std::function func) { +void ObjectList::Iterate(std::function func) { for (Entity* ent = EntityFirst; ent != NULL; ent = ent->NextEntityInList) func(ent); } -PUBLIC void ObjectList::RemoveNonPersistentFromLinkedList(Entity* first, int persistence) { +void ObjectList::RemoveNonPersistentFromLinkedList(Entity* first, int persistence) { for (Entity* ent = first, *next; ent; ent = next) { // Store the "next" so that when/if the current is removed, // it can still be used to point at the end of the loop. @@ -112,18 +91,18 @@ PUBLIC void ObjectList::RemoveNonPersistentFromLinkedList(Entity* first, int per Remove(ent); } } -PUBLIC void ObjectList::RemoveNonPersistentFromLinkedList(Entity* first) { +void ObjectList::RemoveNonPersistentFromLinkedList(Entity* first) { RemoveNonPersistentFromLinkedList(first, Persistence_NONE); } -PUBLIC void ObjectList::ResetPerf() { +void ObjectList::ResetPerf() { Performance.Clear(); } -PUBLIC Entity* ObjectList::GetNth(int n) { +Entity* ObjectList::GetNth(int n) { Entity* ent = EntityFirst; for (ent = EntityFirst; ent != NULL && n > 0; ent = ent->NextEntityInList, n--); return ent; } -PUBLIC Entity* ObjectList::GetClosest(int x, int y) { +Entity* ObjectList::GetClosest(int x, int y) { if (!EntityCount) return NULL; else if (EntityCount == 1) @@ -144,6 +123,6 @@ PUBLIC Entity* ObjectList::GetClosest(int x, int y) { return closest; } -PUBLIC int ObjectList::Count() { +int ObjectList::Count() { return EntityCount; } diff --git a/source/Engine/Types/ObjectRegistry.cpp b/source/Engine/Types/ObjectRegistry.cpp index 89fe80eb..19b195c6 100644 --- a/source/Engine/Types/ObjectRegistry.cpp +++ b/source/Engine/Types/ObjectRegistry.cpp @@ -1,38 +1,28 @@ -#if INTERFACE -#include -#include - -class ObjectRegistry { -public: - vector List; -}; -#endif - #include #include -PUBLIC void ObjectRegistry::Add(Entity* obj) { +void ObjectRegistry::Add(Entity* obj) { if (!Contains(obj)) List.push_back(obj); } -PUBLIC bool ObjectRegistry::Contains(Entity* obj) { +bool ObjectRegistry::Contains(Entity* obj) { return std::find(List.begin(), List.end(), obj) != List.end(); } -PUBLIC void ObjectRegistry::Remove(Entity* obj) { +void ObjectRegistry::Remove(Entity* obj) { if (obj == NULL) return; auto it = std::find(List.begin(), List.end(), obj); if (it != List.end()) List.erase(it); } -PUBLIC void ObjectRegistry::Clear() { +void ObjectRegistry::Clear() { List.clear(); } -PUBLIC void ObjectRegistry::Iterate(std::function func) { +void ObjectRegistry::Iterate(std::function func) { std::for_each(List.begin(), List.end(), func); } -PUBLIC void ObjectRegistry::RemoveNonPersistentFromLinkedList(Entity* first, int persistence) { +void ObjectRegistry::RemoveNonPersistentFromLinkedList(Entity* first, int persistence) { for (Entity* ent = first, *next; ent; ent = next) { // Store the "next" so that when/if the current is removed, // it can still be used to point at the end of the loop. @@ -42,15 +32,15 @@ PUBLIC void ObjectRegistry::RemoveNonPersistentFromLinkedList(Entity* first, int Remove(ent); } } -PUBLIC void ObjectRegistry::RemoveNonPersistentFromLinkedList(Entity* first) { +void ObjectRegistry::RemoveNonPersistentFromLinkedList(Entity* first) { RemoveNonPersistentFromLinkedList(first, Persistence_NONE); } -PUBLIC Entity* ObjectRegistry::GetNth(int n) { +Entity* ObjectRegistry::GetNth(int n) { if (n < 0 || n >= (int)List.size()) return NULL; return List[n]; } -PUBLIC Entity* ObjectRegistry::GetClosest(int x, int y) { +Entity* ObjectRegistry::GetClosest(int x, int y) { if (List.size() == 1) return List[0]; @@ -69,14 +59,14 @@ PUBLIC Entity* ObjectRegistry::GetClosest(int x, int y) { return closest; } -PUBLIC void ObjectRegistry::Dispose() { +void ObjectRegistry::Dispose() { List.clear(); List.shrink_to_fit(); } -PUBLIC ObjectRegistry::~ObjectRegistry() { +ObjectRegistry::~ObjectRegistry() { Dispose(); } -PUBLIC int ObjectRegistry::Count() { +int ObjectRegistry::Count() { return (int)List.size(); } diff --git a/source/Engine/Types/Tileset.cpp b/source/Engine/Types/Tileset.cpp index d3939904..dd1dd73f 100644 --- a/source/Engine/Types/Tileset.cpp +++ b/source/Engine/Types/Tileset.cpp @@ -1,28 +1,7 @@ -#if INTERFACE -#include -#include -#include - -class Tileset { -public: - ISprite* Sprite = nullptr; - char* Filename = nullptr; - int NumCols = 0; - int NumRows = 0; - int TileWidth = 0; - int TileHeight = 0; - size_t StartTile = 0; - size_t FirstGlobalTileID = 0; - size_t TileCount = 0; - unsigned PaletteID = 0; - std::map AnimatorMap; -}; -#endif - #include #include -PUBLIC Tileset::Tileset(ISprite* sprite, int tileWidth, int tileHeight, size_t firstgid, size_t startTile, size_t tileCount, char* filename) { +Tileset::Tileset(ISprite* sprite, int tileWidth, int tileHeight, size_t firstgid, size_t startTile, size_t tileCount, char* filename) { if (sprite->Spritesheets.size() < 1) return; @@ -37,7 +16,7 @@ PUBLIC Tileset::Tileset(ISprite* sprite, int tileWidth, int tileHeight, size_t f Filename = StringUtils::Duplicate(filename); } -PUBLIC void Tileset::RunAnimations() { +void Tileset::RunAnimations() { for (map::iterator it = AnimatorMap.begin(); it != AnimatorMap.end(); it++) { TileAnimator& animator = it->second; if (!animator.Paused) @@ -45,7 +24,7 @@ PUBLIC void Tileset::RunAnimations() { } } -PUBLIC void Tileset::RestartAnimations() { +void Tileset::RestartAnimations() { for (map::iterator it = AnimatorMap.begin(); it != AnimatorMap.end(); it++) { TileAnimator& animator = it->second; animator.RestartAnimation(); @@ -53,7 +32,7 @@ PUBLIC void Tileset::RestartAnimations() { } } -PUBLIC void Tileset::AddTileAnimSequence(int tileID, TileSpriteInfo* tileSpriteInfo, vector& tileIDs, vector& durations) { +void Tileset::AddTileAnimSequence(int tileID, TileSpriteInfo* tileSpriteInfo, vector& tileIDs, vector& durations) { ISprite* tileSprite = Sprite; if (!tileSprite) return; @@ -87,7 +66,7 @@ PUBLIC void Tileset::AddTileAnimSequence(int tileID, TileSpriteInfo* tileSpriteI AnimatorMap.insert( { tileID, animator } ); } -PUBLIC void Tileset::AddTileAnimSequence(int tileID, TileSpriteInfo* tileSpriteInfo, ISprite* animSprite, int animID) { +void Tileset::AddTileAnimSequence(int tileID, TileSpriteInfo* tileSpriteInfo, ISprite* animSprite, int animID) { if (animSprite == nullptr) { AnimatorMap.erase(tileID); return; @@ -99,7 +78,7 @@ PUBLIC void Tileset::AddTileAnimSequence(int tileID, TileSpriteInfo* tileSpriteI AnimatorMap.insert( { tileID, animator } ); } -PUBLIC TileAnimator* Tileset::GetTileAnimSequence(int tileID) { +TileAnimator* Tileset::GetTileAnimSequence(int tileID) { std::map::iterator it = AnimatorMap.find(tileID); if (it == AnimatorMap.end()) return nullptr; diff --git a/source/Engine/Utilities/ColorUtils.cpp b/source/Engine/Utilities/ColorUtils.cpp index c6db53c5..6033e274 100644 --- a/source/Engine/Utilities/ColorUtils.cpp +++ b/source/Engine/Utilities/ColorUtils.cpp @@ -1,23 +1,15 @@ -#if INTERFACE -#include - -class ColorUtils { -public: -}; -#endif - #include #define CLAMP_VAL(v, a, b) if (v < a) v = a; else if (v > b) v = b -PUBLIC STATIC Uint32 ColorUtils::ToRGB(int r, int g, int b) { +Uint32 ColorUtils::ToRGB(int r, int g, int b) { CLAMP_VAL(r, 0x00, 0xFF); CLAMP_VAL(g, 0x00, 0xFF); CLAMP_VAL(b, 0x00, 0xFF); return 0xFF000000U | r << 16 | g << 8 | b; } -PUBLIC STATIC Uint32 ColorUtils::ToRGB(int r, int g, int b, int a) { +Uint32 ColorUtils::ToRGB(int r, int g, int b, int a) { CLAMP_VAL(r, 0x00, 0xFF); CLAMP_VAL(g, 0x00, 0xFF); CLAMP_VAL(b, 0x00, 0xFF); @@ -25,14 +17,14 @@ PUBLIC STATIC Uint32 ColorUtils::ToRGB(int r, int g, int b, int a) { return a << 24 | r << 16 | g << 8 | b; } -PUBLIC STATIC Uint32 ColorUtils::ToRGB(float r, float g, float b) { +Uint32 ColorUtils::ToRGB(float r, float g, float b) { int colR = (int)(r * 0xFF); int colG = (int)(g * 0xFF); int colB = (int)(b * 0xFF); return ColorUtils::ToRGB(colR, colG, colB); } -PUBLIC STATIC Uint32 ColorUtils::ToRGB(float r, float g, float b, float a) { +Uint32 ColorUtils::ToRGB(float r, float g, float b, float a) { int colR = (int)(r * 0xFF); int colG = (int)(g * 0xFF); int colB = (int)(b * 0xFF); @@ -40,40 +32,40 @@ PUBLIC STATIC Uint32 ColorUtils::ToRGB(float r, float g, float b, float a) { return ColorUtils::ToRGB(colR, colG, colB, colA); } -PUBLIC STATIC Uint32 ColorUtils::ToRGB(float *r) { +Uint32 ColorUtils::ToRGB(float *r) { return ToRGB(r[0], r[1], r[2]); } -PUBLIC STATIC Uint32 ColorUtils::ToRGBA(float *r) { +Uint32 ColorUtils::ToRGBA(float *r) { return ToRGB(r[0], r[1], r[2], r[3]); } -PUBLIC STATIC void ColorUtils::SeparateRGB(Uint32 color, float* dest) { +void ColorUtils::SeparateRGB(Uint32 color, float* dest) { dest[0] = (color >> 16 & 0xFF) / 255.f; dest[1] = (color >> 8 & 0xFF) / 255.f; dest[2] = (color & 0xFF) / 255.f; } -PUBLIC STATIC void ColorUtils::Separate(Uint32 color, float* dest) { +void ColorUtils::Separate(Uint32 color, float* dest) { dest[3] = (color >> 24 & 0xFF) / 255.f; SeparateRGB(color, dest); } -PUBLIC STATIC void ColorUtils::SeparateRGB(Uint32 color, Uint8* dest) { +void ColorUtils::SeparateRGB(Uint32 color, Uint8* dest) { dest[0] = (color >> 16) & 0xFF; dest[1] = (color >> 8) & 0xFF; dest[2] = color & 0xFF; } -PUBLIC STATIC void ColorUtils::Separate(Uint32 color, Uint8* dest) { +void ColorUtils::Separate(Uint32 color, Uint8* dest) { dest[3] = (color >> 24) & 0xFF; SeparateRGB(color, dest); } -PUBLIC STATIC void ColorUtils::SeparateRGB(float* color, Uint8* dest) { +void ColorUtils::SeparateRGB(float* color, Uint8* dest) { dest[0] = color[0] * 0xFF; dest[1] = color[1] * 0xFF; dest[2] = color[2] * 0xFF; } -PUBLIC STATIC void ColorUtils::Separate(float* color, Uint8* dest) { +void ColorUtils::Separate(float* color, Uint8* dest) { dest[2] = color[3] * 0xFF; SeparateRGB(color, dest); } -PUBLIC STATIC Uint32 ColorUtils::Tint(Uint32 color, Uint32 colorMult) { +Uint32 ColorUtils::Tint(Uint32 color, Uint32 colorMult) { Uint32 dR = (colorMult >> 16) & 0xFF; Uint32 dG = (colorMult >> 8) & 0xFF; Uint32 dB = colorMult & 0xFF; @@ -85,23 +77,23 @@ PUBLIC STATIC Uint32 ColorUtils::Tint(Uint32 color, Uint32 colorMult) { dB = (Uint8)((dB * sB + 0xFF) >> 8); return dB | (dG << 8) | (dR << 16); } -PUBLIC STATIC Uint32 ColorUtils::Tint(Uint32 color, Uint32 colorMult, Uint16 percentage) { +Uint32 ColorUtils::Tint(Uint32 color, Uint32 colorMult, Uint16 percentage) { return Blend(color, Tint(color, colorMult), percentage); } -PUBLIC STATIC Uint32 ColorUtils::Multiply(Uint32 color, Uint32 colorMult) { +Uint32 ColorUtils::Multiply(Uint32 color, Uint32 colorMult) { Uint32 R = (((colorMult >> 16) & 0xFF) + 1) * (color & 0xFF0000); Uint32 G = (((colorMult >> 8) & 0xFF) + 1) * (color & 0x00FF00); Uint32 B = (((colorMult) & 0xFF) + 1) * (color & 0x0000FF); return (int)((R >> 8) | (G >> 8) | (B >> 8)); } -PUBLIC STATIC Uint32 ColorUtils::Blend(Uint32 color1, Uint32 color2, int percent) { +Uint32 ColorUtils::Blend(Uint32 color1, Uint32 color2, int percent) { Uint32 rb = color1 & 0xFF00FFU; Uint32 g = color1 & 0x00FF00U; rb += (((color2 & 0xFF00FFU) - rb) * percent) >> 8; g += (((color2 & 0x00FF00U) - g) * percent) >> 8; return (rb & 0xFF00FFU) | (g & 0x00FF00U); } -PUBLIC STATIC void ColorUtils::ConvertFromARGBtoABGR(Uint32* argb, int count) { +void ColorUtils::ConvertFromARGBtoABGR(Uint32* argb, int count) { for (int p = 0; p < count; p++) { Uint8 red = (*argb >> 16) & 0xFF; Uint8 green = (*argb >> 8) & 0xFF; @@ -110,7 +102,7 @@ PUBLIC STATIC void ColorUtils::ConvertFromARGBtoABGR(Uint32* argb, int count) argb++; } } -PUBLIC STATIC void ColorUtils::ConvertFromABGRtoARGB(Uint32* argb, int count) { +void ColorUtils::ConvertFromABGRtoARGB(Uint32* argb, int count) { for (int p = 0; p < count; p++) { Uint8 blue = (*argb >> 16) & 0xFF; Uint8 green = (*argb >> 8) & 0xFF; @@ -119,7 +111,7 @@ PUBLIC STATIC void ColorUtils::ConvertFromABGRtoARGB(Uint32* argb, int count) argb++; } } -PUBLIC STATIC int ColorUtils::NearestColor(Uint8 r, Uint8 g, Uint8 b, Uint32* palette, unsigned numColors) { +int ColorUtils::NearestColor(Uint8 r, Uint8 g, Uint8 b, Uint32* palette, unsigned numColors) { Sint64 minDist = 255 * 255 * 3; int bestColor = 0; diff --git a/source/Engine/Utilities/StringUtils.cpp b/source/Engine/Utilities/StringUtils.cpp index c9fd7e7e..493f7504 100644 --- a/source/Engine/Utilities/StringUtils.cpp +++ b/source/Engine/Utilities/StringUtils.cpp @@ -1,37 +1,28 @@ -#if INTERFACE -#include -#include - -class StringUtils { -public: -}; -#endif - #include #include -PUBLIC STATIC char* StringUtils::Create(void* src, size_t length) { +char* StringUtils::Create(void* src, size_t length) { char* string = (char*)Memory::Malloc(length + 1); memcpy(string, src, length); string[length] = '\0'; return string; } -PUBLIC STATIC char* StringUtils::Create(string src) { +char* StringUtils::Create(string src) { return StringUtils::Duplicate(src.c_str()); } -PUBLIC STATIC char* StringUtils::Create(Token token) { +char* StringUtils::Create(Token token) { char* string = (char*)Memory::Malloc(token.Length + 1); memcpy(string, token.Start, token.Length); string[token.Length] = '\0'; return string; } -PUBLIC STATIC char* StringUtils::Duplicate(const char* src) { +char* StringUtils::Duplicate(const char* src) { size_t length = strlen(src) + 1; char* string = (char*)Memory::Malloc(length); memcpy(string, src, length); return string; } -PUBLIC STATIC char* StringUtils::Duplicate(const char* src, size_t length) { +char* StringUtils::Duplicate(const char* src, size_t length) { size_t srcLength = strlen(src); if (length > srcLength) length = srcLength; @@ -40,7 +31,7 @@ PUBLIC STATIC char* StringUtils::Duplicate(const char* src, size_t length) { string[length] = '\0'; return string; } -PUBLIC STATIC char* StringUtils::Resize(char* src, size_t length) { +char* StringUtils::Resize(char* src, size_t length) { size_t originalSize = strlen(src); char* string = (char *)Memory::Realloc(src, length + 1); if (length > originalSize) @@ -49,7 +40,7 @@ PUBLIC STATIC char* StringUtils::Resize(char* src, size_t length) { string[length] = '\0'; return string; } -PUBLIC STATIC bool StringUtils::WildcardMatch(const char* first, const char* second) { +bool StringUtils::WildcardMatch(const char* first, const char* second) { if (*first == 0 && *second == 0) return true; if (*first == 0 && *second == '*' && *(second + 1) != 0) @@ -60,14 +51,14 @@ PUBLIC STATIC bool StringUtils::WildcardMatch(const char* first, const char* sec return StringUtils::WildcardMatch(first, second + 1) || StringUtils::WildcardMatch(first + 1, second); return false; } -PUBLIC STATIC bool StringUtils::StartsWith(const char* string, const char* compare) { +bool StringUtils::StartsWith(const char* string, const char* compare) { size_t cmpLen = strlen(compare); if (strlen(string) < cmpLen) return false; return memcmp(string, compare, cmpLen) == 0; } -PUBLIC STATIC char* StringUtils::StrCaseStr(const char* haystack, const char* needle) { +char* StringUtils::StrCaseStr(const char* haystack, const char* needle) { if (!needle[0]) return (char*)haystack; /* Loop over all possible start positions. */ @@ -89,7 +80,7 @@ PUBLIC STATIC char* StringUtils::StrCaseStr(const char* haystack, const char* ne } return NULL; } -PUBLIC STATIC size_t StringUtils::Copy(char* dst, const char* src, size_t sz) { +size_t StringUtils::Copy(char* dst, const char* src, size_t sz) { char* d = dst; const char* s = src; size_t n = sz; @@ -112,7 +103,7 @@ PUBLIC STATIC size_t StringUtils::Copy(char* dst, const char* src, size_t sz) { return s - src - 1; // count does not include NUL } -PUBLIC STATIC size_t StringUtils::Concat(char* dst, const char* src, size_t sz) { +size_t StringUtils::Concat(char* dst, const char* src, size_t sz) { char *d = dst; const char *s = src; size_t n = sz; @@ -137,7 +128,7 @@ PUBLIC STATIC size_t StringUtils::Concat(char* dst, const char* src, size_t sz) return dlen + (s - src); // count does not include NUL } -PUBLIC STATIC bool StringUtils::ToNumber(int* dst, const char* src) { +bool StringUtils::ToNumber(int* dst, const char* src) { char* end; long num = strtol(src, &end, 10); @@ -151,7 +142,7 @@ PUBLIC STATIC bool StringUtils::ToNumber(int* dst, const char* src) { (*dst) = num; return true; } -PUBLIC STATIC bool StringUtils::ToDecimal(double* dst, const char* src) { +bool StringUtils::ToDecimal(double* dst, const char* src) { char* end; double num = strtod(src, &end); @@ -163,13 +154,13 @@ PUBLIC STATIC bool StringUtils::ToDecimal(double* dst, const char* src) { (*dst) = num; return true; } -PUBLIC STATIC bool StringUtils::ToNumber(int* dst, string src) { +bool StringUtils::ToNumber(int* dst, string src) { return ToNumber(dst, src.c_str()); } -PUBLIC STATIC bool StringUtils::ToDecimal(double* dst, string src) { +bool StringUtils::ToDecimal(double* dst, string src) { return ToDecimal(dst, src.c_str()); } -PUBLIC STATIC char* StringUtils::GetPath(const char* filename) { +char* StringUtils::GetPath(const char* filename) { if (!filename) return nullptr; @@ -189,7 +180,7 @@ PUBLIC STATIC char* StringUtils::GetPath(const char* filename) { return path; } -PUBLIC STATIC char* StringUtils::ConcatPaths(const char* pathA, const char* pathB) { +char* StringUtils::ConcatPaths(const char* pathA, const char* pathB) { if (!pathA || !pathB) return nullptr; @@ -217,7 +208,7 @@ PUBLIC STATIC char* StringUtils::ConcatPaths(const char* pathA, const char* path memcpy(newPath, pathB, lenB); return out; } -PUBLIC STATIC char* StringUtils::ReplacePathSeparators(const char* path) { +char* StringUtils::ReplacePathSeparators(const char* path) { if (!path) return nullptr; @@ -239,7 +230,7 @@ PUBLIC STATIC char* StringUtils::ReplacePathSeparators(const char* path) { return newPath; } -PUBLIC STATIC void StringUtils::ReplacePathSeparatorsInPlace(char* path) { +void StringUtils::ReplacePathSeparatorsInPlace(char* path) { if (!path) return; diff --git a/tools/makeheaders b/tools/makeheaders deleted file mode 100755 index cb6c99a4..00000000 Binary files a/tools/makeheaders and /dev/null differ diff --git a/tools/makeheaders-src/crc32.h b/tools/makeheaders-src/crc32.h deleted file mode 100644 index 3c6352f0..00000000 --- a/tools/makeheaders-src/crc32.h +++ /dev/null @@ -1,91 +0,0 @@ -static uint32_t crc32_t[256] = { - 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L, - 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L, - 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, - 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, - 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L, - 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, - 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, - 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL, - 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, - 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL, - 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, - 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L, - 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L, - 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL, - 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, - 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L, - 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL, - 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L, - 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, - 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L, - 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL, - 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L, - 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L, - 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL, - 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L, - 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L, - 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L, - 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L, - 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L, - 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL, - 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, - 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L, - 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, - 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL, - 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL, - 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L, - 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL, - 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L, - 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, - 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L, - 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL, - 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L, - 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, - 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL, - 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L, - 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L, - 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, - 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L, - 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L, - 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L, - 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, - 0x2d02ef8dL -}; - -uint32_t crc32(char* c, uint32_t len) { - uint32_t crc32val = 0; - uint8_t* s = (uint8_t*)c; - for (uint32_t i = 0; i < len; i++) { - if (c[i] == '\r') continue; - if (!c[i]) break; - crc32val = crc32_t[(crc32val ^ s[i]) & 0xFF] ^ (crc32val >> 8); - } - return crc32val; -} -uint32_t crc32_inc(char* c, uint32_t len, uint32_t crc32val) { - uint8_t* s = (uint8_t*)c; - for (uint32_t i = 0; i < len; i++) { - if (c[i] == '\r') continue; - if (!c[i]) break; - crc32val = crc32_t[(crc32val ^ s[i]) & 0xFF] ^ (crc32val >> 8); - } - return crc32val; -} - -uint32_t crc32_file(FILE* f) { - if (!f) return 0; - - char* buf; - size_t filelen; - - fseek(f, 0, SEEK_END); - filelen = ftell(f); - rewind(f); - - buf = (char*)malloc(filelen); // Enough memory for file + \0 - fread(buf, filelen, 1, f); // Read in the entire file - rewind(f); - - return crc32(buf, filelen); -} diff --git a/tools/makeheaders-src/main.cpp b/tools/makeheaders-src/main.cpp deleted file mode 100644 index 96e441a8..00000000 --- a/tools/makeheaders-src/main.cpp +++ /dev/null @@ -1,852 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#if !MSVC - #include - #include - #include "crc32.h" -#else - #include - #include - #include - #include - #include - #include -#endif - -using namespace std; - -char finalpath[4096]; - -static void MakeDir(const char *dir) { - struct stat st = {0}; - if (stat(dir, &st) == -1) - mkdir(dir, 0700); -} - -static void RecursiveMakeDir(const char *path) { - char tmp[4096]; - - snprintf(tmp, sizeof(tmp), "%s", path); - size_t len = strlen(tmp); - - if (tmp[len - 1] == '/') - tmp[len - 1] = 0; - - for (char *p = tmp + 1; *p; p++) { - if (*p == '/') { - *p = '\0'; - MakeDir(tmp); - *p = '/'; - } - } - - MakeDir(tmp); -} - -struct VARIABLE { - std::string class_type; - std::string variable_name; -}; - -struct CLASSFILE { - std::vector includes; - std::string class_name; - std::string parent_class_name; - std::string file_name; - std::vector public_vars; - std::vector private_vars; - std::vector protected_vars; - std::vector public_funcs; - std::vector private_funcs; - std::vector protected_funcs; - vector classes_needed; -}; - -int class_count_alpha = 0; -bool any_class_changed = false; - -int FindChar(char* str, char c) { - char* strln = str; - do { - if (*strln == c) - return strln - str; - strln++; - } while (*strln != 0); - return -1; -} -int FindLastChar(char* str, char c) { - char* strln = str + strlen(str); - do { - if (*strln == c) - return strln - str; - strln--; - } while (strln != str); - return -1; -} - -string replaceFirstOccurrence(string& s, const string& toReplace, const string& replaceWith) { - std::size_t pos = s.find(toReplace); - if (pos == string::npos) return s; - return s.replace(pos, toReplace.length(), replaceWith); -} - -void print_class(const char* directory, CLASSFILE data) { - string class_name(data.class_name); - if (class_name == string("\x01\x01\x01\x01")) - return; - if (class_name == string("")) - return; - - FILE *fp; - char filename[4096]; - - string direc = string(directory); - string basedirec = string(finalpath); - - direc = replaceFirstOccurrence(direc, "source", "include"); - basedirec = replaceFirstOccurrence(basedirec, "source", "include"); - - - struct stat st = {0}; - - if (direc.find("include") != std::string::npos) { - if (stat(direc.substr(0, direc.find("include") + 7).c_str(), &st) == -1) { - RecursiveMakeDir(direc.substr(0, direc.find("include") + 7).c_str()); - } - } - - if (stat(direc.c_str(), &st) == -1) - RecursiveMakeDir(direc.c_str()); - - snprintf(filename, 4096, "%s%s.h", direc.c_str(), data.file_name.c_str()); - // printf("%s\n", filename); - fp = fopen(filename, "wb"); - int err = errno; - if (!fp) { - printf("Could not open %s because %s\n", filename, strerror(err)); - return; - } - - class_count_alpha++; - - class_name = (direc.c_str() + basedirec.length() + 1); - class_name += data.file_name; - std::transform(class_name.begin(), class_name.end(), class_name.begin(), [](unsigned char c) -> unsigned char { - if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))) - return '_'; - return ::toupper(c); - }); - - fprintf(fp, "#ifndef %s_H\n", class_name.c_str()); - fprintf(fp, "#define %s_H\n", class_name.c_str()); - fprintf(fp, "\n"); - fprintf(fp, "#define PUBLIC\n"); - fprintf(fp, "#define PRIVATE\n"); - fprintf(fp, "#define PROTECTED\n"); - fprintf(fp, "#define STATIC\n"); - fprintf(fp, "#define VIRTUAL\n"); - fprintf(fp, "#define EXPOSED\n"); - fprintf(fp, "\n"); - for (int i = 0; i < data.classes_needed.size(); i++) { - fprintf(fp, "class %s;\n", data.classes_needed[i].c_str()); - } - fprintf(fp, "\n"); - - for (std::vector::iterator it = data.includes.begin(); it != data.includes.end(); ++it) { - fprintf(fp, "#include %s\n", (*it).c_str()); - } - fprintf(fp, "\n"); - fprintf(fp, "class %s%s%s {\n", data.class_name.c_str(), data.parent_class_name != string("") ? " : public " : "", data.parent_class_name != string("") ? data.parent_class_name.c_str() : ""); - bool damada = 0; - if (data.private_vars.size() > 0 || data.private_funcs.size() > 0) { - fprintf(fp, "private:\n"); - bool yamero = 0; - for (std::vector::iterator it = - data.private_vars.begin(); it != - data.private_vars.end(); ++it) { - fprintf(fp, " %s %s\n", (*it).class_type.c_str(), (*it).variable_name.c_str()); - yamero = 1; - } - - if (yamero) - fprintf(fp, "\n"); - - for (std::vector::iterator it = - data.private_funcs.begin(); it != - data.private_funcs.end(); ++it) { - fprintf(fp, " %s\n", (*it).c_str()); - } - damada = 1; - } - if (data.public_vars.size() > 0 || data.public_funcs.size() > 0) { - if (damada) - fprintf(fp, "\n"); - - fprintf(fp, "public:\n"); - bool yamero = 0; - for (std::vector::iterator it = - data.public_vars.begin(); it != - data.public_vars.end(); ++it) { - fprintf(fp, " %s %s\n", (*it).class_type.c_str(), (*it).variable_name.c_str()); - yamero = 1; - } - - if (yamero) - fprintf(fp, "\n"); - - for (std::vector::iterator it = - data.public_funcs.begin(); it != - data.public_funcs.end(); ++it) { - fprintf(fp, " %s\n", (*it).c_str()); - } - } - if (data.protected_vars.size() > 0 || data.protected_funcs.size() > 0) { - if (damada) - fprintf(fp, "\n"); - - fprintf(fp, "protected:\n"); - bool yamero = 0; - for (std::vector::iterator it = - data.protected_vars.begin(); it != - data.protected_vars.end(); ++it) { - fprintf(fp, " %s %s\n", (*it).class_type.c_str(), (*it).variable_name.c_str()); - yamero = 1; - } - - if (yamero) - fprintf(fp, "\n"); - - for (std::vector::iterator it = - data.protected_funcs.begin(); it != - data.protected_funcs.end(); ++it) { - fprintf(fp, " %s\n", (*it).c_str()); - } - } - fprintf(fp, "};\n"); - - fprintf(fp, "\n"); - fprintf(fp, "#endif /* %s_H */\n", class_name.c_str()); - - fclose(fp); -} - -vector ClassNames; -string find_classname(char* filename) { - FILE *fp; - fp = fopen(filename, "rb"); - if (!fp) { - printf("Could not load file (find_classname): %s!\n", filename); - exit(EXIT_FAILURE); - } - - bool in_interface = false; - bool in_interfaced = false; - int in_variables = 0; - - // printf("find: %s\n", filename); - - while (true) { - char first_token[255]; - if (fscanf(fp, "%s", first_token) <= 0) { - break; - } - - if (!strcmp(first_token, "#if")) { - char rest_of_line[255]; - fscanf(fp, "%c", rest_of_line); // clears space - fgets(rest_of_line, 255, fp); - rest_of_line[strcspn(rest_of_line, "\r\n")] = 0; rest_of_line[strcspn(rest_of_line, "\n")] = 0; - - if (!strncmp(rest_of_line, "INTERFACE", 9)) { - in_interface = true; - in_interfaced = true; - } - } - else { - if (!in_interfaced) { - fclose(fp); - return string(""); - } - } - if (!strcmp(first_token, "#endif")) { - char rest_of_line[255]; - fgets(rest_of_line, 255, fp); - if (in_interface) { - in_interface = false; - in_variables = 0; - } - } - else if (!strcmp(first_token, "class")) { - char rest_of_line[255]; - fscanf(fp, "%s", rest_of_line); - fclose(fp); - - return string(rest_of_line); - } - } - return string(""); -} - -CLASSFILE load_class(char* filename) { - FILE *fp; - CLASSFILE test; - fp = fopen(filename, "rb"); - if (!fp) { - printf("Could not load file (load_class): %s!\n", filename); - exit(EXIT_FAILURE); - } - //printf("Loading file: %s\n", filename); - - bool in_interface = false; - bool in_interfaced = false; - int in_variables = 0; - - char ObjectName[256]; - int found = FindLastChar(filename, '/'); - memset(ObjectName, 0, 256); - strcpy(ObjectName, filename + found + 1); - int nextfind = FindChar(ObjectName, '.'); - memset(ObjectName + nextfind, 0, 256 - nextfind); - - test.file_name = string(ObjectName); - - int brackscope = 0; - - while (true) { - char first_token[255]; - if (fscanf(fp, "%s", first_token) <= 0) - break; - - if (!strcmp(first_token, "#if")) { - char rest_of_line[255]; - fscanf(fp, "%c", rest_of_line); // clears space - fgets(rest_of_line, 255, fp); - rest_of_line[strcspn(rest_of_line, "\r\n")] = 0; rest_of_line[strcspn(rest_of_line, "\n")] = 0; - - if (!strncmp(rest_of_line, "INTERFACE", 9)) { - in_interface = true; - in_interfaced = true; - } - } - else { - if (!in_interfaced) { - test.class_name = string("\x01\x01\x01\x01"); - break; - } - } - if (!strcmp(first_token, "#endif")) { - char rest_of_line[255]; - fgets(rest_of_line, 255, fp); - if (in_interface) { - in_interface = false; - in_variables = 0; - } - } - else if (!strcmp(first_token, "#include")) { - char rest_of_line[255]; - fscanf(fp, "%c", rest_of_line); // clears space - fgets(rest_of_line, 255, fp); - rest_of_line[strcspn(rest_of_line, "\r\n")] = 0; rest_of_line[strcspn(rest_of_line, "\n")] = 0; - - if (in_interface) - test.includes.push_back(rest_of_line); - } - else if (!strcmp(first_token, "need_t")) { - char rest_of_line[255]; - fscanf(fp, " "); - fscanf(fp, "%[^;]", rest_of_line); - - test.classes_needed.push_back(string(rest_of_line)); - } - else if (!strcmp(first_token, "class")) { - if (test.class_name.empty()) { - char rest_of_line[255]; - fscanf(fp, "%s", rest_of_line); - - test.class_name = std::string(rest_of_line); - - fgets(rest_of_line, 255, fp); - rest_of_line[strcspn(rest_of_line, "\r\n")] = 0; rest_of_line[strcspn(rest_of_line, "\n")] = 0; - - char enws[255]; - if (sscanf(rest_of_line, " : public %s", enws) > 0) { - test.parent_class_name = std::string(enws); - } - - in_variables = 1; - } - } - else if (!strcmp(first_token, "{") || !strcmp(first_token, "}") || !strcmp(first_token, "};")) { - if (!strcmp(first_token, "};")) { - if (brackscope > 0) { - char rest_of_line[255]; - fscanf(fp, "%c", rest_of_line); // clears space - fgets(rest_of_line, 255, fp); - rest_of_line[strcspn(rest_of_line, "\r\n")] = 0; rest_of_line[strcspn(rest_of_line, "\n")] = 0; - - if (in_interface) { - if (in_variables == 1) - test.private_vars.push_back(VARIABLE { string(first_token), string() }); - else if (in_variables == 2) - test.public_vars.push_back(VARIABLE { string(first_token), string() }); - else if (in_variables == 3) - test.protected_vars.push_back(VARIABLE { string(first_token), string() }); - } - brackscope--; - } - else { - in_variables = 0; - continue; - } - } - } - else if (!strcmp(first_token, "private:")) { - in_variables = 1; - } - else if (!strcmp(first_token, "public:")) { - in_variables = 2; - } - else if (!strcmp(first_token, "protected:")) { - in_variables = 3; - } - else if (in_variables) { - char nom[255]; - sscanf(first_token, "%[A-Za-z0-9_]", nom); - - if (!strcmp(nom, "struct") || !strcmp(nom, "enum")) - brackscope++; - - char rest_of_line[255]; - fscanf(fp, "%c", rest_of_line); // clears space - fgets(rest_of_line, 255, fp); - rest_of_line[strcspn(rest_of_line, "\r\n")] = 0; rest_of_line[strcspn(rest_of_line, "\n")] = 0; - - for (int i = 0; i < ClassNames.size(); i++) { - if (string(nom) == ClassNames[i]) { - test.classes_needed.push_back(string(nom)); - break; - } - } - - if (in_interface) { - if (in_variables == 1) - test.private_vars.push_back(VARIABLE { string(first_token), string(rest_of_line) }); - else if (in_variables == 2) - test.public_vars.push_back(VARIABLE { string(first_token), string(rest_of_line) }); - else if (in_variables == 3) - test.protected_vars.push_back(VARIABLE { string(first_token), string(rest_of_line) }); - } - } - else if ((!strcmp(first_token, "PUBLIC") || !strcmp(first_token, "PRIVATE") || !strcmp(first_token, "PROTECTED")) && !in_interface) { - char* rest_of_line = (char*)malloc(512); - fscanf(fp, "%c", rest_of_line); // clears space - fgets(rest_of_line, 512, fp); - rest_of_line[strcspn(rest_of_line, "\r\n")] = 0; rest_of_line[strcspn(rest_of_line, "\n")] = 0; - - bool statik = false; - bool virtua = false; - if (!strncmp(rest_of_line, "STATIC", 6)) { - statik = true; - char temp[512]; - sprintf(temp, "%s", rest_of_line + 7); - strcpy(rest_of_line, temp); - } - if (!strncmp(rest_of_line, "VIRTUAL", 7)) { - virtua = true; - char temp[512]; - sprintf(temp, "%s", rest_of_line + 8); - strcpy(rest_of_line, temp); - } - - if (FindChar(rest_of_line, ':') < 0) { - printf("\x1b[1;32mFatal Error: \x1b[0mCould not find class name for line '%s'.\n", rest_of_line); - exit(1); - } - - char* wherefunc = strstr(rest_of_line, (test.class_name + "::").c_str()); - if (!wherefunc) { - printf("\x1b[1;32mFatal Error: \x1b[0mIncorrect class name `%.*s` (should be `%s`.)\n", FindChar(rest_of_line, ':'), rest_of_line, test.class_name.c_str()); - exit(1); - } - char* function_name = wherefunc + test.class_name.size() + 2; - int ind = strlen(function_name) - 2; - char* couldbe = strstr(function_name, ": "); - if (couldbe != NULL) { - ind = couldbe - function_name - 1; - } - if (function_name[ind] != ' ') - ind++; - function_name[ind] = ';'; - function_name[ind + 1] = 0; - - char type[500]; - if (wherefunc - rest_of_line > 0) { - sprintf(type, "%s", rest_of_line); - //printf("%s\n", type); - type[wherefunc - rest_of_line] = 0; - } - else { - sprintf(type, "%s", ""); - } - - char finalfunname[500]; - if (statik) - sprintf(finalfunname, "%s%s%s", "static ", type, function_name); - else if (virtua) - sprintf(finalfunname, "%s%s%s", "virtual ", type, function_name); - else - sprintf(finalfunname, "%s%s", type, function_name); - - if (!strcmp(first_token, "PRIVATE")) - test.private_funcs.push_back(string(finalfunname)); - else if (!strcmp(first_token, "PUBLIC")) - test.public_funcs.push_back(string(finalfunname)); - else if (!strcmp(first_token, "PROTECTED")) - test.protected_funcs.push_back(string(finalfunname)); - - free(rest_of_line); - } - else if (!strcmp(first_token, "//") && !in_interface) { - char rest_of_line[512]; - fscanf(fp, "%c", rest_of_line); // clears space - fgets(rest_of_line, 512, fp); - rest_of_line[strcspn(rest_of_line, "\r\n")] = 0; rest_of_line[strcspn(rest_of_line, "\n")] = 0; - } - } - - fclose(fp); - return test; -} - -bool prelistdir(const char *name, int indent) { - DIR *dir; - struct dirent *entry; - - if (!(dir = opendir(name))) - return false; - - while ((entry = readdir(dir)) != NULL) { - if (entry->d_type == DT_DIR) { - char path[4096]; - if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) - continue; - snprintf(path, sizeof(path), "%s/%s", name, entry->d_name); - prelistdir(path, indent + 2); - } - else if (indent == 0) { - continue; - } - else if (strstr(entry->d_name, ".cpp")) { - char path[4096]; - snprintf(path, sizeof(path), "%s/%s", name, entry->d_name); - - char newname[1024]; - snprintf(newname, sizeof(newname), "%s", name); - size_t sz = strlen(name); - if (newname[sz - 1] != '/') { - newname[sz] = '/'; - newname[sz + 1] = 0; - } - - string str = find_classname(path); - if (str != "") { - ClassNames.push_back(str); - } - } - } - closedir(dir); - return true; -} - -struct ClassHash { - uint32_t FilenameHash; - uint32_t InterfaceChecksum; -}; -vector ClassHashes; -int GetClassHash(uint32_t filenameHash) { - for (int i = 0; i < ClassHashes.size(); i++) { - if (ClassHashes[i].FilenameHash == filenameHash) - return i; - } - return -1; -} -int PutClassHash(uint32_t filenameHash, uint32_t checkSum) { - int idx = GetClassHash(filenameHash); - if (idx >= 0) { - ClassHashes[idx].FilenameHash = filenameHash; - ClassHashes[idx].InterfaceChecksum = checkSum; - return 0; - } - - ClassHash ch; - ch.FilenameHash = filenameHash; - ch.InterfaceChecksum = checkSum; - ClassHashes.push_back(ch); - return 1; -} -void LoadClassHashTable() { - #if MSVC - FILE* f = fopen("../makeheaders.bin", "rb"); - #else - FILE* f = fopen("makeheaders.bin", "rb"); - #endif - if (f) { - for (;;) { - ClassHash ch; - if (fread(&ch, sizeof(ClassHash), 1, f) <= 0) - break; - - ClassHashes.push_back(ch); - } - fclose(f); - } -} -void SaveClassHashTable() { - #if MSVC - FILE* f = fopen("../makeheaders.bin", "wb"); - #else - FILE* f = fopen("makeheaders.bin", "wb"); - #endif - if (f) { - for (int i = 0; i < ClassHashes.size(); i++) { - fwrite(&ClassHashes[i], sizeof(ClassHash), 1, f); - } - fclose(f); - } -} - -// Printing -enum class PrintColor { - Default = 0, - Red, - Yellow, - Green, - Purple, -}; -void PrintHeader(FILE* f, const char* str, PrintColor col) { - int color = 0; - #if MSVC - switch (col) { - case PrintColor::Red: color = 4; break; - case PrintColor::Yellow: color = 14; break; - case PrintColor::Green: color = 2; break; - case PrintColor::Purple: color = 5; break; - default: color = 0xF; break; - } - CONSOLE_SCREEN_BUFFER_INFO csbi; - HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); - if (GetConsoleScreenBufferInfo(hStdOut, &csbi)) { - SetConsoleTextAttribute(hStdOut, (csbi.wAttributes & 0xF0) | color); - } - fprintf(f, str); - SetConsoleTextAttribute(hStdOut, csbi.wAttributes); - #else - switch (col) { - case PrintColor::Red: color = 91; break; - case PrintColor::Yellow: color = 93; break; - case PrintColor::Green: color = 92; break; - case PrintColor::Purple: color = 95; break; - default: color = 37; break; - } - fprintf(f, "\x1b[1;%dm%s\x1b[0m", color, str); - #endif -} - -bool MakeHeaderCheck(char* filename) { - if (FindChar(filename, '.') < 0) { - PrintHeader(stderr, "error: ", PrintColor::Red); - fprintf(stderr, "Could not find '.' in '%s'!\n", filename); - exit(EXIT_FAILURE); - return false; - } - - bool didChange = false; - - FILE* f = fopen(filename, "rb"); - if (!f) { - PrintHeader(stderr, "error: ", PrintColor::Red); - fprintf(stderr, "Could not open file '%s'!\n", filename); - exit(EXIT_FAILURE); - } - - int interfaceStart = -1; - int interfaceEnd = -1; - - int found, nextfind; - char* HeaderName = (char*)calloc(1, 256); - - found = FindLastChar(filename, '/'); - nextfind = FindChar(filename + found + 1, '.'); - strncpy(HeaderName, filename + found + 1, nextfind); - memset(HeaderName + nextfind, 0, 256 - nextfind); - - int ifScope = 0; - while (true) { - int64_t tokenStart = ftell(f); - - char first_token[255]; - if (fscanf(f, "%s", first_token) <= 0) { - // printf("reached EOF\n"); - break; - } - - if (!strcmp(first_token, "#if")) { - fscanf(f, " "); - char rest_of_line[255]; - fgets(rest_of_line, 255, f); - rest_of_line[strcspn(rest_of_line, "\n")] = 0; - rest_of_line[strcspn(rest_of_line, "\r\n")] = 0; - - if (!strncmp(rest_of_line, "INTERFACE", 9)) { - interfaceStart = ftell(f); - } - - ifScope++; - } - else if (!strcmp(first_token, "#endif")) { - ifScope--; - if (ifScope == 0) { - interfaceEnd = tokenStart; - break; - } - } - } - - // get function descriptors - // rewind(f); - uint32_t FDChecksum = 0x00000000; - while (true) { - char rest_of_line[1024]; - if (!fgets(rest_of_line, 1024, f)) { - break; - } - - if ((!strncmp(rest_of_line, "PUBLIC", 6) || !strncmp(rest_of_line, "PRIVATE", 7) || !strncmp(rest_of_line, "PROTECTED", 9))) { - rest_of_line[strcspn(rest_of_line, "\r\n")] = 0; rest_of_line[strcspn(rest_of_line, "\n")] = 0; - - FDChecksum = crc32_inc(rest_of_line, strlen(rest_of_line), FDChecksum); - } - } - - if (interfaceStart == -1) { - return false; - } - if (interfaceStart != -1 && interfaceEnd == -1) { - PrintHeader(stderr, "error: ", PrintColor::Red); - fprintf(stderr, "Missing matching #endif in file '%s'!\n", filename); - exit(EXIT_FAILURE); - return false; - } - - char* interfaceField = (char*)calloc(1, interfaceEnd - interfaceStart + 1); - fseek(f, interfaceStart, SEEK_SET); - fread(interfaceField, interfaceEnd - interfaceStart, 1, f); - - uint32_t Namehash = crc32(filename, strlen(filename)); - - uint32_t Checksum = 0x00000000; - uint32_t ComparisonHash = 0x00000000; - - int idx = -1; - if ((idx = GetClassHash(Namehash)) != -1) - ComparisonHash = ClassHashes[idx].InterfaceChecksum; - - Checksum = crc32_inc(interfaceField, interfaceEnd - interfaceStart, FDChecksum); - didChange = Checksum != ComparisonHash; - - if (!didChange) { - SaveClassHashTable(); - return didChange; - } - - PutClassHash(Namehash, Checksum); - - return didChange; -} -bool ListClassDir(const char* name, const char* parent, int indent) { - DIR* dir; - struct dirent* entry; - - if (!(dir = opendir(name))) - return false; - - char path[4096]; - while ((entry = readdir(dir))) { - if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) - continue; - - sprintf(path, "%s/%s", name, entry->d_name); - - if (entry->d_type == DT_DIR) { - ListClassDir(path, parent, indent + 2); - } - else if (strstr(entry->d_name, ".cpp")) { - if (MakeHeaderCheck(path)) { - char parentFolder[4096]; - snprintf(parentFolder, sizeof(parentFolder), "%s", name); - size_t sz = strlen(name); - if (parentFolder[sz - 1] != '/') { - parentFolder[sz] = '/'; - parentFolder[sz + 1] = 0; - } - - // printf("path: %s parentFolder: %s\n", path, parentFolder); - - print_class(parentFolder, load_class(path)); - } - } - } - closedir(dir); - return true; -} - -int main(int argc, char **argv) { - if (argc <= 1) { - printf("No source code path!\n"); - printf("Usage:\n"); - printf(" %s [options] path\n", argv[0]); - return 0; - } - - printf("\n"); - // printf("Desired Directory: '%s' (%s)\n", argv[1], argv[1][0] == '/' ? "ABSOLUTE" : "RELATIVE"); - - if (argv[1][0] == '/') { - sprintf(finalpath, "%s%s", argv[1], ""); - } - else { - char cwd[4096]; - getcwd(cwd, sizeof(cwd)); - sprintf(finalpath, "%s/%s%s", cwd, argv[1], ""); - } - #if MSVC - _fullpath(finalpath, argv[1], 4096); - #else - realpath(argv[1], finalpath); - #endif - // printf("Final Directory: '%s'\n", finalpath); - - clock_t start, stop; - start = clock(); - - LoadClassHashTable(); - if (prelistdir(finalpath, 0)) { - ListClassDir(finalpath, finalpath, 0); - } - SaveClassHashTable(); - - stop = clock(); - PrintHeader(stdout, "makeheaders: ", PrintColor::Green); - printf("Generated %d header(s) in %.3f milliseconds.\n\n", class_count_alpha, (stop - start) * 1000.f / CLOCKS_PER_SEC); - - return 0; -} diff --git a/tools/makeheaders.exe b/tools/makeheaders.exe deleted file mode 100644 index 596d2a6d..00000000 Binary files a/tools/makeheaders.exe and /dev/null differ diff --git a/tools/makeheaders2-src/crc32.h b/tools/makeheaders2-src/crc32.h deleted file mode 100644 index 870c6044..00000000 --- a/tools/makeheaders2-src/crc32.h +++ /dev/null @@ -1,74 +0,0 @@ -static uint32_t crc32_t[256] = { - 0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L, - 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L, - 0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L, - 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL, - 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L, - 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L, - 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L, - 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL, - 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L, - 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL, - 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L, - 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L, - 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L, - 0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL, - 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL, - 0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L, - 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL, - 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L, - 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L, - 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L, - 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL, - 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L, - 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L, - 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL, - 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L, - 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L, - 0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L, - 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L, - 0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L, - 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL, - 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL, - 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L, - 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L, - 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL, - 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL, - 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L, - 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL, - 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L, - 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL, - 0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L, - 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL, - 0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L, - 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L, - 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL, - 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L, - 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L, - 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L, - 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L, - 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L, - 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L, - 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL, - 0x2d02ef8dL -}; - -uint32_t crc32(char* c, uint32_t len) { - uint32_t crc32val = 0; - uint8_t* s = (uint8_t*)c; - for (uint32_t i = 0; i < len; i++) { - if (c[i] == '\r') continue; - if (!c[i]) break; - crc32val = crc32_t[(crc32val ^ s[i]) & 0xFF] ^ (crc32val >> 8); - } - return crc32val; -} -uint32_t crc32_inc(char* c, uint32_t len, uint32_t crc32val) { - uint8_t* s = (uint8_t*)c; - for (uint32_t i = 0; i < len; i++) { - if (c[i] == '\r') continue; - if (!c[i]) break; - crc32val = crc32_t[(crc32val ^ s[i]) & 0xFF] ^ (crc32val >> 8); - } - return crc32val; -} diff --git a/tools/makeheaders2-src/dirent.c b/tools/makeheaders2-src/dirent.c deleted file mode 100644 index c322a7ef..00000000 --- a/tools/makeheaders2-src/dirent.c +++ /dev/null @@ -1,316 +0,0 @@ -/* - * dirent.c - * - * Derived from DIRLIB.C by Matt J. Weinstein - * This note appears in the DIRLIB.H - * DIRLIB.H by M. J. Weinstein Released to public domain 1-Jan-89 - * - * Updated by Jeremy Bettis - * Significantly revised and rewinddir, seekdir and telldir added by Colin - * Peters - * - * $Revision: 1.1 $ - * $Author: tml $ - * $Date: 2001/09/29 22:09:24 $ - * - */ - -#include -#include -#include -#include -#include - -#include "dirent.h" - -#define WIN32_LEAN_AND_MEAN -#include /* for GetFileAttributes */ - -#define SUFFIX "*" -#define SLASH "\\" - -/* - * opendir - * - * Returns a pointer to a DIR structure appropriately filled in to begin - * searching a directory. - */ -DIR * -opendir (const char *szPath) -{ - DIR *nd; - unsigned int rc; - - errno = 0; - - if (!szPath) - { - errno = EFAULT; - return (DIR *) 0; - } - - if (szPath[0] == '\0') - { - errno = ENOTDIR; - return (DIR *) 0; - } - - /* Attempt to determine if the given path really is a directory. */ - rc = GetFileAttributes(szPath); - if (rc == ((DWORD)-1)) - { - /* call GetLastError for more error info */ - errno = ENOENT; - return (DIR *) 0; - } - if (!(rc & FILE_ATTRIBUTE_DIRECTORY)) - { - /* Error, entry exists but not a directory. */ - errno = ENOTDIR; - return (DIR *) 0; - } - - /* Allocate enough space to store DIR structure and the complete - * directory path given. */ - nd = (DIR *) malloc (sizeof (DIR) + strlen (szPath) + strlen (SLASH) + - strlen (SUFFIX)); - - if (!nd) - { - /* Error, out of memory. */ - errno = ENOMEM; - return (DIR *) 0; - } - - /* Create the search expression. */ - strcpy (nd->dd_name, szPath); - - /* Add on a slash if the path does not end with one. */ - if (nd->dd_name[0] != '\0' && - nd->dd_name[strlen (nd->dd_name) - 1] != '/' && - nd->dd_name[strlen (nd->dd_name) - 1] != '\\') - { - strcat (nd->dd_name, SLASH); - } - - /* Add on the search pattern */ - strcat (nd->dd_name, SUFFIX); - - /* Initialize handle to -1 so that a premature closedir doesn't try - * to call _findclose on it. */ - nd->dd_handle = -1; - - /* Initialize the status. */ - nd->dd_stat = 0; - - /* Initialize the dirent structure. ino and reclen are invalid under - * Win32, and name simply points at the appropriate part of the - * findfirst_t structure. */ - nd->dd_dir.d_ino = 0; - nd->dd_dir.d_reclen = 0; - nd->dd_dir.d_namlen = 0; - nd->dd_dir.d_name = nd->dd_dta.name; - - return nd; -} - - -/* - * readdir - * - * Return a pointer to a dirent structure filled with the information on the - * next entry in the directory. - */ -struct dirent * -readdir (DIR * dirp) -{ - errno = 0; - - /* Check for valid DIR struct. */ - if (!dirp) - { - errno = EFAULT; - return (struct dirent *) 0; - } - - if (dirp->dd_dir.d_name != dirp->dd_dta.name) - { - /* The structure does not seem to be set up correctly. */ - errno = EINVAL; - return (struct dirent *) 0; - } - - if (dirp->dd_stat < 0) - { - /* We have already returned all files in the directory - * (or the structure has an invalid dd_stat). */ - return (struct dirent *) 0; - } - else if (dirp->dd_stat == 0) - { - /* We haven't started the search yet. */ - /* Start the search */ - dirp->dd_handle = _findfirst (dirp->dd_name, &(dirp->dd_dta)); - - if (dirp->dd_handle == -1) - { - /* Whoops! Seems there are no files in that - * directory. */ - dirp->dd_stat = -1; - } - else - { - dirp->dd_stat = 1; - } - } - else - { - /* Get the next search entry. */ - if (_findnext (dirp->dd_handle, &(dirp->dd_dta))) - { - /* We are off the end or otherwise error. */ - _findclose (dirp->dd_handle); - dirp->dd_handle = -1; - dirp->dd_stat = -1; - } - else - { - /* Update the status to indicate the correct - * number. */ - dirp->dd_stat++; - } - } - - if (dirp->dd_stat > 0) - { - /* Successfully got an entry. Everything about the file is - * already appropriately filled in except the length of the - * file name. */ - dirp->dd_dir.d_namlen = strlen (dirp->dd_dir.d_name); - return &dirp->dd_dir; - } - - return (struct dirent *) 0; -} - - -/* - * closedir - * - * Frees up resources allocated by opendir. - */ -int -closedir (DIR * dirp) -{ - int rc; - - errno = 0; - rc = 0; - - if (!dirp) - { - errno = EFAULT; - return -1; - } - - if (dirp->dd_handle != -1) - { - rc = _findclose (dirp->dd_handle); - } - - /* Delete the dir structure. */ - free (dirp); - - return rc; -} - -/* - * rewinddir - * - * Return to the beginning of the directory "stream". We simply call findclose - * and then reset things like an opendir. - */ -void -rewinddir (DIR * dirp) -{ - errno = 0; - - if (!dirp) - { - errno = EFAULT; - return; - } - - if (dirp->dd_handle != -1) - { - _findclose (dirp->dd_handle); - } - - dirp->dd_handle = -1; - dirp->dd_stat = 0; -} - -/* - * telldir - * - * Returns the "position" in the "directory stream" which can be used with - * seekdir to go back to an old entry. We simply return the value in stat. - */ -long -telldir (DIR * dirp) -{ - errno = 0; - - if (!dirp) - { - errno = EFAULT; - return -1; - } - return dirp->dd_stat; -} - -/* - * seekdir - * - * Seek to an entry previously returned by telldir. We rewind the directory - * and call readdir repeatedly until either dd_stat is the position number - * or -1 (off the end). This is not perfect, in that the directory may - * have changed while we weren't looking. But that is probably the case with - * any such system. - */ -void -seekdir (DIR * dirp, long lPos) -{ - errno = 0; - - if (!dirp) - { - errno = EFAULT; - return; - } - - if (lPos < -1) - { - /* Seeking to an invalid position. */ - errno = EINVAL; - return; - } - else if (lPos == -1) - { - /* Seek past end. */ - if (dirp->dd_handle != -1) - { - _findclose (dirp->dd_handle); - } - dirp->dd_handle = -1; - dirp->dd_stat = -1; - } - else - { - /* Rewind and read forward to the appropriate index. */ - rewinddir (dirp); - - while ((dirp->dd_stat < lPos) && readdir (dirp)) - ; - } -} \ No newline at end of file diff --git a/tools/makeheaders2-src/dirent.h b/tools/makeheaders2-src/dirent.h deleted file mode 100644 index dcaebd22..00000000 --- a/tools/makeheaders2-src/dirent.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - * DIRENT.H (formerly DIRLIB.H) - * - * by M. J. Weinstein Released to public domain 1-Jan-89 - * - * Because I have heard that this feature (opendir, readdir, closedir) - * it so useful for programmers coming from UNIX or attempting to port - * UNIX code, and because it is reasonably light weight, I have included - * it in the Mingw32 package. I have also added an implementation of - * rewinddir, seekdir and telldir. - * - Colin Peters - * - * This code is distributed in the hope that is will be useful but - * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY - * DISCLAMED. This includeds but is not limited to warranties of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * - * $Revision: 1.1 $ - * $Author: tml $ - * $Date: 2001/09/29 22:09:24 $ - * - */ - -#ifndef __STRICT_ANSI__ - -#ifndef _DIRENT_H_ -#define _DIRENT_H_ - -#include - -#ifndef RC_INVOKED - -#ifdef __cplusplus -extern "C" { -#endif - -struct dirent -{ - long d_ino; /* Always zero. */ - unsigned short d_reclen; /* Always zero. */ - unsigned short d_namlen; /* Length of name in d_name. */ - char* d_name; /* File name. */ - /* NOTE: The name in the dirent structure points to the name in the - * finddata_t structure in the DIR. */ -}; - -/* - * This is an internal data structure. Good programmers will not use it - * except as an argument to one of the functions below. - */ -typedef struct -{ - /* disk transfer area for this dir */ - struct _finddata_t dd_dta; - - /* dirent struct to return from dir (NOTE: this makes this thread - * safe as long as only one thread uses a particular DIR struct at - * a time) */ - struct dirent dd_dir; - - /* _findnext handle */ - long dd_handle; - - /* - * Status of search: - * 0 = not started yet (next entry to read is first entry) - * -1 = off the end - * positive = 0 based index of next entry - */ - short dd_stat; - - /* given path for dir with search pattern (struct is extended) */ - char dd_name[1]; -} DIR; - - -DIR* opendir (const char*); -struct dirent* readdir (DIR*); -int closedir (DIR*); -void rewinddir (DIR*); -long telldir (DIR*); -void seekdir (DIR*, long); - -#ifdef __cplusplus -} -#endif - -#endif /* Not RC_INVOKED */ - -#endif /* Not _DIRENT_H_ */ - -#endif /* Not __STRICT_ANSI__ */ diff --git a/tools/makeheaders2-src/makeheaders.cpp b/tools/makeheaders2-src/makeheaders.cpp deleted file mode 100644 index 932b67d6..00000000 --- a/tools/makeheaders2-src/makeheaders.cpp +++ /dev/null @@ -1,1161 +0,0 @@ -#include -#include -#include -#include -#include -#ifndef _WIN32 - #include - #include -#else - #include - #include - #include "dirent.c" -#endif - -#include "crc32.h" - -using namespace std; - -static char finalpath[4096]; - -// Printing -enum class PrintColor { - Default = 0, - Red, - Yellow, - Green, - Purple, -}; -void PrintHeader(FILE* f, const char* str, PrintColor col) { - int color = 0; -#ifdef _WIN32 - switch (col) { - case PrintColor::Red: color = 4; break; - case PrintColor::Yellow: color = 14; break; - case PrintColor::Green: color = 2; break; - case PrintColor::Purple: color = 5; break; - default: color = 0xF; break; - } - CONSOLE_SCREEN_BUFFER_INFO csbi; - HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); - if (GetConsoleScreenBufferInfo(hStdOut, &csbi)) { - SetConsoleTextAttribute(hStdOut, (csbi.wAttributes & 0xF0) | color); - } - fprintf(f, str); - SetConsoleTextAttribute(hStdOut, csbi.wAttributes); -#else - switch (col) { - case PrintColor::Red: color = 91; break; - case PrintColor::Yellow: color = 93; break; - case PrintColor::Green: color = 92; break; - case PrintColor::Purple: color = 95; break; - default: color = 37; break; - } - fprintf(f, "\x1b[1;%dm%s\x1b[0m", color, str); -#endif -} - -#ifdef _WIN32 -#include - -static ssize_t getline(char** string, size_t* n, FILE* f) { - if (string == NULL || f == NULL || n == NULL) { - errno = EINVAL; - return -1; - } - - int c = getc(f); - if (c == EOF) - return -1; - - size_t pos = 0; - size_t baseSize = 128; - - if (*string == NULL) { - *string = (char*)malloc(baseSize); - if (!*string) - abort(); - *n = baseSize; - } - - for (; c != EOF; c = getc(f)) { - if (pos + 1 >= *n) { - size_t size = max(*n + (*n >> 2), baseSize); - *string = (char*)realloc(*string, size); - if (!*string) - abort(); - *n = size; - } - - ((unsigned char *)(*string))[pos++] = c; - if (c == '\n') - break; - } - - (*string)[pos] = '\0'; - return pos; -} -#endif - -class Scanner { -private: - char* start; - char* current; - - FILE* file; - char* buffer; - size_t buffer_len; - - bool readLine() { - ssize_t result = getline(&buffer, &buffer_len, file); - if (result == -1) { - isDone = true; - return false; - } - - start = current = buffer; - line++; - - return true; - } - - char peek() { - return current[0]; - } - - char peekNext() { - if (isAtEnd()) - return '\0'; - return current[1]; - } - - char advance() { - current++; - return current[-1]; - } - - bool isWhitespace(char c) { - if (c == '\0') - return false; - return isspace(c); - } - - void captureToken() { - while (!isWhitespace(peek())) - advance(); - } - - std::string getLineString() { - std::string output(start, current - start); - - output.erase(output.find_last_not_of("\r\n")+1); - - return output; - } - -public: - int line; - bool isDone; - - Scanner(FILE *f) { - start = current = nullptr; - isDone = false; - line = 0; - - buffer = nullptr; - buffer_len = 0; - - file = f; - readLine(); - } - - bool isAtEnd() { - return current[0] == '\0'; - } - - bool peekToken(const char *token) { - if (isAtEnd() && !readLine()) - return ""; - - char *last = current; - captureToken(); - - int length = strlen(token); - if (current - start == length && !memcmp(start, token, length)) { - current = last; - return true; - } - - current = last; - return false; - } - - bool matchToken(const char *token) { - if (isAtEnd() && !readLine()) - return ""; - - char *last = current; - captureToken(); - - int length = strlen(token); - if (current - start == length && !memcmp(start, token, length)) { - skipWhitespace(); - start = current; - return true; - } - - current = last; - return false; - } - - std::string getToken() { - if (isAtEnd() && !readLine()) - return ""; - - captureToken(); - - std::string output(start, current - start); - - skipWhitespace(); - start = current; - - return output; - } - - std::string peekRestOfLine() { - if (isAtEnd() && !readLine()) - return ""; - - char *last = current; - while (!isAtEnd()) - advance(); - - std::string output = getLineString(); - current = last; - return output; - } - - std::string getRestOfLine() { - if (isAtEnd()) - return ""; - while (!isAtEnd()) - advance(); - return getLineString(); - } - - int findCharPos(char match) { - if (isAtEnd() && !readLine()) - return -1; - - char *last = current; - while (peek() != match) { - advance(); - if (isAtEnd()) { - current = last; - return -1; - } - } - - int pos = current - last; - current = last; - return pos; - } - - std::string getLineUntilChar(char match) { - if (isAtEnd() && !readLine()) - return ""; - - while (peek() != match) { - advance(); - if (isAtEnd()) - break; - } - - std::string output(start, current - start); - return output; - } - - bool gotoNextLine() { - return readLine(); - } - - bool skipWhitespace() { - while (true) { - switch (peek()) { - case ' ': - case '\r': - case '\t': - case '\n': - advance(); - break; - default: - return true; - } - } - - return true; - } - - ~Scanner() { - free(buffer); - } -}; - -static void MakeDir(const char *dir) { - struct stat st = {0}; - if (stat(dir, &st) == -1) { -#ifdef _WIN32 - mkdir(dir); -#else - mkdir(dir, 0700); -#endif - } -} - -static void RecursiveMakeDir(const char *path) { - char tmp[4096]; - - snprintf(tmp, sizeof(tmp), "%s", path); - size_t len = strlen(tmp); - - if (tmp[len - 1] == '/') - tmp[len - 1] = 0; - - for (char *p = tmp + 1; *p; p++) { - if (*p == '/') { - *p = '\0'; - MakeDir(tmp); - *p = '/'; - } - } - - MakeDir(tmp); -} - -struct VARIABLE { - std::string class_type; - std::string variable_name; - int block_depth; -}; - -struct CLASSFILE { - std::vector includes; - std::string class_name; - std::string parent_class_name; - std::string file_name; - std::vector public_vars; - std::vector private_vars; - std::vector protected_vars; - std::vector public_funcs; - std::vector private_funcs; - std::vector protected_funcs; - vector classes_needed; -}; - -int num_generated_headers = 0; - -int FindChar(char* str, char c) { - char* strln = str; - do { - if (*strln == c) - return strln - str; - strln++; - } while (*strln != 0); - return -1; -} -int FindLastChar(char* str, char c) { - char* strln = str + strlen(str); - do { - if (*strln == c) - return strln - str; - strln--; - } while (strln != str); - return -1; -} - -string replaceFirstOccurrence(string& s, const string& toReplace, const string& replaceWith) { - std::size_t pos = s.find(toReplace); - if (pos == string::npos) return s; - return s.replace(pos, toReplace.length(), replaceWith); -} - -void WriteVariable(FILE* fp, VARIABLE var) { - int num = var.block_depth; - do { - fprintf(fp, " "); - } while (num-- > 0); - fprintf(fp, "%s %s\n", var.class_type.c_str(), var.variable_name.c_str()); -} - -void WriteClass(const char* directory, CLASSFILE data) { - string class_name(data.class_name); - if (class_name == string("\x01\x01\x01\x01")) - return; - if (class_name == string("")) - return; - - string direc = string(directory); - string basedirec = string(finalpath); - - direc = replaceFirstOccurrence(direc, "source", "include"); - basedirec = replaceFirstOccurrence(basedirec, "source", "include"); - - struct stat st = {0}; - - if (direc.find("include") != std::string::npos) { - if (stat(direc.substr(0, direc.find("include") + 7).c_str(), &st) == -1) { - RecursiveMakeDir(direc.substr(0, direc.find("include") + 7).c_str()); - } - } - - if (stat(direc.c_str(), &st) == -1) - RecursiveMakeDir(direc.c_str()); - - std::string filename = direc + data.file_name + ".h"; - FILE *fp = fopen(filename.c_str(), "wb"); - int err = errno; - if (!fp) { - PrintHeader(stderr, "error: ", PrintColor::Red); - printf("Could not open %s because %s\n", filename.c_str(), strerror(err)); - return; - } - - num_generated_headers++; - - class_name = (direc.c_str() + basedirec.length() + 1); - class_name += data.file_name; - std::transform(class_name.begin(), class_name.end(), class_name.begin(), [](unsigned char c) -> unsigned char { - if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))) - return '_'; - return ::toupper(c); - }); - - fprintf(fp, "#ifndef %s_H\n", class_name.c_str()); - fprintf(fp, "#define %s_H\n", class_name.c_str()); - fprintf(fp, "\n"); - fprintf(fp, "#define PUBLIC\n"); - fprintf(fp, "#define PRIVATE\n"); - fprintf(fp, "#define PROTECTED\n"); - fprintf(fp, "#define STATIC\n"); - fprintf(fp, "#define VIRTUAL\n"); - fprintf(fp, "#define EXPOSED\n"); - fprintf(fp, "\n"); - for (size_t i = 0; i < data.classes_needed.size(); i++) { - fprintf(fp, "class %s;\n", data.classes_needed[i].c_str()); - } - fprintf(fp, "\n"); - - for (std::vector::iterator it = data.includes.begin(); it != data.includes.end(); ++it) { - fprintf(fp, "#include %s\n", (*it).c_str()); - } - fprintf(fp, "\n"); - fprintf(fp, "class %s%s%s {\n", data.class_name.c_str(), data.parent_class_name != string("") ? " : public " : "", data.parent_class_name != string("") ? data.parent_class_name.c_str() : ""); - - bool did_private = false; - if (data.private_vars.size() > 0 || data.private_funcs.size() > 0) { - fprintf(fp, "private:\n"); - bool wrote_any = false; - for (std::vector::iterator it = - data.private_vars.begin(); it != - data.private_vars.end(); ++it) { - WriteVariable(fp, (*it)); - wrote_any = true; - } - - if (wrote_any) - fprintf(fp, "\n"); - - for (std::vector::iterator it = - data.private_funcs.begin(); it != - data.private_funcs.end(); ++it) { - fprintf(fp, " %s\n", (*it).c_str()); - } - did_private = true; - } - if (data.public_vars.size() > 0 || data.public_funcs.size() > 0) { - if (did_private) - fprintf(fp, "\n"); - - fprintf(fp, "public:\n"); - bool wrote_any = false; - for (std::vector::iterator it = - data.public_vars.begin(); it != - data.public_vars.end(); ++it) { - WriteVariable(fp, (*it)); - wrote_any = true; - } - - if (wrote_any) - fprintf(fp, "\n"); - - for (std::vector::iterator it = - data.public_funcs.begin(); it != - data.public_funcs.end(); ++it) { - fprintf(fp, " %s\n", (*it).c_str()); - } - } - if (data.protected_vars.size() > 0 || data.protected_funcs.size() > 0) { - if (did_private) - fprintf(fp, "\n"); - - fprintf(fp, "protected:\n"); - bool wrote_any = false; - for (std::vector::iterator it = - data.protected_vars.begin(); it != - data.protected_vars.end(); ++it) { - WriteVariable(fp, (*it)); - wrote_any = true; - } - - if (wrote_any) - fprintf(fp, "\n"); - - for (std::vector::iterator it = - data.protected_funcs.begin(); it != - data.protected_funcs.end(); ++it) { - fprintf(fp, " %s\n", (*it).c_str()); - } - } - fprintf(fp, "};\n"); - - fprintf(fp, "\n"); - fprintf(fp, "#endif /* %s_H */\n", class_name.c_str()); - - fclose(fp); -} - -vector ClassNames; -string FindClassName(char* filename) { - FILE *fp = fopen(filename, "rb"); - if (!fp) { - fclose(fp); - printf("Could not load file (FindClassName): %s!\n", filename); - exit(EXIT_FAILURE); - } - - bool found_interface = false; - std::string token; - - Scanner scanner(fp); - if (scanner.isDone) { - fclose(fp); - return string(""); - } - - token = scanner.getToken(); - - while (!scanner.isDone) { - if (token == "#if") { - token = scanner.getToken(); - - if (scanner.isDone) { - fclose(fp); - return string(""); - } - else if (token == "INTERFACE") - found_interface = true; - } - else if (!found_interface) { - fclose(fp); - return string(""); - } - - if (token == "class") { - token = scanner.getToken(); - fclose(fp); - return token; - } - - token = scanner.getToken(); - } - - fclose(fp); - return string(""); -} - -CLASSFILE ReadClass(char* filename) { - FILE *fp; - CLASSFILE test; - fp = fopen(filename, "rb"); - if (!fp) { - printf("Could not load file (ReadClass): %s!\n", filename); - exit(EXIT_FAILURE); - } - - bool in_interface = false; - bool found_interface = false; - int in_variables = 0; - - std::string class_filename = std::string(filename); - std::string class_name; - - std::size_t first = class_filename.find_last_of("/"); - if (first == std::string::npos) - first = 0; - else - first++; - - std::string split = class_filename.substr(first); - std::size_t last = split.find_last_of("."); - if (last == std::string::npos) - last = split.length(); - - test.file_name = split.substr(0, last); - - int ifScope = 0; - int brackscope = 0; - int in_struct_or_enum = 0; - - Scanner scanner(fp); - if (scanner.isDone) { - fclose(fp); - return test; - } - - std::string token = scanner.getToken(); - -#define throw_err_start() { \ - char fmt[4096 + 32]; \ - snprintf(fmt, sizeof(fmt), "error in '%s', line %d: ", filename, scanner.line); \ - PrintHeader(stderr, fmt, PrintColor::Red); \ -} -#define throw_err_end() exit(EXIT_FAILURE) -#define throw_err(msg) \ - throw_err_start(); \ - fprintf(stderr, msg " in class '%s'!\n", test.file_name.c_str()); \ - throw_err_end(); - - while (!scanner.isDone) { - std::string first_token = token; - if (token == "#if") { - token = scanner.getToken(); - if (scanner.isDone) { - throw_err("Unexpected end of file"); - } - - if (token == "INTERFACE") { - in_interface = true; - found_interface = true; - } - - ifScope++; - } - else if (!found_interface) { - test.class_name = string("\x01\x01\x01\x01"); - break; - } - if (token == "#endif") { - if (!scanner.gotoNextLine()) - break; - if (in_interface) { - in_interface = false; - in_variables = 0; - } - if (ifScope > 0) { - ifScope--; - if (ifScope < 0 || brackscope != 0) { - throw_err("Malformed source code"); - } - } - } - else if (token == "#include") { - std::string rest_of_line = scanner.getRestOfLine(); - if (rest_of_line == "") { - throw_err("Malformed source code"); - } - if (in_interface) - test.includes.push_back(rest_of_line); - } - else if (token == "need_t") { - if (scanner.findCharPos(';') == -1) { - throw_err("Missing ';' after class name for 'need_t'"); - } - - std::string rest_of_line = scanner.getLineUntilChar(';'); - if (scanner.isDone) { - throw_err("Unexpected end of file"); - } - else if (rest_of_line == "") { - throw_err("Missing class name for 'need_t'"); - } - - test.classes_needed.push_back(rest_of_line); - } - else if (token == "class") { - if (test.class_name.empty()) { - test.class_name = scanner.getToken(); - if (scanner.isDone) { - throw_err("Unexpected end of file after class name"); - } - - if (scanner.matchToken(":") && scanner.matchToken("public")) { - token = scanner.getToken(); - if (scanner.isDone) { - throw_err("Unexpected end of file after 'public'"); - } - test.parent_class_name = token; - } - if (scanner.isDone) { - throw_err("Unexpected end of file"); - } - - in_variables = 1; - } - } - else if (token == "{" || token == "}" || token == "};") { - if (token == "{") { - if (in_interface) - brackscope++; - } - else if (token == "}" || token == "};") { - if (in_interface) { - brackscope--; - if (brackscope < 0) { - throw_err("Malformed source code"); - } - } - - if (in_struct_or_enum > 0) { - std::string var_name = ""; - if (token == "}") - var_name = scanner.getToken(); - VARIABLE var = VARIABLE { token, var_name, 0 }; - if (in_variables == 1) - test.private_vars.push_back(var); - else if (in_variables == 2) - test.public_vars.push_back(var); - else if (in_variables == 3) - test.protected_vars.push_back(var); - in_struct_or_enum--; - } - } - } - else if (token.rfind("private", 0) == 0) { - if (token.find(":") == std::string::npos && !scanner.matchToken(":")) { - throw_err("Unexpected token after 'private'"); - } - if (scanner.isDone) { - throw_err("Unexpected end of file after 'private:'"); - } - if (in_variables) - in_variables = 1; - } - else if (token.rfind("public", 0) == 0) { - if (token.find(":") == std::string::npos && !scanner.matchToken(":")) { - throw_err("Unexpected token after 'public'"); - } - if (scanner.isDone) { - throw_err("Unexpected end of file after 'public:'"); - } - if (in_variables) - in_variables = 2; - } - else if (token.rfind("protected", 0) == 0) { - if (token.find(":") == std::string::npos && !scanner.matchToken(":")) { - throw_err("Unexpected token after 'protected'"); - } - if (scanner.isDone) { - throw_err("Unexpected end of file after 'protected:'"); - } - if (in_variables) - in_variables = 3; - } - else if (in_variables) { - if (token == "") { - token = scanner.getToken(); - continue; - } - - bool token_is_struct = false; - if (token == "struct" || token == "enum") { - in_struct_or_enum++; - token_is_struct = true; - } - else if (in_interface) { - for (size_t i = 0; i < ClassNames.size(); i++) { - if (token == ClassNames[i]) { - test.classes_needed.push_back(token); - break; - } - } - } - - std::string rest_of_line; - if (token_is_struct) { - if (!scanner.peekToken("{")) - rest_of_line = scanner.getToken() + " {"; - else - rest_of_line = "{"; - if (scanner.isDone) { - throw_err("Unexpected end of file after 'struct' or 'enum'"); - } - } else { - rest_of_line = scanner.getRestOfLine(); - if (scanner.isDone) { - throw_err("Unexpected end of file"); - } - } - - if (in_interface) { - VARIABLE var = VARIABLE { token, rest_of_line, token_is_struct ? 0 : in_struct_or_enum }; - if (in_variables == 1) - test.private_vars.push_back(var); - else if (in_variables == 2) - test.public_vars.push_back(var); - else if (in_variables == 3) - test.protected_vars.push_back(var); - } - } - else if ((token == "PUBLIC" || token == "PRIVATE" || token == "PROTECTED") && !in_interface) { - bool statik = false; - bool virtua = false; - if (scanner.peekToken("STATIC")) { - statik = true; - scanner.getToken(); - if (scanner.isDone) { - throw_err("Unexpected end of file"); - } - } - else if (scanner.peekToken("VIRTUAL")) { - virtua = true; - scanner.getToken(); - if (scanner.isDone) { - throw_err("Unexpected end of file"); - } - } - - token = scanner.getToken(); - - std::string type = ""; - do { - if (token.find(":") != std::string::npos) - break; - else if (token.find("{") != std::string::npos) { - throw_err("Malformed source code"); - } - - type += token + " "; - - token = scanner.getToken(); - if (scanner.isDone) { - throw_err("Unexpected end of file"); - } - } while (true); - - std::string rest_of_line = token + " " + scanner.peekRestOfLine(); - size_t where = rest_of_line.find("::"); - if (where == std::string::npos) { - throw_err("Could not find class name"); - } - - std::string this_class_name = rest_of_line.substr(0, where); - if (test.class_name != this_class_name) { - throw_err_start(); - fprintf(stderr, "Incorrect class name '%s' (should be '%s'!)\n", this_class_name.c_str(), test.file_name.c_str()); - throw_err_end(); - } - - std::string function_name = rest_of_line.substr(where + 2); - - // Remove the { - function_name.erase(function_name.find_first_of("{")); - - // Trim whitespace - size_t last_of_whitespace = function_name.find_last_not_of(" "); - if (last_of_whitespace != std::string::npos) - function_name.erase(last_of_whitespace + 1); - - function_name = type + function_name + ";"; - if (statik) - function_name = "static " + function_name; - else if (virtua) - function_name = "virtual " + function_name; - - if (first_token == "PRIVATE") - test.private_funcs.push_back(string(function_name)); - else if (first_token == "PUBLIC") - test.public_funcs.push_back(string(function_name)); - else if (first_token == "PROTECTED") - test.protected_funcs.push_back(string(function_name)); - - scanner.gotoNextLine(); - } - - token = scanner.getToken(); - } - -#undef throw_err - - fclose(fp); - return test; -} - -bool CheckExtension(const char* filename, const char* extension) { - char *dot = strrchr((char*)filename, '.'); - return dot && !strcmp(dot, extension); -} - -#ifdef _WIN32 -bool IsPathDir(const char *path) { - struct stat fstat; - if (stat(path, &fstat) < 0) - return false; - return (fstat.st_mode & S_IFMT) == S_IFDIR; -} -#endif - -bool FindClasses(const char* name, int depth) { - DIR *dir; - struct dirent *entry; - - if (!(dir = opendir(name))) - return false; - - while ((entry = readdir(dir)) != NULL) { - char path[4096 + 256]; - snprintf(path, sizeof(path), "%s/%s", name, entry->d_name); - -#ifdef _WIN32 - if (IsPathDir(path)) -#else - if (entry->d_type == DT_DIR) -#endif - { - if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) - continue; - - FindClasses(path, depth + 1); - } - else if (depth == 0) - continue; - else if (CheckExtension(entry->d_name, ".cpp")) { - string class_name = FindClassName(path); - if (class_name != "") - ClassNames.push_back(class_name); - } - } - - closedir(dir); - return true; -} - -struct ClassHash { - uint32_t FilenameHash; - uint32_t InterfaceChecksum; -}; -vector ClassHashes; -int GetClassHash(uint32_t filenameHash) { - for (size_t i = 0; i < ClassHashes.size(); i++) { - if (ClassHashes[i].FilenameHash == filenameHash) - return i; - } - return -1; -} -int PutClassHash(uint32_t filenameHash, uint32_t checkSum) { - int idx = GetClassHash(filenameHash); - if (idx >= 0) { - ClassHashes[idx].FilenameHash = filenameHash; - ClassHashes[idx].InterfaceChecksum = checkSum; - return 0; - } - - ClassHash ch; - ch.FilenameHash = filenameHash; - ch.InterfaceChecksum = checkSum; - ClassHashes.push_back(ch); - return 1; -} - -std::string classpath; - -void LoadClassHashTable() { - FILE* f = fopen(classpath.c_str(), "rb"); - if (f) { - for (;;) { - ClassHash ch; - if (fread(&ch, sizeof(ClassHash), 1, f) <= 0) - break; - - ClassHashes.push_back(ch); - } - fclose(f); - } -} -void SaveClassHashTable() { - FILE* f = fopen(classpath.c_str(), "wb"); - if (f) { - for (size_t i = 0; i < ClassHashes.size(); i++) { - fwrite(&ClassHashes[i], sizeof(ClassHash), 1, f); - } - fclose(f); - } -} - -bool MakeHeaderCheck(char* filename) { - FILE* f = fopen(filename, "rb"); - if (!f) { - PrintHeader(stderr, "error: ", PrintColor::Red); - fprintf(stderr, "Could not open file '%s'!\n", filename); - exit(EXIT_FAILURE); - } - - Scanner scanner(f); - if (scanner.isDone) { - PrintHeader(stderr, "error: ", PrintColor::Red); - fprintf(stderr, "Could not find class name in file '%s'!\n", filename); - fclose(f); - return false; - } - - int interfaceStart = -1; - int interfaceEnd = -1; - int ifScope = 0; - - std::string token = scanner.getToken(); - while (!scanner.isDone) { - int64_t tokenStart = ftell(f); - - if (token == "#if") { - ifScope++; - token = scanner.getToken(); - - if (scanner.isDone) { - PrintHeader(stderr, "error: ", PrintColor::Red); - fprintf(stderr, "Unexpected end of file in file '%s'!\n", filename); - fclose(f); - return false; - } - else if (token == "INTERFACE") - interfaceStart = ftell(f); - } - else if (token == "#endif") { - if (--ifScope == 0) { - interfaceEnd = tokenStart; - break; - } - } - - token = scanner.getToken(); - } - - if (interfaceStart == -1) - return false; - else if (interfaceEnd == -1) { - PrintHeader(stderr, "error: ", PrintColor::Red); - fprintf(stderr, "Missing matching #endif in file '%s'!\n", filename); - exit(EXIT_FAILURE); - return false; - } - - // get function descriptors - uint32_t FDChecksum = 0x00000000; - while (!scanner.isDone) { - if (!scanner.gotoNextLine()) - break; - - std::string token = scanner.getToken(); - if (token == "PUBLIC" || token == "PRIVATE" || token == "PROTECTED") { - std::string rest_of_line = scanner.getRestOfLine(); - std::size_t found = rest_of_line.find_last_of("{"); - if (found != std::string::npos) - rest_of_line.erase(found, 1); - const char* line = rest_of_line.c_str(); - FDChecksum = crc32_inc((char*)line, strlen(line), FDChecksum); - } - } - - char* interfaceField = (char*)calloc(1, interfaceEnd - interfaceStart + 1); - fseek(f, interfaceStart, SEEK_SET); - fread(interfaceField, interfaceEnd - interfaceStart, 1, f); - - uint32_t NameHash = crc32(filename, strlen(filename)); - uint32_t ComparisonHash = 0x00000000; - - int idx = GetClassHash(NameHash); - if (idx != -1) - ComparisonHash = ClassHashes[idx].InterfaceChecksum; - - uint32_t Checksum = crc32_inc(interfaceField, interfaceEnd - interfaceStart, FDChecksum); - if (Checksum == ComparisonHash) { - SaveClassHashTable(); - return false; - } - - PutClassHash(NameHash, Checksum); - - return true; -} -bool ListClassDir(const char* name, const char* parent) { - DIR* dir; - struct dirent* entry; - - if (!(dir = opendir(name))) - return false; - - while ((entry = readdir(dir))) { - if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) - continue; - - char path[4096]; - snprintf(path, sizeof(path), "%s/%s", name, entry->d_name); - -#ifdef _WIN32 - if (IsPathDir(path)) -#else - if (entry->d_type == DT_DIR) -#endif - ListClassDir(path, parent); - else if (CheckExtension(entry->d_name, ".cpp") && MakeHeaderCheck(path)) { - char parentFolder[4096]; - snprintf(parentFolder, sizeof(parentFolder), "%s", name); - size_t sz = strlen(name); - if (parentFolder[sz - 1] != '/') { - parentFolder[sz] = '/'; - parentFolder[sz + 1] = 0; - } - - WriteClass(parentFolder, ReadClass(path)); - } - } - - closedir(dir); - return true; -} - -int main(int argc, char **argv) { - if (argc <= 1) { - printf("No source code path!\n"); - printf("Usage:\n"); - printf(" %s [options] path\n", argv[0]); - return 0; - } - -#ifdef _WIN32 - _fullpath(finalpath, argv[1], sizeof(finalpath)); -#else - realpath(argv[1], finalpath); -#endif - - std::string direc = std::string(finalpath); - classpath = replaceFirstOccurrence(direc, "source", "include"); - - struct stat st = {0}; - if (stat(direc.c_str(), &st) == -1) - RecursiveMakeDir(direc.c_str()); - - classpath += "/makeheaders.bin"; - - clock_t start, stop; - start = clock(); - - LoadClassHashTable(); - if (FindClasses(finalpath, 0)) - ListClassDir(finalpath, finalpath); - SaveClassHashTable(); - - stop = clock(); - PrintHeader(stdout, "makeheaders: ", PrintColor::Green); - printf("Generated %d header(s) in %.3f milliseconds.\n\n", num_generated_headers, (stop - start) * 1000.f / CLOCKS_PER_SEC); - - return 0; -}