From 9ac6fffd4d4843e864de3b4123abf38caeb6ab65 Mon Sep 17 00:00:00 2001 From: Alug Date: Thu, 5 Jun 2025 16:53:22 +0200 Subject: [PATCH] busted ass multithreading for le soft --- src/Makefile | 3 +- src/command.h | 8 + src/core/CMakeLists.txt | 1 + src/core/Sourcefile | 2 + src/core/memory.cpp | 71 +++++++ src/core/memory.h | 32 +++ src/core/spmc_queue.hpp | 192 ++++++++++++++++++ src/core/static_vec.hpp | 255 ++++++++++++++++++++++++ src/core/thread_pool.cpp | 346 +++++++++++++++++++++++++++++++++ src/core/thread_pool.h | 163 ++++++++++++++++ src/cxxutil.hpp | 152 +++++++++++++++ src/d_clisrv.h | 9 + src/d_main.c | 4 + src/d_netcmd.c | 5 - src/d_netcmd.h | 13 ++ src/doomdef.h | 10 + src/doomtype.h | 10 + src/i_system.h | 8 + src/m_argv.h | 8 + src/p_mobj.h | 9 + src/p_setup.h | 8 + src/r_bsp.h | 9 + src/r_data.h | 8 + src/r_draw.h | 10 +- src/r_fps.h | 8 + src/r_local.h | 8 + src/{r_main.c => r_main.cpp} | 70 ++++--- src/r_main.h | 11 +- src/{r_plane.c => r_plane.cpp} | 169 ++++++++++++---- src/r_plane.h | 9 + src/r_portal.h | 8 + src/r_segs.c | 126 +++++++----- src/r_segs.h | 8 + src/r_things.c | 2 +- src/r_things.h | 8 + src/sdl/i_system.c | 24 ++- src/tables.h | 8 + src/v_video.h | 8 + src/w_wad.h | 8 + src/z_zone.h | 8 + 40 files changed, 1685 insertions(+), 134 deletions(-) create mode 100644 src/core/CMakeLists.txt create mode 100644 src/core/Sourcefile create mode 100644 src/core/memory.cpp create mode 100644 src/core/memory.h create mode 100644 src/core/spmc_queue.hpp create mode 100644 src/core/static_vec.hpp create mode 100644 src/core/thread_pool.cpp create mode 100644 src/core/thread_pool.h create mode 100644 src/cxxutil.hpp rename src/{r_main.c => r_main.cpp} (94%) rename src/{r_plane.c => r_plane.cpp} (87%) diff --git a/src/Makefile b/src/Makefile index 56edb6db9..6713bc624 100644 --- a/src/Makefile +++ b/src/Makefile @@ -181,7 +181,8 @@ objdir:=$(makedir)/objs # very sophisticated dependency sources+=\ - $(call List,Sourcefile) + $(call List,Sourcefile)\ + $(call List,core/Sourcefile) sources+=\ $(call List,blua/Sourcefile) diff --git a/src/command.h b/src/command.h index 2276a0ae2..6d1944f9a 100644 --- a/src/command.h +++ b/src/command.h @@ -13,6 +13,10 @@ #ifndef __COMMAND_H__ #define __COMMAND_H__ +#ifdef __cplusplus +extern "C" { +#endif + #include #include "doomdef.h" @@ -189,4 +193,8 @@ UINT8 CV_CheatsEnabled(void); // Returns cvar by name. Exposed here for Lua. consvar_t *CV_FindVar(const char *name); +#ifdef __cplusplus +} // extern "C" +#endif + #endif // __COMMAND_H__ diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt new file mode 100644 index 000000000..db8bc5a15 --- /dev/null +++ b/src/core/CMakeLists.txt @@ -0,0 +1 @@ +target_sourcefile(cpp) diff --git a/src/core/Sourcefile b/src/core/Sourcefile new file mode 100644 index 000000000..e8701d507 --- /dev/null +++ b/src/core/Sourcefile @@ -0,0 +1,2 @@ +memory.cpp +thread_pool.cpp diff --git a/src/core/memory.cpp b/src/core/memory.cpp new file mode 100644 index 000000000..e75cf91f7 --- /dev/null +++ b/src/core/memory.cpp @@ -0,0 +1,71 @@ +// BLANKART +//----------------------------------------------------------------------------- +// Copyright (C) 2024 by Ronald "Eidolon" Kinard +// Copyright (C) 2024 by Kart Krew +// +// This program is free software distributed under the +// terms of the GNU General Public License, version 2. +// See the 'LICENSE' file for more details. +//----------------------------------------------------------------------------- + +#include "memory.h" + +#include +#include + +#include "../z_zone.h" + +namespace +{ + +class LinearMemory +{ + size_t size_; + size_t height_; + void* memory_; + +public: + constexpr explicit LinearMemory(size_t size) noexcept; + + void* allocate(size_t size); + void reset() noexcept; +}; + +constexpr LinearMemory::LinearMemory(size_t size) noexcept : size_(size), height_{0}, memory_{nullptr} {} + +void* LinearMemory::allocate(size_t size) +{ + size_t aligned_size = (size + 15) & ~15; + if (height_ + aligned_size > size_) + { + throw std::bad_alloc(); + } + + if (memory_ == nullptr) + { + memory_ = Z_Malloc(size_, PU_STATIC, nullptr); + } + + void* ptr = (void*)((uintptr_t)(memory_) + height_); + height_ += aligned_size; + return ptr; +} + +void LinearMemory::reset() noexcept +{ + height_ = 0; +} + +} // namespace + +static LinearMemory g_frame_memory {4 * 1024 * 1024}; + +void* Z_Frame_Alloc(size_t size) +{ + return g_frame_memory.allocate(size); +} + +void Z_Frame_Reset() +{ + g_frame_memory.reset(); +} diff --git a/src/core/memory.h b/src/core/memory.h new file mode 100644 index 000000000..ba49e3d51 --- /dev/null +++ b/src/core/memory.h @@ -0,0 +1,32 @@ +// BLANKART +//----------------------------------------------------------------------------- +// Copyright (C) 2024 by Ronald "Eidolon" Kinard +// Copyright (C) 2024 by Kart Krew +// +// This program is free software distributed under the +// terms of the GNU General Public License, version 2. +// See the 'LICENSE' file for more details. +//----------------------------------------------------------------------------- + +#ifndef __SRB2_CORE_MEMORY_H__ +#define __SRB2_CORE_MEMORY_H__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif // __cpluspplus + +/// @brief Allocate a block of memory with a lifespan of the current main-thread frame. +/// This function is NOT thread-safe, but the allocated memory may be used across threads. +/// @return a pointer to a block of memory aligned with libc malloc alignment, or null if allocation fails +void* Z_Frame_Alloc(size_t size); + +/// @brief Resets per-frame memory. Not thread safe. +void Z_Frame_Reset(void); + +#ifdef __cplusplus +} // extern "C" +#endif // __cplusplus + +#endif // __SRB2_CORE_MEMORY_H__ diff --git a/src/core/spmc_queue.hpp b/src/core/spmc_queue.hpp new file mode 100644 index 000000000..d85e1300d --- /dev/null +++ b/src/core/spmc_queue.hpp @@ -0,0 +1,192 @@ +/* + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */ + +// This class is derived from Conor Williams' implementation of a concurrent deque +// https://github.com/ConorWilliams/ConcurrentDeque +// Copyright (C) 2021 Conor Williams + +// The original version was for C++23. This one has been shrunk slightly and adapted to our conventions. + +#ifndef __SRB2_CORE_SPMC_QUEUE_HPP__ +#define __SRB2_CORE_SPMC_QUEUE_HPP__ + +#include +#include +#include +#include +#include + +//#include + +#include "../cxxutil.hpp" + +namespace srb2 +{ + +template +class SpMcQueue +{ + struct RingBuff { + public: + explicit RingBuff(int64_t cap) : _cap{cap}, _mask{cap - 1} + { + SRB2_ASSERT(cap && (!(cap & (cap - 1))) && "Capacity must be buf power of 2!"); + _buff = std::unique_ptr(new T[_cap]); + } + + std::int64_t capacity() const noexcept { return _cap; } + + // Store (copy) at modulo index + void store(int64_t i, T&& x) noexcept + { + _buff[i & _mask] = std::move(x); + } + + // Load (copy) at modulo index + T load(int64_t i) const noexcept + { + return _buff[i & _mask]; + } + + // Allocates and returns a new ring buffer, copies elements in range [b, t) into the new buffer. + RingBuff* resize(std::int64_t b, std::int64_t t) const + { + //ZoneScoped; + RingBuff* ptr = new RingBuff{2 * _cap}; + for (std::int64_t i = t; i != b; ++i) { + ptr->store(i, load(i)); + } + return ptr; + } + + private: + int64_t _cap; // Capacity of the buffer + int64_t _mask; // Bit mask to perform modulo capacity operations + + std::unique_ptr _buff; + }; + + alignas(64) std::atomic bottom_; + alignas(64) std::atomic top_; + alignas(64) std::atomic buffer_; + + std::vector> garbage_; + +public: + SpMcQueue(size_t capacity) : bottom_(0), top_(0), buffer_(new RingBuff(capacity)) + { + garbage_.reserve(32); + } + ~SpMcQueue() noexcept + { + delete buffer_.load(std::memory_order_relaxed); + }; + + size_t size() const noexcept + { + int64_t bottom = bottom_.load(std::memory_order_relaxed); + int64_t top = top_.load(std::memory_order_relaxed); + return static_cast(bottom >= top ? bottom - top : 0); + } + + bool empty() const noexcept + { + return size() == 0; + } + + void push(T&& v) noexcept + { + int64_t bottom = bottom_.load(std::memory_order_relaxed); + int64_t top = top_.load(std::memory_order_acquire); + RingBuff* buf = buffer_.load(std::memory_order_relaxed); + + if (buf->capacity() < (bottom - top) + 1) + { + // Queue is full, build a new one + RingBuff* newbuf = buf->resize(bottom, top); + garbage_.emplace_back(buf); + buffer_.store(newbuf, std::memory_order_relaxed); + buf = newbuf; + } + + // Construct new object, this does not have to be atomic as no one can steal this item until after we + // store the new value of bottom, ordering is maintained by surrounding atomics. + buf->store(bottom, std::move(v)); + + std::atomic_thread_fence(std::memory_order_release); + bottom_.store(bottom + 1, std::memory_order_relaxed); + } + + std::optional pop() noexcept + { + int64_t bottom = bottom_.load(std::memory_order_relaxed) - 1; + RingBuff* buf = buffer_.load(std::memory_order_relaxed); + + bottom_.store(bottom, std::memory_order_relaxed); // Stealers can no longer steal + + std::atomic_thread_fence(std::memory_order_seq_cst); + int64_t top = top_.load(std::memory_order_relaxed); + + if (top <= bottom) + { + // Non-empty deque + if (top == bottom) + { + // The last item could get stolen, by a stealer that loaded bottom before our write above + if (!top_.compare_exchange_strong(top, top + 1, std::memory_order_seq_cst, std::memory_order_relaxed)) + { + // Failed race, thief got the last item. + bottom_.store(bottom + 1, std::memory_order_relaxed); + return std::nullopt; + } + bottom_.store(bottom + 1, std::memory_order_relaxed); + } + + // Can delay load until after acquiring slot as only this thread can push(), this load is not + // required to be atomic as we are the exclusive writer. + return buf->load(bottom); + + } + else + { + bottom_.store(bottom + 1, std::memory_order_relaxed); + return std::nullopt; + } + } + + std::optional steal() noexcept + { + int64_t top = top_.load(std::memory_order_acquire); + std::atomic_thread_fence(std::memory_order_seq_cst); + int64_t bottom = bottom_.load(std::memory_order_acquire); + + if (top < bottom) + { + // Must load *before* acquiring the slot as slot may be overwritten immediately after acquiring. + // This load is NOT required to be atomic even-though it may race with an overrite as we only + // return the value if we win the race below garanteeing we had no race during our read. If we + // loose the race then 'x' could be corrupt due to read-during-write race but as T is trivially + // destructible this does not matter. + T x = buffer_.load(std::memory_order_consume)->load(top); + + if (!top_.compare_exchange_strong(top, top + 1, std::memory_order_seq_cst, std::memory_order_relaxed)) + { + return std::nullopt; + } + + return x; + + } + else + { + return std::nullopt; + } + } +}; + +} // namespace srb2 + +#endif // __SRB2_CORE_SPMC_QUEUE_HPP__ diff --git a/src/core/static_vec.hpp b/src/core/static_vec.hpp new file mode 100644 index 000000000..a5a529564 --- /dev/null +++ b/src/core/static_vec.hpp @@ -0,0 +1,255 @@ +// BLANKART +//----------------------------------------------------------------------------- +// Copyright (C) 2024 by Ronald "Eidolon" Kinard +// Copyright (C) 2024 by Kart Krew +// +// This program is free software distributed under the +// terms of the GNU General Public License, version 2. +// See the 'LICENSE' file for more details. +//----------------------------------------------------------------------------- + +#ifndef __SRB2_CORE_STATIC_VEC_HPP__ +#define __SRB2_CORE_STATIC_VEC_HPP__ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../cxxutil.hpp" + +namespace srb2 +{ + +template +class StaticVec; + +template +class StaticVec +{ + std::array arr_ {{}}; + size_t size_ = 0; + +public: + using value_type = T; + + constexpr StaticVec() {} + + StaticVec(const StaticVec& rhs) + { + for (size_t i = size_; i > 0; i--) + { + arr_[i] = T(); + } + size_ = rhs.size(); + for (size_t i = 0; i < size_; i++) + { + arr_[i] = rhs.arr_[i]; + } + } + + StaticVec(StaticVec&& rhs) noexcept(std::is_nothrow_move_assignable_v) + { + for (size_t i = size_; i > 0; i--) + { + arr_[i] = T(); + } + size_ = rhs.size(); + for (size_t i = 0; i < size_; i++) + { + arr_[i] = std::move(rhs.arr_[i]); + } + while (rhs.size() > 0) + { + rhs.pop_back(); + } + } + + constexpr StaticVec(std::initializer_list list) noexcept(std::is_nothrow_move_assignable_v) + { + size_ = list.size(); + size_t i = 0; + for (auto itr = list.begin(); itr != list.end(); itr++) + { + arr_[i] = *itr; + i++; + } + } + + ~StaticVec() = default; + + StaticVec& operator=(const StaticVec& rhs) + { + for (size_t i = size_; i > 0; i--) + { + arr_[i] = T(); + } + size_ = rhs.size(); + for (size_t i = 0; i < size_; i++) + { + arr_[i] = rhs.arr_[i]; + } + return *this; + } + + StaticVec& operator=(StaticVec&& rhs) noexcept(std::is_nothrow_move_constructible_v) + { + for (size_t i = size_; i > 0; i--) + { + arr_[i] = T(); + } + size_ = rhs.size(); + for (size_t i = 0; i < size_; i++) + { + arr_[i] = std::move(rhs.arr_[i]); + } + while (rhs.size() > 0) + { + rhs.pop_back(); + } + return *this; + } + + void push_back(const T& value) { arr_[size_++] = value; } + + void pop_back() { arr_[--size_] = T(); } + + void resize(size_t size, T value = T()) + { + if (size >= Limit) + { + throw std::length_error("new size >= Capacity"); + } + + if (size == size_) + { + return; + } + else if (size < size_) + { + while (size_ > size) + { + pop_back(); + } + } + else + { + while (size_ < size) + { + push_back(value); + } + } + } + + void clear() + { + arr_ = {{}}; + size_ = 0; + } + + using iterator = typename std::array::iterator; + using const_iterator = typename std::array::const_iterator; + + constexpr iterator begin() noexcept { return arr_.begin(); } + + constexpr const_iterator begin() const noexcept { return arr_.cbegin(); } + + constexpr const_iterator cbegin() const noexcept { return arr_.cbegin(); } + + constexpr iterator end() noexcept { return std::next(arr_.begin(), size_); } + + constexpr const_iterator end() const noexcept { return cend(); } + + constexpr const_iterator cend() const noexcept { return std::next(arr_.cbegin(), size_); } + + constexpr std::reverse_iterator rbegin() noexcept { return std::reverse_iterator(this->end()); } + + constexpr std::reverse_iterator crbegin() const noexcept { return std::reverse_iterator(this->cend()); } + + constexpr std::reverse_iterator rend() noexcept { return std::reverse_iterator(this->begin()); } + + constexpr std::reverse_iterator crend() const noexcept { return std::reverse_iterator(this->cbegin()); } + + constexpr bool empty() const noexcept { return size_ == 0; } + + constexpr size_t size() const noexcept { return size_; } + + constexpr size_t capacity() const noexcept { return Limit; } + + constexpr size_t max_size() const noexcept { return Limit; } + + constexpr T& operator[](size_t index) noexcept { return arr_[index]; } + + T& at(size_t index) + { + if (index >= size_) + { + throw std::out_of_range("index >= size"); + } + return this[index]; + } + + constexpr const T& operator[](size_t index) const noexcept { return arr_[index]; } + + const T& at(size_t index) const + { + if (index >= size_) + { + throw std::out_of_range("index >= size"); + } + return this[index]; + } + + T& front() { return *arr_[0]; } + + T& back() { return *arr_[size_ - 1]; } +}; + +} // namespace srb2 + +template +bool operator==(const srb2::StaticVec& lhs, const srb2::StaticVec& rhs) +{ + const size_t size = lhs.size(); + if (size != rhs.size()) + { + return false; + } + for (size_t i = 0; i < lhs; i++) + { + if (rhs[i] != lhs[i]) + { + return false; + } + } + return true; +} + +template +bool operator!=(const srb2::StaticVec& lhs, const srb2::StaticVec& rhs) +{ + return !(lhs == rhs); +} + +template +struct std::hash> +{ + size_t operator()(const srb2::StaticVec& input) const + { + constexpr size_t prime = sizeof(size_t) == 8 ? 0x00000100000001B3 : 0x01000193; + constexpr size_t basis = sizeof(size_t) == 8 ? 0xcbf29ce484222325 : 0x811c9dc5; + + size_t ret = basis; + for (auto itr = input.begin(); itr != input.end(); itr++) + { + ret = (ret * prime) ^ std::hash(*itr); + } + return ret; + } +}; + +#endif // __SRB2_CORE_STATIC_VEC_HPP__ diff --git a/src/core/thread_pool.cpp b/src/core/thread_pool.cpp new file mode 100644 index 000000000..820f21f67 --- /dev/null +++ b/src/core/thread_pool.cpp @@ -0,0 +1,346 @@ +// BLANKART +//----------------------------------------------------------------------------- +// Copyright (C) 2024 by Ronald "Eidolon" Kinard +// Copyright (C) 2024 by Kart Krew +// +// This program is free software distributed under the +// terms of the GNU General Public License, version 2. +// See the 'LICENSE' file for more details. +//----------------------------------------------------------------------------- + +#include "thread_pool.h" + +#include +#include +#include +#include +#include +#include + +#include +//#include + +#include "../cxxutil.hpp" +#include "../m_argv.h" + +using namespace srb2; + +static void do_work(ThreadPool::Task& work) +{ + try + { + //ZoneScoped; + (work.thunk)(work.raw.data()); + } + catch (...) + { + // can't do anything + } + + (work.deleter)(work.raw.data()); + if (work.pseudosema) + { + work.pseudosema->fetch_sub(1, std::memory_order_relaxed); + } +} + +static void pool_executor( + int thread_index, + std::shared_ptr> pool_alive, + std::shared_ptr worker_ready_mutex, + std::shared_ptr worker_ready_condvar, + std::shared_ptr my_wq, + std::vector> other_wqs +) +{ + { + //std::string thread_name = fmt::format("Thread Pool Thread {}", thread_index); + //tracy::SetThreadName(thread_name.c_str()); + } + + int spins = 0; + while (true) + { + std::optional work = my_wq->steal(); + bool did_work = false; + if (work) + { + do_work(*work); + + did_work = true; + spins = 0; + } + else + { + for (auto& q : other_wqs) + { + work = q->steal(); + if (work) + { + do_work(*work); + + did_work = true; + spins = 0; + + // We only want to steal one work item at a time, to prioritize our own queue + break; + } + } + } + + if (!did_work) + { + // Spin a few loops to avoid yielding, then wait for the ready lock + spins += 1; + if (spins > 100) + { + std::unique_lock ready_lock {*worker_ready_mutex}; + while (my_wq->empty() && pool_alive->load()) + { + worker_ready_condvar->wait(ready_lock); + } + + if (!pool_alive->load()) + { + break; + } + } + } + } +} + +ThreadPool::ThreadPool() +{ + immediate_mode_ = true; +} + +ThreadPool::ThreadPool(size_t threads) +{ + next_queue_index_ = 0; + pool_alive_ = std::make_shared>(true); + + for (size_t i = 0; i < threads; i++) + { + std::shared_ptr wsq = std::make_shared(2048); + work_queues_.push_back(wsq); + + std::shared_ptr mutex = std::make_shared(); + worker_ready_mutexes_.push_back(std::move(mutex)); + std::shared_ptr condvar = std::make_shared(); + worker_ready_condvars_.push_back(std::move(condvar)); + } + + for (size_t i = 0; i < threads; i++) + { + std::shared_ptr my_queue = work_queues_[i]; + std::vector> other_queues; + for (size_t j = 0; j < threads; j++) + { + // Order the other queues starting from the next adjacent worker + // i.e. if this is worker 2 of 8, then other queues is 3, 4, 5, 6, 7, 0, 1 + // This tries to balance out work stealing behavior + + size_t other_index = j + i; + if (other_index >= threads) + { + other_index -= threads; + } + + if (other_index != i) + { + other_queues.push_back(work_queues_[other_index]); + } + } + + std::thread thread; + try + { + thread = std::thread + { + pool_executor, + i, + pool_alive_, + worker_ready_mutexes_[i], + worker_ready_condvars_[i], + my_queue, + other_queues + }; + } + catch (const std::system_error& error) + { + // Safe shutdown and rethrow + pool_alive_->store(false); + for (auto& t : threads_) + { + t.join(); + } + throw error; + } + + threads_.push_back(std::move(thread)); + } +} + +ThreadPool::ThreadPool(ThreadPool&&) = default; +ThreadPool::~ThreadPool() = default; + +ThreadPool& ThreadPool::operator=(ThreadPool&&) = default; + +void ThreadPool::begin_sema() +{ + sema_begun_ = true; +} + +ThreadPool::Sema ThreadPool::end_sema() +{ + Sema ret = Sema(std::move(cur_sema_)); + cur_sema_ = nullptr; + sema_begun_ = false; + return ret; +} + +void ThreadPool::notify() +{ + for (size_t i = 0; i < work_queues_.size(); i++) + { + auto& q = work_queues_[i]; + size_t count = q->size(); + if (count > 0) + { + worker_ready_condvars_[i]->notify_one(); + } + } +} + +void ThreadPool::notify_sema(const ThreadPool::Sema& sema) +{ + if (!sema.pseudosema_) + { + return; + } + notify(); +} + +void ThreadPool::wait_idle() +{ + if (immediate_mode_) + { + return; + } + + //ZoneScoped; + + for (size_t i = 0; i < work_queues_.size(); i++) + { + auto& q = work_queues_[i]; + + std::optional work; + while ((work = q->pop()).has_value()) + { + do_work(*work); + } + } +} + +void ThreadPool::wait_sema(const Sema& sema) +{ + if (!sema.pseudosema_) + { + return; + } + + //ZoneScoped; + + while (sema.pseudosema_->load(std::memory_order_seq_cst) > 0) + { + // spin to win + for (size_t i = 0; i < work_queues_.size(); i++) + { + auto& q = work_queues_[i]; + + std::optional work; + if ((work = q->pop()).has_value()) + { + do_work(*work); + break; + } + } + } + + if (sema.pseudosema_->load(std::memory_order_seq_cst) != 0) + { + throw std::exception(); + } +} + +void ThreadPool::shutdown() +{ + if (immediate_mode_) + { + return; + } + + wait_idle(); + + pool_alive_->store(false); + + for (auto& condvar : worker_ready_condvars_) + { + condvar->notify_all(); + } + for (auto& t : threads_) + { + t.join(); + } +} + +std::unique_ptr srb2::g_main_threadpool; + +void I_ThreadPoolInit(void) +{ + SRB2_ASSERT(g_main_threadpool == nullptr); + size_t thread_count = std::min(static_cast(9), std::thread::hardware_concurrency()); + if (thread_count > 1) + { + // The main thread will act as a worker when waiting for pool idle + // Make one less worker thread to avoid unnecessary context switching + thread_count -= 1; + } + + if (M_CheckParm("-singlethreaded")) + { + g_main_threadpool = std::make_unique(); + } + else + { + g_main_threadpool = std::make_unique(thread_count); + } +} + +void I_ThreadPoolShutdown(void) +{ + if (!g_main_threadpool) + { + return; + } + + g_main_threadpool->shutdown(); + g_main_threadpool = nullptr; +} + +void I_ThreadPoolSubmit(srb2cthunk_t thunk, void* data) +{ + SRB2_ASSERT(g_main_threadpool != nullptr); + + g_main_threadpool->schedule([=]() { + (thunk)(data); + }); + g_main_threadpool->notify(); +} + +void I_ThreadPoolWaitIdle(void) +{ + SRB2_ASSERT(g_main_threadpool != nullptr); + + g_main_threadpool->wait_idle(); +} diff --git a/src/core/thread_pool.h b/src/core/thread_pool.h new file mode 100644 index 000000000..75961614e --- /dev/null +++ b/src/core/thread_pool.h @@ -0,0 +1,163 @@ +// BLANKART +//----------------------------------------------------------------------------- +// Copyright (C) 2024 by Ronald "Eidolon" Kinard +// Copyright (C) 2024 by Kart Krew +// +// This program is free software distributed under the +// terms of the GNU General Public License, version 2. +// See the 'LICENSE' file for more details. +//----------------------------------------------------------------------------- + +#ifndef __SRB2_CORE_THREAD_POOL_H__ +#define __SRB2_CORE_THREAD_POOL_H__ + +#include + +#ifdef __cplusplus + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "spmc_queue.hpp" + +namespace srb2 +{ + +class ThreadPool +{ +public: + struct Task + { + void (*thunk)(void*); + void (*deleter)(void*); + std::shared_ptr> pseudosema; + std::array>)> raw; + }; + + using Queue = SpMcQueue; + + class Sema + { + std::shared_ptr> pseudosema_; + + explicit Sema(std::shared_ptr> sema) : pseudosema_(sema) {} + + friend class ThreadPool; + public: + Sema() = default; + }; + +private: + std::shared_ptr> pool_alive_; + std::vector> worker_ready_mutexes_; + std::vector> worker_ready_condvars_; + std::vector> work_queues_; + std::vector threads_; + size_t next_queue_index_ = 0; + std::shared_ptr> cur_sema_; + + bool immediate_mode_ = false; + bool sema_begun_ = false; + +public: + ThreadPool(); + explicit ThreadPool(size_t threads); + ThreadPool(const ThreadPool&) = delete; + ThreadPool(ThreadPool&&); + ~ThreadPool(); + + ThreadPool& operator=(const ThreadPool&) = delete; + ThreadPool& operator=(ThreadPool&&); + + void begin_sema(); + ThreadPool::Sema end_sema(); + + /// Enqueue but don't notify + template void schedule(T&& thunk); + /// Notify threads after several schedules + void notify(); + void notify_sema(const Sema& sema); + void wait_idle(); + void wait_sema(const Sema& sema); + void shutdown(); +}; + +extern std::unique_ptr g_main_threadpool; + +template +void callable_caller(F* f) +{ + (*f)(); +} + +template +void callable_destroyer(F* f) +{ + f->~F(); +} + +template +void ThreadPool::schedule(T&& thunk) +{ + static_assert(sizeof(T) <= sizeof(std::declval().raw)); + + if (immediate_mode_) + { + (thunk)(); + return; + } + + if (sema_begun_) + { + if (cur_sema_ == nullptr) + { + cur_sema_ = std::make_shared>(0); + } + cur_sema_->fetch_add(1, std::memory_order_relaxed); + } + + size_t qi = next_queue_index_; + + { + std::shared_ptr q = work_queues_[qi]; + Task task; + task.thunk = reinterpret_cast(callable_caller); + task.deleter = reinterpret_cast(callable_destroyer); + task.pseudosema = cur_sema_; + new (reinterpret_cast(task.raw.data())) T(std::move(thunk)); + + q->push(std::move(task)); + } + // worker_ready_condvars_[qi]->notify_one(); + + next_queue_index_ += 1; + if (next_queue_index_ >= threads_.size()) + { + next_queue_index_ = 0; + } +} + +} // namespace srb2 + +extern "C" { + +#endif // __cplusplus + +typedef void (*srb2cthunk_t)(void*); + +void I_ThreadPoolInit(void); +void I_ThreadPoolShutdown(void); +void I_ThreadPoolSubmit(srb2cthunk_t thunk, void* data); +void I_ThreadPoolWaitIdle(void); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // __SRB2_CORE_THREAD_POOL_H__ diff --git a/src/cxxutil.hpp b/src/cxxutil.hpp new file mode 100644 index 000000000..74349a0ff --- /dev/null +++ b/src/cxxutil.hpp @@ -0,0 +1,152 @@ +#ifndef __SRB2_CXXUTIL_HPP__ +#define __SRB2_CXXUTIL_HPP__ + +#include +#include +#include + +#include "doomdef.h" + +namespace srb2 { + +template +class Finally { +public: + explicit Finally(const F& f) noexcept : f_(f) {} + explicit Finally(F&& f) noexcept : f_(f) {} + + Finally(Finally&& from) noexcept : f_(std::move(from.f_)), call_(std::exchange(from.call_, false)) {} + + Finally(const Finally& from) = delete; + void operator=(const Finally& from) = delete; + void operator=(Finally&& from) = delete; + + ~Finally() noexcept { + if (call_) + f_(); + } + +private: + F f_; + bool call_ = true; +}; + +template +Finally> finally(F&& f) noexcept { + return Finally {std::forward(f)}; +} + +struct SourceLocation { + const char* file_name; + unsigned int line_number; +}; + +#define SRB2_SOURCE_LOCATION \ + srb2::SourceLocation { __FILE__, __LINE__ } + +#ifndef SRB2_ASSERT_HANDLER +#define SRB2_ASSERT_HANDLER srb2::IErrorAssertHandler +#endif + +#if !defined(NDEBUG) || defined(PARANOIA) +// An assertion level of 2 will activate all invocations of the SRB2_ASSERT macro +#define SRB2_ASSERTION_LEVEL 2 +#else +// The minimum assertion level is 1 +#define SRB2_ASSERTION_LEVEL 1 +#endif + +/// Assert a precondition expression in debug builds. +#define SRB2_ASSERT(expr) srb2::do_assert<2, SRB2_ASSERT_HANDLER>([&] { return (expr); }, SRB2_SOURCE_LOCATION, #expr) + +class IErrorAssertHandler { +public: + static void handle(const SourceLocation& source_location, const char* expression) { + I_Error("Assertion failed at %s:%u: %s != true", + source_location.file_name, + source_location.line_number, + expression); + } +}; + +class NoOpAssertHandler { +public: + static void handle(const SourceLocation& source_location, const char* expression) {} +}; + +/// @brief Assert a precondition expression, aborting the application if it fails. +/// @tparam Expr +/// @tparam Level the level of this assertion; if it is less than or equal to SRB2_ASSERTION_LEVEL, this overload will +/// activate. +/// @param expr a callable which returns a bool +/// @param source_location a struct containing the source location of the assertion, e.g. SRB2_SOURCE_LOCATION +/// @param expression the expression evaluated in the expression callable +/// @param message an optional message to display for the assertion +template +std::enable_if_t<(Level <= SRB2_ASSERTION_LEVEL), void> +do_assert(const Expr& expr, const SourceLocation& source_location, const char* expression = "") noexcept { + static_assert(Level > 0, "level of an assertion must not be 0"); + if (!expr()) { + Handler::handle(source_location, expression); + std::abort(); + } +} + +template +std::enable_if_t<(Level > SRB2_ASSERTION_LEVEL), void> +do_assert(const Expr&, const SourceLocation&, const char* = "") noexcept { +} + +template +class NotNull final { + T ptr_; + +public: + static_assert(std::is_convertible_v() != nullptr), bool>, + "T is not comparable with nullptr_t"); + + /// @brief Move-construct from the pointer value U, asserting that it is not null. Allows construction of a + /// NotNull from any compatible pointer U, for example with polymorphic classes. + template >> + constexpr NotNull(U&& rhs) : ptr_(std::forward(rhs)) { + SRB2_ASSERT(ptr_ != nullptr); + } + + /// @brief Wrap the pointer type T, asserting that the pointer is not null. + template >> + constexpr NotNull(T rhs) : ptr_(std::move(rhs)) { + SRB2_ASSERT(ptr_ != nullptr); + } + + /// @brief Copy construction from NotNull of convertible type U. Only if the incoming pointer is NotNull already. + template >> + constexpr NotNull(const NotNull& rhs) : NotNull(rhs.get()) { + // Value is guaranteed to be not null by construction; no assertion necessary + } + + NotNull(const NotNull& rhs) = default; + NotNull& operator=(const NotNull& rhs) = default; + + /// @brief Get the stored pointer. + constexpr T get() const { return ptr_; } + + /// @brief Convert to T (the pointer type). + constexpr operator T() const { return get(); } + + /// @brief Arrow-dereference to *T (the actual value pointed to). + constexpr decltype(auto) operator->() const { return get(); } + + /// @brief Dereference to *T (the actual value pointed to). + constexpr decltype(auto) operator*() const { return *get(); } + + // It is not allowed to construct NotNull with nullptr regardless of T. + NotNull(std::nullptr_t) = delete; + NotNull& operator=(std::nullptr_t) = delete; +}; + +template +NotNull(T) -> NotNull; + +} // namespace srb2 + +#endif // __SRB2_CXXUTIL_HPP__ diff --git a/src/d_clisrv.h b/src/d_clisrv.h index 35c77ce12..7ba47cfd6 100644 --- a/src/d_clisrv.h +++ b/src/d_clisrv.h @@ -13,6 +13,10 @@ #ifndef __D_CLISRV__ #define __D_CLISRV__ +#ifdef __cplusplus +extern "C" { +#endif + #include "d_ticcmd.h" #include "d_net.h" #include "d_netcmd.h" @@ -694,4 +698,9 @@ typedef struct rewind_s { void CL_ClearRewinds(void); rewind_t *CL_SaveRewindPoint(size_t demopos); rewind_t *CL_RewindToTime(tic_t time); + +#ifdef __cplusplus +} // extern "C" +#endif + #endif diff --git a/src/d_main.c b/src/d_main.c index 38a6efb2f..abdd3fa2a 100644 --- a/src/d_main.c +++ b/src/d_main.c @@ -73,6 +73,8 @@ #include "m_perfstats.h" #include "k_kart.h" +#include "core/memory.h" + #include "lua_script.h" #ifdef CMAKECONFIG @@ -739,6 +741,8 @@ void D_SRB2Loop(void) precise_t enterprecise = I_GetPreciseTime(); precise_t finishprecise = enterprecise; + Z_Frame_Reset(); + // Casting the return value of a function is bad practice (apparently) double budget = ((R_GetFramerateCap() == 0) ? 0.0 : round((1.0 / R_GetFramerateCap()) * I_GetPrecisePrecision())); capbudget = (precise_t)budget; diff --git a/src/d_netcmd.c b/src/d_netcmd.c index 91ea8e945..abe3dd8c9 100644 --- a/src/d_netcmd.c +++ b/src/d_netcmd.c @@ -204,11 +204,6 @@ static void Command_Archivetest_f(void); // CLIENT VARIABLES // ========================================================================= -void SendWeaponPref(void); -void SendWeaponPref2(void); -void SendWeaponPref3(void); -void SendWeaponPref4(void); - static CV_PossibleValue_t usemouse_cons_t[] = {{0, "Off"}, {1, "On"}, {2, "Force"}, {0, NULL}}; static CV_PossibleValue_t autobalance_cons_t[] = {{0, "MIN"}, {4, "MAX"}, {0, NULL}}; diff --git a/src/d_netcmd.h b/src/d_netcmd.h index b4ee22d93..657686af4 100644 --- a/src/d_netcmd.h +++ b/src/d_netcmd.h @@ -15,8 +15,17 @@ #ifndef __D_NETCMD__ #define __D_NETCMD__ +#ifdef __cplusplus +extern "C" { +#endif + #include "command.h" +void SendWeaponPref(void); +void SendWeaponPref2(void); +void SendWeaponPref3(void); +void SendWeaponPref4(void); + // console vars extern consvar_t cv_playername; extern consvar_t cv_playercolor; @@ -318,4 +327,8 @@ void D_SetPassword(const char *pw); // used for the player setup menu UINT8 CanChangeSkin(INT32 playernum); +#ifdef __cplusplus +} // extern "C" +#endif + #endif diff --git a/src/doomdef.h b/src/doomdef.h index f9467199b..dbeabce63 100644 --- a/src/doomdef.h +++ b/src/doomdef.h @@ -58,6 +58,9 @@ // warning C4152: nonstandard extension, function/data pointer conversion in expression // warning C4213: nonstandard extension used : cast on l-value +#ifdef __cplusplus +extern "C" { +#endif #include "doomtype.h" @@ -524,12 +527,15 @@ UINT32 quickncasehash (const char *p, size_t n) return x; } +#ifndef __cplusplus #ifndef min // Double-Check with WATTCP-32's cdefs.h #define min(x, y) (((x) < (y)) ? (x) : (y)) #endif #ifndef max // Double-Check with WATTCP-32's cdefs.h #define max(x, y) (((x) > (y)) ? (x) : (y)) #endif +#endif + #ifndef CLAMP #define CLAMP(x, y, z) ((x) < (y) ? (y) : ((x) > (z) ? (z) : (x))) #endif @@ -657,4 +663,8 @@ extern const char *compdate, *comptime, *comprevision, *compbranch; #undef UPDATE_ALERT #endif +#ifdef __cplusplus +} // extern "C" +#endif + #endif // __DOOMDEF__ diff --git a/src/doomtype.h b/src/doomtype.h index 174bba5b1..79806365d 100644 --- a/src/doomtype.h +++ b/src/doomtype.h @@ -17,6 +17,10 @@ #ifndef __DOOMTYPE__ #define __DOOMTYPE__ +#ifdef __cplusplus +extern "C" { +#endif + #if defined (_WIN32) //#define WIN32_LEAN_AND_MEAN #define RPC_NO_WINDOWS_H @@ -100,8 +104,10 @@ typedef long ssize_t; #define strnicmp(x,y,n) strncasecmp(x,y,n) #endif +#ifndef __cplusplus char *strcasestr(const char *in, const char *what); #define stristr strcasestr +#endif #if defined (macintosh) //|| defined (__APPLE__) //skip all boolean/Boolean crap #define true 1 @@ -385,4 +391,8 @@ unset_bit_array (bitarray_t * const array, const int value) typedef UINT64 precise_t; +#ifdef __cplusplus +} // extern "C" +#endif + #endif //__DOOMTYPE__ diff --git a/src/i_system.h b/src/i_system.h index e7fb26a41..b26db7a82 100644 --- a/src/i_system.h +++ b/src/i_system.h @@ -14,6 +14,10 @@ #ifndef __I_SYSTEM__ #define __I_SYSTEM__ +#ifdef __cplusplus +extern "C" { +#endif + #include "d_ticcmd.h" #include "d_event.h" @@ -256,4 +260,8 @@ const char *I_ClipboardPaste(void); void I_RegisterSysCommands(void); +#ifdef __cplusplus +} // extern "C" +#endif + #endif diff --git a/src/m_argv.h b/src/m_argv.h index f31a531d0..8f1a08ec4 100644 --- a/src/m_argv.h +++ b/src/m_argv.h @@ -14,6 +14,10 @@ #ifndef __M_ARGV__ #define __M_ARGV__ +#ifdef __cplusplus +extern "C" { +#endif + // // MISC // @@ -42,4 +46,8 @@ const char *M_GetNextParm(void); // Finds and loads a response file (@moreargs.txt) void M_FindResponseFile(void); +#ifdef __cplusplus +} // extern "C" +#endif + #endif //__M_ARGV__ diff --git a/src/p_mobj.h b/src/p_mobj.h index 733153017..cd4033157 100644 --- a/src/p_mobj.h +++ b/src/p_mobj.h @@ -14,6 +14,10 @@ #ifndef __P_MOBJ__ #define __P_MOBJ__ +#ifdef __cplusplus +extern "C" { +#endif + // Basics. #include "tables.h" #include "m_fixed.h" @@ -536,4 +540,9 @@ extern mapthing_t *huntemeralds[MAXHUNTEMERALDS]; extern INT32 numhuntemeralds; extern boolean runemeraldmanager; extern INT32 numstarposts; + +#ifdef __cplusplus +} // extern "C" +#endif + #endif diff --git a/src/p_setup.h b/src/p_setup.h index 97209e154..86b958adf 100644 --- a/src/p_setup.h +++ b/src/p_setup.h @@ -14,6 +14,10 @@ #ifndef __P_SETUP__ #define __P_SETUP__ +#ifdef __cplusplus +extern "C" { +#endif + #include "doomdata.h" #include "doomstat.h" #include "r_defs.h" @@ -116,4 +120,8 @@ UINT8 P_GetGrade(UINT32 pscore, INT16 map, UINT8 mare); UINT8 P_HasGrades(INT16 map, UINT8 mare); UINT32 P_GetScoreForGrade(INT16 map, UINT8 mare, UINT8 grade); +#ifdef __cplusplus +} // extern "C" +#endif + #endif diff --git a/src/r_bsp.h b/src/r_bsp.h index 167f3311f..b9e4e291d 100644 --- a/src/r_bsp.h +++ b/src/r_bsp.h @@ -14,6 +14,10 @@ #ifndef __R_BSP__ #define __R_BSP__ +#ifdef __cplusplus +extern "C" { +#endif + #ifdef __GNUG__ #pragma interface #endif @@ -62,4 +66,9 @@ boolean R_IsEmptyLine(seg_t *line, const sector_t *front, const sector_t *back); INT32 R_GetPlaneLight(sector_t *sector, fixed_t planeheight, boolean underside); void R_Prep3DFloors(sector_t *sector); + +#ifdef __cplusplus +} // extern "C" +#endif + #endif diff --git a/src/r_data.h b/src/r_data.h index 65dd6ccbb..45f7ee484 100644 --- a/src/r_data.h +++ b/src/r_data.h @@ -14,6 +14,10 @@ #ifndef __R_DATA__ #define __R_DATA__ +#ifdef __cplusplus +extern "C" { +#endif + #include "r_defs.h" #include "r_state.h" @@ -111,4 +115,8 @@ UINT8 NearestPaletteColor(UINT8 r, UINT8 g, UINT8 b, RGBA_t *palette); extern INT32 numtextures; +#ifdef __cplusplus +} // extern "C" +#endif + #endif diff --git a/src/r_draw.h b/src/r_draw.h index 3654fdeb2..5a57ae978 100644 --- a/src/r_draw.h +++ b/src/r_draw.h @@ -14,6 +14,10 @@ #ifndef __R_DRAW__ #define __R_DRAW__ +#ifdef __cplusplus +extern "C" { +#endif + #include "r_defs.h" #include "r_things.h" @@ -118,7 +122,7 @@ extern void (*basespanfunc)(drawspandata_t*); extern void (*splatfunc)(drawspandata_t*); // Draws a single visplane. -void R_DrawSinglePlane(drawspandata_t* ds, visplane_t *pl); +void R_DrawSinglePlane(drawspandata_t* ds, visplane_t *pl, boolean allow_parallel); // Vectors for Software's tilted slope drawers extern floatv3_t *ds_su, *ds_sv, *ds_sz; @@ -240,5 +244,9 @@ void R_DrawTiltedSplat(drawspandata_t* ds); void R_DrawSplat(drawspandata_t* ds); void R_DrawTranslucentSplat(drawspandata_t* ds); +#ifdef __cplusplus +} // extern "C" +#endif + // ========================================================================= #endif // __R_DRAW__ diff --git a/src/r_fps.h b/src/r_fps.h index 7ed55c848..870fa70f1 100644 --- a/src/r_fps.h +++ b/src/r_fps.h @@ -15,6 +15,10 @@ #ifndef __R_FPS_H__ #define __R_FPS_H__ +#ifdef __cplusplus +extern "C" { +#endif + #include "m_fixed.h" #include "p_local.h" #include "r_state.h" @@ -175,4 +179,8 @@ void R_UpdateMobjInterpolators(void); void R_ResetMobjInterpolationState(mobj_t *mobj); void R_ResetPrecipitationMobjInterpolationState(precipmobj_t *mobj); +#ifdef __cplusplus +} // extern "C" +#endif + #endif diff --git a/src/r_local.h b/src/r_local.h index 1d3187750..4701cb400 100644 --- a/src/r_local.h +++ b/src/r_local.h @@ -14,6 +14,10 @@ #ifndef __R_LOCAL__ #define __R_LOCAL__ +#ifdef __cplusplus +extern "C" { +#endif + // Screen size related parameters. #include "doomdef.h" @@ -38,4 +42,8 @@ extern drawseg_t *firstseg; void SplitScreen_OnChange(void); +#ifdef __cplusplus +} // extern "C" +#endif + #endif // __R_LOCAL__ diff --git a/src/r_main.c b/src/r_main.cpp similarity index 94% rename from src/r_main.c rename to src/r_main.cpp index a0f6361d6..55475c407 100644 --- a/src/r_main.c +++ b/src/r_main.cpp @@ -13,6 +13,8 @@ /// utility functions (BSP, geometry, trigonometry). /// See tables.c, too. +#include + #include "doomdef.h" #include "g_game.h" #include "g_input.h" @@ -37,6 +39,8 @@ #include "r_fps.h" // Frame interpolation/uncapped #include "tables.h" +#include "core/thread_pool.h" + #ifdef HWRENDER #include "hardware/hw_main.h" #endif @@ -157,10 +161,6 @@ static void FlipCam_OnChange(void); static void FlipCam2_OnChange(void); static void FlipCam3_OnChange(void); static void FlipCam4_OnChange(void); -void SendWeaponPref(void); -void SendWeaponPref2(void); -void SendWeaponPref3(void); -void SendWeaponPref4(void); static void DirLight_OnChange(void); @@ -504,10 +504,10 @@ void R_GetRenderBlockMapDimensions(fixed_t drawdist, INT32 *xl, INT32 *xh, INT32 const fixed_t vyright = viewy + FixedMul(drawdist, FSIN(right)); // Try to narrow the search to within only the field of view - *xl = (unsigned)(min(viewx, min(vxleft, vxright)) - bmaporgx)>>MAPBLOCKSHIFT; - *xh = (unsigned)(max(viewx, max(vxleft, vxright)) - bmaporgx)>>MAPBLOCKSHIFT; - *yl = (unsigned)(min(viewy, min(vyleft, vyright)) - bmaporgy)>>MAPBLOCKSHIFT; - *yh = (unsigned)(max(viewy, max(vyleft, vyright)) - bmaporgy)>>MAPBLOCKSHIFT; + *xl = (unsigned)(std::min(viewx, std::min(vxleft, vxright)) - bmaporgx)>>MAPBLOCKSHIFT; + *xh = (unsigned)(std::max(viewx, std::max(vxleft, vxright)) - bmaporgx)>>MAPBLOCKSHIFT; + *yl = (unsigned)(std::min(viewy, std::min(vyleft, vyright)) - bmaporgy)>>MAPBLOCKSHIFT; + *yh = (unsigned)(std::max(viewy, std::max(vyleft, vyright)) - bmaporgy)>>MAPBLOCKSHIFT; if (*xh >= bmapwidth) *xh = bmapwidth - 1; @@ -681,9 +681,9 @@ void R_CheckViewMorph(void) if (viewmorph.scrmapsize != vid.width*vid.height) { viewmorph.scrmapsize = vid.width*vid.height; - viewmorph.scrmap = realloc(viewmorph.scrmap, vid.width*vid.height * sizeof(INT32)); - viewmorph.ceilingclip = realloc(viewmorph.ceilingclip, vid.width * sizeof(INT16)); - viewmorph.floorclip = realloc(viewmorph.floorclip, vid.width * sizeof(INT16)); + viewmorph.scrmap = static_cast(realloc(viewmorph.scrmap, vid.width*vid.height * sizeof(INT32))); + viewmorph.ceilingclip = static_cast(realloc(viewmorph.ceilingclip, vid.width * sizeof(INT16))); + viewmorph.floorclip = static_cast(realloc(viewmorph.floorclip, vid.width * sizeof(INT16))); } temp = FINECOSINE(rollangle); @@ -695,7 +695,7 @@ void R_CheckViewMorph(void) x1 = (vid.width*fabsf(rollcos) + vid.height*fabsf(rollsin)) / vid.width; y1 = (vid.height*fabsf(rollcos) + vid.width*fabsf(rollsin)) / vid.height; - temp = max(x1, y1)*FRACUNIT; + temp = std::max(x1, y1)*FRACUNIT; if (temp < FRACUNIT) temp = FRACUNIT; else @@ -741,10 +741,10 @@ void R_CheckViewMorph(void) xb = vid.width-1-xa; yb = vid.height-1-ya; - viewmorph.ceilingclip[xa] = min(viewmorph.ceilingclip[xa], ya); - viewmorph.floorclip[xa] = max(viewmorph.floorclip[xa], ya); - viewmorph.ceilingclip[xb] = min(viewmorph.ceilingclip[xb], yb); - viewmorph.floorclip[xb] = max(viewmorph.floorclip[xb], yb); + viewmorph.ceilingclip[xa] = std::min(viewmorph.ceilingclip[xa], ya); + viewmorph.floorclip[xa] = std::max(viewmorph.floorclip[xa], ya); + viewmorph.ceilingclip[xb] = std::min(viewmorph.ceilingclip[xb], yb); + viewmorph.floorclip[xb] = std::max(viewmorph.floorclip[xb], yb); x2 += rollcos; y2 += rollsin; } @@ -758,10 +758,10 @@ void R_CheckViewMorph(void) xb = vid.width-1-xa; yb = vid.height-1-ya; - viewmorph.ceilingclip[xa] = min(viewmorph.ceilingclip[xa], ya); - viewmorph.floorclip[xa] = max(viewmorph.floorclip[xa], ya); - viewmorph.ceilingclip[xb] = min(viewmorph.ceilingclip[xb], yb); - viewmorph.floorclip[xb] = max(viewmorph.floorclip[xb], yb); + viewmorph.ceilingclip[xa] = std::min(viewmorph.ceilingclip[xa], ya); + viewmorph.floorclip[xa] = std::max(viewmorph.floorclip[xa], ya); + viewmorph.ceilingclip[xb] = std::min(viewmorph.ceilingclip[xb], yb); + viewmorph.floorclip[xb] = std::max(viewmorph.floorclip[xb], yb); x2 -= rollsin; y2 += rollcos; } @@ -978,7 +978,7 @@ void R_ExecuteSetViewSize(void) fixed_t R_GetPlayerFov(player_t *player) { fixed_t fov = cv_fov.value + player->fovadd; - return max(MINFOV*FRACUNIT, min(fov, MAXFOV*FRACUNIT)); + return std::max(MINFOV*FRACUNIT, std::min(fov, MAXFOV*FRACUNIT)); } static void R_SetFov(fixed_t playerfov) @@ -1095,7 +1095,7 @@ void R_SkyboxFrame(int s) camera_t *thiscam = &camera[s]; subsector_t * subsector = NULL; - R_SetViewContext(VIEWCONTEXT_SKY1 + s); + R_SetViewContext(static_cast(VIEWCONTEXT_SKY1 + s)); // cut-away view stuff newview->sky = true; @@ -1193,7 +1193,8 @@ void R_SetupFrame(int s, boolean skybox) boolean chasecam = (cv_chasecam[s].value); sector_t * sector = NULL; - R_SetViewContext(VIEWCONTEXT_PLAYER1 + s); + R_SetViewContext(static_cast(VIEWCONTEXT_PLAYER1 + s)); + if (thiscam->reset) { R_ResetViewInterpolation(s); @@ -1336,10 +1337,13 @@ static fixed_t viewfov[MAXSPLITSCREENPLAYERS]; void R_RenderPlayerView(player_t *player) { UINT8 nummasks = 1; - maskcount_t* masks = malloc(sizeof(maskcount_t)); + maskcount_t* masks = static_cast(malloc(sizeof(maskcount_t))); const boolean skybox = (skyboxmo[0] && cv_skybox.value); UINT8 i; + srb2::ThreadPool::Sema tp_sema; + srb2::g_main_threadpool->begin_sema(); + // if this is display player 1 if (cv_homremoval.value && player == &players[displayplayers[0]]) { @@ -1352,7 +1356,7 @@ void R_RenderPlayerView(player_t *player) else if (splitscreen == 2 && player == &players[displayplayers[2]]) { // V_DrawPatchFill, but for the fourth screen only - patch_t *pat = W_CachePatchName("SRB2BACK", PU_CACHE); + patch_t *pat = static_cast(W_CachePatchName("SRB2BACK", PU_CACHE)); INT32 dupz = (vid.dupx < vid.dupy ? vid.dupx : vid.dupy); INT32 x, y, pw = SHORT(pat->width) * dupz, ph = SHORT(pat->height) * dupz; @@ -1399,7 +1403,6 @@ void R_RenderPlayerView(player_t *player) #ifdef FLOORSPLATS R_ClearVisibleFloorSplats(); #endif - R_RenderViewpoint(&masks[nummasks - 1], false); R_ClipSprites(); @@ -1407,6 +1410,11 @@ void R_RenderPlayerView(player_t *player) #ifdef FLOORSPLATS R_DrawVisibleFloorSplats(); #endif + // well sometimes synchronization is off and may result in some visual glitching, oh well + tp_sema = srb2::g_main_threadpool->end_sema(); + srb2::g_main_threadpool->notify_sema(tp_sema); + srb2::g_main_threadpool->wait_sema(tp_sema); + srb2::g_main_threadpool->begin_sema(); R_DrawMasked(masks, nummasks); } PS_STOP_TIMING(ps_skyboxtime); @@ -1446,7 +1454,12 @@ void R_RenderPlayerView(player_t *player) ps_numbspcalls.value.i = ps_numpolyobjects.value.i = ps_numdrawnodes.value.i = 0; PS_START_TIMING(ps_bsptime); + //tp_sema = srb2::g_main_threadpool->end_sema(); + //srb2::g_main_threadpool->notify_sema(tp_sema); + //srb2::g_main_threadpool->wait_sema(tp_sema); + //srb2::g_main_threadpool->begin_sema(); R_RenderViewpoint(&masks[nummasks - 1], true); + PS_STOP_TIMING(ps_bsptime); PS_START_TIMING(ps_sw_spritecliptime); R_ClipSprites(); @@ -1481,7 +1494,7 @@ void R_RenderPlayerView(player_t *player) validcount++; // Render the BSP from the new viewpoint, and clip - masks = realloc(masks, (++nummasks)*sizeof(maskcount_t)); + masks = static_cast(realloc(masks, (++nummasks)*sizeof(maskcount_t))); // Render the BSP from the new viewpoint, and clip // any sprites with the new clipsegs and window. @@ -1496,6 +1509,9 @@ void R_RenderPlayerView(player_t *player) PS_START_TIMING(ps_sw_planetime); R_DrawPlanes(); + tp_sema = srb2::g_main_threadpool->end_sema(); + srb2::g_main_threadpool->notify_sema(tp_sema); + srb2::g_main_threadpool->wait_sema(tp_sema); PS_STOP_TIMING(ps_sw_planetime); #ifdef FLOORSPLATS R_DrawVisibleFloorSplats(); diff --git a/src/r_main.h b/src/r_main.h index d3284764d..6f62855da 100644 --- a/src/r_main.h +++ b/src/r_main.h @@ -14,6 +14,10 @@ #ifndef __R_MAIN__ #define __R_MAIN__ +#ifdef __cplusplus +extern "C" { +#endif + #include "d_player.h" #include "r_data.h" #include "m_perfstats.h" @@ -84,7 +88,7 @@ extern lighttable_t *zlight[LIGHTLEVELS][MAXLIGHTZ]; // // killough 5/2/98: reformatted // -FUNCINLINE static ATTRINLINE PUREFUNC INT32 R_PointOnSide(fixed_t x, fixed_t y, const node_t *restrict node) +FUNCINLINE static ATTRINLINE PUREFUNC INT32 R_PointOnSide(fixed_t x, fixed_t y, const node_t *node) { if (!node->dx) return x <= node->x ? node->dy > 0 : node->dy < 0; @@ -245,4 +249,9 @@ void R_RegisterEngineStuff(void); INT32 R_GetHudUncap(void); // same as above but keeps interpolation during pause INT32 R_GetMenuUncap(void); + +#ifdef __cplusplus +} // extern "C" +#endif + #endif diff --git a/src/r_plane.c b/src/r_plane.cpp similarity index 87% rename from src/r_plane.c rename to src/r_plane.cpp index d5faa122b..e605d1b8e 100644 --- a/src/r_plane.c +++ b/src/r_plane.cpp @@ -29,6 +29,8 @@ #include "p_tick.h" #include "r_fps.h" #include "r_portal.h" +#include "core/thread_pool.h" + // // opening @@ -91,8 +93,8 @@ static INT16 *ffloor_c_clip; static void R_ReallocPlaneBounds(visplane_t *pl) { - pl->top_memory = Z_Realloc(pl->top_memory, sizeof(UINT16) * (viewwidth + 2), PU_STATIC, NULL); - pl->bottom_memory = Z_Realloc(pl->bottom_memory, sizeof(UINT16) * (viewwidth + 2), PU_STATIC, NULL); + pl->top_memory = static_cast(Z_Realloc(pl->top_memory, sizeof(UINT16) * (viewwidth + 2), PU_STATIC, NULL)); + pl->bottom_memory = static_cast(Z_Realloc(pl->bottom_memory, sizeof(UINT16) * (viewwidth + 2), PU_STATIC, NULL)); pl->top = pl->top_memory + 1; pl->bottom = pl->bottom_memory + 1; } @@ -122,8 +124,8 @@ void R_AllocPlaneMemory(void) } // Alloc ffloor clip tables - ffloor_f_clip = Z_Realloc(ffloor_f_clip, sizeof(*ffloor_f_clip) * (viewwidth * MAXFFLOORS), PU_STATIC, NULL); - ffloor_c_clip = Z_Realloc(ffloor_c_clip, sizeof(*ffloor_c_clip) * (viewwidth * MAXFFLOORS), PU_STATIC, NULL); + ffloor_f_clip = static_cast(Z_Realloc(ffloor_f_clip, sizeof(*ffloor_f_clip) * (viewwidth * MAXFFLOORS), PU_STATIC, NULL)); + ffloor_c_clip = static_cast(Z_Realloc(ffloor_c_clip, sizeof(*ffloor_c_clip) * (viewwidth * MAXFFLOORS), PU_STATIC, NULL)); for (unsigned i = 0; i < MAXFFLOORS; i++) { @@ -131,8 +133,8 @@ void R_AllocPlaneMemory(void) ffloor[i].c_clip = ffloor_c_clip + (i * viewwidth); } - yslopetab = Z_Realloc(yslopetab, sizeof(*yslopetab) * (viewheight * 16), PU_STATIC, NULL); - spanstart = Z_Realloc(spanstart, sizeof(*spanstart) * viewheight, PU_STATIC, NULL); + yslopetab = static_cast(Z_Realloc(yslopetab, sizeof(*yslopetab) * (viewheight * 16), PU_STATIC, NULL)); + spanstart = static_cast(Z_Realloc(spanstart, sizeof(*spanstart) * viewheight, PU_STATIC, NULL)); } // @@ -225,6 +227,19 @@ static void R_HandleRipplePlane(drawspandata_t* ds, visplane_t *pl) } } + +static bool R_CheckMapPlane(const char* funcname, INT32 y, INT32 x1, INT32 x2) +{ + if (x1 == x2) + return true; + + if (x1 < x2 && x1 >= 0 && x2 < viewwidth && y >= 0 && y < viewheight) + return true; + + CONS_Debug(DBG_RENDER, "%s: x1=%d, x2=%d at y=%d\n", funcname, x1, x2, y); + return false; +} + // // R_MapPlane // @@ -237,16 +252,14 @@ static void R_HandleRipplePlane(drawspandata_t* ds, visplane_t *pl) // viewsin // viewcos // viewheight -static void R_MapPlane(drawspandata_t *ds, INT32 y, INT32 x1, INT32 x2) +static void R_MapPlane(drawspandata_t *ds, INT32 y, INT32 x1, INT32 x2, boolean allow_parallel) { angle_t angle, planecos, planesin; fixed_t distance = 0, span; size_t pindex; -#ifdef RANGECHECK - if (x2 < x1 || x1 < 0 || x2 >= viewwidth || y > viewheight) - I_Error("R_MapPlane: %d, %d at %d", x1, x2, y); -#endif + if (!R_CheckMapPlane(__func__, y, x1, x2)) + return; if (x1 >= vid.width) x1 = vid.width - 1; @@ -383,11 +396,11 @@ static visplane_t *new_visplane(unsigned hash) visplane_t *check = freetail; if (!check) { - check = calloc(1, sizeof (*check)); + check = static_cast(calloc(1, sizeof (*check))); if (check == NULL) I_Error("new_visplane: Out of memory"); - check->top_memory = Z_Malloc(sizeof(UINT16) * (viewwidth + 2), PU_STATIC, NULL); - check->bottom_memory = Z_Malloc(sizeof(UINT16) * (viewwidth + 2), PU_STATIC, NULL); + check->top_memory = static_cast(Z_Malloc(sizeof(UINT16) * (viewwidth + 2), PU_STATIC, NULL)); + check->bottom_memory = static_cast(Z_Malloc(sizeof(UINT16) * (viewwidth + 2), PU_STATIC, NULL)); check->top = check->top_memory + 1; check->bottom = check->bottom_memory + 1; } @@ -648,7 +661,7 @@ void R_ExpandPlane(visplane_t *pl, INT32 start, INT32 stop) // // R_MakeSpans // -static void R_MakeSpans(drawspandata_t* ds, INT32 x, INT32 t1, INT32 b1, INT32 t2, INT32 b2) +static void R_MakeSpans(drawspandata_t* ds, INT32 x, INT32 t1, INT32 b1, INT32 t2, INT32 b2, boolean allow_parallel) { // Alam: from r_splats's R_RenderFloorSplat if (t1 >= vid.height) t1 = vid.height-1; @@ -657,17 +670,69 @@ static void R_MakeSpans(drawspandata_t* ds, INT32 x, INT32 t1, INT32 b1, INT32 t if (b2 >= vid.height) b2 = vid.height-1; if (x-1 >= vid.width) x = vid.width; + // We want to draw N spans per subtask to ensure the work is + // coarse enough to not be too slow due to task scheduling overhead. + // To safely do this, we need to copy part of spanstart to a local. + // This is essentially loop unrolling across threads. + constexpr const int kSpanTaskGranularity = 8; drawspandata_t dc_copy = *ds; - while (t1 < t2 && t1 <= b1) { - R_MapPlane(&dc_copy, t1, spanstart[t1], x - 1); - t1++; + INT32 spanstartcopy[kSpanTaskGranularity] = {0}; + INT32 taskspans = 0; + for (int i = 0; i < kSpanTaskGranularity; i++) + { + if (!((t1 + i) < t2 && (t1 + i) <= b1)) + { + break; + } + spanstartcopy[i] = spanstart[t1 + i]; + taskspans += 1; + } + auto task = [=]() mutable -> void { + for (int i = 0; i < taskspans; i++) + { + R_MapPlane(&dc_copy, t1 + i, spanstartcopy[i], x - 1, false); + } + }; + if (allow_parallel) + { + srb2::g_main_threadpool->schedule(std::move(task)); + } + else + { + (task)(); + } + t1 += taskspans; } while (b1 > b2 && b1 >= t1) { - R_MapPlane(&dc_copy, b1, spanstart[b1], x - 1); - b1--; + INT32 spanstartcopy[kSpanTaskGranularity] = {0}; + INT32 taskspans = 0; + for (int i = 0; i < kSpanTaskGranularity; i++) + { + if (!((b1 - i) > b2 && (b1 - i) >= t1)) + { + break; + } + spanstartcopy[i] = spanstart[b1 - i]; + taskspans += 1; + } + auto task = [=]() mutable -> void { + for (int i = 0; i < taskspans; i++) + { + R_MapPlane(&dc_copy, b1 - i, spanstartcopy[i], x - 1, false); + } + }; + if (allow_parallel) + { + srb2::g_main_threadpool->schedule(std::move(task)); + } + else + { + (task)(); + } + b1 -= taskspans; } while (t2 < t1 && t2 <= b2) @@ -692,14 +757,14 @@ void R_DrawPlanes(void) if (pl->ffloor != NULL || pl->polyobj != NULL) continue; - R_DrawSinglePlane(&ds, pl); + R_DrawSinglePlane(&ds, pl, true); } } R_UpdatePlaneRipple(&ds); } -static void R_DrawSkyPlane(visplane_t *pl) +static void R_DrawSkyPlane(visplane_t *pl, boolean allow_parallel) { INT32 x; drawcolumndata_t dc = {0}; @@ -727,30 +792,54 @@ static void R_DrawSkyPlane(visplane_t *pl) dc.texheight = textureheight[skytexture] >>FRACBITS; dc.sourcelength = dc.texheight; + x = pl->minx; + // Precache the texture so we don't corrupt the zoned heap off-main thread if (!texturecache[texturetranslation[skytexture]]) { R_GenerateTexture(texturetranslation[skytexture]); } - for (x = pl->minx; x <= pl->maxx; x++) + while (x <= pl->maxx) { - dc.yl = pl->top[x]; - dc.yh = pl->bottom[x]; + // Tune concurrency granularity here to maximize throughput + // The cheaper colfunc is, the more coarse the task should be + constexpr const int kSkyPlaneMacroColumns = 8; - if (dc.yl > dc.yh) + auto thunk = [=]() mutable -> void { + for (int i = 0; i < kSkyPlaneMacroColumns && i + x <= pl->maxx; i++) + { + dc.yl = pl->top[x + i]; + dc.yh = pl->bottom[x + i]; + + if (dc.yl > dc.yh) + { + continue; + } + + INT32 angle = (pl->viewangle + xtoviewangle[x + i])>>ANGLETOSKYSHIFT; + dc.iscale = FixedMul(skyscale, FINECOSINE(xtoviewangle[x + i]>>ANGLETOFINESHIFT)); + dc.x = x + i; + dc.source = + R_GetColumn(texturetranslation[skytexture], + -angle); // get negative of angle for each column to display sky correct way round! --Monster Iestyn 27/01/18 + + colfunc(&dc); + } + }; + + if (allow_parallel) { - continue; + srb2::g_main_threadpool->schedule(std::move(thunk)); + } + else + { + (thunk)(); } - INT32 angle = (pl->viewangle + xtoviewangle[x])>>ANGLETOSKYSHIFT; - dc.iscale = FixedMul(skyscale, FINECOSINE(xtoviewangle[x]>>ANGLETOFINESHIFT)); - dc.x = x; - dc.source = - R_GetColumn(texturetranslation[skytexture], - -angle); // get negative of angle for each column to display sky correct way round! --Monster Iestyn 27/01/18 - wallcolfunc(&dc); + x += kSkyPlaneMacroColumns; } + } // Potentially override other stuff for now cus we're mean. :< But draw a slope plane! @@ -833,11 +922,11 @@ d.z = (v1.x * v2.y) - (v1.y * v2.x) static void R_SetSlopePlaneVectors(drawspandata_t* ds, visplane_t *pl, INT32 y, fixed_t xoff, fixed_t yoff, float fudge) { if (ds_su == NULL) - ds_su = Z_Malloc(sizeof(*ds_su) * vid.height, PU_STATIC, NULL); + ds_su = static_cast(Z_Malloc(sizeof(*ds_su) * vid.height, PU_STATIC, NULL)); if (ds_sv == NULL) - ds_sv = Z_Malloc(sizeof(*ds_sv) * vid.height, PU_STATIC, NULL); + ds_sv = static_cast(Z_Malloc(sizeof(*ds_sv) * vid.height, PU_STATIC, NULL)); if (ds_sz == NULL) - ds_sz = Z_Malloc(sizeof(*ds_sz) * vid.height, PU_STATIC, NULL); + ds_sz = static_cast(Z_Malloc(sizeof(*ds_sz) * vid.height, PU_STATIC, NULL)); ds->sup = ds_su[y]; ds->svp = ds_sv[y]; @@ -846,7 +935,7 @@ static void R_SetSlopePlaneVectors(drawspandata_t* ds, visplane_t *pl, INT32 y, R_CalculateSlopeVectors(ds, pl->slope, pl->viewx, pl->viewy, pl->viewz, FRACUNIT, FRACUNIT, xoff, yoff, pl->viewangle, pl->plangle, fudge); } -void R_DrawSinglePlane(drawspandata_t* ds, visplane_t *pl) +void R_DrawSinglePlane(drawspandata_t* ds, visplane_t *pl, boolean allow_parallel) { INT32 light = 0; INT32 x; @@ -860,7 +949,7 @@ void R_DrawSinglePlane(drawspandata_t* ds, visplane_t *pl) // sky flat if (pl->picnum == skyflatnum) { - R_DrawSkyPlane(pl); + R_DrawSkyPlane(pl, allow_parallel); return; } @@ -1128,7 +1217,7 @@ void R_DrawSinglePlane(drawspandata_t* ds, visplane_t *pl) for (x = pl->minx; x <= stop; x++) { - R_MakeSpans(ds, x, pl->top[x-1], pl->bottom[x-1], pl->top[x], pl->bottom[x]); + R_MakeSpans(ds, x, pl->top[x-1], pl->bottom[x-1], pl->top[x], pl->bottom[x], allow_parallel); } /* diff --git a/src/r_plane.h b/src/r_plane.h index dbaaac306..78b92cc83 100644 --- a/src/r_plane.h +++ b/src/r_plane.h @@ -14,6 +14,10 @@ #ifndef __R_PLANE__ #define __R_PLANE__ +#ifdef __cplusplus +extern "C" { +#endif + #include "screen.h" // needs MAXVIDWIDTH/MAXVIDHEIGHT #include "r_data.h" #include "p_polyobj.h" @@ -110,4 +114,9 @@ typedef struct planemgr_s extern visffloor_t ffloor[MAXFFLOORS]; extern INT32 numffloors; + +#ifdef __cplusplus +} // extern "C" +#endif + #endif diff --git a/src/r_portal.h b/src/r_portal.h index b45631e0b..62312da54 100644 --- a/src/r_portal.h +++ b/src/r_portal.h @@ -14,6 +14,10 @@ #ifndef __R_PORTAL__ #define __R_PORTAL__ +#ifdef __cplusplus +extern "C" { +#endif + #include "r_data.h" #include "r_plane.h" // visplanes @@ -56,4 +60,8 @@ void Portal_ClipApply (const portal_t* portal); void Portal_AddSkybox(const visplane_t* plane); void Portal_AddSkyboxPortals(void); +#ifdef __cplusplus +} // extern "C" +#endif + #endif diff --git a/src/r_segs.c b/src/r_segs.c index 3e36db3de..fb671ece4 100644 --- a/src/r_segs.c +++ b/src/r_segs.c @@ -27,6 +27,9 @@ #include "p_slopes.h" #include "console.h" // con_clipviewtop +#include "core/memory.h" +#include "core/thread_pool.h" + // OPTIMIZE: closed two sided lines as single sided // True if any of the segs textures might be visible. @@ -278,12 +281,20 @@ static void R_Render2sidedMultiPatchColumn(drawcolumndata_t* dc, column_t *colum dc->source = (UINT8 *)column + 3; dc->sourcelength = lengthcol; + + // Drawn by R_DrawColumn. + drawcolumndata_t dc_copy = *dc; + void (*colfunccopy)(drawcolumndata_t*); + colfunccopy = colfunc; + if (colfunc == wallcolfunc) - twosmultipatchfunc(dc); + colfunccopy = twosmultipatchfunc; else if (colfunc == fuzzcolfunc) - twosmultipatchtransfunc(dc); + colfunccopy = twosmultipatchtransfunc; else colfunc(dc); + + colfunccopy((drawcolumndata_t*)(&dc_copy)); } } @@ -292,7 +303,7 @@ transnum_t R_GetLinedefTransTable(fixed_t alpha) return (20*(FRACUNIT - alpha - 1) + FRACUNIT) >> (FRACBITS+1); } -void R_RenderMaskedSegRange(drawseg_t *ds, INT32 x1, INT32 x2) +void R_RenderMaskedSegRange(drawseg_t *drawseg, INT32 x1, INT32 x2) { size_t pindex; column_t *col; @@ -314,7 +325,7 @@ void R_RenderMaskedSegRange(drawseg_t *ds, INT32 x1, INT32 x2) // Use different light tables // for horizontal / vertical / diagonal. Diagonal? // OPTIMIZE: get rid of LIGHTSEGSHIFT globally - curline = ds->curline; + curline = drawseg->curline; frontsector = curline->frontsector; backsector = curline->backsector; texnum = R_GetTextureNum(curline->sidedef->midtexture); @@ -359,9 +370,9 @@ void R_RenderMaskedSegRange(drawseg_t *ds, INT32 x1, INT32 x2) colfunc = fuzzcolfunc; } - range = max(ds->x2-ds->x1, 1); - rw_scalestep = ds->scalestep; - spryscale = ds->scale1 + (x1 - ds->x1)*rw_scalestep; + range = max(drawseg->x2-drawseg->x1, 1); + rw_scalestep = drawseg->scalestep; + spryscale = drawseg->scale1 + (x1 - drawseg->x1)*rw_scalestep; // Texture must be cached before setting colfunc_2s, // otherwise texture[texnum]->holes may be false when it shouldn't be @@ -383,8 +394,14 @@ void R_RenderMaskedSegRange(drawseg_t *ds, INT32 x1, INT32 x2) dc->numlights = frontsector->numlights; if (dc->numlights >= dc->maxlights) { + r_lightlist_t* old_lightlist = dc->lightlist; + INT32 old_maxlights = dc->maxlights; dc->maxlights = dc->numlights; - dc->lightlist = Z_Realloc(dc->lightlist, sizeof (*dc->lightlist) * dc->maxlights, PU_STATIC, NULL); + dc->lightlist = (Z_Frame_Alloc(sizeof (*dc->lightlist) * dc->maxlights)); + if (old_lightlist != NULL) + { + M_Memcpy(dc->lightlist, old_lightlist, sizeof (*dc->lightlist) * old_maxlights); + } } for (i = 0; i < dc->numlights; i++) @@ -393,14 +410,14 @@ void R_RenderMaskedSegRange(drawseg_t *ds, INT32 x1, INT32 x2) light = &frontsector->lightlist[i]; rlight = &dc->lightlist[i]; - leftheight = P_GetLightZAt(light, ds-> leftpos.x, ds-> leftpos.y); - rightheight = P_GetLightZAt(light, ds->rightpos.x, ds->rightpos.y); + leftheight = P_GetLightZAt(light, drawseg-> leftpos.x, drawseg-> leftpos.y); + rightheight = P_GetLightZAt(light, drawseg->rightpos.x, drawseg->rightpos.y); leftheight -= viewz; rightheight -= viewz; - rlight->height = (centeryfrac) - FixedMul(leftheight, ds->scale1); - rlight->heightstep = (centeryfrac) - FixedMul(rightheight, ds->scale2); + rlight->height = (centeryfrac) - FixedMul(leftheight, drawseg->scale1); + rlight->heightstep = (centeryfrac) - FixedMul(rightheight, drawseg->scale2); rlight->heightstep = (rlight->heightstep-rlight->height)/(range); rlight->startheight = rlight->height; // keep starting value here to reset for each repeat rlight->lightlevel = *light->lightlevel; @@ -448,10 +465,10 @@ void R_RenderMaskedSegRange(drawseg_t *ds, INT32 x1, INT32 x2) walllights = scalelight[lightnum]; } - maskedtexturecol = ds->maskedtexturecol; + maskedtexturecol = drawseg->maskedtexturecol; - mfloorclip = ds->sprbottomclip; - mceilingclip = ds->sprtopclip; + mfloorclip = drawseg->sprbottomclip; + mceilingclip = drawseg->sprtopclip; if (frontsector->heightsec != -1) front = §ors[frontsector->heightsec]; @@ -463,8 +480,8 @@ void R_RenderMaskedSegRange(drawseg_t *ds, INT32 x1, INT32 x2) else back = backsector; - if (ds->curline->sidedef->repeatcnt) - repeats = 1 + ds->curline->sidedef->repeatcnt; + if (drawseg->curline->sidedef->repeatcnt) + repeats = 1 + drawseg->curline->sidedef->repeatcnt; else if (ldef->flags & ML_EFFECT5) { fixed_t high, low; @@ -490,8 +507,8 @@ void R_RenderMaskedSegRange(drawseg_t *ds, INT32 x1, INT32 x2) { if (times > 0) { - rw_scalestep = ds->scalestep; - spryscale = ds->scale1 + (x1 - ds->x1)*rw_scalestep; + rw_scalestep = drawseg->scalestep; + spryscale = drawseg->scale1 + (x1 - drawseg->x1)*rw_scalestep; if (dc->numlights) { // reset all lights to their starting heights for (i = 0; i < dc->numlights; i++) @@ -507,7 +524,7 @@ void R_RenderMaskedSegRange(drawseg_t *ds, INT32 x1, INT32 x2) // draw the columns for (dc->x = x1; dc->x <= x2; dc->x++) { - dc->texturemid = ds->maskedtextureheight[dc->x]; + dc->texturemid = drawseg->maskedtextureheight[dc->x]; if (!!(curline->linedef->flags & ML_DONTPEGBOTTOM) ^ !!(curline->linedef->flags & ML_EFFECT3)) dc->texturemid += (textureheight[texnum])*times + textureheight[texnum]; @@ -667,7 +684,7 @@ static boolean R_IsFFloorTranslucent(visffloor_t *pfloor) // // R_RenderThickSideRange // Renders all the thick sides in the given range. -void R_RenderThickSideRange(drawseg_t *ds, INT32 x1, INT32 x2, ffloor_t *pfloor) +void R_RenderThickSideRange(drawseg_t *drawseg, INT32 x1, INT32 x2, ffloor_t *pfloor) { size_t pindex = 0; column_t * col; @@ -702,7 +719,7 @@ void R_RenderThickSideRange(drawseg_t *ds, INT32 x1, INT32 x2, ffloor_t *pfloor) // for horizontal / vertical / diagonal. Diagonal? // OPTIMIZE: get rid of LIGHTSEGSHIFT globally - curline = ds->curline; + curline = drawseg->curline; backsector = pfloor->target; frontsector = curline->frontsector == pfloor->target ? curline->backsector : curline->frontsector; texnum = R_GetTextureNum(sides[pfloor->master->sidenum[0]].midtexture); @@ -739,10 +756,10 @@ void R_RenderThickSideRange(drawseg_t *ds, INT32 x1, INT32 x2, ffloor_t *pfloor) else if (pfloor->flags & FF_FOG) colfunc = R_DrawFogColumn; - range = max(ds->x2-ds->x1, 1); + range = max(drawseg->x2-drawseg->x1, 1); //SoM: Moved these up here so they are available for my lightlist calculations - rw_scalestep = ds->scalestep; - spryscale = ds->scale1 + (x1 - ds->x1)*rw_scalestep; + rw_scalestep = drawseg->scalestep; + spryscale = drawseg->scale1 + (x1 - drawseg->x1)*rw_scalestep; dc->numlights = 0; if (frontsector->numlights) @@ -750,8 +767,14 @@ void R_RenderThickSideRange(drawseg_t *ds, INT32 x1, INT32 x2, ffloor_t *pfloor) dc->numlights = frontsector->numlights; if (dc->numlights > dc->maxlights) { + r_lightlist_t* old_lightlist = dc->lightlist; + INT32 old_maxlights = dc->maxlights; dc->maxlights = dc->numlights; - dc->lightlist = Z_Realloc(dc->lightlist, sizeof (*dc->lightlist) * dc->maxlights, PU_STATIC, NULL); + dc->lightlist = (Z_Frame_Alloc(sizeof (*dc->lightlist) * dc->maxlights)); + if (old_lightlist != NULL) + { + M_Memcpy(dc->lightlist, old_lightlist, sizeof (*dc->lightlist) * old_maxlights); + } } for (i = p = 0; i < dc->numlights; i++) @@ -763,8 +786,8 @@ void R_RenderThickSideRange(drawseg_t *ds, INT32 x1, INT32 x2, ffloor_t *pfloor) rlight = &dc->lightlist[p]; #define SLOPEPARAMS(slope, end1, end2, normalheight) \ - end1 = P_GetZAt(slope, ds->leftpos.x, ds->leftpos.y, normalheight); \ - end2 = P_GetZAt(slope, ds->rightpos.x, ds->rightpos.y, normalheight); + end1 = P_GetZAt(slope, drawseg->leftpos.x, drawseg->leftpos.y, normalheight); \ + end2 = P_GetZAt(slope, drawseg->rightpos.x, drawseg->rightpos.y, normalheight); SLOPEPARAMS(light->slope, leftheight, rightheight, light->height) SLOPEPARAMS(*pfloor->b_slope, pfloorleft, pfloorright, *pfloor->bottomheight) @@ -777,8 +800,8 @@ void R_RenderThickSideRange(drawseg_t *ds, INT32 x1, INT32 x2, ffloor_t *pfloor) if (leftheight > pfloorleft && rightheight > pfloorright && i+1 < dc->numlights) { lightlist_t *nextlight = &frontsector->lightlist[i+1]; - if ((P_GetLightZAt(nextlight, ds->leftpos.x, ds->leftpos.y) > pfloorleft) - && (P_GetLightZAt(nextlight, ds->rightpos.x, ds->rightpos.y) > pfloorright)) + if ((P_GetLightZAt(nextlight, drawseg->leftpos.x, drawseg->leftpos.y) > pfloorleft) + && (P_GetLightZAt(nextlight, drawseg->rightpos.x, drawseg->rightpos.y) > pfloorright)) continue; } @@ -788,12 +811,12 @@ void R_RenderThickSideRange(drawseg_t *ds, INT32 x1, INT32 x2, ffloor_t *pfloor) #define CLAMPMAX INT32_MAX #define CLAMPMIN (-INT32_MAX) // This is not INT32_MIN on purpose! INT32_MIN makes the drawers freak out. // Monster Iestyn (25/03/18): do not skip these lights if they fail overflow test, just clamp them instead so they behave. - overflow_test = (INT64)centeryfrac - (((INT64)leftheight*ds->scale1)>>FRACBITS); + overflow_test = (INT64)centeryfrac - (((INT64)leftheight*drawseg->scale1)>>FRACBITS); if (overflow_test > (INT64)CLAMPMAX) rlight->height = CLAMPMAX; else if (overflow_test > (INT64)CLAMPMIN) rlight->height = (fixed_t)overflow_test; else rlight->height = CLAMPMIN; - overflow_test = (INT64)centeryfrac - (((INT64)rightheight*ds->scale2)>>FRACBITS); + overflow_test = (INT64)centeryfrac - (((INT64)rightheight*drawseg->scale2)>>FRACBITS); if (overflow_test > (INT64)CLAMPMAX) rlight->heightstep = CLAMPMAX; else if (overflow_test > (INT64)CLAMPMIN) rlight->heightstep = (fixed_t)overflow_test; else rlight->heightstep = CLAMPMIN; @@ -807,12 +830,12 @@ void R_RenderThickSideRange(drawseg_t *ds, INT32 x1, INT32 x2, ffloor_t *pfloor) rightheight -= viewz; // Monster Iestyn (25/03/18): do not skip these lights if they fail overflow test, just clamp them instead so they behave. - overflow_test = (INT64)centeryfrac - (((INT64)leftheight*ds->scale1)>>FRACBITS); + overflow_test = (INT64)centeryfrac - (((INT64)leftheight*drawseg->scale1)>>FRACBITS); if (overflow_test > (INT64)CLAMPMAX) rlight->botheight = CLAMPMAX; else if (overflow_test > (INT64)CLAMPMIN) rlight->botheight = (fixed_t)overflow_test; else rlight->botheight = CLAMPMIN; - overflow_test = (INT64)centeryfrac - (((INT64)rightheight*ds->scale2)>>FRACBITS); + overflow_test = (INT64)centeryfrac - (((INT64)rightheight*drawseg->scale2)>>FRACBITS); if (overflow_test > (INT64)CLAMPMAX) rlight->botheightstep = CLAMPMAX; else if (overflow_test > (INT64)CLAMPMIN) rlight->botheightstep = (fixed_t)overflow_test; else rlight->botheightstep = CLAMPMIN; @@ -864,15 +887,15 @@ void R_RenderThickSideRange(drawseg_t *ds, INT32 x1, INT32 x2, ffloor_t *pfloor) walllights = scalelight[lightnum]; } - maskedtexturecol = ds->thicksidecol; + maskedtexturecol = drawseg->thicksidecol; - mfloorclip = ds->sprbottomclip; - mceilingclip = ds->sprtopclip; + mfloorclip = drawseg->sprbottomclip; + mceilingclip = drawseg->sprtopclip; dc->texheight = textureheight[texnum]>>FRACBITS; - // calculate both left ends - left_top = P_GetFFloorTopZAt (pfloor, ds->leftpos.x, ds->leftpos.y) - viewz; - left_bottom = P_GetFFloorBottomZAt(pfloor, ds->leftpos.x, ds->leftpos.y) - viewz; + // calculate both left endrawseg + left_top = P_GetFFloorTopZAt (pfloor, drawseg->leftpos.x, drawseg->leftpos.y) - viewz; + left_bottom = P_GetFFloorBottomZAt(pfloor, drawseg->leftpos.x, drawseg->leftpos.y) - viewz; skewslope = *pfloor->t_slope; // skew using top slope by default @@ -942,20 +965,20 @@ void R_RenderThickSideRange(drawseg_t *ds, INT32 x1, INT32 x2, ffloor_t *pfloor) fixed_t right_top, right_bottom; // calculate right ends now - right_top = P_GetFFloorTopZAt (pfloor, ds->rightpos.x, ds->rightpos.y) - viewz; - right_bottom = P_GetFFloorBottomZAt(pfloor, ds->rightpos.x, ds->rightpos.y) - viewz; + right_top = P_GetFFloorTopZAt (pfloor, drawseg->rightpos.x, drawseg->rightpos.y) - viewz; + right_bottom = P_GetFFloorBottomZAt(pfloor, drawseg->rightpos.x, drawseg->rightpos.y) - viewz; // using INT64 to avoid 32bit overflow - top_frac = (INT64)centeryfrac - (((INT64)left_top * ds->scale1) >> FRACBITS); - bottom_frac = (INT64)centeryfrac - (((INT64)left_bottom * ds->scale1) >> FRACBITS); - top_step = (INT64)centeryfrac - (((INT64)right_top * ds->scale2) >> FRACBITS); - bottom_step = (INT64)centeryfrac - (((INT64)right_bottom * ds->scale2) >> FRACBITS); + top_frac = (INT64)centeryfrac - (((INT64)left_top * drawseg->scale1) >> FRACBITS); + bottom_frac = (INT64)centeryfrac - (((INT64)left_bottom * drawseg->scale1) >> FRACBITS); + top_step = (INT64)centeryfrac - (((INT64)right_top * drawseg->scale2) >> FRACBITS); + bottom_step = (INT64)centeryfrac - (((INT64)right_bottom * drawseg->scale2) >> FRACBITS); top_step = (top_step-top_frac)/(range); bottom_step = (bottom_step-bottom_frac)/(range); - top_frac += top_step * (x1 - ds->x1); - bottom_frac += bottom_step * (x1 - ds->x1); + top_frac += top_step * (x1 - drawseg->x1); + bottom_frac += bottom_step * (x1 - drawseg->x1); } // draw the columns @@ -2454,11 +2477,8 @@ void R_StoreWallRange(INT32 start, INT32 stop) if (frontsector->numlights) { dc.numlights = frontsector->numlights; - if (dc.numlights >= dc.maxlights) - { - dc.maxlights = dc.numlights; - dc.lightlist = Z_Realloc(dc.lightlist, sizeof (*dc.lightlist) * dc.maxlights, PU_STATIC, NULL); - } + dc.maxlights = dc.numlights; + dc.lightlist = (Z_Frame_Alloc(sizeof(*dc.lightlist) * dc.maxlights)); for (i = p = 0; i < dc.numlights; i++) { diff --git a/src/r_segs.h b/src/r_segs.h index 23d4ec36b..27dbbe54f 100644 --- a/src/r_segs.h +++ b/src/r_segs.h @@ -14,6 +14,10 @@ #ifndef __R_SEGS__ #define __R_SEGS__ +#ifdef __cplusplus +extern "C" { +#endif + #ifdef __GNUG__ #pragma interface #endif @@ -26,4 +30,8 @@ void R_AllocSegMemory(void); transnum_t R_GetLinedefTransTable(fixed_t alpha); +#ifdef __cplusplus +} // extern "C" +#endif + #endif diff --git a/src/r_things.c b/src/r_things.c index 88433c793..17cf5a155 100644 --- a/src/r_things.c +++ b/src/r_things.c @@ -2944,7 +2944,7 @@ static void R_DrawMaskedList (drawnode_t* head) if (r2->plane) { next = r2->prev; - R_DrawSinglePlane(&ds, r2->plane); + R_DrawSinglePlane(&ds, r2->plane, false); R_DoneWithNode(r2); r2 = next; } diff --git a/src/r_things.h b/src/r_things.h index 79d4dea11..f4752d166 100644 --- a/src/r_things.h +++ b/src/r_things.h @@ -14,6 +14,10 @@ #ifndef __R_THINGS__ #define __R_THINGS__ +#ifdef __cplusplus +extern "C" { +#endif + #include "sounds.h" #include "r_plane.h" #include "r_patch.h" @@ -310,4 +314,8 @@ FUNCMATH FUNCINLINE static ATTRINLINE boolean R_ValidSpriteAngle(UINT8 rotation) return ((rotation <= 8) || (rotation == ROT_L) || (rotation == ROT_R)); } +#ifdef __cplusplus +} // extern "C" +#endif + #endif //__R_THINGS__ diff --git a/src/sdl/i_system.c b/src/sdl/i_system.c index afda0caa2..84d0fb218 100644 --- a/src/sdl/i_system.c +++ b/src/sdl/i_system.c @@ -189,6 +189,9 @@ static char returnWadPath[256]; #include "../r_main.h" // Frame interpolation/uncapped #include "../r_fps.h" +#include "../s_sound.h" +#include "../core/thread_pool.h" + #ifdef MAC_ALERT #include "macosx/mac_alert.h" #endif @@ -493,6 +496,15 @@ static void I_ReportSignal(int num, int coredumped) #ifndef NEWSIGNALHANDLER FUNCNORETURN static ATTRNORETURN void signal_handler(INT32 num) { + if (g_main_thread_id != std::this_thread::get_id()) + { + // Do not attempt any sort of recovery if this signal triggers off the main thread + signal(num, SIG_DFL); + raise(num); + exit(-2); + } + + g_in_exiting_signal_handler = true; D_QuitNetGame(); // Fix server freezes @@ -1524,7 +1536,7 @@ void I_SetGamepadIndicatorColor(INT32 playernum, UINT8 red, UINT8 green, UINT8 b #define DEG2RAD (0.017453292519943295769236907684883l) // TAU/360 or PI/180 #define MUMBLEUNIT (64.0f) // FRACUNITS in a Meter -static struct { +static struct mumble_s { #ifdef WINMUMBLE UINT32 uiVersion; DWORD uiTick; @@ -1557,7 +1569,7 @@ static void I_SetupMumble(void) if (!hMap) return; - mumble = MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(*mumble)); + mumble = static_cast(MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(*mumble))); if (!mumble) CloseHandle(hMap); #elif defined (HAVE_SHM) @@ -1570,7 +1582,7 @@ static void I_SetupMumble(void) if(shmfd < 0) return; - mumble = mmap(NULL, sizeof(*mumble), PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0); + mumble = (mmap(NULL, sizeof(*mumble), PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0)); if (mumble == MAP_FAILED) mumble = NULL; #endif @@ -1586,7 +1598,7 @@ void I_UpdateMumble(const mobj_t *mobj, const listener_t listener) return; if(mumble->uiVersion != 2) { - wcsncpy(mumble->name, L"SRB2Kart "VERSIONSTRINGW, 256); + wcsncpy(mumble->name, L"SRB2Kart " VERSIONSTRINGW, 256); wcsncpy(mumble->description, L"Sonic Robo Blast 2 Kart with integrated Mumble Link support.", 2048); mumble->uiVersion = 2; } @@ -1900,6 +1912,8 @@ INT32 I_StartupSystem(void) #ifdef HAVE_THREADS I_start_threads(); I_AddExitFunc(I_stop_threads); + I_ThreadPoolInit(); + I_AddExitFunc(I_ThreadPoolShutdown); #endif I_RegisterSignals(); I_OutputMsg("Compiled for SDL version: %d.%d.%d\n", @@ -2373,7 +2387,7 @@ const char *I_ClipboardPaste(void) */ static boolean isWadPathOk(const char *path) { - char *wad3path = malloc(256); + char *wad3path = (malloc(256)); if (!wad3path) return false; diff --git a/src/tables.h b/src/tables.h index 4856c90ea..2f492bebb 100644 --- a/src/tables.h +++ b/src/tables.h @@ -14,6 +14,10 @@ #ifndef __TABLES__ #define __TABLES__ +#ifdef __cplusplus +extern "C" { +#endif + #ifdef LINUX #include #endif @@ -134,4 +138,8 @@ void FM_Rotate(matrix_t *dest, angle_t angle, fixed_t x, fixed_t y, fixed_t z); #define FSIN(n) FINESINE(ANGLETOFINE(n)) #define FCOS(n) FINECOSINE(ANGLETOFINE(n)) +#ifdef __cplusplus +} // extern "C" +#endif + #endif diff --git a/src/v_video.h b/src/v_video.h index d60496dfb..d5a4adf5e 100644 --- a/src/v_video.h +++ b/src/v_video.h @@ -14,6 +14,10 @@ #ifndef __V_VIDEO__ #define __V_VIDEO__ +#ifdef __cplusplus +extern "C" { +#endif + #include "doomdef.h" #include "doomtype.h" #include "r_defs.h" @@ -285,4 +289,8 @@ void V_DrawHorizontallyScaledFullScreenPatch(patch_t *patch); void VID_BlitLinearScreen(const UINT8 *srcptr, UINT8 *destptr, INT32 width, INT32 height, size_t srcrowbytes, size_t destrowbytes); +#ifdef __cplusplus +} // extern "C" +#endif + #endif diff --git a/src/w_wad.h b/src/w_wad.h index 12ad8cea7..9b1035fa2 100644 --- a/src/w_wad.h +++ b/src/w_wad.h @@ -14,6 +14,10 @@ #ifndef __W_WAD__ #define __W_WAD__ +#ifdef __cplusplus +extern "C" { +#endif + #ifdef HWRENDER #include "hardware/hw_data.h" #endif @@ -233,4 +237,8 @@ int W_VerifyNMUSlumps(const char *filename); int W_CheckPostLoadList(const char *filename); +#ifdef __cplusplus +} // extern "C" +#endif + #endif // __W_WAD__ diff --git a/src/z_zone.h b/src/z_zone.h index 41ea1d669..ab908bfec 100644 --- a/src/z_zone.h +++ b/src/z_zone.h @@ -14,6 +14,10 @@ #ifndef __Z_ZONE__ #define __Z_ZONE__ +#ifdef __cplusplus +extern "C" { +#endif + #include #include "doomdef.h" #include "doomtype.h" @@ -153,4 +157,8 @@ size_t Z_TagsUsage(INT32 lowtag, INT32 hightag); // char *Z_StrDup(const char *in); +#ifdef __cplusplus +} // extern "C" +#endif + #endif