Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
PhysicsTaskPool.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
28#pragma once
29
30#ifndef __EMSCRIPTEN__
31
32#include <box2d/types.h>
33
34#include <atomic>
35#include <condition_variable>
36#include <cstdint>
37#include <deque>
38#include <mutex>
39#include <thread>
40#include <vector>
41
42namespace esengine::physics {
43
49class TaskPool {
50public:
53 TaskPool();
54 ~TaskPool();
55
56 TaskPool(const TaskPool&) = delete;
57 TaskPool& operator=(const TaskPool&) = delete;
58
61 int workerCount() const { return workerCount_; }
62
65 void configure(b2WorldDef& def);
66
67private:
69 struct Group {
70 std::atomic<int> pending{0};
72 bool free = true;
73 };
74
76 struct Job {
77 b2TaskCallback* fn = nullptr;
78 int startIndex = 0;
79 int endIndex = 0;
80 void* taskContext = nullptr;
81 Group* group = nullptr;
82 };
83
84 static void* enqueueTask(b2TaskCallback* task, int itemCount, int minRange,
85 void* taskContext, void* userContext);
86 static void finishTask(void* userTask, void* userContext);
87
88 void* submit(b2TaskCallback* task, int itemCount, int minRange, void* taskContext);
89 void wait(Group* group);
90 void workerLoop(uint32_t workerIndex);
91 Group* acquireGroup();
92
93 int workerCount_ = 0;
94 std::vector<std::thread> threads_;
95 std::deque<Job> queue_;
96 // Groups are pooled rather than allocated per task: a step enqueues on the
97 // order of a dozen, every frame, forever.
98 std::deque<Group> groups_;
99 std::mutex mutex_;
100 std::condition_variable queued_;
101 bool stopping_ = false;
102};
103
104} // namespace esengine::physics
105
106#endif // __EMSCRIPTEN__
TaskPool(const TaskPool &)=delete
void configure(b2WorldDef &def)
TaskPool & operator=(const TaskPool &)=delete