#include "entity_list.h" #include "entity_effect.h" #include "entity_npc.h" #include "entity_player.h" #include "entity_projectile.h" #include "entity_tear.h" #include "game.h" #include "log.h" #include "manager.h" #include "room.h" #include #include #include #include constexpr const char* SHADOW_PNG = "gfx/shadow.png"; constexpr int FAMILIAR_WISP = 206; constexpr int FAMILIAR_CUBE_BABY = 239; constexpr int BOMB_ROCKET = 19; constexpr int BOMB_ROCKET_GIGA = 20; constexpr int ENTITY_ULTRA_GREED = 406; constexpr int ENTITY_BUMBINO = 916; constexpr int KNIFE_MAIN = 0; // The boss bar flashes for this many frames when the bosses' health changes. constexpr int BOSS_BAR_FLASH_FRAMES = 8; // The render bands sort_by_render_z first partitions the list into: background, doors, and the rest. constexpr uint32_t RENDER_Z_DOOR_START = 5000; constexpr uint32_t RENDER_Z_NORMAL_START = 10000; // The swaps a frame's sort may make: a sixteenth of the original's fixed render list capacity, plus one. constexpr int RENDER_LIST_CAPACITY = 0x4000; constexpr int RENDER_SORT_SWAP_BUDGET = (RENDER_LIST_CAPACITY >> 4) + 1; // The room's render surface, its size and margin, centered on the screen. constexpr float ROOM_SURFACE_WIDTH = 338; constexpr float ROOM_SURFACE_HEIGHT = 182; constexpr float ROOM_SURFACE_MARGIN = 52; // A surface surfaces_bake draws into: the flag of the entities drawn there, the flags that keep them, and whether any // is to be drawn. struct SurfacePass { KAGE::Graphics::ImageBase* surface = nullptr; uint64_t flag = 0; uint64_t keptFlags = 0; bool isUsed = false; }; // Formats a message for KAGE_LogMessage, whose declaration takes nothing to format with. [[gnu::format(printf, 2, 3)]] static void log_format(uint32_t level, const char* format, ...) { char message[256]; va_list args; va_start(args, format); std::vsnprintf(message, sizeof(message), format, args); va_end(args); KAGE_LogMessage(level, (uint8_t*)message); } static bool is_unit_size(const Entity& entity) { return entity.sizeMulti.x == 1 && entity.sizeMulti.y == 1; } // 00417670 Drops every occurrence of the entity. void EntityList_EL::remove(Entity* entity) { std::erase(*this, entity); } // 0085e0c0 The entity at the index, the last one for an index past the end. // The original read before the list when it was empty: nothing is returned then. Entity* EntityList_EL::Get(uint32_t index) { if (empty()) return nullptr; return (*this)[std::min(index, size() - 1)]; } // Sizes the grid to cover width by height in cells of size, owned by the list whose collision pairs it marks. void CellSpace::layout(EntityList& list, float width, float height, float size) { owner = &list; cellSize = size; rows = (int)(height / size + 0.5f); columns = (int)(width / size + 0.5f); cells.assign((size_t)(rows * columns), Cell{}); } // 0041baf0 Empties every cell. void CellSpace::clear() { for (Cell& cell : cells) cell.count = 0; } // The cell at the column and row, counted through the grid in rows, or null past either end. CellSpace::Cell* CellSpace::cell_get(int column, int row) { int index = columns * row + column; return index >= 0 && index < (int)cells.size() ? &cells[index] : nullptr; } // 0041bb50 Lists the entity in every cell its collision box covers, turned with its sprite when stretched. void CellSpace::insert(Entity& entity) { float halfWidth = entity.sizeMulti.x * entity.size; float halfHeight = entity.sizeMulti.y * entity.size; if (!is_unit_size(entity) && entity.sprite.rotation != 0) { float angle = entity.sprite.rotation * 0.017453292f; float cosine = std::cos(angle); float sine = std::sin(angle); float turnedHeight = std::fabs(halfHeight * cosine) + std::fabs(halfWidth * sine); halfWidth = std::fabs(halfHeight * sine) + std::fabs(halfWidth * cosine); halfHeight = turnedHeight; } float left = entity.pos.x - halfWidth; float right = halfWidth + entity.pos.x; float top = entity.pos.y - halfHeight; float bottom = halfHeight + entity.pos.y; if (right <= left || bottom <= top) log_format(LOG_ASSERT, "Entity Teleport Detected! Type: %d, Variant: %d, Subtype: %d; Pos: %f, %f; Size: %f, %f\n", entity.type, entity.variant, entity.subtype, entity.pos.x, entity.pos.y, halfWidth, halfHeight); int firstRow = (int)(top / cellSize); int lastRow = (int)(bottom / cellSize); if (lastRow < firstRow) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"CellSpace::insert: y1 > y2\n"); int firstColumn = (int)(left / cellSize); int lastColumn = (int)(right / cellSize); if (lastColumn < firstColumn) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"CellSpace::insert: x1 > x2\n"); for (int row = firstRow; row <= lastRow; row++) { for (int column = firstColumn; column <= lastColumn; column++) { Cell* cell = cell_get(column, row); if (cell && cell->count < CELL_CAPACITY) cell->entities[cell->count++] = &entity; } } } // 0041bdf0 Pushes the entities in the cells under the entity's box off it, each pair once a frame. void CellSpace::collide_entity(Entity& entity) { if (entity.entityCollisionClass == ENTCOLL_NONE) return; float halfWidth = entity.size * entity.sizeMulti.x; float halfHeight = entity.size * entity.sizeMulti.y; int lastRow = (int)((halfHeight + entity.pos.y) / cellSize); int lastColumn = (int)((halfWidth + entity.pos.x) / cellSize); for (int row = (int)((entity.pos.y - halfHeight) / cellSize); row <= lastRow; row++) { for (int column = (int)((entity.pos.x - halfWidth) / cellSize); column <= lastColumn; column++) { Cell* cell = cell_get(column, row); for (int i = 0; cell && i < cell->count; i++) { Entity& other = *cell->entities[i]; if (&other == &entity || !owner->is_pair_new(other, entity)) continue; other.collide_with_entity(&entity); } } } } // 0041c070 Pushes this partition's entities off the other's that share their cells, each pair once a frame. void CellSpace::collide(CellSpace& other) { if (cells.size() != other.cells.size()) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"CellSpace::collide - cell counts don't match!\n"); for (size_t c = 0; c < std::min(cells.size(), other.cells.size()); c++) { for (int i = 0; i < cells[c].count; i++) { for (int j = 0; j < other.cells[c].count; j++) { Entity& first = *cells[c].entities[i]; Entity& second = *other.cells[c].entities[j]; if (&first != &second && owner->is_pair_new(first, second)) first.collide_with_entity(&second); } } } } // 0041c2a0 Pushes the entities sharing each cell off each other, each pair once a frame. void CellSpace::collide_self() { for (Cell& cell : cells) { for (int i = 0; i < cell.count; i++) { for (int j = i + 1; j < cell.count; j++) { Entity& first = *cell.entities[i]; Entity& second = *cell.entities[j]; if (&first != &second && owner->is_pair_new(first, second)) first.collide_with_entity(&second); } } } } // 0041c490 Adds the entities listed in the cells under a box to the result, each once. void CellSpace::query_box(EntityList_EL& result, const Vector& position, const Vector& extent) { if (owner->collisionPairStride == 0) return; std::vector isSeen((size_t)owner->collisionPairStride); int lastRow = (int)((extent.y + position.y) / cellSize); int firstColumn = (int)((position.x - extent.x) / cellSize); int lastColumn = (int)((extent.x + position.x) / cellSize); for (int row = (int)((position.y - extent.y) / cellSize); row <= lastRow; row++) { for (int column = firstColumn; column <= lastColumn; column++) { Cell* cell = cell_get(column, row); for (int i = 0; cell && i < cell->count; i++) { Entity* entity = cell->entities[i]; if (isSeen[entity->collisionIndex]) continue; result.push_back(entity); isSeen[entity->collisionIndex] = true; } } } } // Whether the pair has not collided yet this frame, marking it as collided. bool EntityList::is_pair_new(Entity& first, Entity& second) { uint32_t high = std::max(first.collisionIndex, second.collisionIndex); uint32_t low = std::min(first.collisionIndex, second.collisionIndex); size_t pair = (size_t)high * (size_t)collisionPairStride + low; if (pair >= collisionPairs.size() || collisionPairs[pair]) return false; collisionPairs[pair] = true; return true; } EntityList::EntityList() { for (CellSpace& partition : partitions) partition.layout(*this, PARTITION_WIDTH, PARTITION_HEIGHT, PARTITION_CELL_SIZE); shadowImage = Manager::LoadImage(SHADOW_PNG); Reset(); } // 00418230 Removes every entity but the persistent ones, and starts the lists over with those. void EntityList::Reset() { updateEL.clear(); renderEL.clear(); effectEL.clear(); for (Entity* entity : mainEL) { if (entity->HasEntityFlags(FLAG_PERSISTENT)) { updateEL.push_back(entity); renderEL.push_back(entity); continue; } entity->ClearReferences(); entity->isValid = false; entity->Remove(); } mainEL.assign(updateEL.begin(), updateEL.end()); wispEL.clear(); for (Entity* entity : persistentEL) { updateEL.push_back(entity); renderEL.push_back(entity); } for (Entity* entity : updateEL) if (entity->type == ENTITY_FAMILIAR && entity->variant == FAMILIAR_WISP) wispEL.push_back(entity); renderCursor = 0; renderMode = RENDER_NULL; pendingEnemyCount = 0; enemyCount = 0; pendingBossCount = 0; bossCount = 0; bossMaxHealth = 0; enemyDamageInflicted = 0; isAnyBaited = false; typeCache.clear(); } // 00418500 Adds a new entity to its lists, the render list in depth order, counting the enemies that shut the doors. // One already listed moves to the end of the update list. void EntityList::AddEntity(Entity* entity) { if (!entity->isValid) { bool isPersistent = entity->type == ENTITY_PLAYER || entity->type == ENTITY_FAMILIAR || (entity->type == ENTITY_KNIFE && entity->subtype == KNIFE_MAIN); (isPersistent ? persistentEL : mainEL).push_back(entity); if (entity->CanShutDoors() && entity->type != ENTITY_DARK_ESAU) { pendingEnemyCount++; if (entity->IsBoss()) pendingBossCount++; } entity->isValid = true; size_t at = 0; while (at < renderEL.size() && entity->GetRenderZ() > renderEL[at]->GetRenderZ()) at++; renderEL.insert(renderEL.begin() + (long)at, entity); if (entity->type == ENTITY_FAMILIAR && entity->variant == FAMILIAR_WISP) wispEL.push_back(entity); } else updateEL.remove(entity); if (!entity->HasEntityFlags(FLAG_RENDER_FLOOR)) updateEL.push_back(entity); invalidate_type_cache(entity->type, entity->variant, entity->subtype); } // 0041b4f0 Moves an entity to the persistent list, unless that list is nearly full. void EntityList::AddPersistentEntity(Entity* entity) { if (persistentEL.size() + PERSISTENT_RESERVE >= PERSISTENT_CAPACITY) { KAGE_LogMessage(LOG_INFO, (uint8_t*)"[warn] Can't add more persistent entities, persistent list is full!\n"); return; } mainEL.remove(entity); bool isListed = std::find(persistentEL.begin(), persistentEL.end(), entity) != persistentEL.end(); if (!isListed) persistentEL.push_back(entity); } // Draws the entities flagged to render into the floor or the walls into the backdrop's surfaces, at the room // surface's corner on screen snapped to the display's pixels, and removes them. One drawn into both stays for the // walls, and one with FLAG_NO_REMOVE_ON_TEX_RENDER stays. Whether any was removed. static bool surfaces_bake(EntityList_EL& renderEL) { Backdrop& backdrop = g_game->room->backdrop; std::array passes = {{ {backdrop.floorBuffer.get(), FLAG_RENDER_FLOOR, FLAG_RENDER_WALL | FLAG_NO_REMOVE_ON_TEX_RENDER}, {backdrop.wallsBuffer.get(), FLAG_RENDER_WALL, FLAG_NO_REMOVE_ON_TEX_RENDER}, }}; auto isDrawn = [](Entity* entity, uint64_t flag) { return entity->isExists && entity->HasEntityFlags(flag); }; for (SurfacePass& pass : passes) pass.isUsed = std::any_of(renderEL.begin(), renderEL.end(), [&pass, &isDrawn](Entity* entity) { return isDrawn(entity, pass.flag); }); if (!passes[0].isUsed && !passes[1].isUsed) return false; KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; float pixelScale = g_displayPixelRatio * g_screenPointScale; auto corner = [pixelScale](float screen, float surface) { return -(std::floor(pixelScale * ((screen - surface) * 0.5f - ROOM_SURFACE_MARGIN) + 0.5f) / pixelScale); }; Vector offset = vector_make(corner(g_screenWidth, ROOM_SURFACE_WIDTH), corner(g_screenHeight, ROOM_SURFACE_HEIGHT)); auto size = graphics.isScreenTarget ? KAGE::Graphics::TARGET_SCREEN_SIZE : KAGE::Graphics::TARGET_OWN_SIZE; graphics.render_target_push(graphics.renderTarget, size, KAGE::Graphics::PRESENT_FLUSH); graphics.isCullOffscreen = false; graphics.blend_set(KAGE::Graphics::BLEND_NORMAL); bool isRemoved = false; for (SurfacePass& pass : passes) { if (!pass.isUsed) continue; graphics.SetRenderTarget(pass.surface, KAGE::Graphics::TARGET_OWN_SIZE); for (size_t i = 0; i < renderEL.size(); i++) { Entity* entity = renderEL[i]; if (!isDrawn(entity, pass.flag)) continue; entity->Render(offset); if (entity->HasEntityFlags(pass.keptFlags)) continue; entity->Remove(); isRemoved = true; } graphics.Present(KAGE::Graphics::PRESENT_FINISH); } graphics.isCullOffscreen = true; graphics.render_target_pop(KAGE::Graphics::PRESENT_FLUSH); return isRemoved; } // 004186c0 One frame of the room's entities: pre-updates and updates (only those that update in transitions during // one), the players' in-between updates without interpolation, the enemy and boss counts and the boss bar, the // removal of the entities that stopped existing, then the collisions and the draw order. // Netplay's per-entity checksums are left out: netplay is offline. void EntityList::Update(UpdateMode mode) { typeCache.clear(); UpdateTally tally; if (updateEL.empty()) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"EntityList: e_update is empty!\n"); else entities_update(mode, tally); for (Entity_Player* player : g_game->playerManager.extraPlayers) player->Update(); if (!g_manager->optionsConfig.render.isInterpolationEnabled) players_update(mode); enemyCount = pendingEnemyCount + tally.activeEnemies; pendingEnemyCount = 0; bossCount = pendingBossCount + tally.bosses; pendingBossCount = 0; isAnyBaited = tally.isAnyBaited; boss_bar_update(tally); enemyDamageInflicted = tally.damageInflicted; bool isBakedAway = surfaces_bake(renderEL); if (tally.isAnyRemoved || isBakedAway) removed_drop(); if (mode == UPDATE_NORMAL) rebuild_sublists(); sort_by_render_z(); } // Whether the entity sits this update out: drawn into the floor or walls and gone, or still during a transition. static bool is_update_skipped(Entity& entity, UpdateMode mode) { bool isDrawnAway = entity.HasEntityFlags(FLAG_RENDER_FLOOR) && !entity.HasEntityFlags(FLAG_NO_REMOVE_ON_TEX_RENDER); return isDrawnAway || (mode == UPDATE_TRANSITION && !entity.HasEntityFlags(FLAG_TRANSITION_UPDATE)); } // The damage an enemy has taken so far, which the frame's total compares before and after its update. static float damage_taken_get(Entity& entity) { if (!Entity::is_enemy_type(entity.type)) return 0; if (entity.type == ENTITY_PLAYER) reconstruction_missing("EntityList::Update 004186c0: a versus player's damage"); return static_cast(entity).totalDamageTaken; } // Pre-updates then updates the entities listed at the start of the frame, tallying the door-holding enemies, the // bosses and their health, the damage the enemies took, and whether any is baited or stopped existing. void EntityList::entities_update(UpdateMode mode, UpdateTally& tally) { Entity* last = updateEL.back(); for (size_t i = 0;; i++) { Entity* entity = updateEL[i]; if (entity->isExists && !is_update_skipped(*entity, mode)) entity->PreUpdate(); if (entity == last || i + 1 >= updateEL.size()) break; } for (size_t i = 0;; i++) { Entity* entity = updateEL[i]; float damageBefore = damage_taken_get(*entity); if (entity->isExists && !is_update_skipped(*entity, mode)) entity->Update(); if (entity->isExists && entity->type != ENTITY_DARK_ESAU) { if (entity->CanShutDoors()) { tally.activeEnemies++; if (entity->IsBoss() && !entity->HasEntityFlags(FLAG_BOSSDEATH_TRIGGERED)) { bool isCounted = !entity->HasEntityFlags(FLAG_DONT_COUNT_BOSS_HP); if (isCounted) tally.bosses++; if (isCounted && entity->FrameCount() > 0) { tally.bossHealth += std::max(entity->health, 0.0f); tally.bossMaxHealth = entity->maxHitPoints + tally.bossMaxHealth; } } if (entity->type == ENTITY_EFFECT && entity->variant == EFFECT_SPAWN_PENTAGRAM) { Entity_Effect& pentagram = static_cast(*entity); EntityConfig_Entity* spawned = g_manager->entityConfig.GetEntity( pentagram.spawnType, pentagram.spawnVariant, pentagram.spawnSubtype); if (spawned && spawned->isBoss) tally.bosses++; } } bool isDamageCounted = (entity->CanShutDoors() || entity->type == ENTITY_FROZEN_ENEMY) && (Entity::is_enemy_type(entity->type) || entity->type == ENTITY_FROZEN_ENEMY) && !entity->IsFriendly(); bool isTrailingSegment = entity->type == ENTITY_PIN && entity->parent && entity->GetLastParent() != entity; if (isDamageCounted && !isTrailingSegment) { float damageAfter = std::min(damage_taken_get(*entity), entity->maxHitPoints); tally.damageInflicted += std::max(damageAfter - damageBefore, 0.0f); } } if (!entity->isExists) tally.isAnyRemoved = true; if (entity->HasEntityFlags(FLAG_BAITED)) tally.isAnyBaited = true; if (entity == last || i + 1 >= updateEL.size()) break; } } // Updates the players and extra players a second time, flagged as the in-between frame, when the options turn // interpolation off. void EntityList::players_update(UpdateMode mode) { std::vector& players = g_game->playerManager.playerList; for (size_t i = 0; i < players.size(); i++) { Entity_Player* player = players[i]; if (mode == UPDATE_TRANSITION && !player->HasEntityFlags(FLAG_TRANSITION_UPDATE)) continue; player->AddEntityFlags(FLAG_INTERPOLATION_UPDATE); player->Update(); player->PlayerCollideWithGrid(GRID_COLLISION_APPLY); player->ClearEntityFlags(FLAG_INTERPOLATION_UPDATE); } for (Entity_Player* player : g_game->playerManager.extraPlayers) { player->AddEntityFlags(FLAG_INTERPOLATION_UPDATE); player->Update(); player->ClearEntityFlags(FLAG_INTERPOLATION_UPDATE); } } // Sets the boss bar to the bosses' share of health left, against the most health they have had, flashing it on a // change. Without bosses the bar hides. void EntityList::boss_bar_update(const UpdateTally& tally) { HUD& hud = g_game->hud; float fill = BOSS_BAR_HIDDEN; if (tally.bosses < 1) { bossMaxHealth = 0; if (hud.bossHPBarFill > BOSS_BAR_HIDDEN) hud.bossHPBarDamageFlash = BOSS_BAR_FLASH_FRAMES; } else { bossMaxHealth = std::max(tally.bossMaxHealth, bossMaxHealth); fill = tally.bossHealth / bossMaxHealth; if (fill < hud.bossHPBarFill) hud.bossHPBarDamageFlash = BOSS_BAR_FLASH_FRAMES; } if (hud.bossHPBarFill < fill && hud.bossHPBarFill != BOSS_BAR_HIDDEN) { hud.bossHPBarDamageFlash = FLASH_OFF; hud.bossHPBarHealFlash = BOSS_BAR_FLASH_FRAMES; } hud.bossHPBarFill = fill; } // Drops the entities that stopped existing from every list, unlinking them, and frees a removed player. void EntityList::removed_drop() { auto isGone = [](Entity* entity) { return !entity->isExists; }; std::erase_if(updateEL, isGone); std::erase_if(renderEL, isGone); std::erase_if(wispEL, isGone); std::erase_if(mainEL, [](Entity* entity) { if (entity->isExists) return false; entity->ClearReferences(); entity->isValid = false; return true; }); std::erase_if(persistentEL, [](Entity* entity) { if (entity->isExists) return false; bool wasValid = entity->isValid; entity->ClearReferences(); entity->isValid = false; if (entity->type == ENTITY_PLAYER && wasValid) delete entity; return true; }); } // 00419e70 Sorts the colliding entities into the partitions, collides the partitions that touch, pushes twins apart, // then collides everything but lasers with the grid. void EntityList::rebuild_sublists() { effectEL.clear(); for (CellSpace& partition : partitions) partition.clear(); bool isShieldPresent = false; uint32_t indexCount = 0; for (Entity* entity : updateEL) { entity->isCollidesWithEntity = false; if (entity->entityCollisionClass == ENTCOLL_NONE) continue; int type = entity->type; bool isIndexed = true; if (type == ENTITY_FAMILIAR && entity->variant == FAMILIAR_CUBE_BABY) { partitions[PARTITION_ENEMIES].insert(*entity); partitions[PARTITION_ENEMY_TARGETS].insert(*entity); } else if (type == ENTITY_FAMILIAR) partitions[PARTITION_FAMILIARS].insert(*entity); else if (type == ENTITY_PROJECTILE) { uint64_t projectileFlags = static_cast(entity)->projectileFlags; partitions[PARTITION_PROJECTILES].insert(*entity); if (projectileFlags & PROJECTILE_SHIELDED) isShieldPresent = true; if (projectileFlags & PROJECTILE_HIT_ENEMIES) partitions[PARTITION_ENEMY_HITTERS].insert(*entity); } else if (type == ENTITY_TEAR || type == ENTITY_KNIFE) { bool isShieldTear = type == ENTITY_TEAR && static_cast(entity)->tearFlags[TEAR_SHIELDED]; if (isShieldTear) isShieldPresent = true; partitions[PARTITION_SHOTS].insert(*entity); } else if (Entity::is_enemy_type(type) || type == ENTITY_BOMB) { partitions[PARTITION_ENEMIES].insert(*entity); bool isRocketVariant = entity->variant == BOMB_ROCKET || entity->variant == BOMB_ROCKET_GIGA; bool isRocket = type == ENTITY_BOMB && isRocketVariant; bool isPickupTaker = type == ENTITY_ULTRA_GREED || type == ENTITY_BUMBINO || isRocket; if (isPickupTaker) partitions[PARTITION_PICKUP_TAKERS].insert(*entity); bool isTargetable = entity->IsFriendly() || type == ENTITY_POOP || type == ENTITY_FROZEN_ENEMY || entity->HasEntityFlags(FLAG_BAITED) || type == ENTITY_BLOOD_PUPPY || type == ENTITY_DARK_ESAU; if (isTargetable) partitions[PARTITION_ENEMY_TARGETS].insert(*entity); } else if (type == ENTITY_PICKUP || type == ENTITY_SLOT) partitions[PARTITION_PICKUPS].insert(*entity); else isIndexed = type == ENTITY_PLAYER; if (isIndexed) entity->collisionIndex = indexCount++; if (type == ENTITY_EFFECT) effectEL.push_back(entity); } collisionPairs.assign((size_t)indexCount * indexCount, false); collisionPairStride = (int)indexCount; std::vector& players = g_game->playerManager.playerList; bool isVersus = g_game->deathmatchManager.is_active(); auto playersCollide = [&players](CellSpace& partition) { for (Entity_Player* player : players) partition.collide_entity(*player); }; CellSpace& familiars = partitions[PARTITION_FAMILIARS]; CellSpace& shots = partitions[PARTITION_SHOTS]; CellSpace& enemies = partitions[PARTITION_ENEMIES]; CellSpace& projectiles = partitions[PARTITION_PROJECTILES]; CellSpace& pickups = partitions[PARTITION_PICKUPS]; if (isVersus) { familiars.collide(shots); shots.collide(shots); } familiars.collide(projectiles); familiars.collide(enemies); playersCollide(familiars); shots.collide(enemies); enemies.collide_self(); playersCollide(enemies); playersCollide(projectiles); playersCollide(pickups); if (isVersus) playersCollide(shots); pickups.collide_self(); pickups.collide(partitions[PARTITION_PICKUP_TAKERS]); partitions[PARTITION_ENEMY_HITTERS].collide(enemies); if (isShieldPresent) projectiles.collide(shots); partitions[PARTITION_ENEMY_TARGETS].collide(projectiles); partitions[PARTITION_ENEMY_TARGETS].collide(enemies); twins_push_apart(); for (Entity* entity : updateEL) { if (entity->type == ENTITY_LASER) continue; if (entity->type == ENTITY_PLAYER) entity->PlayerCollideWithGrid(GRID_COLLISION_APPLY); else entity->CollideWithGrid(GRID_COLLISION_APPLY); } } // Pushes each pair of twin players apart once, the order alternating every frame. void EntityList::twins_push_apart() { for (Entity_Player* player : g_game->playerManager.playerList) { Entity_Player* twin = static_cast(player->twinPlayer.get()); if (!twin) continue; if (twin->playerIndex != -1 && player->playerIndex > twin->playerIndex && twin != player) continue; bool isEvenFrame = (g_game->frameCount & 1) == 0; Entity_Player* first = isEvenFrame ? player : twin; Entity_Player* second = isEvenFrame ? twin : player; first->collide_with_entity(second); second->collide_with_entity(first); } } // 00419750 Puts the render list back in draw order: one pass moves the normal layer behind the rest, another the // door layer behind the background, then an insertion sort runs with a swap budget, its direction alternating every // frame. void EntityList::sort_by_render_z() { if (renderEL.empty()) return; std::vector depths(renderEL.size()); auto swap = [&](int a, int b) { std::swap(renderEL[a], renderEL[b]); std::swap(depths[a], depths[b]); }; int low = 0; int high = (int)renderEL.size() - 1; for (; low < high; high--) { depths[high] = (uint32_t)renderEL[high]->GetRenderZ(); if (depths[high] >= RENDER_Z_NORMAL_START) continue; for (; low < high; low++) { depths[low] = (uint32_t)renderEL[low]->GetRenderZ(); if (depths[low] < RENDER_Z_NORMAL_START) continue; swap(low, high); break; } } depths[low] = (uint32_t)renderEL[low]->GetRenderZ(); int count = (int)renderEL.size(); int doorHigh = count - 1 <= high ? high : high + 1; for (low = 0; low < doorHigh; doorHigh--) { if (depths[doorHigh] >= RENDER_Z_DOOR_START) continue; for (; low < doorHigh; low++) { if (depths[low] < RENDER_Z_DOOR_START) continue; swap(low, doorHigh); break; } } int budget = RENDER_SORT_SWAP_BUDGET; if ((g_game->frameCount & 1) == 0) { for (int i = 1; i < count && budget > 0; i++) { for (int j = i; j > 0 && depths[j - 1] > depths[j]; j--, budget--) swap(j, j - 1); } return; } for (int i = count - 1; i > 0 && budget > 0; i--) { for (int j = i; j < count && depths[j - 1] > depths[j]; j++, budget--) swap(j, j - 1); } } // 004199d0 Draws the render list from the cursor up to a depth, as the room's render pass asks: normally, or only // what shows above, through or mirrored in its water. void EntityList::render_up_to(uint32_t maxDepth, const Vector& offset) { for (; renderCursor < renderEL.size(); renderCursor++) { Entity* entity = renderEL[renderCursor]; if ((uint32_t)entity->GetRenderZ() >= maxDepth) return; if (renderMode == RENDER_SKIP) continue; if (renderMode >= RENDER_WATER_ABOVE && renderMode <= RENDER_WATER_REFLECT) reconstruction_missing("EntityList::render_up_to 004199d0: the water passes (get_water_splash_variant)"); entity->Render(offset); } } // 0041b570 Forgets the cached queries an entity of the type, variant and subtype now belongs to. void EntityList::invalidate_type_cache(int type, int variant, int subType) { typeCache.erase({type, variant, subType}); typeCache.erase({type, variant, -1}); typeCache.erase({type, -1, -1}); } // 0041b7b0 (0041b690) How many entities updating match the type, variant and subtype (negatives match any), spawned // by the spawner when one is given. With a spawner a type of 0 matches any too. int EntityList::CountEntities(Entity* spawner, int type, int variant, int subType) { return (int)std::count_if(updateEL.begin(), updateEL.end(), [&](Entity* entity) { bool isTypeMatch = entity->type == type || (spawner && type == 0); return isTypeMatch && (variant < 0 || entity->variant == variant) && (subType < 0 || entity->subtype == subType) && (!spawner || entity->spawnerEntity.get() == spawner); }); } // 00431640 Whether a sorted hit list holds the entity's hit index. bool EntityList::HitListContains(const std::vector& hitList, Entity& entity) { return std::binary_search(hitList.begin(), hitList.end(), entity.GetHitListIndex()); }