diff --git a/CMakeLists.txt b/CMakeLists.txt index 876160f..5589a08 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,6 +2,7 @@ cmake_minimum_required(VERSION 3.5) project(CG1_Tracer LANGUAGES CXX) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_FLAGS "-O3 -pthread") if(NOT WIN32) find_package(Threads REQUIRED) diff --git a/common/ray.cpp b/common/ray.cpp index 2ec18a8..a44cd46 100644 --- a/common/ray.cpp +++ b/common/ray.cpp @@ -1,3 +1,3 @@ #include "ray.h" -int Ray::rayCount = 0; +std::atomic_int Ray::rayCount = 0; diff --git a/common/ray.h b/common/ray.h index c130a17..494857f 100644 --- a/common/ray.h +++ b/common/ray.h @@ -42,7 +42,7 @@ private: int remainingBounces = ICG_RAY_BOUNCES; #endif - static int rayCount; + static std::atomic_int rayCount; }; #endif diff --git a/renderer/simplerenderer.cpp b/renderer/simplerenderer.cpp index d455107..6ad3fa9 100644 --- a/renderer/simplerenderer.cpp +++ b/renderer/simplerenderer.cpp @@ -4,6 +4,7 @@ #include #include #include +#include Texture SimpleRenderer::renderImage(Scene const &scene, Camera const &camera, int width, int height) { Texture image(width, height); @@ -17,28 +18,35 @@ Texture SimpleRenderer::renderImage(Scene const &scene, Camera const &camera, in // Super-hacky progress bar! std::cout << "(SimpleRenderer): Begin rendering..." << std::endl; std::cout << "| 0%"; - int const barSize = 50; - int const stepSize = (width * height) / barSize; - for (int i = 0; i < barSize - 3 - 5; ++i) - std::cout << " "; + int const barSizeGoal = 100; + int const stepSize = width / barSizeGoal; + for (int i = 0; i < width / stepSize - 3 - 5; ++i) + std::cout << " "; std::cout << "100% |" << std::endl << "|"; int k = 0; // Start timer start = std::chrono::steady_clock::now(); - float const aspectRatio = static_cast(height) / width; - for (int x = 0; x < image.width(); ++x) { - for (int y = 0; y < image.height(); ++y) { - Ray ray = camera.createRay((static_cast(x) / width * 2 - 1), -(static_cast(y) / height * 2 - 1) * aspectRatio); - image.setPixelAt(x, y, clamped(scene.traceRay(ray))); - - // Super hacky progress bar! - if (++k % stepSize == 0) { - std::cout << "=" << std::flush; - } + float const aspectRatio = static_cast(height) / static_cast(width); + std::vector threads; + threads.reserve(width); + for (int x = 0; x < image.width(); ++x) { + threads.emplace_back([&image, aspectRatio](auto camera, auto scene, int x) { + for (int y = 0; y < image.height(); ++y) { + Ray ray = camera->createRay((static_cast(x) / image.width() * 2.0f - 1), + -(static_cast(y) / image.height() * 2 - 1) * aspectRatio); + image.setPixelAt(x, y, clamped(scene->traceRay(ray))); + } + }, &camera, &scene, x); + } + for (auto &thread: threads) { + thread.join(); + // Super hacky progress bar! + if (++k % stepSize == 0) { + std::cout << "=" << std::flush; + } } - } // Stop timer stop = std::chrono::steady_clock::now();