Last active
August 29, 2015 14:26
-
-
Save OllieReynolds/0d4ad31dc34748cce0ed to your computer and use it in GitHub Desktop.
raymarch_ascii
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Windows.h> | |
#define GLM_SWIZZLE | |
#include <glm/glm.hpp> | |
#include <ctime> | |
const auto WIDTH = 100; | |
const auto HEIGHT = 50; | |
const auto PALETTE = " `-_:/~|(%zr*uwJ$khOZ8W@B#M"; | |
const auto STEP = 0.037037f; | |
glm::vec3 opRep(glm::vec3 p, glm::vec3 c) { | |
return mod(p, c) - 0.5f * c; | |
} | |
float sdBox(glm::vec3 p, glm::vec3 b) { | |
auto d = abs(p) - b; | |
return glm::min(glm::max(d.x, glm::max(d.y, d.z)), 0.f) + length(max(d, 0.f)); | |
} | |
float trace(glm::vec3 o, glm::vec3 r) { | |
auto t = 0.f; | |
for (auto i = 0; i < 50; i++) { | |
auto p = o + r * t; | |
t += sdBox(opRep(p, glm::vec3(66.f)), glm::vec3(8.f)); | |
} | |
return t; | |
} | |
glm::mat2 rotate(float angle) { | |
return glm::mat2(cos(angle), -sin(angle), sin(angle), cos(angle)); | |
} | |
int main() { | |
auto wHnd = GetStdHandle(STD_OUTPUT_HANDLE); | |
SMALL_RECT windowSize = {0, 0, WIDTH, HEIGHT}; | |
SetConsoleWindowInfo(wHnd, TRUE, &windowSize); | |
SetConsoleScreenBufferSize(wHnd, {WIDTH, HEIGHT}); | |
CHAR_INFO consoleBuffer[WIDTH * HEIGHT]; | |
SMALL_RECT writeArea = {0, 0, WIDTH - 1, HEIGHT - 1}; | |
while (1) { | |
for (auto y = 0; y < HEIGHT; ++y) { | |
for (auto x = 0; x <= WIDTH; ++x) { | |
auto uv = glm::vec2(x, y) / glm::vec2(WIDTH, HEIGHT) * 2.f - 1.f; | |
uv.x *= WIDTH / HEIGHT; | |
auto r = normalize(glm::vec3(uv, 1.f)); | |
r.xz = rotate(clock() * 0.001f) * r.xz; | |
r.yz = rotate(clock() * 0.001f) * r.yz; | |
auto o = glm::vec3(0.f, 3.f, clock() * 0.1f); | |
auto t = trace(o, r); | |
auto fc = 1.f / (1.f + t * t * 0.00004f); | |
auto i = static_cast<int>(fc / STEP); | |
consoleBuffer[x + WIDTH * y].Char.AsciiChar = PALETTE[i]; | |
consoleBuffer[x + WIDTH * y].Attributes = FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN; | |
} | |
} | |
WriteConsoleOutputA(wHnd, consoleBuffer, {WIDTH, HEIGHT}, {0, 0}, &writeArea); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice!