From 6b181382bd44730ca97b39022c6caf7245d370a2 Mon Sep 17 00:00:00 2001 From: "Zed A. Shaw" Date: Thu, 2 Jan 2025 11:47:02 -0500 Subject: [PATCH] First build that actually works. SDL_main errors before but didn't figure out the cause. --- .gitignore | 29 + .vimrc_proj | 1 + Makefile | 26 + charset.png | Bin 0 -> 3988 bytes main.cpp | 34 + meson.build | 27 + quickcg.cpp | 2005 ++++++++++++++++++++++++++++++++++++ quickcg.h | 334 ++++++ raycaster_flat.cpp | 242 +++++ scripts/coverage_reset.ps1 | 7 + scripts/coverage_reset.sh | 11 + scripts/reset_build.ps1 | 7 + scripts/reset_build.sh | 11 + sdlprog.cpp | 36 + tests/base.cpp | 9 + wraps/catch2.wrap | 11 + wraps/fmt.wrap | 13 + wraps/freetype2.wrap | 11 + wraps/libpng.wrap | 13 + wraps/nlohmann_json.wrap | 11 + wraps/sdl2.wrap | 15 + 21 files changed, 2853 insertions(+) create mode 100644 .gitignore create mode 100644 .vimrc_proj create mode 100644 Makefile create mode 100644 charset.png create mode 100644 main.cpp create mode 100644 meson.build create mode 100644 quickcg.cpp create mode 100644 quickcg.h create mode 100644 raycaster_flat.cpp create mode 100644 scripts/coverage_reset.ps1 create mode 100644 scripts/coverage_reset.sh create mode 100644 scripts/reset_build.ps1 create mode 100644 scripts/reset_build.sh create mode 100644 sdlprog.cpp create mode 100644 tests/base.cpp create mode 100644 wraps/catch2.wrap create mode 100644 wraps/fmt.wrap create mode 100644 wraps/freetype2.wrap create mode 100644 wraps/libpng.wrap create mode 100644 wraps/nlohmann_json.wrap create mode 100644 wraps/sdl2.wrap diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..20a7cf2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# ---> Vim +# Swap +[._]*.s[a-v][a-z] +!*.svg # comment out if you don't need vector files +[._]*.sw[a-p] +[._]s[a-rt-v][a-z] +[._]ss[a-gi-z] +[._]sw[a-p] + +# Session +Session.vim +Sessionx.vim + +# Temporary +.netrwhist +*~ +# Auto-generated tag files +tags +# Persistent undo +[._]*.un~ + +subprojects +builddir +ttassets +backup +*.exe +*.dll +*.world +coverage diff --git a/.vimrc_proj b/.vimrc_proj new file mode 100644 index 0000000..2b745b4 --- /dev/null +++ b/.vimrc_proj @@ -0,0 +1 @@ +set makeprg=meson\ compile\ -C\ . diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..247d28f --- /dev/null +++ b/Makefile @@ -0,0 +1,26 @@ +all: build test + +reset: + powershell -executionpolicy bypass .\scripts\reset_build.ps1 + +%.cpp : %.rl + ragel -o $@ $< + +build: + meson compile -j 10 -C builddir + +test: build + ./builddir/runtests + +run: build test + powershell "cp ./builddir/lodecaster.exe ." + ./lodecaster + +clean: + meson compile --clean -C builddir + +debug_test: build + gdb --nx -x .gdbinit --ex run --args builddir/runtests.exe + +cover: + gcovr --html coverage/index.html --gcov-ignore-errors=no_working_dir_found --exclude "scratchpad.*" --exclude "subprojects.*" --html-nested coverage/ diff --git a/charset.png b/charset.png new file mode 100644 index 0000000000000000000000000000000000000000..464f7320258f22b5239284fca783deb8d547f3a7 GIT binary patch literal 3988 zcmV;F4{Pv=P)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!~g&e!~vBn4jTXf4=G7RK~#8N?VXEu z+(-^Xll=cbXB+K-7Y*}OQpsuCea}&>B1n)`()f{NW`6(r_3Q8LD*5|2PWk;C<#Qct zy?3BRaiBe_oJ`A5--ym{wchioXK|ACLEdx*=II)DW%WJDh9OO4&TaK zb@kDh=0;TgCuk3cn(LTFW4Pyh;}<|T6m8BMOv!Q?$4AfcSfo2uKIry$X8&08B9X@g z)aj)}aqX)b<4d0b^m4R0n*hC681M9sXcmygKO4@0{rH~z4D@WL`#;O4d6!<`7GMLs@Uf^myqT2)gJkR6acO^fY z0XdluQ9bK{wR-U$ACVDv7qp4u4ISz`&>oR*r)Oldlg?{W?>U(#^HlHl71b!vsd?^Q zyZ!PvE3Qyu;thz$vvmY=GTr-hWb=`;`d8%sJpeYA9kP?dw@J%3t5uN5_xvS{I)*19g=;-F_^eNek$#pa@w60gAXFWjY zr`*2;{CEEW3|yJ{hM3#Mvo(qOX09^-@;V(<{u5Xaj(T4;+q0qj8U0y+9VDE2Sl4BXS`1vrClI=a_^^vduJ0NzJh6mupy-a}Ds;`OhHX2adb9R-}( znAS!q^pKqDfFiG~&m^wBR_4sSohnaz zgKEytrs_TZ5`f|(!)r}+kKyzJ-pAvbt9acM_07m;1FB8D9OUvkN>Lw5BOf1r8H z@mf;#P;FA*&DZI>V4qe0uCAK@j}}wV0^GZSGN}idPO2V&_3A^S9!{op^L6?zw9hKl zT;2Q+-vdMjS{QLw2b0YshnLdTPWta4noX(nY7eaQ%VDi+-Tu?R58y>i%god!%E@&1 zo%Zp3Wm-$zqtii_bF_C>w@T#~X%8;|gv?;oIKy+L{Rbw!x;2@`vpmx2N2olhIaTh8 z_WmW{=!V=FYaQCx4(jwGncopuul`4Zv%V|-oySofOmZU5cw_aZyts^`5B4*-zW^Li@nN$~M75yHqu$kLIzUdR zldgZZ23f5WV;ZC9rDxF@TvtPxTv+)P$_=BCY^-lva#L+<}WSb|Q4!94WPiJ2t^2%5_nwLJ|-|@wlVf2SVo-%pEchythwFVkn)w6X( zmXr0$sOlBuRX!2#UjhK`xn@%x&^2(j9=OL>ME3`xeRvMw+RsFZ>Ks4sDO-OGtcYF& z5N)j6>`vIr4{&7$_gJ0Z>sRrH>} z=};?Z&#q4t_Zsz^5cQnaMy&Qf%ljV&fvhQp$~NdVz5!i(j8uL^>mBuTZ^C${SFFsJ z>7dg|bUu^1BcRhY&M%&V?!|e30hqY@Plz@+@=up?#_MS9v~F@fQO?Bw=)BT)=^@61c7Jb>!qkAV*3)S{*!%F%(ddaQXlU43>>yk6H1w5UgvtI&Hw)xSe$ z(tDsYM0uG$`VxQwUT4ukKr~=P)?aI?`Uz+2J9MwBux9s+?F%q{KvS{@*}?v+b1?U4 z-<{|zM_AeSl%?MY!sVOr7~_mp8gO0Lz;(unu3aPW;N@gBO4S4F%EL9^AIR=^;O7VQ z9B{X{zM7|c0dSCC?EqKkUXYoM`JJzG2K2ckYsl{2Z& z&|3F-_)DR<*R_76<_4PYwZQ9nDY}mID`79r>HC}DGwVJ4rk?JjFs^3zxO!9!waATu!#f`95gj5x4mIXyYf#PQbt_ysUsn&*gY5JNS^VM0 zK+qXxMj2WDs!zvJzt5U4BkFUccUP0?A6|eX(40hGRZdsGTL&v1JNvsvs+_LA>tAvD zGeEbFsB*gcRsG03y6*hCHOb;il{58?@)#qkefYP7fj60;^%2ygoJs>{^(m7c8J+&G z;7oX?`mD+Q_W@Kq3OypPXb4hi;H=IV^7M+JN90v$pwq9W+84-lO!^RIl5Qe1W{&I8 z0aPBV{$#2<%vaq#rW!b_gQNYaF}AwKueVs<;Jfe>_IQN*3-EUPcu1=U!e64uigv-7M08tG1;qBH*)}Oc!U~bi8 zbv_b#PiO1qV!T>M9=Lmp{!n-*iXZYWq6e@W-H*QnzEUZE(jzqPIbNIf0=~wtx7ed0$%bN_tm*`L)V$Ypy#t?bw|6yrq$`=W zYeu+y?E2yost4?3FALc9@WJ~F0CR7~HSeR3BwOPnp{_CIjILVebA-*8D8J&IoJ|fds{7KX^^6zxz zsE#=4^!pzNdqK3$J~D?;Bg_GeYfL$#s}|*TI=Irm(?5f#@6&$|@ZwrtKLz}7@U-5a zls`nL(>t!NuXNR-yiV`<3iVO^^8ZNGi{}Qf!rNA>qd zyuQQzSL>bS{k2Y|jYs+sBCja+U1?tce9Eb=E9m??eFgQ3 zuJ2CzZwK#!hnTg|LymH$`g9w}Kf7g}Njd8~A?r>N{ zcaLhoin)TkP6y1%)*W5F&VX3tU-eY2tId2W{}sCaj%&WgueaD+5J1qR&cN58%8Bwp z76;Uv$RA|=)JOZcf23uxPFK3P!@Nq*Jc;YRZvRdoK|IqO=v|KE{fYKe&#AxH0bNJ_ zJ_A6E*D78Y-Rn#`N2e3!YR!a)Zvtto%?M&q<6Y1*>irCG|306eiSI+#Ub_?eul9L( z0elk*V!pXuxUcqF;mC|pPpws5KTiES+#hI3$F?;|=LRDN7XWI5hz zG6SgcIuD&eb37j9X$)jNGP>D7*28Okjb9%tjY;!=$=Uh*;K;M=_v-U+UjR}KG97Y~ zrw_#QcFd4b_1%f~0q7OQlukdx{ilHFT7d&qb=0ciJ!f@}4EXRO(f#he73k$>k@aV8 zrk~;d?*>K}K{IXWYr>jHV@!Q_<8u@AR*mytIm;DrZjkL$uPLMdSTtZ-c5r8PaKwW# zr|J`-K4mv7 +#include +#include +#include + +#include "quickcg.h" +using namespace QuickCG; +using namespace std; + +//place the example code below here: + +int main(int argc, char *argv[]) +{ + screen(256, 256, 0, "Small Test Script"); + for (int x = 0; x < w; x++) + for (int y = 0; y < h; y++) + { + pset(x, y, ColorRGBA(x, y, 128, 255)); + } + print("Hello, world!", 8, 8); + + std::string test; + test.resize(20); + + redraw(); + sleep(); + + return 0; +} diff --git a/meson.build b/meson.build new file mode 100644 index 0000000..b82f73b --- /dev/null +++ b/meson.build @@ -0,0 +1,27 @@ +project('lodecaster', 'cpp', + default_options: ['cpp_std=c++20']) + +catch2 = dependency('catch2-with-main') +fmt = dependency('fmt') +json = dependency('nlohmann_json') +sdl2 = dependency('sdl2') +sdl2_main = dependency('sdl2main') + +dependencies = [ + sdl2, sdl2_main, + fmt, json +] + +executable('runtests', [ + 'quickcg.cpp', + 'main.cpp', + ], + win_subsystem: 'windows', + dependencies: dependencies) + +executable('lodecaster', [ + 'quickcg.cpp', + 'raycaster_flat.cpp', + ], + win_subsystem: 'windows', + dependencies: dependencies) diff --git a/quickcg.cpp b/quickcg.cpp new file mode 100644 index 0000000..2102492 --- /dev/null +++ b/quickcg.cpp @@ -0,0 +1,2005 @@ +/* +QuickCG SDL2 20190709 + +Copyright (c) 2004-2007, Lode Vandevenne + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/* +QuickCG is an SDL codebase that wraps some of the SDL functionality. +It's used by Lode's Computer Graphics Tutorial to work with simple C++ calls +to demonstrate graphical programs. This SDL2.0 port was made by Chrissy573. + +QuickCG can handle some things that standard C++ doesn't but that are commonly useful, such as: +-drawing graphics +-a bitmap font +-simplified saving and loading of files +-reading keyboard and mouse input +-playing sound +-color models +-loading images +*/ + +#include +#include "quickcg.h" +#include +#include +#include +#include +#include +#include + +namespace QuickCG +{ + + + //////////////////////////////////////////////////////////////////////////////// + //VARIABLES///////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + + int w; //width of the screen + int h; //height of the screen + + std::map keypressed; //for the "keyPressed" function to detect a keypress only once + SDL_Window* scr; //the single SDL window used + SDL_Surface* srf; + SDL_Renderer* render; + SDL_Texture* tex; + SDL_PixelFormat *fmt; + const Uint8* inkeys; + SDL_Event event = { 0 }; + + + //////////////////////////////////////////////////////////////////////////////// + //KEYBOARD FUNCTIONS//////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + + bool keyDown(int key) //this checks if the key is held down, returns true all the time until the key is up + { + return (inkeys[key] != 0); + } + + bool keyPressed(int key) //this checks if the key is *just* pressed, returns true only once until the key is up again + { + if (keypressed.find(key) == keypressed.end()) keypressed[key] = false; + if (inkeys[key]) + { + if (keypressed[key] == false) + { + keypressed[key] = true; + return true; + } + } + else keypressed[key] = false; + + return false; + } + + + //////////////////////////////////////////////////////////////////////////////// + //BASIC SCREEN FUNCTIONS//////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + + //The screen function: sets up the window for 32-bit color graphics. + //Creates a graphical screen of width*height pixels in 32-bit color. + //Set fullscreen to 0 for a window, or to 1 for fullscreen output + //text is the caption or title of the window + //also inits SDL + void screen(int width, int height, bool fullscreen, const std::string& text) + { + w = width; + h = height; + + if (SDL_Init(SDL_INIT_EVERYTHING) < 0) + { + printf("Unable to init SDL: %s\n", SDL_GetError()); + SDL_Quit(); + std::exit(1); + } + + std::atexit(SDL_Quit); + if (fullscreen) + { + scr = SDL_CreateWindow(text.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_FULLSCREEN | SDL_WINDOW_OPENGL); + lock(); + } + else + { + scr = SDL_CreateWindow(text.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_OPENGL); + } + if (scr == NULL) + { + printf("Unable to set video: %s\n", SDL_GetError()); + SDL_Quit(); + std::exit(1); + } + + render = SDL_CreateRenderer(scr, -1, 0); + if (render == NULL) + { + printf("Unable to set renderer: %s\n", SDL_GetError()); + SDL_Quit(); + std::exit(1); + } + + srf = SDL_CreateRGBSurface(0, w, h, 32, + 0xFF000000, + 0x00FF0000, + 0x0000FF00, + 0x000000FF); + if (srf == NULL) + { + printf("Unable to set surface: %s\n", SDL_GetError()); + SDL_Quit(); + std::exit(1); + } + + tex = SDL_CreateTexture(render, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, w, h); + if (tex == NULL) + { + printf("Unable to set texture: %s\n", SDL_GetError()); + SDL_Quit(); + std::exit(1); + } + SDL_SetTextureBlendMode(tex, SDL_BLENDMODE_BLEND); + + fmt = srf->format; + if (fmt == NULL) + { + printf("Unable to set pixel format: %s\n", SDL_GetError()); + SDL_Quit(); + std::exit(1); + } + } + + //Locks the screen + void lock() + { + if (SDL_MUSTLOCK(srf)) + if (SDL_LockSurface(srf) < 0) + return; + } + + //Unlocks the screen + void unlock() + { + if (SDL_MUSTLOCK(srf)) + SDL_UnlockSurface(srf); + } + + //Updates the screen. Has to be called to view new pixels, but use only after + //drawing the whole screen because it's slow. + void redraw() + { + SDL_UpdateTexture(tex, NULL, srf->pixels, srf->pitch); + SDL_RenderClear(render); + SDL_RenderCopy(render, tex, NULL, NULL); + SDL_RenderPresent(render); + } + + //Clears the screen to black + void cls(const ColorRGBA& color) + { + SDL_SetRenderDrawColor(render, color.r, color.g, color.b, color.a); + SDL_RenderClear(render); + SDL_RenderPresent(render); + } + + //Puts an RGBA color pixel at position x,y + void pset(int x, int y, const ColorRGBA& color) + { + if (x < 0 || y < 0 || x >= w || y >= h) return; + Uint32 colorSDL = SDL_MapRGBA(fmt, color.r, color.g, color.b, color.a); + Uint32* bufp; + bufp = (Uint32*)srf->pixels + y * srf->pitch / 4 + x; + *bufp = colorSDL; + } + + //Gets RGB color of pixel at position x,y + ColorRGBA pget(int x, int y) + { + if (x < 0 || y < 0 || x >= w || y >= h) return RGB_Black; + Uint32* bufp; + bufp = (Uint32*)srf->pixels + y * srf->pitch / 4 + x; + Uint32 colorSDL = *bufp; + ColorRGBA8bit colorRGBA; + SDL_GetRGBA(colorSDL, fmt, &colorRGBA.r, &colorRGBA.g, &colorRGBA.b, &colorRGBA.a); + return ColorRGBA(colorRGBA); + } + + //Draws a buffer of pixels to the screen + void drawBuffer(Uint32* buffer) + { + Uint32* bufp; + bufp = (Uint32*)srf->pixels; + + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + *bufp = buffer[y * w + x]; + bufp++; + } + bufp += srf->pitch / 4; + bufp -= w; + } + } + + void getScreenBuffer(std::vector& buffer) + { + Uint32* bufp; + bufp = (Uint32*)srf->pixels; + + buffer.resize(w * h); + + for (int y = 0; y < h; y++) + { + for (int x = 0; x < w; x++) + { + buffer[y * w + x] = *bufp; + bufp++; + } + bufp += srf->pitch / 4; + bufp -= w; + } + } + + bool onScreen(int x, int y) + { + return (x >= 0 && y >= 0 && x < w && y < h); + } + + + //////////////////////////////////////////////////////////////////////////////// + //NON GRAPHICAL FUNCTIONS/////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + + //Waits until you press a key. First the key has to be loose, this means, if you put two sleep functions in a row, the second will only work after you first released the key. + void sleep() + { + int done = 0; + SDL_PollEvent(&event); + while (done == 0) + { + while (SDL_PollEvent(&event)) + { + if (event.type == SDL_QUIT) end(); + if (event.type == SDL_KEYDOWN) done = 1; + } + SDL_Delay(5); //so it consumes less processing power + } + } + + void sleep(double seconds) + { + SDL_Delay((Uint32)seconds * 1000); + } + + void waitFrame(double oldTime, double frameDuration) //in seconds + { + double time = getTime(); + while (time - oldTime < frameDuration) + { + time = getTime(); + SDL_PollEvent(&event); + if (event.type == SDL_QUIT) end(); + inkeys = SDL_GetKeyboardState(NULL); + if (inkeys[SDLK_ESCAPE]) end(); + SDL_Delay(5); //so it consumes less processing power + } + } + + //Returns 1 if you close the window or press the escape key. Also handles everything that's needed per frame. + //Never put key input code right before done() or SDL may see the key as SDL_QUIT + bool done(bool quit_if_esc, bool delay) //delay makes CPU have some free time, use once per frame to avoid 100% usage of a CPU core + { + if (delay) SDL_Delay(5); //so it consumes less processing power + bool done = false; + if (!SDL_PollEvent(&event)) return 0; + readKeys(); + if (quit_if_esc && inkeys[SDLK_ESCAPE]) done = true; + if (event.type == SDL_QUIT) done = true; + return done; + } + + //Ends the program + void end() + { + SDL_Quit(); + std::exit(1); + } + + //Gives value of pressed key to inkeys. + //the variable inkeys can then be used anywhere to check for input + //Normally you have to use readkeys every time you want to use inkeys, but the done() function also uses inkeys so it's not needed to use readkeys if you use done(). + void readKeys() + { + SDL_PollEvent(&event); + inkeys = SDL_GetKeyboardState(NULL); + } + + void getMouseState(int& mouseX, int& mouseY) + { + SDL_GetMouseState(&mouseX, &mouseY); + } + + void getMouseState(int& mouseX, int& mouseY, bool& LMB, bool& RMB) + { + Uint8 mouseState = SDL_GetMouseState(&mouseX, &mouseY); + + if (mouseState & 1) LMB = true; + else LMB = false; + if (mouseState & 4) RMB = true; + else RMB = false; + } + + //Returns the time in milliseconds since the program started + unsigned long getTicks() + { + return SDL_GetTicks(); + } + + + //////////////////////////////////////////////////////////////////////////////// + //2D SHAPES///////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + + //Fast horizontal line from (x1,y) to (x2,y), with rgb color + bool horLine(int y, int x1, int x2, const ColorRGBA& color) + { + if (x2 < x1) { x1 += x2; x2 = x1 - x2; x1 -= x2; } //swap x1 and x2, x1 must be the leftmost endpoint + if (x2 < 0 || x1 >= w || y < 0 || y >= h) return 0; //no single point of the line is on screen + if (x1 < 0) x1 = 0; //clip + if (x2 >= w) x2 = w - 1; //clip + + Uint32 colorSDL = SDL_MapRGBA(fmt, color.r, color.g, color.b, color.a); + Uint32* bufp; + bufp = (Uint32*)srf->pixels + y * srf->pitch / 4 + x1; + for (int x = x1; x <= x2; x++) + { + *bufp = colorSDL; + bufp++; + } + return 1; + } + + + //Fast vertical line from (x,y1) to (x,y2), with rgb color + bool verLine(int x, int y1, int y2, const ColorRGBA& color) + { + if (y2 < y1) { y1 += y2; y2 = y1 - y2; y1 -= y2; } //swap y1 and y2 + if (y2 < 0 || y1 >= h || x < 0 || x >= w) return 0; //no single point of the line is on screen + if (y1 < 0) y1 = 0; //clip + if (y2 >= w) y2 = h - 1; //clip + + Uint32 colorSDL = SDL_MapRGBA(fmt, color.r, color.g, color.b, color.a); + Uint32* bufp; + + bufp = (Uint32*)srf->pixels + y1 * srf->pitch / 4 + x; + for (int y = y1; y <= y2; y++) + { + *bufp = colorSDL; + bufp += srf->pitch / 4; + } + return 1; + } + + + //Bresenham line from (x1,y1) to (x2,y2) with rgb color + bool drawLine(int x1, int y1, int x2, int y2, const ColorRGBA& color) + { + if (x1 < 0 || x1 > w - 1 || x2 < 0 || x2 > w - 1 || y1 < 0 || y1 > h - 1 || y2 < 0 || y2 > h - 1) return 0; + + int deltax = std::abs(x2 - x1); //The difference between the x's + int deltay = std::abs(y2 - y1); //The difference between the y's + int x = x1; //Start x off at the first pixel + int y = y1; //Start y off at the first pixel + int xinc1, xinc2, yinc1, yinc2, den, num, numadd, numpixels, curpixel; + + if (x2 >= x1) //The x-values are increasing + { + xinc1 = 1; + xinc2 = 1; + } + else //The x-values are decreasing + { + xinc1 = -1; + xinc2 = -1; + } + if (y2 >= y1) //The y-values are increasing + { + yinc1 = 1; + yinc2 = 1; + } + else //The y-values are decreasing + { + yinc1 = -1; + yinc2 = -1; + } + if (deltax >= deltay) //There is at least one x-value for every y-value + { + xinc1 = 0; //Don't change the x when numerator >= denominator + yinc2 = 0; //Don't change the y for every iteration + den = deltax; + num = deltax / 2; + numadd = deltay; + numpixels = deltax; //There are more x-values than y-values + } + else //There is at least one y-value for every x-value + { + xinc2 = 0; //Don't change the x for every iteration + yinc1 = 0; //Don't change the y when numerator >= denominator + den = deltay; + num = deltay / 2; + numadd = deltax; + numpixels = deltay; //There are more y-values than x-values + } + for (curpixel = 0; curpixel <= numpixels; curpixel++) + { + pset(x % w, y % h, color); //Draw the current pixel + num += numadd; //Increase the numerator by the top of the fraction + if (num >= den) //Check if numerator >= denominator + { + num -= den; //Calculate the new numerator value + x += xinc1; //Change the x as appropriate + y += yinc1; //Change the y as appropriate + } + x += xinc2; //Change the x as appropriate + y += yinc2; //Change the y as appropriate + } + + return 1; + } + + + //Bresenham circle with center at (xc,yc) with radius and red green blue color + bool drawCircle(int xc, int yc, int radius, const ColorRGBA& color) + { + if (xc - radius < 0 || xc + radius >= w || yc - radius < 0 || yc + radius >= h) return 0; + int x = 0; + int y = radius; + int p = 3 - (radius << 1); + int a, b, c, d, e, f, g, h; + while (x <= y) + { + a = xc + x; //8 pixels can be calculated at once thanks to the symmetry + b = yc + y; + c = xc - x; + d = yc - y; + e = xc + y; + f = yc + x; + g = xc - y; + h = yc - x; + pset(a, b, color); + pset(c, d, color); + pset(e, f, color); + pset(g, f, color); + if (x > 0) //avoid drawing pixels at same position as the other ones + { + pset(a, d, color); + pset(c, b, color); + pset(e, h, color); + pset(g, h, color); + } + if (p < 0) p += (x++ << 2) + 6; + else p += ((x++ - y--) << 2) + 10; + } + + return 1; + } + + + //Filled bresenham circle with center at (xc,yc) with radius and red green blue color + bool drawDisk(int xc, int yc, int radius, const ColorRGBA& color) + { + if (xc + radius < 0 || xc - radius >= w || yc + radius < 0 || yc - radius >= h) return 0; //every single pixel outside screen, so don't waste time on it + int x = 0; + int y = radius; + int p = 3 - (radius << 1); + int a, b, c, d, e, f, g, h; + int pb = yc + radius + 1, pd = yc + radius + 1; //previous values: to avoid drawing horizontal lines multiple times (ensure initial value is outside the range) + while (x <= y) + { + // write data + a = xc + x; + b = yc + y; + c = xc - x; + d = yc - y; + e = xc + y; + f = yc + x; + g = xc - y; + h = yc - x; + if (b != pb) horLine(b, a, c, color); + if (d != pd) horLine(d, a, c, color); + if (f != b) horLine(f, e, g, color); + if (h != d && h != f) horLine(h, e, g, color); + pb = b; + pd = d; + if (p < 0) p += (x++ << 2) + 6; + else p += ((x++ - y--) << 2) + 10; + } + + return 1; + } + + //Rectangle with corners (x1,y1) and (x2,y2) and rgb color + bool drawRect(int x1, int y1, int x2, int y2, const ColorRGBA& color) + { + if (x1 < 0 || x1 > w - 1 || x2 < 0 || x2 > w - 1 || y1 < 0 || y1 > h - 1 || y2 < 0 || y2 > h - 1) return 0; + SDL_Rect rec; + rec.x = x1; + rec.y = y1; + rec.w = x2 - x1 + 1; + rec.h = y2 - y1 + 1; + Uint32 colorSDL = SDL_MapRGBA(fmt, color.r, color.g, color.b, color.a); + SDL_FillRect(srf, &rec, colorSDL); //SDL's ability to draw a hardware rectangle is used for now + return 1; + } + + //Functions for clipping a 2D line to the screen, which is the rectangle (0,0)-(w,h) + //This is the Cohen-Sutherland Clipping Algorithm + //Each of 9 regions gets an outcode, based on if it's at the top, bottom, left or right of the screen + // 1001 1000 1010 9 8 10 + // 0001 0000 0010 1 0 2 + // 0101 0100 0110 5 4 6 + //int findregion returns which of the 9 regions a point is in, void clipline does the actual clipping + int findRegion(int x, int y) + { + int code = 0; + if (y >= h) + code |= 1; //top + else if (y < 0) + code |= 2; //bottom + if (x >= w) + code |= 4; //right + else if (x < 0) + code |= 8; //left + return(code); + } + bool clipLine(int x1, int y1, int x2, int y2, int & x3, int & y3, int & x4, int & y4) + { + int code1, code2, codeout; + bool accept = 0, done = 0; + code1 = findRegion(x1, y1); //the region outcodes for the endpoints + code2 = findRegion(x2, y2); + do //In theory, this can never end up in an infinite loop, it'll always come in one of the trivial cases eventually + { + if (!(code1 | code2)) accept = done = 1; //accept because both endpoints are in screen or on the border, trivial accept + else if (code1 & code2) done = 1; //the line isn't visible on screen, trivial reject + else //if no trivial reject or accept, continue the loop + { + int x, y; + codeout = code1 ? code1 : code2; + if (codeout & 1) //top + { + x = x1 + (x2 - x1) * (h - y1) / (y2 - y1); + y = h - 1; + } + else if (codeout & 2) //bottom + { + x = x1 + (x2 - x1) * -y1 / (y2 - y1); + y = 0; + } + else if (codeout & 4) //right + { + y = y1 + (y2 - y1) * (w - x1) / (x2 - x1); + x = w - 1; + } + else //left + { + y = y1 + (y2 - y1) * -x1 / (x2 - x1); + x = 0; + } + if (codeout == code1) //first endpoint was clipped + { + x1 = x; y1 = y; + code1 = findRegion(x1, y1); + } + else //second endpoint was clipped + { + x2 = x; y2 = y; + code2 = findRegion(x2, y2); + } + } + } while (done == 0); + + if (accept) + { + x3 = x1; + x4 = x2; + y3 = y1; + y4 = y2; + return 1; + } + else + { + x3 = x4 = y3 = y4 = 0; + return 0; + } + } + + + //////////////////////////////////////////////////////////////////////////////// + //COLOR STRUCTS///////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + ColorRGBA::ColorRGBA(Uint8 r, Uint8 g, Uint8 b, Uint8 a) + { + this->r = r; + this->g = g; + this->b = b; + this->a = a; + } + ColorRGBA::ColorRGBA(const ColorRGBA8bit& color) + { + this->r = color.r; + this->g = color.g; + this->b = color.b; + this->a = color.a; + } + ColorRGBA::ColorRGBA() + { + this->r = 0; + this->g = 0; + this->b = 0; + this->a = 0; + } + ColorRGBA8bit::ColorRGBA8bit(Uint8 r, Uint8 g, Uint8 b, Uint8 a) + { + this->r = r; + this->g = g; + this->b = b; + this->a = a; + } + ColorRGBA8bit::ColorRGBA8bit(const ColorRGBA& color) + { + this->r = color.r; + this->g = color.g; + this->b = color.b; + this->a = color.a; + } + ColorRGBA8bit::ColorRGBA8bit() + { + this->r = 0; + this->g = 0; + this->b = 0; + this->a = 0; + } + + //Add two colors + ColorRGBA operator+(const ColorRGBA& color, const ColorRGBA& color2) + { + ColorRGBA c; + c.r = color.r + color2.r; + c.g = color.g + color2.g; + c.b = color.b + color2.b; + c.a = color.a + color2.a; + return c; + } + + //Subtract two colors + ColorRGBA operator-(const ColorRGBA& color, const ColorRGBA& color2) + { + ColorRGBA c; + c.r = color.r - color2.r; + c.g = color.g - color2.g; + c.b = color.b - color2.b; + c.a = color.a - color2.a; + return c; + } + + //Multiplies a color with an integer + ColorRGBA operator*(const ColorRGBA& color, int a) + { + ColorRGBA c; + c.r = color.r * a; + c.g = color.g * a; + c.b = color.b * a; + c.a = color.a * a; + return c; + } + + //Multiplies a color with an integer + ColorRGBA operator*(int a, const ColorRGBA& color) + { + ColorRGBA c; + c.r = color.r * a; + c.g = color.g * a; + c.b = color.b * a; + c.a = color.a * a; + return c; + } + + //Divides a color through an integer + ColorRGBA operator/(const ColorRGBA& color, int a) + { + if (a == 0) return color; + ColorRGBA c; + c.r = color.r / a; + c.g = color.g / a; + c.b = color.b / a; + c.a = color.a / a; + return c; + } + + ColorRGBA overlay(const ColorRGBA& color, const ColorRGBA& color2) + { + ColorRGBA c; + c.r = (color.r * color.a / 255) + (color2.r * color2.a * (255 - color.a) / (255 * 255)); + c.g = (color.g * color.a / 255) + (color2.g * color2.a * (255 - color.a) / (255 * 255)); + c.b = (color.b * color.a / 255) + (color2.b * color2.a * (255 - color.a) / (255 * 255)); + c.a = color.a + (color2.a * (255 - color.a) / 255); + return c; + } + + //Are both colors equal? + bool operator==(const ColorRGBA& color, const ColorRGBA& color2) + { + return(color.r == color2.r && color.g == color2.g && color.b == color2.b && color.a == color2.a); + } + + //Are both colors not equal? + bool operator!=(const ColorRGBA& color, const ColorRGBA& color2) + { + return(!(color.r == color2.r && color.g == color2.g && color.b == color2.b && color.a == color2.a)); + } + + ColorHSL::ColorHSL(Uint8 h, Uint8 s, Uint8 l, Uint8 a) + { + this->h = h; + this->s = s; + this->l = l; + this->a = a; + } + ColorHSL::ColorHSL() + { + this->h = 0; + this->s = 0; + this->l = 0; + this->a = 0; + } + ColorHSV::ColorHSV(Uint8 h, Uint8 s, Uint8 v, Uint8 a) + { + this->h = h; + this->s = s; + this->v = v; + this->a = a; + } + ColorHSV::ColorHSV() + { + this->h = 0; + this->s = 0; + this->v = 0; + this->a = 0; + } + + + //////////////////////////////////////////////////////////////////////////////// + //COLOR CONVERSIONS///////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + /* + Convert colors from one type to another + r=red g=green b=blue h=hue s=saturation l=lightness v=value + Color components from the color structs are Uint8's between 0 and 255 + color components used in the calculations are normalized between 0.0-1.0 + */ + + //Converts an RGB color to HSL color + ColorHSL RGBtoHSL(const ColorRGBA& ColorRGBA) + { + double r, g, b, a, h = 0, s = 0, l; //this function works with floats between 0 and 1 + r = ColorRGBA.r / 256.0; + g = ColorRGBA.g / 256.0; + b = ColorRGBA.b / 256.0; + a = ColorRGBA.a / 256.0; + + const double maxColor = std::max(r, std::max(g, b)); + const double minColor = std::min(r, std::min(g, b)); + + if (minColor == maxColor) //R = G = B, so it's a shade of grey + { + h = 0; //it doesn't matter what value it has + s = 0; + l = r; //doesn't matter if you pick r, g, or b + } + else + { + l = (minColor + maxColor) / 2; + + if (l < 0.5) s = (maxColor - minColor) / (maxColor + minColor); + if (l >= 0.5) s = (maxColor - minColor) / (2.0 - maxColor - minColor); + + if (r == maxColor) h = (g - b) / (maxColor - minColor); + if (g == maxColor) h = 2.0 + (b - r) / (maxColor - minColor); + if (b == maxColor) h = 4.0 + (r - g) / (maxColor - minColor); + + h /= 6; //to bring it to a number between 0 and 1 + if (h < 0) h += 1; + } + + ColorHSL colorHSL; + colorHSL.h = int(h * 255.0); + colorHSL.s = int(s * 255.0); + colorHSL.l = int(l * 255.0); + colorHSL.a = int(a * 255.0); + return colorHSL; + } + + //Converts an HSL color to RGB color + ColorRGBA HSLtoRGB(const ColorHSL& colorHSL) + { + double r, g, b, a, h, s, l; //this function works with floats between 0 and 1 + double temp1, temp2, tempr, tempg, tempb; + h = colorHSL.h / 256.0; + s = colorHSL.s / 256.0; + l = colorHSL.l / 256.0; + a = colorHSL.a / 256.0; + + //If saturation is 0, the color is a shade of grey + if (s == 0) r = g = b = l; + //If saturation > 0, more complex calculations are needed + else + { + //set the temporary values + if (l < 0.5) temp2 = l * (1 + s); + else temp2 = (l + s) - (l * s); + temp1 = 2 * l - temp2; + tempr = h + 1.0 / 3.0; + if (tempr > 1.0) tempr--; + tempg = h; + tempb = h - 1.0 / 3.0; + if (tempb < 0.0) tempb++; + + //red + if (tempr < 1.0 / 6.0) r = temp1 + (temp2 - temp1) * 6.0 * tempr; + else if (tempr < 0.5) r = temp2; + else if (tempr < 2.0 / 3.0) r = temp1 + (temp2 - temp1) * ((2.0 / 3.0) - tempr) * 6.0; + else r = temp1; + + //green + if (tempg < 1.0 / 6.0) g = temp1 + (temp2 - temp1) * 6.0 * tempg; + else if (tempg < 0.5) g = temp2; + else if (tempg < 2.0 / 3.0) g = temp1 + (temp2 - temp1) * ((2.0 / 3.0) - tempg) * 6.0; + else g = temp1; + + //blue + if (tempb < 1.0 / 6.0) b = temp1 + (temp2 - temp1) * 6.0 * tempb; + else if (tempb < 0.5) b = temp2; + else if (tempb < 2.0 / 3.0) b = temp1 + (temp2 - temp1) * ((2.0 / 3.0) - tempb) * 6.0; + else b = temp1; + } + + ColorRGBA ColorRGBA; + ColorRGBA.r = int(r * 255.0); + ColorRGBA.g = int(g * 255.0); + ColorRGBA.b = int(b * 255.0); + ColorRGBA.a = int(a * 255.0); + return ColorRGBA; + } + + //Converts an RGB color to HSV color + ColorHSV RGBtoHSV(const ColorRGBA& ColorRGBA) + { + double r, g, b, a, h = 0.0, s = 0.0, v; //this function works with floats between 0 and 1 + r = ColorRGBA.r / 256.0; + g = ColorRGBA.g / 256.0; + b = ColorRGBA.b / 256.0; + a = ColorRGBA.a / 256.0; + + const double maxColor = std::max(r, std::max(g, b)); + const double minColor = std::min(r, std::min(g, b)); + + v = maxColor; + + if (maxColor != 0.0) //avoid division by zero when the color is black + { + s = (maxColor - minColor) / maxColor; + } + + if (s == 0.0) + { + h = 0.0; //it doesn't matter what value it has + } + else + { + if (r == maxColor) h = (g - b) / (maxColor - minColor); + if (g == maxColor) h = 2.0 + (b - r) / (maxColor - minColor); + if (b == maxColor) h = 4.0 + (r - g) / (maxColor - minColor); + + h /= 6.0; //to bring it to a number between 0 and 1 + if (h < 0.0) h++; + } + + ColorHSV colorHSV; + colorHSV.h = int(h * 255.0); + colorHSV.s = int(s * 255.0); + colorHSV.v = int(v * 255.0); + colorHSV.a = int(a * 255.0); + return colorHSV; + } + + //Converts an HSV color to RGB color + ColorRGBA HSVtoRGB(const ColorHSV& colorHSV) + { + double r, g, b, a, h, s, v; //this function works with floats between 0 and 1 + h = colorHSV.h / 256.0; + s = colorHSV.s / 256.0; + v = colorHSV.v / 256.0; + a = colorHSV.a / 256.0; + + //if saturation is 0, the color is a shade of grey + if (s == 0.0) r = g = b = v; + //if saturation > 0, more complex calculations are needed + else + { + double f, p, q, t; + int i; + h *= 6.0; //to bring hue to a number between 0 and 6, better for the calculations + i = int(floor(h)); //e.g. 2.7 becomes 2 and 3.01 becomes 3 or 4.9999 becomes 4 + f = h - i;//the fractional part of h + + p = v * (1.0 - s); + q = v * (1.0 - (s * f)); + t = v * (1.0 - (s * (1.0 - f))); + + switch (i) + { + case 0: r = v; g = t; b = p; break; + case 1: r = q; g = v; b = p; break; + case 2: r = p; g = v; b = t; break; + case 3: r = p; g = q; b = v; break; + case 4: r = t; g = p; b = v; break; + case 5: r = v; g = p; b = q; break; + default: r = g = b = 0; break; + } + } + ColorRGBA ColorRGBA; + ColorRGBA.r = int(r * 255.0); + ColorRGBA.g = int(g * 255.0); + ColorRGBA.b = int(b * 255.0); + ColorRGBA.a = int(a * 255.0); + return ColorRGBA; + } + + Uint32 RGBtoINT(const ColorRGBA& ColorRGBA) + { + return (ColorRGBA.a | (ColorRGBA.b << 8) | (ColorRGBA.g << 16) | (ColorRGBA.r << 24)); + } + + ColorRGBA INTtoRGB(Uint32 colorINT) + { + ColorRGBA ColorRGBA; + ColorRGBA.r = (colorINT & 0xFF000000) >> 24; + ColorRGBA.g = (colorINT & 0x00FF0000) >> 16; + ColorRGBA.b = (colorINT & 0x0000FF00) >> 8; + ColorRGBA.a = (colorINT & 0x000000FF); + return ColorRGBA; + } + + //////////////////////////////////////////////////////////////////////////////// + //FILE FUNCTIONS//////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + void loadFile(std::vector& buffer, const std::string& filename) //designed for loading files from hard disk in an std::vector + { + std::ifstream file(filename.c_str(), std::ios::in | std::ios::binary | std::ios::ate); + + //get filesize + std::streamsize size = 0; + if (file.seekg(0, std::ios::end).good()) size = file.tellg(); + if (file.seekg(0, std::ios::beg).good()) size -= file.tellg(); + + //read contents of the file into the vector + buffer.resize(size_t(size)); + if (size > 0) file.read((char*)(&buffer[0]), size); + } + + //write given buffer to the file, overwriting the file, it doesn't append to it. + void saveFile(const std::vector& buffer, const std::string& filename) + { + std::ofstream file(filename.c_str(), std::ios::out | std::ios::binary); + file.write(buffer.size() ? (char*)&buffer[0] : 0, std::streamsize(buffer.size())); + } + + //////////////////////////////////////////////////////////////////////////////// + //IMAGE FUNCTIONS/////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + int loadImage(std::vector& out, unsigned long& w, unsigned long& h, const std::string& filename) + { + std::vector file, image; + loadFile(file, filename); + if (decodePNG(image, w, h, file)) return 1; + + out.resize(image.size() / 4); + + for (size_t i = 0; i < out.size(); i++) + { + out[i].r = image[i * 4 + 0]; + out[i].g = image[i * 4 + 1]; + out[i].b = image[i * 4 + 2]; + out[i].a = image[i * 4 + 3]; + } + + return 0; + } + + int loadImage(std::vector& out, unsigned long& w, unsigned long& h, const std::string& filename) + { + std::vector file, image; + loadFile(file, filename); + if (decodePNG(image, w, h, file)) return 1; + + out.resize(image.size() / 4); + + for (size_t i = 0; i < out.size(); i++) + { + out[i] = (Uint32)0x100000000 * image[i * 4 + 3] + 0x10000 * image[i * 4 + 0] + 0x100 * image[i * 4 + 1] + image[i * 4 + 2]; + } + + return 0; + } + + //////////////////////////////////////////////////////////////////////////////// + //TEXT FUNCTIONS//////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + //Draws character n at position x,y with color RGB and, if enabled, background color + //This function is used by the text printing functions below, and uses the font data + //defined below to draw the letter pixel by pixel + void drawLetter(unsigned char n, int x, int y, const ColorRGBA& color, bool bg, const ColorRGBA& color2) + { + int u, v; + + for (v = 0; v < 8; v++) + for (u = 0; u < 8; u++) + { + if (font[n][u][v]) pset(x + u, y + v, color); + else if (bg) pset(x + u, y + v, color2); + } + } + + //Draws a string of text + int printString(const std::string& text, int x, int y, const ColorRGBA& color, bool bg, const ColorRGBA& color2, int forceLength) + { + int amount = 0; + for (size_t i = 0; i < text.size(); i++) + { + amount++; + drawLetter(text[i], x, y, color, bg, color2); + x += 8; + if (x > w - 8) { x %= 8; y += 8; } + if (y > h - 8) { y %= 8; } + } + while (amount < forceLength) + { + amount++; + drawLetter(' ', x, y, color, bg, color2); + x += 8; + if (x > w - 8) { x %= 8; y += 8; } + if (y > h - 8) { y %= 8; } + } + return h * x + y; + } + + //////////////////////////////////////////////////////////////////////////////// + //TEXT INPUT FUNCTIONS////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + const int ASCII_ENTER = 13; + const int ASCII_BACKSPACE = 8; + const int ASCII_SPACE = 32; //smallest printable ascii char + + Uint8 getInputCharacter() + { + int ascii = 0; + static int previouschar = 0; + + if ((event.key.keysym.sym & 0xFF80) == 0) + { + if (event.type == SDL_KEYDOWN) + { + ascii = event.key.keysym.sym & 0x7F; + } + } + + if (ascii < ASCII_SPACE && ascii != ASCII_ENTER && ascii != ASCII_BACKSPACE) ascii = 0; //<32 ones, except enter and backspace + + if (ascii != previouschar) previouschar = ascii; + else ascii = 0; + + return ascii; + } + //returns a string, length is the maximum length of the given string array + void getInputString(std::string& text, const std::string& message, bool clear, int x, int y, const ColorRGBA& color, bool bg, const ColorRGBA& color2) + { + std::vector screenBuffer; + getScreenBuffer(screenBuffer); + + bool enter = 0; + bool change = 1; + text.clear(); + + while (enter == 0) + { + if (done()) end(); + Uint8 temp = getInputCharacter(); + if (temp >= ASCII_SPACE) + { + text.push_back(temp); + change = 1; + } + if (temp == ASCII_BACKSPACE && text.size() > 0) { text.resize(text.size() - 1); change = 1; } + + if (change) + { + drawBuffer(&screenBuffer[0]); + int pos = print(message, x, y, color, bg, color2); + int x2 = pos / h, y2 = pos % h; + print(text, x2, y2, color, bg, color2); + redraw(); + } + if (temp == ASCII_ENTER) { enter = 1; } + } + + //remove the input stuff from the screen again so there is room for possible next input + if (clear) + { + drawBuffer(&screenBuffer[0]); + redraw(); + } + } + + void encodeBase64(const std::vector& in, std::string& out) + { + const std::string characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + unsigned long bit24 = 0; + unsigned long sextet[4] = { 0, 0, 0, 0 }; + unsigned long octet[3] = { 0, 0, 0 }; + + out.clear(); + out.reserve((4 * in.size()) / 3); + + for (size_t pos = 0; pos < in.size(); pos += 3) + { + octet[0] = in[pos + 0]; + octet[1] = (pos + 1 < in.size()) ? in[pos + 1] : 0; + octet[2] = (pos + 2 < in.size()) ? in[pos + 2] : 0; + + bit24 = 256 * 256 * octet[0]; + bit24 += 256 * octet[1]; + bit24 += octet[2]; + + sextet[0] = (bit24 / (64 * 64 * 64)) % 64; + sextet[1] = (bit24 / (64 * 64)) % 64; + sextet[2] = (bit24 / (64)) % 64; + sextet[3] = (bit24 / (1)) % 64; + + for (size_t i = 0; i < 4; i++) + { + if (pos + i - 1 < in.size()) out.push_back(characters[sextet[i]]); + else out.push_back('='); + } + + if (pos % 57 == 0 && pos != 0) out.push_back(10); //newline char every 76 chars (57 = 3/4th of 76) + } + } + + void decodeBase64(std::vector& out, const std::string& in) + { + unsigned long bit24 = 0; + unsigned long sextet[4] = { 0, 0, 0, 0 }; + unsigned char octet[3] = { 0, 0, 0 }; + + out.clear(); + out.reserve((3 * in.size()) / 4); + + for (size_t pos = 0; pos < in.size() - 3; pos += 4) + { + for (size_t i = 0; i < 4; i++) + { + unsigned long c = in[pos + i]; + if (c >= 65 && c <= 90) sextet[i] = c - 65; + else if (c >= 97 && c <= 122) sextet[i] = c - 71; + else if (c >= 48 && c <= 57) sextet[i] = c + 4; + else if (c == '+') sextet[i] = 62; + else if (c == '/') sextet[i] = 63; + else if (c == '=') sextet[i] = 0; //value doesn't matter + else //unknown char, can be whitespace, newline, ... + { + pos++; + if (pos > in.size() - 3) return; + i--; + } + } + + bit24 = 64 * 64 * 64 * sextet[0]; + bit24 += 64 * 64 * sextet[1]; + bit24 += 64 * sextet[2]; + bit24 += sextet[3]; + + octet[0] = (bit24 / (256 * 256)) % 256; + octet[1] = (bit24 / (256)) % 256; + octet[2] = (bit24 / (1)) % 256; + + for (size_t i = 0; i < 3; i++) + { + if (in[pos + 1 + i] != '=') out.push_back(octet[i]); + } + } + } + + //////////////////////////////////////////////////////////////////////////////// + // PNG // + //////////////////////////////////////////////////////////////////////////////// + + int decodePNG(std::vector& out_image, unsigned long& image_width, unsigned long& image_height, const unsigned char* in_png, size_t in_size, bool convert_to_rgba32) + { + // picoPNG version 20101224 + // Copyright (c) 2005-2010 Lode Vandevenne + // + // This software is provided 'as-is', without any express or implied + // warranty. In no event will the authors be held liable for any damages + // arising from the use of this software. + // + // Permission is granted to anyone to use this software for any purpose, + // including commercial applications, and to alter it and redistribute it + // freely, subject to the following restrictions: + // + // 1. The origin of this software must not be misrepresented; you must not + // claim that you wrote the original software. If you use this software + // in a product, an acknowledgment in the product documentation would be + // appreciated but is not required. + // 2. Altered source versions must be plainly marked as such, and must not be + // misrepresented as being the original software. + // 3. This notice may not be removed or altered from any source distribution. + + static const unsigned long LENBASE[29] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 }; + static const unsigned long LENEXTRA[29] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; + static const unsigned long DISTBASE[30] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 }; + static const unsigned long DISTEXTRA[30] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; + static const unsigned long CLCL[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; //code length code lengths + struct Zlib //nested functions for zlib decompression + { + static unsigned long readBitFromStream(size_t& bitp, const unsigned char* bits) { unsigned long result = (bits[bitp >> 3] >> (bitp & 0x7)) & 1; bitp++; return result; } + static unsigned long readBitsFromStream(size_t& bitp, const unsigned char* bits, size_t nbits) + { + unsigned long result = 0; + for (size_t i = 0; i < nbits; i++) result += (readBitFromStream(bitp, bits)) << i; + return result; + } + struct HuffmanTree + { + int makeFromLengths(const std::vector& bitlen, unsigned long maxbitlen) + { //make tree given the lengths + unsigned long numcodes = (unsigned long)(bitlen.size()), treepos = 0, nodefilled = 0; + std::vector tree1d(numcodes), blcount(maxbitlen + 1, 0), nextcode(maxbitlen + 1, 0); + for (unsigned long bits = 0; bits < numcodes; bits++) blcount[bitlen[bits]]++; //count number of instances of each code length + for (unsigned long bits = 1; bits <= maxbitlen; bits++) nextcode[bits] = (nextcode[bits - 1] + blcount[bits - 1]) << 1; + for (unsigned long n = 0; n < numcodes; n++) if (bitlen[n] != 0) tree1d[n] = nextcode[bitlen[n]]++; //generate all the codes + tree2d.clear(); tree2d.resize(numcodes * 2, 32767); //32767 here means the tree2d isn't filled there yet + for (unsigned long n = 0; n < numcodes; n++) //the codes + for (unsigned long i = 0; i < bitlen[n]; i++) //the bits for this code + { + unsigned long bit = (tree1d[n] >> (bitlen[n] - i - 1)) & 1; + if (treepos > numcodes - 2) return 55; + if (tree2d[2 * treepos + bit] == 32767) //not yet filled in + { + if (i + 1 == bitlen[n]) { tree2d[2 * treepos + bit] = n; treepos = 0; } //last bit + else { tree2d[2 * treepos + bit] = ++nodefilled + numcodes; treepos = nodefilled; } //addresses are encoded as values > numcodes + } + else treepos = tree2d[2 * treepos + bit] - numcodes; //subtract numcodes from address to get address value + } + return 0; + } + int decode(bool& decoded, unsigned long& result, size_t& treepos, unsigned long bit) const + { //Decodes a symbol from the tree + unsigned long numcodes = (unsigned long)tree2d.size() / 2; + if (treepos >= numcodes) return 11; //error: you appeared outside the codetree + result = tree2d[2 * treepos + bit]; + decoded = (result < numcodes); + treepos = decoded ? 0 : result - numcodes; + return 0; + } + std::vector tree2d; //2D representation of a huffman tree: The one dimension is "0" or "1", the other contains all nodes and leaves of the tree. + }; + struct Inflator + { + int error; + void inflate(std::vector& out, const std::vector& in, size_t inpos = 0) + { + size_t bp = 0, pos = 0; //bit pointer and byte pointer + error = 0; + unsigned long BFINAL = 0; + while (!BFINAL && !error) + { + if (bp >> 3 >= in.size()) { error = 52; return; } //error, bit pointer will jump past memory + BFINAL = readBitFromStream(bp, &in[inpos]); + unsigned long BTYPE = readBitFromStream(bp, &in[inpos]); BTYPE += 2 * readBitFromStream(bp, &in[inpos]); + if (BTYPE == 3) { error = 20; return; } //error: invalid BTYPE + else if (BTYPE == 0) inflateNoCompression(out, &in[inpos], bp, pos, in.size()); + else inflateHuffmanBlock(out, &in[inpos], bp, pos, in.size(), BTYPE); + } + if (!error) out.resize(pos); //Only now we know the true size of out, resize it to that + } + void generateFixedTrees(HuffmanTree& tree, HuffmanTree& treeD) //get the tree of a deflated block with fixed tree + { + std::vector bitlen(288, 8), bitlenD(32, 5);; + for (size_t i = 144; i <= 255; i++) bitlen[i] = 9; + for (size_t i = 256; i <= 279; i++) bitlen[i] = 7; + tree.makeFromLengths(bitlen, 15); + treeD.makeFromLengths(bitlenD, 15); + } + HuffmanTree codetree, codetreeD, codelengthcodetree; //the code tree for Huffman codes, dist codes, and code length codes + unsigned long huffmanDecodeSymbol(const unsigned char* in, size_t& bp, const HuffmanTree& codetree, size_t inlength) + { //decode a single symbol from given list of bits with given code tree. return value is the symbol + bool decoded; unsigned long ct; + for (size_t treepos = 0;;) + { + if ((bp & 0x07) == 0 && (bp >> 3) > inlength) { error = 10; return 0; } //error: end reached without endcode + error = codetree.decode(decoded, ct, treepos, readBitFromStream(bp, in)); if (error) return 0; //stop, an error happened + if (decoded) return ct; + } + } + void getTreeInflateDynamic(HuffmanTree& tree, HuffmanTree& treeD, const unsigned char* in, size_t& bp, size_t inlength) + { //get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree + std::vector bitlen(288, 0), bitlenD(32, 0); + if (bp >> 3 >= inlength - 2) { error = 49; return; } //the bit pointer is or will go past the memory + size_t HLIT = readBitsFromStream(bp, in, 5) + 257; //number of literal/length codes + 257 + size_t HDIST = readBitsFromStream(bp, in, 5) + 1; //number of dist codes + 1 + size_t HCLEN = readBitsFromStream(bp, in, 4) + 4; //number of code length codes + 4 + std::vector codelengthcode(19); //lengths of tree to decode the lengths of the dynamic tree + for (size_t i = 0; i < 19; i++) codelengthcode[CLCL[i]] = (i < HCLEN) ? readBitsFromStream(bp, in, 3) : 0; + error = codelengthcodetree.makeFromLengths(codelengthcode, 7); if (error) return; + size_t i = 0, replength; + while (i < HLIT + HDIST) + { + unsigned long code = huffmanDecodeSymbol(in, bp, codelengthcodetree, inlength); if (error) return; + if (code <= 15) { if (i < HLIT) bitlen[i++] = code; else bitlenD[i++ - HLIT] = code; } //a length code + else if (code == 16) //repeat previous + { + if (bp >> 3 >= inlength) { error = 50; return; } //error, bit pointer jumps past memory + replength = 3 + readBitsFromStream(bp, in, 2); + unsigned long value; //set value to the previous code + if ((i - 1) < HLIT) value = bitlen[i - 1]; + else value = bitlenD[i - HLIT - 1]; + for (size_t n = 0; n < replength; n++) //repeat this value in the next lengths + { + if (i >= HLIT + HDIST) { error = 13; return; } //error: i is larger than the amount of codes + if (i < HLIT) bitlen[i++] = value; else bitlenD[i++ - HLIT] = value; + } + } + else if (code == 17) //repeat "0" 3-10 times + { + if (bp >> 3 >= inlength) { error = 50; return; } //error, bit pointer jumps past memory + replength = 3 + readBitsFromStream(bp, in, 3); + for (size_t n = 0; n < replength; n++) //repeat this value in the next lengths + { + if (i >= HLIT + HDIST) { error = 14; return; } //error: i is larger than the amount of codes + if (i < HLIT) bitlen[i++] = 0; else bitlenD[i++ - HLIT] = 0; + } + } + else if (code == 18) //repeat "0" 11-138 times + { + if (bp >> 3 >= inlength) { error = 50; return; } //error, bit pointer jumps past memory + replength = 11 + readBitsFromStream(bp, in, 7); + for (size_t n = 0; n < replength; n++) //repeat this value in the next lengths + { + if (i >= HLIT + HDIST) { error = 15; return; } //error: i is larger than the amount of codes + if (i < HLIT) bitlen[i++] = 0; else bitlenD[i++ - HLIT] = 0; + } + } + else { error = 16; return; } //error: somehow an unexisting code appeared. This can never happen. + } + if (bitlen[256] == 0) { error = 64; return; } //the length of the end code 256 must be larger than 0 + error = tree.makeFromLengths(bitlen, 15); if (error) return; //now we've finally got HLIT and HDIST, so generate the code trees, and the function is done + error = treeD.makeFromLengths(bitlenD, 15); if (error) return; + } + void inflateHuffmanBlock(std::vector& out, const unsigned char* in, size_t& bp, size_t& pos, size_t inlength, unsigned long btype) + { + if (btype == 1) { generateFixedTrees(codetree, codetreeD); } + else if (btype == 2) { getTreeInflateDynamic(codetree, codetreeD, in, bp, inlength); if (error) return; } + for (;;) + { + unsigned long code = huffmanDecodeSymbol(in, bp, codetree, inlength); if (error) return; + if (code == 256) return; //end code + else if (code <= 255) //literal symbol + { + if (pos >= out.size()) out.resize((pos + 1) * 2); //reserve more room + out[pos++] = (unsigned char)(code); + } + else if (code >= 257 && code <= 285) //length code + { + size_t length = LENBASE[code - 257], numextrabits = LENEXTRA[code - 257]; + if ((bp >> 3) >= inlength) { error = 51; return; } //error, bit pointer will jump past memory + length += readBitsFromStream(bp, in, numextrabits); + unsigned long codeD = huffmanDecodeSymbol(in, bp, codetreeD, inlength); if (error) return; + if (codeD > 29) { error = 18; return; } //error: invalid dist code (30-31 are never used) + unsigned long dist = DISTBASE[codeD], numextrabitsD = DISTEXTRA[codeD]; + if ((bp >> 3) >= inlength) { error = 51; return; } //error, bit pointer will jump past memory + dist += readBitsFromStream(bp, in, numextrabitsD); + size_t start = pos, back = start - dist; //backwards + if (pos + length >= out.size()) out.resize((pos + length) * 2); //reserve more room + for (size_t i = 0; i < length; i++) { out[pos++] = out[back++]; if (back >= start) back = start - dist; } + } + } + } + void inflateNoCompression(std::vector& out, const unsigned char* in, size_t& bp, size_t& pos, size_t inlength) + { + while ((bp & 0x7) != 0) bp++; //go to first boundary of byte + size_t p = bp / 8; + if (p >= inlength - 4) { error = 52; return; } //error, bit pointer will jump past memory + unsigned long LEN = in[p] + 256 * in[p + 1], NLEN = in[p + 2] + 256 * in[p + 3]; p += 4; + if (LEN + NLEN != 65535) { error = 21; return; } //error: NLEN is not one's complement of LEN + if (pos + LEN >= out.size()) out.resize(pos + LEN); + if (p + LEN > inlength) { error = 23; return; } //error: reading outside of in buffer + for (unsigned long n = 0; n < LEN; n++) out[pos++] = in[p++]; //read LEN bytes of literal data + bp = p * 8; + } + }; + int decompress(std::vector& out, const std::vector& in) //returns error value + { + Inflator inflator; + if (in.size() < 2) { return 53; } //error, size of zlib data too small + if ((in[0] * 256 + in[1]) % 31 != 0) { return 24; } //error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way + unsigned long CM = in[0] & 15, CINFO = (in[0] >> 4) & 15, FDICT = (in[1] >> 5) & 1; + if (CM != 8 || CINFO > 7) { return 25; } //error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec + if (FDICT != 0) { return 26; } //error: the specification of PNG says about the zlib stream: "The additional flags shall not specify a preset dictionary." + inflator.inflate(out, in, 2); + return inflator.error; //note: adler32 checksum was skipped and ignored + } + }; + struct PNG //nested functions for PNG decoding + { + struct Info + { + unsigned long width, height, colorType, bitDepth, compressionMethod, filterMethod, interlaceMethod, key_r, key_g, key_b, key_a; + bool key_defined; //is a transparent color key given? + std::vector palette; + } info; + int error; + void decode(std::vector& out, const unsigned char* in, size_t size, bool convert_to_rgba32) + { + error = 0; + if (size == 0 || in == 0) { error = 48; return; } //the given data is empty + readPngHeader(&in[0], size); if (error) return; + size_t pos = 33; //first byte of the first chunk after the header + std::vector idat; //the data from idat chunks + bool IEND = false, known_type = true; + info.key_defined = false; + while (!IEND) //loop through the chunks, ignoring unknown chunks and stopping at IEND chunk. IDAT data is put at the start of the in buffer + { + if (pos + 8 >= size) { error = 30; return; } //error: size of the in buffer too small to contain next chunk + size_t chunkLength = read32bitInt(&in[pos]); pos += 4; + if (chunkLength > 2147483647) { error = 63; return; } + if (pos + chunkLength >= size) { error = 35; return; } //error: size of the in buffer too small to contain next chunk + if (in[pos + 0] == 'I' && in[pos + 1] == 'D' && in[pos + 2] == 'A' && in[pos + 3] == 'T') //IDAT chunk, containing compressed image data + { + idat.insert(idat.end(), &in[pos + 4], &in[pos + 4 + chunkLength]); + pos += (4 + chunkLength); + } + else if (in[pos + 0] == 'I' && in[pos + 1] == 'E' && in[pos + 2] == 'N' && in[pos + 3] == 'D') { pos += 4; IEND = true; } + else if (in[pos + 0] == 'P' && in[pos + 1] == 'L' && in[pos + 2] == 'T' && in[pos + 3] == 'E') //palette chunk (PLTE) + { + pos += 4; //go after the 4 letters + info.palette.resize(4 * (chunkLength / 3)); + if (info.palette.size() > (4 * 256)) { error = 38; return; } //error: palette too big + for (size_t i = 0; i < info.palette.size(); i += 4) + { + for (size_t j = 0; j < 4; j++) info.palette[i + j] = in[pos++]; //RGBA + } + } + else if (in[pos + 0] == 't' && in[pos + 1] == 'R' && in[pos + 2] == 'N' && in[pos + 3] == 'S') //palette transparency chunk (tRNS) + { + pos += 4; //go after the 4 letters + if (info.colorType == 3) + { + if (4 * chunkLength > info.palette.size()) { error = 39; return; } //error: more alpha values given than there are palette entries + for (size_t i = 0; i < chunkLength; i++) info.palette[4 * i + 3] = in[pos++]; + } + else if (info.colorType == 0) + { + if (chunkLength != 2) { error = 40; return; } //error: this chunk must be 2 bytes for greyscale image + info.key_defined = 1; info.key_r = info.key_g = info.key_b = 256 * in[pos] + in[pos + 1]; pos += 2; + } + else if (info.colorType == 2) + { + if (chunkLength != 6) { error = 41; return; } //error: this chunk must be 6 bytes for RGB image + info.key_defined = 1; + info.key_r = 256 * in[pos] + in[pos + 1]; pos += 2; + info.key_g = 256 * in[pos] + in[pos + 1]; pos += 2; + info.key_b = 256 * in[pos] + in[pos + 1]; pos += 2; + } + else { error = 42; return; } //error: tRNS chunk not allowed for other color models + } + else //it's not an implemented chunk type, so ignore it: skip over the data + { + if (!(in[pos + 0] & 32)) { error = 69; return; } //error: unknown critical chunk (5th bit of first byte of chunk type is 0) + pos += (chunkLength + 4); //skip 4 letters and uninterpreted data of unimplemented chunk + known_type = false; + } + pos += 4; //step over CRC (which is ignored) + } + unsigned long bpp = getBpp(info); + std::vector scanlines(((info.width * (info.height * bpp + 7)) / 8) + info.height); //now the out buffer will be filled + Zlib zlib; //decompress with the Zlib decompressor + error = zlib.decompress(scanlines, idat); if (error) return; //stop if the zlib decompressor returned an error + size_t bytewidth = (bpp + 7) / 8, outlength = (info.height * info.width * bpp + 7) / 8; + out.resize(outlength); //time to fill the out buffer + unsigned char* out_ = outlength ? &out[0] : 0; //use a regular pointer to the std::vector for faster code if compiled without optimization + if (info.interlaceMethod == 0) //no interlace, just filter + { + size_t linestart = 0, linelength = (info.width * bpp + 7) / 8; //length in bytes of a scanline, excluding the filtertype byte + if (bpp >= 8) //byte per byte + for (unsigned long y = 0; y < info.height; y++) + { + unsigned long filterType = scanlines[linestart]; + const unsigned char* prevline = (y == 0) ? 0 : &out_[(y - 1) * info.width * bytewidth]; + unFilterScanline(&out_[linestart - y], &scanlines[linestart + 1], prevline, bytewidth, filterType, linelength); if (error) return; + linestart += (1 + linelength); //go to start of next scanline + } + else //less than 8 bits per pixel, so fill it up bit per bit + { + std::vector templine((info.width * bpp + 7) >> 3); //only used if bpp < 8 + for (size_t y = 0, obp = 0; y < info.height; y++) + { + unsigned long filterType = scanlines[linestart]; + const unsigned char* prevline = (y == 0) ? 0 : &out_[(y - 1) * info.width * bytewidth]; + unFilterScanline(&templine[0], &scanlines[linestart + 1], prevline, bytewidth, filterType, linelength); if (error) return; + for (size_t bp = 0; bp < info.width * bpp;) setBitOfReversedStream(obp, out_, readBitFromReversedStream(bp, &templine[0])); + linestart += (1 + linelength); //go to start of next scanline + } + } + } + else //interlaceMethod is 1 (Adam7) + { + size_t passw[7] = { (info.width + 7) / 8, (info.width + 3) / 8, (info.width + 3) / 4, (info.width + 1) / 4, (info.width + 1) / 2, (info.width + 0) / 2, (info.width + 0) / 1 }; + size_t passh[7] = { (info.height + 7) / 8, (info.height + 7) / 8, (info.height + 3) / 8, (info.height + 3) / 4, (info.height + 1) / 4, (info.height + 1) / 2, (info.height + 0) / 2 }; + size_t passstart[7] = { 0 }; + size_t pattern[28] = { 0, 4, 0, 2, 0, 1, 0, 0, 0, 4, 0, 2, 0, 1, 8, 8, 4, 4, 2, 2, 1, 8, 8, 8, 4, 4, 2, 2 }; //values for the adam7 passes + for (int i = 0; i < 6; i++) passstart[i + 1] = passstart[i] + passh[i] * ((passw[i] ? 1 : 0) + (passw[i] * bpp + 7) / 8); + std::vector scanlineo((info.width * bpp + 7) / 8), scanlinen((info.width * bpp + 7) / 8); //"old" and "new" scanline + for (int i = 0; i < 7; i++) + adam7Pass(&out_[0], &scanlinen[0], &scanlineo[0], &scanlines[passstart[i]], info.width, pattern[i], pattern[i + 7], pattern[i + 14], pattern[i + 21], passw[i], passh[i], bpp); + } + if (convert_to_rgba32 && (info.colorType != 6 || info.bitDepth != 8)) //conversion needed + { + std::vector data = out; + error = convert(out, &data[0], info, info.width, info.height); + } + } + void readPngHeader(const unsigned char* in, size_t inlength) //read the information from the header and store it in the Info + { + if (inlength < 29) { error = 27; return; } //error: the data length is smaller than the length of the header + if (in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71 || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) { error = 28; return; } //no PNG signature + if (in[12] != 'I' || in[13] != 'H' || in[14] != 'D' || in[15] != 'R') { error = 29; return; } //error: it doesn't start with a IHDR chunk! + info.width = read32bitInt(&in[16]); info.height = read32bitInt(&in[20]); + info.bitDepth = in[24]; info.colorType = in[25]; + info.compressionMethod = in[26]; if (in[26] != 0) { error = 32; return; } //error: only compression method 0 is allowed in the specification + info.filterMethod = in[27]; if (in[27] != 0) { error = 33; return; } //error: only filter method 0 is allowed in the specification + info.interlaceMethod = in[28]; if (in[28] > 1) { error = 34; return; } //error: only interlace methods 0 and 1 exist in the specification + error = checkColorValidity(info.colorType, info.bitDepth); + } + void unFilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon, size_t bytewidth, unsigned long filterType, size_t length) + { + switch (filterType) + { + case 0: for (size_t i = 0; i < length; i++) recon[i] = scanline[i]; break; + case 1: + for (size_t i = 0; i < bytewidth; i++) recon[i] = scanline[i]; + for (size_t i = bytewidth; i < length; i++) recon[i] = scanline[i] + recon[i - bytewidth]; + break; + case 2: + if (precon) for (size_t i = 0; i < length; i++) recon[i] = scanline[i] + precon[i]; + else for (size_t i = 0; i < length; i++) recon[i] = scanline[i]; + break; + case 3: + if (precon) + { + for (size_t i = 0; i < bytewidth; i++) recon[i] = scanline[i] + precon[i] / 2; + for (size_t i = bytewidth; i < length; i++) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) / 2); + } + else + { + for (size_t i = 0; i < bytewidth; i++) recon[i] = scanline[i]; + for (size_t i = bytewidth; i < length; i++) recon[i] = scanline[i] + recon[i - bytewidth] / 2; + } + break; + case 4: + if (precon) + { + for (size_t i = 0; i < bytewidth; i++) recon[i] = scanline[i] + paethPredictor(0, precon[i], 0); + for (size_t i = bytewidth; i < length; i++) recon[i] = scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth]); + } + else + { + for (size_t i = 0; i < bytewidth; i++) recon[i] = scanline[i]; + for (size_t i = bytewidth; i < length; i++) recon[i] = scanline[i] + paethPredictor(recon[i - bytewidth], 0, 0); + } + break; + default: error = 36; return; //error: unexisting filter type given + } + } + void adam7Pass(unsigned char* out, unsigned char* linen, unsigned char* lineo, const unsigned char* in, unsigned long w, size_t passleft, size_t passtop, size_t spacex, size_t spacey, size_t passw, size_t passh, unsigned long bpp) + { //filter and reposition the pixels into the output when the image is Adam7 interlaced. This function can only do it after the full image is already decoded. The out buffer must have the correct allocated memory size already. + if (passw == 0) return; + size_t bytewidth = (bpp + 7) / 8, linelength = 1 + ((bpp * passw + 7) / 8); + for (unsigned long y = 0; y < passh; y++) + { + unsigned char filterType = in[y * linelength], *prevline = (y == 0) ? 0 : lineo; + unFilterScanline(linen, &in[y * linelength + 1], prevline, bytewidth, filterType, (w * bpp + 7) / 8); if (error) return; + if (bpp >= 8) for (size_t i = 0; i < passw; i++) for (size_t b = 0; b < bytewidth; b++) //b = current byte of this pixel + out[bytewidth * w * (passtop + spacey * y) + bytewidth * (passleft + spacex * i) + b] = linen[bytewidth * i + b]; + else for (size_t i = 0; i < passw; i++) + { + size_t obp = bpp * w * (passtop + spacey * y) + bpp * (passleft + spacex * i), bp = i * bpp; + for (size_t b = 0; b < bpp; b++) setBitOfReversedStream(obp, out, readBitFromReversedStream(bp, &linen[0])); + } + unsigned char* temp = linen; linen = lineo; lineo = temp; //swap the two buffer pointers "line old" and "line new" + } + } + static unsigned long readBitFromReversedStream(size_t& bitp, const unsigned char* bits) { unsigned long result = (bits[bitp >> 3] >> (7 - (bitp & 0x7))) & 1; bitp++; return result; } + static unsigned long readBitsFromReversedStream(size_t& bitp, const unsigned char* bits, unsigned long nbits) + { + unsigned long result = 0; + for (size_t i = nbits - 1; i < nbits; i--) result += ((readBitFromReversedStream(bitp, bits)) << i); + return result; + } + void setBitOfReversedStream(size_t& bitp, unsigned char* bits, unsigned long bit) { bits[bitp >> 3] |= (bit << (7 - (bitp & 0x7))); bitp++; } + unsigned long read32bitInt(const unsigned char* buffer) { return (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]; } + int checkColorValidity(unsigned long colorType, unsigned long bd) //return type is a LodePNG error code + { + if ((colorType == 2 || colorType == 4 || colorType == 6)) { if (!(bd == 8 || bd == 16)) return 37; else return 0; } + else if (colorType == 0) { if (!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; else return 0; } + else if (colorType == 3) { if (!(bd == 1 || bd == 2 || bd == 4 || bd == 8)) return 37; else return 0; } + else return 31; //unexisting color type + } + unsigned long getBpp(const Info& info) + { + if (info.colorType == 2) return (3 * info.bitDepth); + else if (info.colorType >= 4) return (info.colorType - 2) * info.bitDepth; + else return info.bitDepth; + } + int convert(std::vector& out, const unsigned char* in, Info& infoIn, unsigned long w, unsigned long h) + { //converts from any color type to 32-bit. return value = LodePNG error code + size_t numpixels = w * h, bp = 0; + out.resize(numpixels * 4); + unsigned char* out_ = out.empty() ? 0 : &out[0]; //faster if compiled without optimization + if (infoIn.bitDepth == 8 && infoIn.colorType == 0) //greyscale + for (size_t i = 0; i < numpixels; i++) + { + out_[4 * i + 0] = out_[4 * i + 1] = out_[4 * i + 2] = in[i]; + out_[4 * i + 3] = (infoIn.key_defined && in[i] == infoIn.key_r) ? 0 : 255; + } + else if (infoIn.bitDepth == 8 && infoIn.colorType == 2) //RGB color + for (size_t i = 0; i < numpixels; i++) + { + for (size_t c = 0; c < 3; c++) out_[4 * i + c] = in[3 * i + c]; + out_[4 * i + 3] = (infoIn.key_defined == 1 && in[3 * i + 0] == infoIn.key_r && in[3 * i + 1] == infoIn.key_g && in[3 * i + 2] == infoIn.key_b) ? 0 : 255; + } + else if (infoIn.bitDepth == 8 && infoIn.colorType == 3) //indexed color (palette) + for (size_t i = 0; i < numpixels; i++) + { + if (4U * in[i] >= infoIn.palette.size()) return 46; + for (size_t c = 0; c < 4; c++) out_[4 * i + c] = infoIn.palette[4 * in[i] + c]; //get rgb colors from the palette + } + else if (infoIn.bitDepth == 8 && infoIn.colorType == 4) //greyscale with alpha + for (size_t i = 0; i < numpixels; i++) + { + out_[4 * i + 0] = out_[4 * i + 1] = out_[4 * i + 2] = in[2 * i + 0]; + out_[4 * i + 3] = in[2 * i + 1]; + } + else if (infoIn.bitDepth == 8 && infoIn.colorType == 6) for (size_t i = 0; i < numpixels; i++) for (size_t c = 0; c < 4; c++) out_[4 * i + c] = in[4 * i + c]; //RGB with alpha + else if (infoIn.bitDepth == 16 && infoIn.colorType == 0) //greyscale + for (size_t i = 0; i < numpixels; i++) + { + out_[4 * i + 0] = out_[4 * i + 1] = out_[4 * i + 2] = in[2 * i]; + out_[4 * i + 3] = (infoIn.key_defined && 256U * in[i] + in[i + 1] == infoIn.key_r) ? 0 : 255; + } + else if (infoIn.bitDepth == 16 && infoIn.colorType == 2) //RGB color + for (size_t i = 0; i < numpixels; i++) + { + for (size_t c = 0; c < 3; c++) out_[4 * i + c] = in[6 * i + 2 * c]; + out_[4 * i + 3] = (infoIn.key_defined && 256U * in[6 * i + 0] + in[6 * i + 1] == infoIn.key_r && 256U * in[6 * i + 2] + in[6 * i + 3] == infoIn.key_g && 256U * in[6 * i + 4] + in[6 * i + 5] == infoIn.key_b) ? 0 : 255; + } + else if (infoIn.bitDepth == 16 && infoIn.colorType == 4) //greyscale with alpha + for (size_t i = 0; i < numpixels; i++) + { + out_[4 * i + 0] = out_[4 * i + 1] = out_[4 * i + 2] = in[4 * i]; //most significant byte + out_[4 * i + 3] = in[4 * i + 2]; + } + else if (infoIn.bitDepth == 16 && infoIn.colorType == 6) for (size_t i = 0; i < numpixels; i++) for (size_t c = 0; c < 4; c++) out_[4 * i + c] = in[8 * i + 2 * c]; //RGB with alpha + else if (infoIn.bitDepth < 8 && infoIn.colorType == 0) //greyscale + for (size_t i = 0; i < numpixels; i++) + { + unsigned long value = (readBitsFromReversedStream(bp, in, infoIn.bitDepth) * 255) / ((1 << infoIn.bitDepth) - 1); //scale value from 0 to 255 + out_[4 * i + 0] = out_[4 * i + 1] = out_[4 * i + 2] = (unsigned char)(value); + out_[4 * i + 3] = (infoIn.key_defined && value && ((1U << infoIn.bitDepth) - 1U) == infoIn.key_r && ((1U << infoIn.bitDepth) - 1U)) ? 0 : 255; + } + else if (infoIn.bitDepth < 8 && infoIn.colorType == 3) //palette + for (size_t i = 0; i < numpixels; i++) + { + unsigned long value = readBitsFromReversedStream(bp, in, infoIn.bitDepth); + if (4 * value >= infoIn.palette.size()) return 47; + for (size_t c = 0; c < 4; c++) out_[4 * i + c] = infoIn.palette[4 * value + c]; //get rgb colors from the palette + } + return 0; + } + unsigned char paethPredictor(short a, short b, short c) //Paeth predicter, used by PNG filter type 4 + { + short p = a + b - c, pa = p > a ? (p - a) : (a - p), pb = p > b ? (p - b) : (b - p), pc = p > c ? (p - c) : (c - p); + return (unsigned char)((pa <= pb && pa <= pc) ? a : pb <= pc ? b : c); + } + }; + PNG decoder; decoder.decode(out_image, in_png, in_size, convert_to_rgba32); + image_width = decoder.info.width; image_height = decoder.info.height; + return decoder.error; + } + + int decodePNG(std::vector& out_image_32bit, unsigned long& image_width, unsigned long& image_height, const std::vector& in_png) + { + return decodePNG(out_image_32bit, image_width, image_height, in_png.size() ? &in_png[0] : 0, in_png.size()); + } + + + //////////////////////////////////////////////////////////////////////////////// + //DATA////////////////////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + + bool font[256][8][8]; + struct GenerateFont + { + GenerateFont() + { + /* + The full extended ASCII character set, in the form 256 bitmap symbols of 8x8 + pixels in one 128x128 PNG. + The background color is black, not transparent. + */ + + std::vector png, image; + loadFile(png, "charset.png"); + + unsigned long w, h; + decodePNG(image, w, h, &png[0], png.size()); + for (size_t c = 0; c < 256; c++) + for (size_t y = 0; y < 8; y++) + for (size_t x = 0; x < 8; x++) + { + font[c][x][y] = image[4 * 128 * (8 * (c / 16) + y) + 4 * (8 * (c % 16) + x)] != 0; + } + } + }; + GenerateFont generateFont; + + //////////////////////////////////////////////////////////////////////////////// + //Multithreading helper functions/////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + //SDL's C functions don't have destructors and such so therefore this here is needed + + //currently only needed for audio, therefor it's not in a different cpp file. + + //this creates SDL mutexes and makes sure that they're destroyed at the end. MutexFactory does the deletion! + struct MutexFactory + { + SDL_mutex* createMutex() + { + mutexes.push_back(SDL_CreateMutex()); + return mutexes.back(); + } + + ~MutexFactory() + { + for (size_t i = 0; i < mutexes.size(); i++) + SDL_DestroyMutex(mutexes[i]); + } + + private: + + std::vector mutexes; + }; + + MutexFactory mutexFactory; + + //this does SDL_mutexP in the ctor and SDL_mutexV in the dtor so no matter where you leave a function, SDL_mutexV is called + struct Mutex + { + SDL_mutex** m; + + Mutex(SDL_mutex*& mutex) + { + m = &mutex; + SDL_mutexP(*m); + } + + ~Mutex() + { + SDL_mutexV(*m); + } + }; + + //////////////////////////////////////////////////////////////////////////////// + //Soundcard functions/////////////////////////////////////////////////////////// + //////////////////////////////////////////////////////////////////////////////// + + size_t audio_min_samples = 4096; //safety buffer to avoid clicks + size_t audio_max_samples = 8192; //avoid too long queue + + double audio_volume = 1.0; + int audio_mode = 2; //0=off, 1=full (volume ignored), 2=volume-controlled + + void audioSetBufferSamplesRange(size_t min_samples, size_t max_samples) + { + audio_min_samples = min_samples; + audio_max_samples = max_samples; + } + + void audioSetMode(int mode) //0: silent, 1: full (no volume calculations ==> faster), 2: volume-controlled (= default value) + { + audio_mode = mode; + } + + void audioSetVolume(double volume) //multiplier used if mode is 2 (volume-controlled). Default value is 1.0. + { + audio_volume = volume; + } + + /* + Avoid the callback function and pushSamples function to be called at the same time, + or the std::vector can be invalid as two threads at the same time change it. + This SDL_mutex helps eliminate that problem. + */ + SDL_mutex* audio_lock = mutexFactory.createMutex(); + + std::vector audio_data(audio_min_samples, 0); + + SDL_AudioSpec audiospec_wanted, audiospec_obtained; + + size_t audioSamplesShortage() //returns value > 0 if the soundcard is consuming more samples than you're producing + { + if (audio_data.size() < audio_min_samples) return audio_min_samples - audio_data.size(); + else return 0; + } + + size_t audioSamplesOverflow() //returns value > 0 if you're producing more samples than the soundard is consuming - so take it easy a bit + { + if (audio_data.size() > audio_max_samples) return audio_data.size() - audio_max_samples; + else return 0; + } + + void audioCallback(void* /*userdata*/, Uint8* stream, int len) + { + Mutex mutex(audio_lock); + + size_t dataLengthLeft = audio_data.size(); + + //only play if we have data left + if (dataLengthLeft <= 0) return; + + int nsamples = len / 2; //always 16-bit, so always 2 bytes per sample, hence the amount of samples being len / 2 + size_t fill_len = (nsamples < dataLengthLeft ? nsamples : dataLengthLeft); + + for (int i = 0; i < nsamples; i++) + { + if (i < fill_len) + { + int s = int(audio_data[i] * 32768); + if (s < -32768) s = -32768; + if (s > 32767) s = 32767; + + stream[i * 2 + 0] = Uint8(s % 256); + stream[i * 2 + 1] = Uint8(s / 256); + } + else stream[i * 2 + 0] = stream[i * 2 + 1] = 0; + } + + audio_data.erase(audio_data.begin(), audio_data.begin() + fill_len); + } + + int audioOpen(int samplerate, int framesize) //always 16-bit mono sound for now + { + //set the audio format + audiospec_wanted.freq = samplerate; + audiospec_wanted.format = AUDIO_S16; + audiospec_wanted.channels = 1; //1 = mono, 2 = stereo + audiospec_wanted.samples = framesize; + audiospec_wanted.callback = audioCallback; + audiospec_wanted.userdata = NULL; + + /* + when using alsa and 44100 samples/second, then the framesize (samples) + will be 940 instead of 1024. Resampled to 48000Hz, this gives back 1024. + */ + + //open the audio device, forcing the wanted format + if (SDL_OpenAudio(&audiospec_wanted, &audiospec_obtained) < 0) + { + return 1; + } + + SDL_PauseAudio(0); + + return 0; + } + + void audioClose() + { + SDL_CloseAudio(); + } + + int audioReOpen() //closes and opens again with same parameters + { + SDL_PauseAudio(1); + SDL_CloseAudio(); + if (SDL_OpenAudio(&audiospec_wanted, &audiospec_obtained) < 0) + { + return 1; + } + SDL_PauseAudio(0); + + return 0; + } + + + //only works correct for 16 bit audio currently + void audioPushSamples(const std::vector& samples, size_t pos, size_t end) + { + if (audio_mode == 0) return; + + Mutex mutex(audio_lock); + + if (audio_mode == 1) + { + audio_data.insert(audio_data.end(), samples.begin() + pos, samples.begin() + end); + } + else if (audio_mode == 2) + { + size_t j = audio_data.size(); + audio_data.resize(j + samples.size()); + for (size_t i = 0; i < samples.size(); i++) + { + audio_data[j + i] = samples[i] * audio_volume; + } + } + } + + void audioPlay(const std::vector& samples) + { + if (audio_mode == 0) return; + + Mutex mutex(audio_lock); + + //the *current* time is at the first sample of audio_data, the rest has been played through soundcard already + + if (samples.size() > audio_data.size()) audio_data.resize(samples.size(), 0.0); + + if (audio_mode == 1) for (size_t i = 0; i < samples.size(); i++) audio_data[i] += samples[i]; + else if (audio_mode == 2) for (size_t i = 0; i < samples.size(); i++) audio_data[i] += samples[i] * audio_volume; + } + +} diff --git a/quickcg.h b/quickcg.h new file mode 100644 index 0000000..373507d --- /dev/null +++ b/quickcg.h @@ -0,0 +1,334 @@ +/* +QuickCG SDL2 20190709 + +Copyright (c) 2004-2007, Lode Vandevenne + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +/* +QuickCG is an SDL 2.0 codebase that wraps some of the SDL 2.0 functionality. +It's used by Lode's Computer Graphics Tutorial to work with simple function calls +to demonstrate graphical programs. It may or may not be of industrial strength +for games, though I've actually used it for some. + +QuickCG can handle some things that standard C++ does not but that are useful, such as: +-drawing graphics +-a bitmap font +-simplified saving and loading of files +-reading keyboard and mouse input +-playing sound +-color models +-loading images + +Contact info: +My email address is (puzzle the account and domain together with an @ symbol): +Domain: gmail dot com. +Account: lode dot vandevenne. +*/ + +#ifndef _quickcg_h_included +#define _quickcg_h_included + +#include + +#include +#include +#include +#include +#include //std::min and std::max + +namespace QuickCG +{ + +//////////////////////////////////////////////////////////////////////////////// +//useful templates////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// + +//don't know why, but the standard C++ abs sometimes gives cryptic errors? if so use this :D +template +const T template_abs(const T &a) +{ + return (a < 0) ? -a : a; +} + +//usage: std::string str = valtostr(25454.91654654f); +template +std::string valtostr(const T& val) +{ + std::ostringstream sstream; + sstream << val; + return sstream.str(); +} + +//usage: double val = strtoval("465498.654"); +template +T strtoval(const std::string& s) +{ + std::istringstream sstream(s); + T val; + sstream >> val; + return val; +} + +//length is decimal precision of the floating point number +template +std::string valtostr(const T& val, int length, bool fixed = true) +{ + std::ostringstream sstream; + if(fixed) sstream << std::fixed; + sstream << std::setprecision(length) << val; + return sstream.str(); +} + +//////////////////////////////////////////////////////////////////////////////// +//COLOR STRUCTS///////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// + +struct ColorRGBA8bit; +//a color with 4 components: r, g, b and a +struct ColorRGBA +{ + int r; + int g; + int b; + int a; + + ColorRGBA(Uint8 r, Uint8 g, Uint8 b, Uint8 a); + ColorRGBA(const ColorRGBA8bit& color); + ColorRGBA(); +}; + +ColorRGBA operator+(const ColorRGBA& color, const ColorRGBA& color2); +ColorRGBA operator-(const ColorRGBA& color, const ColorRGBA& color2); +ColorRGBA operator*(const ColorRGBA& color, int a); +ColorRGBA operator*(int a, const ColorRGBA& color); +ColorRGBA operator/(const ColorRGBA& color, int a); +ColorRGBA overlay(const ColorRGBA& color, const ColorRGBA& color2); +bool operator==(const ColorRGBA& color, const ColorRGBA& color2); +bool operator!=(const ColorRGBA& color, const ColorRGBA& color2); + +static const ColorRGBA RGB_Black ( 0, 0, 0, 255); +static const ColorRGBA RGB_Red (255, 0, 0, 255); +static const ColorRGBA RGB_Green ( 0, 255, 0, 255); +static const ColorRGBA RGB_Blue ( 0, 0, 255, 255); +static const ColorRGBA RGB_Cyan ( 0, 255, 255, 255); +static const ColorRGBA RGB_Magenta (255, 0, 255, 255); +static const ColorRGBA RGB_Yellow (255, 255, 0, 255); +static const ColorRGBA RGB_White (255, 255, 255, 255); +static const ColorRGBA RGB_Gray (128, 128, 128, 255); +static const ColorRGBA RGB_Grey (192, 192, 192, 255); +static const ColorRGBA RGB_Maroon (128, 0, 0, 255); +static const ColorRGBA RGB_Darkgreen( 0, 128, 0, 255); +static const ColorRGBA RGB_Navy ( 0, 0, 128, 255); +static const ColorRGBA RGB_Teal ( 0, 128, 128, 255); +static const ColorRGBA RGB_Purple (128, 0, 128, 255); +static const ColorRGBA RGB_Olive (128, 128, 0, 255); + +//a color with 4 components: r, g, b and a +struct ColorRGBA8bit +{ + Uint8 r; + Uint8 g; + Uint8 b; + Uint8 a; + + ColorRGBA8bit(Uint8 r, Uint8 g, Uint8 b, Uint8 a); + ColorRGBA8bit(const ColorRGBA& color); + ColorRGBA8bit(); +}; + +//a color with 3 components: h, s and l +struct ColorHSL +{ + int h; + int s; + int l; + int a; + + ColorHSL(Uint8 h, Uint8 s, Uint8 l, Uint8 a); + ColorHSL(); +}; + +//a color with 3 components: h, s and v +struct ColorHSV +{ + int h; + int s; + int v; + int a; + + ColorHSV(Uint8 h, Uint8 s, Uint8 v, Uint8 a); + ColorHSV(); +}; + +//////////////////////////////////////////////////////////////////////////////// +//GLOBAL VARIABLES////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// + +extern int w; +extern int h; + +//////////////////////////////////////////////////////////////////////////////// +//KEYBOARD FUNCTIONS//////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// + +bool keyDown(int key); //this checks if the key is held down, returns true all the time until the key is up +bool keyPressed(int key); //this checks if the key is *just* pressed, returns true only once until the key is up again + +//////////////////////////////////////////////////////////////////////////////// +//BASIC SCREEN FUNCTIONS//////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// + +void screen(int width = 640, int height = 400, bool fullscreen = 0, const std::string& text = " "); +void lock(); +void unlock(); +void redraw(); +void cls(const ColorRGBA& color = RGB_Black); +void pset(int x, int y, const ColorRGBA& color); +ColorRGBA pget(int x, int y); +void drawBuffer(Uint32* buffer); +bool onScreen(int x, int y); + +//////////////////////////////////////////////////////////////////////////////// +//NON GRAPHICAL FUNCTIONS/////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// + +void sleep(); +void sleep(double seconds); +void waitFrame(double oldTime, double frameDuration); //in seconds +bool done(bool quit_if_esc = true, bool delay = true); +void end(); +void readKeys(); +void getMouseState(int& mouseX, int& mouseY); +void getMouseState(int& mouseX, int& mouseY, bool& LMB, bool& RMB); +unsigned long getTicks(); //ticks in milliseconds +inline double getTime() { return getTicks() / 1000.0; } //time in seconds + +//////////////////////////////////////////////////////////////////////////////// +//2D SHAPES///////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// + +bool horLine(int y, int x1, int x2, const ColorRGBA& color); +bool verLine(int x, int y1, int y2, const ColorRGBA& color); +bool drawLine(int x1, int y1, int x2, int y2, const ColorRGBA& color); +bool drawCircle(int xc, int yc, int radius, const ColorRGBA& color); +bool drawDisk(int xc, int yc, int radius, const ColorRGBA& color); +bool drawRect(int x1, int y1, int x2, int y2, const ColorRGBA& color); +bool clipLine(int x1,int y1,int x2, int y2, int & x3, int & y3, int & x4, int & y4); + +//////////////////////////////////////////////////////////////////////////////// +//COLOR CONVERSIONS///////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// +ColorHSL RGBtoHSL(const ColorRGBA& ColorRGBA); +ColorRGBA HSLtoRGB(const ColorHSL& colorHSL); +ColorHSV RGBtoHSV(const ColorRGBA& ColorRGBA); +ColorRGBA HSVtoRGB(const ColorHSV& colorHSV); +Uint32 RGBtoINT(const ColorRGBA& ColorRGBA); +ColorRGBA INTtoRGB(Uint32 colorINT); + +//////////////////////////////////////////////////////////////////////////////// +//FILE FUNCTIONS//////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// + +void loadFile(std::vector& buffer, const std::string& filename); +void saveFile(const std::vector& buffer, const std::string& filename); + +//////////////////////////////////////////////////////////////////////////////// +//IMAGE FUNCTIONS/////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// + +int loadImage(std::vector& out, unsigned long& w, unsigned long& h, const std::string& filename); +int loadImage(std::vector& out, unsigned long& w, unsigned long& h, const std::string& filename); +int decodePNG(std::vector& out_image, unsigned long& image_width, unsigned long& image_height, const unsigned char* in_png, size_t in_size, bool convert_to_rgba32 = true); +int decodePNG(std::vector& out_image_32bit, unsigned long& image_width, unsigned long& image_height, const std::vector& in_png); + +//////////////////////////////////////////////////////////////////////////////// +//TEXT FUNCTIONS//////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// +extern bool font[256][8][8]; +void drawLetter(unsigned char n, int x, int y, const ColorRGBA& color = RGB_White, bool bg = 0, const ColorRGBA& color2 = RGB_Black); +int printString(const std::string& text, int x = 0, int y = 0, const ColorRGBA& color = RGB_White, bool bg = 0, const ColorRGBA& color2 = RGB_Black, int forceLength = 0); + +//print something (string, int, float, ...) +template +int print(const T& val, int x = 0, int y = 0, const ColorRGBA& color = RGB_White, bool bg = 0, const ColorRGBA& color2 = RGB_Black, int forceLength = 0) +{ + std::string text = valtostr(val); + return printString(text, x, y, color, bg, color2, forceLength); +} + +//print some floating point number, this one allows printing floating point numbers with limited length +template +int fprint(const T& val, int length, int x = 0, int y = 0, const ColorRGBA& color = RGB_White, bool bg = 0, const ColorRGBA& color2 = RGB_Black, int forceLength = 0) +{ + std::string text = valtostr(val, length, true); + return printString(text, x, y, color, bg, color2, forceLength); +} + +//////////////////////////////////////////////////////////////////////////////// +//TEXT INPUT FUNCTIONS////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// +Uint8 getInputCharacter(); +void getInputString(std::string& text, const std::string& message = "", bool clear = false, int x = 0, int y = 0, const ColorRGBA& color = RGB_White, bool bg = 0, const ColorRGBA& color2 = RGB_Black); + +template +T getInput(const std::string& message = "", bool clear = false, int x = 0, int y = 0, const ColorRGBA& color = RGB_White, bool bg = 0, const ColorRGBA& color2 = RGB_Black) +{ + std::string text; + getInputString(text, message, clear, x, y, color, bg, color2); + return strtoval(text); +} + +//////////////////////////////////////////////////////////////////////////////// +//SOUNDCARD FUNCTIONS/////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// + +int audioOpen(int samplerate, int framesize); //always 16-bit mono sound for now; returns 0 if no error happened +void audioClose(); +int audioReOpen(); //closes and opens again with same parameters + +/* +push samples to the soundcard, making sure not to cause shortage or overflow +pos and end are the range in the samples vector that you want to push to the audio card +*/ +void audioPushSamples(const std::vector& samples, size_t pos, size_t end); + +size_t audioSamplesShortage(); //returns value > 0 if the soundcard is consuming more samples than you're producing +size_t audioSamplesOverflow(); //returns value > 0 if you're producing more samples than the soundard is consuming - so take it easy a bit +void audioSetBufferSamplesRange(size_t min_samples, size_t max_samples); //set shortage and overflow values. E.g. 4096 and 8192. + +/* +This plays the sound starting at this time, until it's done +The difference with audioPushSamples is: +audioPlay allows playing multiple sounds at the same time: it doesn't push at the end, +but elementwise-adds or pushes back samples if needed. +The duration depends on samplerate, make sure the samples in the vector have the correct samplerate. +*/ +void audioPlay(const std::vector& samples); + +void audioSetMode(int mode); //0: silent, 1: full (no volume calculations ==> faster), 2: volume-controlled (= default value) +void audioSetVolume(double volume); //multiplier used if mode is 2 (volume-controlled). Default value is 1.0. + +} //end of namespace QuickCG + +#endif + + diff --git a/raycaster_flat.cpp b/raycaster_flat.cpp new file mode 100644 index 0000000..f052663 --- /dev/null +++ b/raycaster_flat.cpp @@ -0,0 +1,242 @@ +/* +Copyright (c) 2004-2021, Lode Vandevenne + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#include +#include +#include + +#include "quickcg.h" +using namespace QuickCG; + +/* +g++ *.cpp -lSDL -O3 -W -Wall -ansi -pedantic +g++ *.cpp -lSDL +*/ + +//place the example code below here: + +#define screenWidth 640 +#define screenHeight 480 +#define mapWidth 24 +#define mapHeight 24 + +int worldMap[mapWidth][mapHeight]= +{ + {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, + {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, + {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, + {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, + {1,0,0,0,0,0,2,2,2,2,2,0,0,0,0,3,0,3,0,3,0,0,0,1}, + {1,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,1}, + {1,0,0,0,0,0,2,0,0,0,2,0,0,0,0,3,0,0,0,3,0,0,0,1}, + {1,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,1}, + {1,0,0,0,0,0,2,2,0,2,2,0,0,0,0,3,0,3,0,3,0,0,0,1}, + {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, + {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, + {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, + {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, + {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, + {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, + {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, + {1,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, + {1,4,0,4,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, + {1,4,0,0,0,0,5,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, + {1,4,0,4,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, + {1,4,0,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, + {1,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, + {1,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, + {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1} +}; + +int main(int /*argc*/, char */*argv*/[]) +{ + double posX = 22, posY = 12; //x and y start position + double dirX = -1, dirY = 0; //initial direction vector + double planeX = 0, planeY = 0.66; //the 2d raycaster version of camera plane + + double time = 0; //time of current frame + double oldTime = 0; //time of previous frame + + screen(screenWidth, screenHeight, 0, "Raycaster"); + while(!done()) + { + for(int x = 0; x < w; x++) + { + //calculate ray position and direction + double cameraX = 2 * x / (double)w - 1; //x-coordinate in camera space + double rayDirX = dirX + planeX * cameraX; + double rayDirY = dirY + planeY * cameraX; + //which box of the map we're in + int mapX = int(posX); + int mapY = int(posY); + + //length of ray from current position to next x or y-side + double sideDistX; + double sideDistY; + + //length of ray from one x or y-side to next x or y-side + //these are derived as: + //deltaDistX = sqrt(1 + (rayDirY * rayDirY) / (rayDirX * rayDirX)) + //deltaDistY = sqrt(1 + (rayDirX * rayDirX) / (rayDirY * rayDirY)) + //which can be simplified to abs(|rayDir| / rayDirX) and abs(|rayDir| / rayDirY) + //where |rayDir| is the length of the vector (rayDirX, rayDirY). Its length, + //unlike (dirX, dirY) is not 1, however this does not matter, only the + //ratio between deltaDistX and deltaDistY matters, due to the way the DDA + //stepping further below works. So the values can be computed as below. + // Division through zero is prevented, even though technically that's not + // needed in C++ with IEEE 754 floating point values. + double deltaDistX = (rayDirX == 0) ? 1e30 : std::abs(1 / rayDirX); + double deltaDistY = (rayDirY == 0) ? 1e30 : std::abs(1 / rayDirY); + + double perpWallDist; + + //what direction to step in x or y-direction (either +1 or -1) + int stepX; + int stepY; + + int hit = 0; //was there a wall hit? + int side; //was a NS or a EW wall hit? + //calculate step and initial sideDist + if(rayDirX < 0) + { + stepX = -1; + sideDistX = (posX - mapX) * deltaDistX; + } + else + { + stepX = 1; + sideDistX = (mapX + 1.0 - posX) * deltaDistX; + } + if(rayDirY < 0) + { + stepY = -1; + sideDistY = (posY - mapY) * deltaDistY; + } + else + { + stepY = 1; + sideDistY = (mapY + 1.0 - posY) * deltaDistY; + } + //perform DDA + while(hit == 0) + { + //jump to next map square, either in x-direction, or in y-direction + if(sideDistX < sideDistY) + { + sideDistX += deltaDistX; + mapX += stepX; + side = 0; + } + else + { + sideDistY += deltaDistY; + mapY += stepY; + side = 1; + } + //Check if ray has hit a wall + if(worldMap[mapX][mapY] > 0) hit = 1; + } + //Calculate distance projected on camera direction. This is the shortest distance from the point where the wall is + //hit to the camera plane. Euclidean to center camera point would give fisheye effect! + //This can be computed as (mapX - posX + (1 - stepX) / 2) / rayDirX for side == 0, or same formula with Y + //for size == 1, but can be simplified to the code below thanks to how sideDist and deltaDist are computed: + //because they were left scaled to |rayDir|. sideDist is the entire length of the ray above after the multiple + //steps, but we subtract deltaDist once because one step more into the wall was taken above. + if(side == 0) perpWallDist = (sideDistX - deltaDistX); + else perpWallDist = (sideDistY - deltaDistY); + + //Calculate height of line to draw on screen + int lineHeight = (int)(h / perpWallDist); + + //calculate lowest and highest pixel to fill in current stripe + int drawStart = -lineHeight / 2 + h / 2; + if(drawStart < 0) drawStart = 0; + int drawEnd = lineHeight / 2 + h / 2; + if(drawEnd >= h) drawEnd = h - 1; + + //choose wall color + ColorRGB color; + switch(worldMap[mapX][mapY]) + { + case 1: color = RGB_Red; break; //red + case 2: color = RGB_Green; break; //green + case 3: color = RGB_Blue; break; //blue + case 4: color = RGB_White; break; //white + default: color = RGB_Yellow; break; //yellow + } + + //give x and y sides different brightness + if(side == 1) {color = color / 2;} + + //draw the pixels of the stripe as a vertical line + verLine(x, drawStart, drawEnd, color); + } + //timing for input and FPS counter + oldTime = time; + time = getTicks(); + double frameTime = (time - oldTime) / 1000.0; //frameTime is the time this frame has taken, in seconds + print(1.0 / frameTime); //FPS counter + redraw(); + cls(); + + //speed modifiers + double moveSpeed = frameTime * 5.0; //the constant value is in squares/second + double rotSpeed = frameTime * 3.0; //the constant value is in radians/second + readKeys(); + //move forward if no wall in front of you + if(keyDown(SDLK_UP)) + { + if(worldMap[int(posX + dirX * moveSpeed)][int(posY)] == false) posX += dirX * moveSpeed; + if(worldMap[int(posX)][int(posY + dirY * moveSpeed)] == false) posY += dirY * moveSpeed; + } + //move backwards if no wall behind you + if(keyDown(SDLK_DOWN)) + { + if(worldMap[int(posX - dirX * moveSpeed)][int(posY)] == false) posX -= dirX * moveSpeed; + if(worldMap[int(posX)][int(posY - dirY * moveSpeed)] == false) posY -= dirY * moveSpeed; + } + //rotate to the right + if(keyDown(SDLK_RIGHT)) + { + //both camera direction and camera plane must be rotated + double oldDirX = dirX; + dirX = dirX * cos(-rotSpeed) - dirY * sin(-rotSpeed); + dirY = oldDirX * sin(-rotSpeed) + dirY * cos(-rotSpeed); + double oldPlaneX = planeX; + planeX = planeX * cos(-rotSpeed) - planeY * sin(-rotSpeed); + planeY = oldPlaneX * sin(-rotSpeed) + planeY * cos(-rotSpeed); + } + //rotate to the left + if(keyDown(SDLK_LEFT)) + { + //both camera direction and camera plane must be rotated + double oldDirX = dirX; + dirX = dirX * cos(rotSpeed) - dirY * sin(rotSpeed); + dirY = oldDirX * sin(rotSpeed) + dirY * cos(rotSpeed); + double oldPlaneX = planeX; + planeX = planeX * cos(rotSpeed) - planeY * sin(rotSpeed); + planeY = oldPlaneX * sin(rotSpeed) + planeY * cos(rotSpeed); + } + } +} diff --git a/scripts/coverage_reset.ps1 b/scripts/coverage_reset.ps1 new file mode 100644 index 0000000..4799ae6 --- /dev/null +++ b/scripts/coverage_reset.ps1 @@ -0,0 +1,7 @@ +mv .\subprojects\packagecache . +rm -recurse -force .\subprojects\,.\builddir\ +mkdir subprojects +mv .\packagecache .\subprojects\ +mkdir builddir +cp wraps\*.wrap subprojects\ +meson setup --default-library=static --prefer-static -Db_coverage=true builddir diff --git a/scripts/coverage_reset.sh b/scripts/coverage_reset.sh new file mode 100644 index 0000000..9970738 --- /dev/null +++ b/scripts/coverage_reset.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -e + +mv -f ./subprojects/packagecache . +rm -rf subprojects builddir +mkdir subprojects +mv packagecache ./subprojects/ +mkdir builddir +cp wraps/*.wrap subprojects/ +# on OSX you can't do this with static +meson setup -Db_coverage=true builddir diff --git a/scripts/reset_build.ps1 b/scripts/reset_build.ps1 new file mode 100644 index 0000000..af8305b --- /dev/null +++ b/scripts/reset_build.ps1 @@ -0,0 +1,7 @@ +mv .\subprojects\packagecache . +rm -recurse -force .\subprojects\,.\builddir\ +mkdir subprojects +mv .\packagecache .\subprojects\ +mkdir builddir +cp wraps\*.wrap subprojects\ +meson setup --default-library=static --prefer-static builddir diff --git a/scripts/reset_build.sh b/scripts/reset_build.sh new file mode 100644 index 0000000..9d56a7f --- /dev/null +++ b/scripts/reset_build.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +set -e + +mv -f ./subprojects/packagecache . +rm -rf subprojects builddir +mkdir subprojects +mv packagecache ./subprojects/ +mkdir builddir +cp wraps/*.wrap subprojects/ +# on OSX you can't do this with static +meson setup builddir diff --git a/sdlprog.cpp b/sdlprog.cpp new file mode 100644 index 0000000..a641a0b --- /dev/null +++ b/sdlprog.cpp @@ -0,0 +1,36 @@ +#include "SDL.h" + +int main(int argc, char *argv[]) +{ + SDL_Window *window; + SDL_Renderer *renderer; + SDL_Surface *surface; + SDL_Event event; + + if (SDL_Init(SDL_INIT_VIDEO) < 0) { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s", SDL_GetError()); + return 3; + } + + if (SDL_CreateWindowAndRenderer(320, 240, SDL_WINDOW_RESIZABLE, &window, &renderer)) { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window and renderer: %s", SDL_GetError()); + return 3; + } + + while (1) { + SDL_PollEvent(&event); + if (event.type == SDL_QUIT) { + break; + } + SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00); + SDL_RenderClear(renderer); + SDL_RenderPresent(renderer); + } + + SDL_DestroyRenderer(renderer); + SDL_DestroyWindow(window); + + SDL_Quit(); + + return 0; +} diff --git a/tests/base.cpp b/tests/base.cpp new file mode 100644 index 0000000..4097258 --- /dev/null +++ b/tests/base.cpp @@ -0,0 +1,9 @@ +#include +#include +#include + +using namespace fmt; + +TEST_CASE("base test", "[base]") { + REQUIRE(1 == 1); +} diff --git a/wraps/catch2.wrap b/wraps/catch2.wrap new file mode 100644 index 0000000..f9bf436 --- /dev/null +++ b/wraps/catch2.wrap @@ -0,0 +1,11 @@ +[wrap-file] +directory = Catch2-3.7.1 +source_url = https://github.com/catchorg/Catch2/archive/v3.7.1.tar.gz +source_filename = Catch2-3.7.1.tar.gz +source_hash = c991b247a1a0d7bb9c39aa35faf0fe9e19764213f28ffba3109388e62ee0269c +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/catch2_3.7.1-1/Catch2-3.7.1.tar.gz +wrapdb_version = 3.7.1-1 + +[provide] +catch2 = catch2_dep +catch2-with-main = catch2_with_main_dep diff --git a/wraps/fmt.wrap b/wraps/fmt.wrap new file mode 100644 index 0000000..fd50847 --- /dev/null +++ b/wraps/fmt.wrap @@ -0,0 +1,13 @@ +[wrap-file] +directory = fmt-11.0.2 +source_url = https://github.com/fmtlib/fmt/archive/11.0.2.tar.gz +source_filename = fmt-11.0.2.tar.gz +source_hash = 6cb1e6d37bdcb756dbbe59be438790db409cdb4868c66e888d5df9f13f7c027f +patch_filename = fmt_11.0.2-1_patch.zip +patch_url = https://wrapdb.mesonbuild.com/v2/fmt_11.0.2-1/get_patch +patch_hash = 90c9e3b8e8f29713d40ca949f6f93ad115d78d7fb921064112bc6179e6427c5e +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/fmt_11.0.2-1/fmt-11.0.2.tar.gz +wrapdb_version = 11.0.2-1 + +[provide] +fmt = fmt_dep diff --git a/wraps/freetype2.wrap b/wraps/freetype2.wrap new file mode 100644 index 0000000..acad6f4 --- /dev/null +++ b/wraps/freetype2.wrap @@ -0,0 +1,11 @@ +[wrap-file] +directory = freetype-2.13.3 +source_url = https://download.savannah.gnu.org/releases/freetype/freetype-2.13.3.tar.xz +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/freetype2_2.13.3-1/freetype-2.13.3.tar.xz +source_filename = freetype-2.13.3.tar.xz +source_hash = 0550350666d427c74daeb85d5ac7bb353acba5f76956395995311a9c6f063289 +wrapdb_version = 2.13.3-1 + +[provide] +freetype2 = freetype_dep +freetype = freetype_dep diff --git a/wraps/libpng.wrap b/wraps/libpng.wrap new file mode 100644 index 0000000..06044a9 --- /dev/null +++ b/wraps/libpng.wrap @@ -0,0 +1,13 @@ +[wrap-file] +directory = libpng-1.6.44 +source_url = https://github.com/glennrp/libpng/archive/v1.6.44.tar.gz +source_filename = libpng-1.6.44.tar.gz +source_hash = 0ef5b633d0c65f780c4fced27ff832998e71478c13b45dfb6e94f23a82f64f7c +patch_filename = libpng_1.6.44-1_patch.zip +patch_url = https://wrapdb.mesonbuild.com/v2/libpng_1.6.44-1/get_patch +patch_hash = 394b07614c45fbd1beac8b660386216a490fe12f841a1a445799b676c9c892fb +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/libpng_1.6.44-1/libpng-1.6.44.tar.gz +wrapdb_version = 1.6.44-1 + +[provide] +libpng = libpng_dep diff --git a/wraps/nlohmann_json.wrap b/wraps/nlohmann_json.wrap new file mode 100644 index 0000000..8c46676 --- /dev/null +++ b/wraps/nlohmann_json.wrap @@ -0,0 +1,11 @@ +[wrap-file] +directory = nlohmann_json-3.11.3 +lead_directory_missing = true +source_url = https://github.com/nlohmann/json/releases/download/v3.11.3/include.zip +source_filename = nlohmann_json-3.11.3.zip +source_hash = a22461d13119ac5c78f205d3df1db13403e58ce1bb1794edc9313677313f4a9d +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/nlohmann_json_3.11.3-1/nlohmann_json-3.11.3.zip +wrapdb_version = 3.11.3-1 + +[provide] +nlohmann_json = nlohmann_json_dep diff --git a/wraps/sdl2.wrap b/wraps/sdl2.wrap new file mode 100644 index 0000000..bb790fb --- /dev/null +++ b/wraps/sdl2.wrap @@ -0,0 +1,15 @@ +[wrap-file] +directory = SDL2-2.30.6 +source_url = https://github.com/libsdl-org/SDL/releases/download/release-2.30.6/SDL2-2.30.6.tar.gz +source_filename = SDL2-2.30.6.tar.gz +source_hash = c6ef64ca18a19d13df6eb22df9aff19fb0db65610a74cc81dae33a82235cacd4 +patch_filename = sdl2_2.30.6-2_patch.zip +patch_url = https://wrapdb.mesonbuild.com/v2/sdl2_2.30.6-2/get_patch +patch_hash = aa9f6a4947b07510c2ea84fb457e965bebe5a5deeb9f5059fbcf10dfe6b76d1f +source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/sdl2_2.30.6-2/SDL2-2.30.6.tar.gz +wrapdb_version = 2.30.6-2 + +[provide] +sdl2 = sdl2_dep +sdl2main = sdl2main_dep +sdl2_test = sdl2_test_dep