fix segfault for real

This commit is contained in:
2025-07-08 11:08:38 -04:00
parent 9c631d3d9a
commit cda06a5169
9 changed files with 176 additions and 139 deletions

View File

@@ -47,15 +47,18 @@ void Aquarium::ensureEntitiesSorted() {
void Aquarium::redraw() {
clearCurrentFrame();
ensureBigEntityExists();
std::vector<std::unique_ptr<Entity>> newEntities;
bool entities_modified = false;
// Use static vectors to avoid per-frame allocations
static std::vector<std::unique_ptr<Entity>> newEntities;
static std::vector<size_t> entitiesToRemove;
// Update and check for removal/replacement
for (auto it = entities.begin(); it != entities.end();) {
auto &entity = *it;
newEntities.clear();
entitiesToRemove.clear();
// Update all entities and collect changes
for (size_t i = 0; i < entities.size(); ++i) {
auto &entity = entities[i];
entity->update();
// Handle fish bubble spawning
@@ -69,30 +72,32 @@ void Aquarium::redraw() {
if (entity->shouldBeRemoved()) {
auto replacement = entity->createReplacement();
if (replacement) {
*it = std::move(replacement);
entities_modified = true;
++it;
entity = std::move(replacement); // Replace in-place
entities_need_sorting = true;
} else {
it = entities.erase(it);
entities_modified = true;
entitiesToRemove.push_back(i); // Mark for removal
}
} else {
++it;
}
}
// Add new entities if any
// Remove entities in reverse order to maintain indices
for (auto it = entitiesToRemove.rbegin(); it != entitiesToRemove.rend();
++it) {
entities.erase(entities.begin() + *it);
entities_need_sorting = true;
}
// Add new entities (only if we have them)
if (!newEntities.empty()) {
// Reserve space to minimize reallocations
entities.reserve(entities.size() + newEntities.size());
for (auto &newEntity : newEntities) {
entities.emplace_back(std::move(newEntity));
}
entities_modified = true;
}
// Only sort if entities were modified
if (entities_modified) {
entities_need_sorting = true;
}
ensureEntitiesSorted();
// Draw all entities