Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
PhysicsTaskPool.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
4
5#ifndef __EMSCRIPTEN__
6
7#include <algorithm>
8
10namespace {
11
14constexpr int kReservedCores = 2;
17constexpr int kMaxWorkers = 4;
18
19} // namespace
20
22 const int cores = static_cast<int>(std::thread::hardware_concurrency());
23 workerCount_ = std::clamp(cores - kReservedCores, 0, kMaxWorkers);
24 if (workerCount_ < 2) {
25 // One worker is the serial solver with extra bookkeeping; take the
26 // serial path instead and report no workers.
27 workerCount_ = 0;
28 return;
29 }
30
31 // Worker 0 is whoever steps the world — it helps from finishTask — so the
32 // pool owns the rest. One thread per index, and only one: Box2D indexes its
33 // per-worker scratch by these, and two threads on one index corrupt a step.
34 threads_.reserve(static_cast<size_t>(workerCount_ - 1));
35 for (int i = 1; i < workerCount_; i++) {
36 threads_.emplace_back([this, i] { workerLoop(static_cast<uint32_t>(i)); });
37 }
38}
39
41 {
42 std::lock_guard<std::mutex> lock(mutex_);
43 stopping_ = true;
44 }
45 queued_.notify_all();
46 for (auto& thread : threads_) {
47 if (thread.joinable()) thread.join();
48 }
49}
50
51void TaskPool::configure(b2WorldDef& def) {
52 if (workerCount_ == 0) return; // serial world; leave Box2D's defaults
53 def.workerCount = workerCount_;
54 def.enqueueTask = &TaskPool::enqueueTask;
55 def.finishTask = &TaskPool::finishTask;
56 def.userTaskContext = this;
57}
58
59TaskPool::Group* TaskPool::acquireGroup() {
60 for (auto& group : groups_) {
61 if (group.free) {
62 group.free = false;
63 group.pending.store(0, std::memory_order_relaxed);
64 return &group;
65 }
66 }
67 // deque keeps existing elements addressable, which matters because a Group
68 // is held by pointer while its jobs run.
69 groups_.emplace_back();
70 groups_.back().free = false;
71 return &groups_.back();
72}
73
74void* TaskPool::submit(b2TaskCallback* task, int itemCount, int minRange, void* taskContext) {
75 if (itemCount <= 0) return nullptr;
76
77 // Honour minRange: below it the split costs more than it saves, and Box2D
78 // states the range each worker gets should not be smaller.
79 const int maxSlices = std::max(1, itemCount / std::max(1, minRange));
80 const int slices = std::clamp(maxSlices, 1, workerCount_);
81
82 Group* group = nullptr;
83 {
84 std::lock_guard<std::mutex> lock(mutex_);
85 group = acquireGroup();
86 group->pending.store(slices, std::memory_order_relaxed);
87
88 const int base = itemCount / slices;
89 const int remainder = itemCount % slices;
90 int start = 0;
91 for (int i = 0; i < slices; i++) {
92 const int size = base + (i < remainder ? 1 : 0);
93 queue_.push_back(Job{task, start, start + size, taskContext, group});
94 start += size;
95 }
96 }
97 if (slices == 1) queued_.notify_one();
98 else queued_.notify_all();
99 return group;
100}
101
102void TaskPool::wait(Group* group) {
103 // The calling thread is worker 0, so it works rather than blocks. Box2D
104 // enqueues the island split alongside the whole worker set; a thread that
105 // only waited could leave a solver worker queued behind it, and its peers
106 // spin on a barrier that worker never reaches.
107 while (group->pending.load(std::memory_order_acquire) != 0) {
108 Job job;
109 {
110 std::lock_guard<std::mutex> lock(mutex_);
111 if (!queue_.empty()) {
112 job = queue_.front();
113 queue_.pop_front();
114 }
115 }
116 if (!job.fn) {
117 // Nothing queued: the remaining slices are already running on pool
118 // threads, so give up the core rather than spinning on them.
119 std::this_thread::yield();
120 continue;
121 }
122 job.fn(job.startIndex, job.endIndex, 0u, job.taskContext);
123 job.group->pending.fetch_sub(1, std::memory_order_acq_rel);
124 }
125 std::lock_guard<std::mutex> lock(mutex_);
126 group->free = true;
127}
128
129void TaskPool::workerLoop(uint32_t workerIndex) {
130 while (true) {
131 Job job;
132 {
133 std::unique_lock<std::mutex> lock(mutex_);
134 queued_.wait(lock, [this] { return stopping_ || !queue_.empty(); });
135 if (stopping_ && queue_.empty()) return;
136 job = queue_.front();
137 queue_.pop_front();
138 }
139 // This thread owns this index for the pool's lifetime, which is the
140 // guarantee Box2D asks for.
141 job.fn(job.startIndex, job.endIndex, workerIndex, job.taskContext);
142 job.group->pending.fetch_sub(1, std::memory_order_acq_rel);
143 }
144}
145
146void* TaskPool::enqueueTask(b2TaskCallback* task, int itemCount, int minRange,
147 void* taskContext, void* userContext) {
148 return static_cast<TaskPool*>(userContext)->submit(task, itemCount, minRange, taskContext);
149}
150
151void TaskPool::finishTask(void* userTask, void* userContext) {
152 if (!userTask) return;
153 static_cast<TaskPool*>(userContext)->wait(static_cast<Group*>(userTask));
154}
155
156} // namespace esengine::physics
157
158#endif // __EMSCRIPTEN__
The worker pool Box2D solves across on a device.
void configure(b2WorldDef &def)