[
  {
    "path": ".gitignore",
    "content": "gel\nobj/\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2018 Gustav Louw\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "Makefile",
    "content": "BIN = gel\n\nCFLAGS = -std=c99 -Wall -Wextra -pedantic -Ofast -flto -march=native\n\nLDFLAGS = -lm -lSDL2 -lSDL2_image\n\nCC = gcc\n\nSRC = main.c\n\nall:\n\t$(CC) $(CFLAGS) $(LDFLAGS) $(SRC) -o $(BIN)\n\nrun:\n\t./$(BIN)\n\nclean:\n\trm -f $(BIN)\n"
  },
  {
    "path": "README.md",
    "content": "![screenshot](img/logo.png)\n\nGel (Graphical Emulation Layer) is an N64-like software renderer.\n\n    make; ./gel path/to/obj path/to/bmp\n\nDependencies:\n\n    SDL2-devel\n    SDL2-image-devel\n\nModels, for educational purposes, can be found here:\n\n    https://www.models-resource.com/nintendo_64/\n\nModels must be bundled with a single obj file and texture file. The obj file\nmust include vertex normals.\n\nRotate the screen with the mouse.\n\n![screenshot](img/salesman.gif)\n"
  },
  {
    "path": "main.c",
    "content": "#include <SDL2/SDL.h>\n#include <SDL2/SDL_image.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <float.h>\n#include <math.h>\n\ntypedef struct\n{\n    float x, y, z;\n}\nVertex;\n\ntypedef struct\n{\n    Vertex* vertex;\n    int count;\n    int max;\n}\nVertices;\n\ntypedef struct\n{\n    int va, vb, vc;\n    int ta, tb, tc;\n    int na, nb, nc;\n}\nFace;\n\ntypedef struct\n{\n    Face* face;\n    int count;\n    int max;\n}\nFaces;\n\ntypedef struct\n{\n    Vertices vsv, vsn, vst;\n    Faces fs;\n}\nObj;\n\ntypedef struct\n{\n    Vertex a, b, c;\n}\nTriangle;\n\ntypedef struct\n{\n    Triangle* triangle;\n    int count;\n}\nTriangles;\n\ntypedef struct\n{\n    Triangle vew, nrm, tex;\n    SDL_Surface* fdif;\n}\nTarget;\n\ntypedef struct\n{\n    SDL_Window* window;\n    SDL_Renderer* renderer;\n    SDL_Texture* canvas;\n    int xres;\n    int yres;\n}\nSdl;\n\ntypedef struct\n{\n    float xt;\n    float yt;\n    float sens;\n    int done;\n}\nInput;\n\nstatic int flns(FILE* const file)\n{\n    int ch = EOF;\n    int lines = 0;\n    int pc = '\\n';\n    while((ch = getc(file)) != EOF)\n    {\n        if(ch == '\\n')\n            lines++;\n        pc = ch;\n    }\n    if(pc != '\\n')\n        lines++;\n    rewind(file);\n    return lines;\n}\n\nstatic char* freadln(FILE* const file)\n{\n    int ch = EOF;\n    int reads = 0;\n    int size = 128;\n    char* line = (char*) malloc(sizeof(char) * size);\n    while((ch = getc(file)) != '\\n' && ch != EOF)\n    {\n        line[reads++] = ch;\n        if(reads + 1 == size)\n            line = (char*) realloc(line, sizeof(char) * (size *= 2));\n    }\n    line[reads] = '\\0';\n    return line;\n}\n\nstatic Vertices vsnew(const int max)\n{\n    const Vertices vs = { (Vertex*) malloc(sizeof(Vertex) * max), 0, max };\n    return vs;\n}\n\nstatic Faces fsnew(const int max)\n{\n    const Faces fs = { (Face*) malloc(sizeof(Face) * max), 0, max };\n    return fs;\n}\n\nstatic Obj oparse(FILE* const file)\n{\n    const int lines = flns(file);\n    const int size = 128;\n    Vertices vsv = vsnew(size);\n    Vertices vsn = vsnew(size);\n    Vertices vst = vsnew(size);\n    Faces fs = fsnew(size);\n    for(int i = 0; i < lines; i++)\n    {\n        Face f;\n        Vertex v;\n        char* line = freadln(file);\n        if(line[0] == 'v' && line[1] == 'n')\n        {\n            if(vsn.count == vsn.max)\n                vsn.vertex = (Vertex*) realloc(vsn.vertex, sizeof(Vertex) * (vsn.max *= 2));\n            sscanf(line, \"vn %f %f %f\", &v.x, &v.y, &v.z);\n            vsn.vertex[vsn.count++] = v;\n        }\n        else if(line[0] == 'v' && line[1] == 't')\n        {\n            if(vst.count == vst.max)\n                vst.vertex = (Vertex*) realloc(vst.vertex, sizeof(Vertex) * (vst.max *= 2));\n            sscanf(line, \"vt %f %f %f\", &v.x, &v.y, &v.z);\n            vst.vertex[vst.count++] = v;\n        }\n        else if(line[0] == 'v')\n        {\n            if(vsv.count == vsv.max)\n                vsv.vertex = (Vertex*) realloc(vsv.vertex, sizeof(Vertex) * (vsv.max *= 2));\n            sscanf(line, \"v %f %f %f\", &v.x, &v.y, &v.z);\n            vsv.vertex[vsv.count++] = v;\n        }\n        else if(line[0] == 'f')\n        {\n            if(fs.count == fs.max)\n                fs.face = (Face*) realloc(fs.face, sizeof(Face) * (fs.max *= 2));\n            sscanf(line, \"f %d/%d/%d %d/%d/%d %d/%d/%d\", &f.va, &f.ta, &f.na, &f.vb, &f.tb, &f.nb, &f.vc, &f.tc, &f.nc);\n            const Face indexed = {\n                f.va - 1, f.vb - 1, f.vc - 1,\n                f.ta - 1, f.tb - 1, f.tc - 1,\n                f.na - 1, f.nb - 1, f.nc - 1\n            };\n            fs.face[fs.count++] = indexed;\n        }\n        free(line);\n    }\n    rewind(file);\n    const Obj obj = { vsv, vsn, vst, fs };\n    return obj;\n}\n\nstatic Vertex vsub(const Vertex a, const Vertex b)\n{\n    const Vertex v = { a.x - b.x, a.y - b.y, a.z - b.z };\n    return v;\n}\n\nstatic Vertex vcross(const Vertex a, const Vertex b)\n{\n    const Vertex c = { a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x };\n    return c;\n}\n\nstatic Vertex vmul(const Vertex v, const float n)\n{\n    const Vertex m = { v.x * n, v.y * n, v.z * n };\n    return m;\n}\n\nstatic float vdot(const Vertex a, const Vertex b)\n{\n    return a.x * b.x + a.y * b.y + a.z * b.z;\n}\n\nstatic float vlen(const Vertex v)\n{\n    return sqrtf(v.x * v.x + v.y * v.y + v.z * v.z);\n}\n\nstatic Vertex vunit(const Vertex v)\n{\n    return vmul(v, 1.0f / vlen(v));\n}\n\nstatic Triangle tunit(const Triangle t)\n{\n    const Triangle u = { vunit(t.a), vunit(t.b), vunit(t.c) };\n    return u;\n}\n\nstatic Triangle tmul(const Triangle t, const float scale)\n{\n    const Triangle s = { vmul(t.a, scale), vmul(t.b, scale), vmul(t.c, scale) };\n    return s;\n}\n\nstatic Triangles tsnew(const int count)\n{\n    const Triangles ts = { (Triangle*) malloc(sizeof(Triangle) * count), count };\n    return ts;\n}\n\nstatic float vmaxlen(const Vertices vsv)\n{\n    float max = 0.0f;\n    for(int i = 0; i < vsv.count; i++)\n        if(vlen(vsv.vertex[i]) > max)\n            max = vlen(vsv.vertex[i]);\n    return max;\n}\n\nstatic Triangles tvgen(const Obj obj)\n{\n    const int scale = vmaxlen(obj.vsv);\n    Triangles tv = tsnew(obj.fs.count);\n    for(int i = 0; i < obj.fs.count; i++)\n    {\n        const Triangle t = {\n            obj.vsv.vertex[obj.fs.face[i].va],\n            obj.vsv.vertex[obj.fs.face[i].vb],\n            obj.vsv.vertex[obj.fs.face[i].vc],\n        };\n        tv.triangle[i] = tmul(t, 1.0f / scale);\n    }\n    return tv;\n}\n\nstatic Triangles tngen(const Obj obj)\n{\n    Triangles tn = tsnew(obj.fs.count);\n    for(int i = 0; i < obj.fs.count; i++)\n    {\n        const Triangle t = {\n            obj.vsn.vertex[obj.fs.face[i].na],\n            obj.vsn.vertex[obj.fs.face[i].nb],\n            obj.vsn.vertex[obj.fs.face[i].nc],\n        };\n        tn.triangle[i] = t;\n    }\n    return tn;\n}\n\nstatic Triangles ttgen(const Obj obj)\n{\n    Triangles tt = tsnew(obj.fs.count);\n    for(int i = 0; i < obj.fs.count; i++)\n    {\n        const Triangle t = {\n            obj.vst.vertex[obj.fs.face[i].ta],\n            obj.vst.vertex[obj.fs.face[i].tb],\n            obj.vst.vertex[obj.fs.face[i].tc],\n        };\n        tt.triangle[i] = t;\n    }\n    return tt;\n}\n\nstatic Triangle tviewport(const Triangle t, const Sdl sdl)\n{\n    const float w = sdl.yres / 1.5f;\n    const float h = sdl.yres / 1.5f;\n    const float x = sdl.xres / 2.0f;\n    const float y = sdl.yres / 4.0f;\n    const Triangle v = {\n        { w * t.a.x + x, h * t.a.y + y, (t.a.z + 1.0f) / 1.5f },\n        { w * t.b.x + x, h * t.b.y + y, (t.b.z + 1.0f) / 1.5f },\n        { w * t.c.x + x, h * t.c.y + y, (t.c.z + 1.0f) / 1.5f },\n    };\n    return v;\n}\n\nstatic Triangle tperspective(const Triangle t)\n{\n    const float c = 3.0f;\n    const float za = 1.0f - t.a.z / c;\n    const float zb = 1.0f - t.b.z / c;\n    const float zc = 1.0f - t.c.z / c;\n    const Triangle p = {\n        { t.a.x / za, t.a.y / za, t.a.z / za },\n        { t.b.x / zb, t.b.y / zb, t.b.z / zb },\n        { t.c.x / zc, t.c.y / zc, t.c.z / zc },\n    };\n    return p;\n}\n\nstatic Vertex tbarycenter(const Triangle t, const int x, const int y)\n{\n    const Vertex p = { (float) x, (float) y, 0.0f };\n    const Vertex v0 = vsub(t.b, t.a);\n    const Vertex v1 = vsub(t.c, t.a);\n    const Vertex v2 = vsub(p, t.a);\n    const float d00 = vdot(v0, v0);\n    const float d01 = vdot(v0, v1);\n    const float d11 = vdot(v1, v1);\n    const float d20 = vdot(v2, v0);\n    const float d21 = vdot(v2, v1);\n    const float v = (d11 * d20 - d01 * d21) / (d00 * d11 - d01 * d01);\n    const float w = (d00 * d21 - d01 * d20) / (d00 * d11 - d01 * d01);\n    const float u = 1.0f - v - w;\n    const Vertex vertex = { v, w, u };\n    return vertex;\n}\n\nstatic uint32_t pshade(const uint32_t pixel, const int shading)\n{\n    const uint32_t r = (((pixel >> 0x10) /****/) * shading) >> 0x08;\n    const uint32_t g = (((pixel >> 0x08) & 0xFF) * shading) >> 0x08;\n    const uint32_t b = (((pixel /*****/) & 0xFF) * shading) >> 0x08;\n    return r << 0x10 | g << 0x08 | b;\n}\n\nstatic void tdraw(const int yres, uint32_t* const pixel, float* const zbuff, const Target t, const Vertex lights)\n{\n    const int x0 = fminf(t.vew.a.x, fminf(t.vew.b.x, t.vew.c.x));\n    const int y0 = fminf(t.vew.a.y, fminf(t.vew.b.y, t.vew.c.y));\n    const int x1 = fmaxf(t.vew.a.x, fmaxf(t.vew.b.x, t.vew.c.x));\n    const int y1 = fmaxf(t.vew.a.y, fmaxf(t.vew.b.y, t.vew.c.y));\n    for(int x = x0; x <= x1; x++)\n    for(int y = y0; y <= y1; y++)\n    {\n        const Vertex bc = tbarycenter(t.vew, x, y);\n        if(bc.x >= 0.0f && bc.y >= 0.0f && bc.z >= 0.0f)\n        {\n            // Barycenter above is upwards. Everything below rotated 90 degrees to accomodate sideways renderer.\n            const float z = bc.x * t.vew.b.z + bc.y * t.vew.c.z + bc.z * t.vew.a.z;\n            if(z > zbuff[y + x * yres])\n            {\n                const Vertex varying = { vdot(lights, t.nrm.b), vdot(lights, t.nrm.c), vdot(lights, t.nrm.a) };\n                const uint32_t* const pixels = (uint32_t*) t.fdif->pixels;\n                const int xx = (t.fdif->w - 1) * (0.0f + (bc.x * t.tex.b.x + bc.y * t.tex.c.x + bc.z * t.tex.a.x));\n                const int yy = (t.fdif->h - 1) * (1.0f - (bc.x * t.tex.b.y + bc.y * t.tex.c.y + bc.z * t.tex.a.y));\n                const float intensity = vdot(bc, varying);\n                const int shading = 0xFF * (intensity < 0.0f ? 0.0f : intensity > 1.0f ? 1.0f : intensity);\n                // Image is upwards contrary to sideways renderer.\n                zbuff[y + x * yres] = z;\n                pixel[y + x * yres] = pshade(pixels[xx + yy * t.fdif->w], shading);\n            }\n        }\n    }\n}\n\nstatic Triangle tviewtri(const Triangle t, const Vertex x, const Vertex y, const Vertex z, const Vertex eye)\n{\n    const Triangle o = {\n        { vdot(t.a, x) - vdot(x, eye), vdot(t.a, y) - vdot(y, eye), vdot(t.a, z) - vdot(z, eye) },\n        { vdot(t.b, x) - vdot(x, eye), vdot(t.b, y) - vdot(y, eye), vdot(t.b, z) - vdot(z, eye) },\n        { vdot(t.c, x) - vdot(x, eye), vdot(t.c, y) - vdot(y, eye), vdot(t.c, z) - vdot(z, eye) },\n    };\n    return o;\n}\n\nstatic Triangle tviewnrm(const Triangle n, const Vertex x, const Vertex y, const Vertex z)\n{\n    const Triangle o = {\n        { vdot(n.a, x), vdot(n.a, y), vdot(n.a, z) },\n        { vdot(n.b, x), vdot(n.b, y), vdot(n.b, z) },\n        { vdot(n.c, x), vdot(n.c, y), vdot(n.c, z) },\n    };\n    return tunit(o);\n}\n\nstatic Input iinit()\n{\n    const Input input = { 0.0f, 0.0f, 0.005f, 0 };\n    SDL_SetRelativeMouseMode(SDL_FALSE);\n    return input;\n}\n\nstatic Input ipump(Input input)\n{\n    int dx;\n    int dy;\n    SDL_Event event;\n    SDL_PollEvent(&event);\n    if(event.type == SDL_QUIT)\n        input.done = 1;\n    SDL_GetRelativeMouseState(&dx, &dy);\n    input.xt -= input.sens * dx;\n    input.yt += input.sens * dy;\n    return input;\n}\n\nstatic void reset(float* const zbuff, uint32_t* const pixel, const int size)\n{\n    for(int i = 0; i < size; i++)\n        zbuff[i] = -FLT_MAX, pixel[i] = 0x0;\n}\n\nstatic void spresent(const Sdl sdl)\n{\n    SDL_RenderPresent(sdl.renderer);\n}\n\nstatic void schurn(const Sdl sdl)\n{\n    const SDL_Rect dst = {\n        (sdl.xres - sdl.yres) / 2,\n        (sdl.yres - sdl.xres) / 2,\n        sdl.yres, sdl.xres\n    };\n    SDL_RenderCopyEx(sdl.renderer, sdl.canvas, NULL, &dst, -90, NULL, SDL_FLIP_NONE);\n}\n\nstatic Sdl ssetup(const int xres, const int yres)\n{\n    Sdl sdl;\n    SDL_Init(SDL_INIT_VIDEO);\n    SDL_CreateWindowAndRenderer(xres, yres, 0, &sdl.window, &sdl.renderer);\n    SDL_SetWindowTitle(sdl.window, \"Gel-1.2\");\n    // Notice the flip between xres and yres - the renderer is on its side to maximize cache effeciency.\n    sdl.canvas = SDL_CreateTexture(sdl.renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, yres, xres);\n    sdl.xres = xres;\n    sdl.yres = yres;\n    return sdl;\n}\n\nstatic void sunlock(const Sdl sdl)\n{\n    SDL_UnlockTexture(sdl.canvas);\n}\n\nstatic uint32_t* slock(const Sdl sdl)\n{\n    void* pixel;\n    int pitch;\n    SDL_LockTexture(sdl.canvas, NULL, &pixel, &pitch);\n    return (uint32_t*) pixel;\n}\n\nstatic FILE* oload(const char* const path)\n{\n    FILE* const file = fopen(path, \"r\");\n    if(file == NULL)\n    {\n        printf(\"could not open %s\\n\", path);\n        exit(1);\n    }\n    return file;\n}\n\nstatic SDL_Surface* sload(const char* const path)\n{\n    SDL_Surface* const bmp = IMG_Load(path);\n    if(bmp == NULL)\n    {\n        puts(IMG_GetError());\n        exit(1);\n    }\n    SDL_PixelFormat* const allocation = SDL_AllocFormat(SDL_PIXELFORMAT_RGB888);\n    SDL_Surface* const converted = SDL_ConvertSurface(bmp, allocation, 0);\n    SDL_FreeFormat(allocation);\n    SDL_FreeSurface(bmp);\n    return converted;\n}\n\nint main(int argc, char* argv[])\n{\n    if(argc != 3)\n    {\n        puts(\"args: path/to/obj path/to/bmp\");\n        return 1;\n    }\n    FILE* const fobj = oload(argv[1]);\n    SDL_Surface* const fdif = sload(argv[2]);\n    const Obj obj = oparse(fobj);\n    const Triangles tv = tvgen(obj); // Triangle Vertices.\n    const Triangles tt = ttgen(obj); // Triangle Textures.\n    const Triangles tn = tngen(obj); // Triangle Normals.\n    const Sdl sdl = ssetup(800, 600);\n    float* const zbuff = (float*) malloc(sizeof(float) * sdl.xres * sdl.yres);\n    for(Input input = iinit(); !input.done; input = ipump(input))\n    {\n        const int t0 = SDL_GetTicks();\n        uint32_t* const pixel = slock(sdl);\n        reset(zbuff, pixel, sdl.xres * sdl.yres);\n        const Vertex center = { 0.0f, 0.0f, 0.0f };\n        const Vertex upward = { 0.0f, 1.0f, 0.0f };\n        const Vertex lights = { 0.0f, 0.0f, 1.0f };\n        const Vertex eye = { sinf(input.xt), sinf(input.yt), cosf(input.xt) };\n        const Vertex z = vunit(vsub(eye, center));\n        const Vertex x = vunit(vcross(upward, z));\n        const Vertex y = vcross(z, x);\n        for(int i = 0; i < tv.count; i++)\n        {\n            const Triangle nrm = tviewnrm(tn.triangle[i], x, y, z);\n            const Triangle tex = tt.triangle[i];\n            const Triangle tri = tviewtri(tv.triangle[i], x, y, z, eye);\n            const Triangle per = tperspective(tri);\n            const Triangle vew = tviewport(per, sdl);\n            const Target target = { vew, nrm, tex, fdif };\n            tdraw(sdl.yres, pixel, zbuff, target, lights);\n        }\n        sunlock(sdl);\n        schurn(sdl);\n        spresent(sdl);\n        const int t1 = SDL_GetTicks();\n        const int ms = 1000.0f / 60.0f - (t1 - t0);\n        SDL_Delay(ms < 0 ? 0 : ms);\n    }\n    return 0;\n}\n"
  }
]