Files
isaac-port/src/entity_effect_ambient.cpp
T

2183 lines
94 KiB
C++

#include "entity_effect_ambient.h"
#include "data.h"
#include "deathmatch_manager.h"
#include "entity_tear.h"
#include "entity_list.h"
#include "entity_player.h"
#include "fx_layers.h"
#include "game.h"
#include "grid_entity.h"
#include "grid_entity_door.h"
#include "kage_graphics.h"
#include "npc_ai.h"
#include "room.h"
#include "room_config.h"
#include "room_descriptor.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdio>
#include <string>
#include <unordered_map>
#include "stb_image.h"
// The ambient and environment variants (Lua's EffectVariant).
enum AmbientVariant : int
{
EFFECT_BLOOD_EXPLOSION = 2,
EFFECT_BLOOD_SPLAT = 7,
EFFECT_TINY_BUG = 21,
EFFECT_TINY_FLY = 33,
EFFECT_WATER_DROPLET = 41,
EFFECT_BEETLE = 64,
EFFECT_EMBER_PARTICLE = 66,
EFFECT_WALL_BUG = 68,
EFFECT_ISAACS_CARPET = 74,
EFFECT_DICE_FLOOR = 76,
EFFECT_FALLING_EMBER = 87,
EFFECT_BROKEN_SHOVEL_SHADOW = 115,
EFFECT_SPAWNER = 120,
EFFECT_LIGHT = 121,
EFFECT_WATER_RIPPLE = 133,
EFFECT_RAIN_DROP = 135,
EFFECT_BACKDROP_DECORATION = 140,
EFFECT_DOOR_OUTLINE = 154,
EFFECT_TALL_LADDER = 156,
EFFECT_WISP = 65,
EFFECT_HEAVEN_LIGHT_DOOR = 39,
EFFECT_TADPOLE = 158,
EFFECT_LIL_GHOST = 159,
EFFECT_CREEP_RED = 22,
EFFECT_CREEP_GREEN = 23,
EFFECT_CREEP_YELLOW = 24,
EFFECT_CREEP_WHITE = 25,
EFFECT_CREEP_BLACK = 26,
EFFECT_PLAYER_CREEP_LEMON_MISHAP = 32,
EFFECT_PLAYER_CREEP_HOLYWATER = 37,
EFFECT_PLAYER_CREEP_WHITE = 44,
EFFECT_PLAYER_CREEP_BLACK = 45,
EFFECT_PLAYER_CREEP_RED = 46,
EFFECT_PLAYER_CREEP_GREEN = 53,
EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL = 54,
EFFECT_CREEP_BROWN = 56,
EFFECT_PLAYER_CREEP_LEMON_PARTY = 78,
EFFECT_PLAYER_CREEP_PUDDLE_MILK = 90,
EFFECT_PLAYER_CREEP_BLACKPOWDER = 92,
EFFECT_PENTAGRAM_BLACKPOWDER = 93,
EFFECT_CREEP_SLIPPERY_BROWN = 94,
EFFECT_CREEP_STATIC = 169,
EFFECT_PLAYER_CREEP_YELLOW = 204
};
// What an ambient variant runs: its part of Init, its frame and its draw. A missing one keeps the shared default.
struct AmbientBehaviour
{
int variant = -1;
void (*init)(Entity_Effect&) = nullptr;
EffectUpdateEnd (*update)(Entity_Effect&) = nullptr;
void (*render)(Entity_Effect&, const Vector&) = nullptr;
};
// An update that always goes on to Update's shared end.
template <void (*UPDATE)(Entity_Effect&)> EffectUpdateEnd finishing(Entity_Effect& effect)
{
UPDATE(effect);
return EFFECT_UPDATE_FINISH;
}
constexpr int STAGE_ID_CATHEDRAL = 15;
constexpr int BACKDROP_DROSS = 45;
constexpr int ROOM_BARREN_TYPE = 19;
constexpr int SOUND_DROPLET_SPLASH = 397;
constexpr int SOUND_SPAWNER_SUMMON = 265;
constexpr int DOOR_STATE_KEEPS_DECORATIONS = 7;
constexpr int RENDER_Z_DECORATION_LIMIT = 0x40000000;
constexpr float NEAR_PLAYER_RANGE_SQUARED = 10000;
constexpr float FULL_TURN = 360;
constexpr float HALF_TURN = 180;
constexpr float RIGHT_ANGLE = 90;
// The tiny fly: white in the Cathedral, how it wanders, flees the nearest player within range, dies to tears,
// knives and fires, and drops down in circles when dead.
constexpr int FLY_WANDER_ODDS = 5;
constexpr int FLY_JITTER_FRAMES = 5;
constexpr float FLY_FRICTION = 0.98f;
constexpr float FLY_DEAD_FRICTION = 0.8f;
constexpr float FLY_PULL = 0.5f;
constexpr float FLY_JITTER = 0.9f;
constexpr float FLY_FLEE_RANGE = 60;
constexpr float FLY_FLEE_PUSH = -0.2f;
constexpr float FLY_HIT_RADIUS = 0.5f;
constexpr float FLY_KNIFE_REACH = 1.5f;
constexpr float FLY_FIRE_REACH = 2;
constexpr float FLY_FALL_STEP = 0.25f;
constexpr float FLY_FALL_HEIGHT = 16;
constexpr float FLY_CIRCLE_SPEED = 15;
constexpr float FLY_CIRCLE_RADIUS = 3;
constexpr float FLY_CLAMP_MARGIN = 2;
constexpr float FLY_SPLAT_SCALE = 0.1f;
constexpr float FLY_BURST_SCALE = 0.3f;
constexpr float FLY_BURST_RISE = -16;
constexpr float MIN_DISTANCE = 0.01f;
// The crawling bugs: how they idle, run in bursts and turn, flee a player close by, stay off the walls and grid, and
// splat when stepped on or hit by a tear's splash.
constexpr int BUG_BURST_ODDS = 30;
constexpr int BUG_BURST_MIN = 15;
constexpr int BUG_BURST_SPAN = 120;
constexpr int BUG_STEP_ODDS = 5;
constexpr int BUG_FLEE_ODDS = 3;
constexpr int BUG_FLEE_MIN = 30;
constexpr int BUG_FLEE_SPAN = 100;
constexpr float BUG_FRICTION = 0.8f;
constexpr float BUG_STEP = 0.5f;
constexpr float BUG_FLEE_PUSH = 2;
constexpr float BUG_TURN_SPAN = 50;
constexpr float BUG_TURN_BACK = 25;
constexpr float BUG_ROOM_MARGIN = -2;
constexpr float BUG_CELL_EDGE = 20;
constexpr float BUG_STOPPED_SPEED = 0.1f;
constexpr float BUG_SQUASH_RANGE_SQUARED = 100;
constexpr float BUG_SPLASH_RANGE_SQUARED = 400;
constexpr float BUG_SPLAT_SCALE = 0.3f;
constexpr int WALL_BUG_RENDER_Z = 5000;
constexpr float WALL_BUG_START_SPAN = 10000;
constexpr float WALL_BUG_INSET_SPAN = 40;
constexpr float WALL_BUG_TURN_RATE = 0.2f;
constexpr float WALL_BUG_DOOR_STEP = 2;
// The walls a wall bug walks: its depth into them, clamped, and the outer and inner edges it lies between.
constexpr float WALL_DEPTH = 40;
constexpr float WALL_INSET_MIN = -10;
// The wisps' drift, their pull toward a moving player and back into the room, and their float.
constexpr float WISP_DRIFT_SPEED = 8;
constexpr float WISP_DRIFT_RATE_MIN = 0.01f;
constexpr float WISP_DRIFT_RATE_SPAN = 0.03f;
constexpr float WISP_WALL_MARGIN = 40;
constexpr float WISP_CENTER_PULL = 0.08f;
constexpr float WISP_FLOAT_HEIGHT = -50;
constexpr float WISP_FLOAT_RATE = 0.01f;
constexpr float WISP_SCALE_MIN = 0.5f;
constexpr float WISP_SCALE_SPAN = 0.5f;
// The stages whose wisps glow yellow (the Womb, Utero, Scarred Womb, the Dross' rooms, Mausoleum, Corpse and the
// Scarred Womb's alternate) and red (Sheol and Gehenna).
constexpr std::array<int, 7> WISP_YELLOW_STAGES = {10, 11, 12, 28, 30, 33, 34};
constexpr std::array<int, 2> WISP_RED_STAGES = {16, 31};
constexpr int WISP_ORANGE_STAGE = 32;
// The water droplets that fall from the ceiling and splash or stain where they land.
constexpr int DROPLET_KINDS = 3;
constexpr int STAGE_DEPTHS_2 = 6;
constexpr int STAGE_DEPTHS = 5;
constexpr int STAGE_WOMB = 7;
constexpr int STAGE_TYPE_AFTERBIRTH = 2;
constexpr float DROPLET_HEIGHT = -10;
constexpr float DROPLET_LANDED_HEIGHT = 10;
constexpr float DROPLET_GRAVITY = 1;
constexpr float DROPLET_FRICTION = 0.98f;
constexpr float DROPLET_FLOOR_OFFSET = 12;
// The embers: the particles fires shed, fading as they rise, and the ones falling from the Burning Basement's
// ceiling.
constexpr int EMBER_GLOWING_SUBTYPE = 10;
constexpr int EMBER_GLOW_MIN = 30;
constexpr int EMBER_GLOW_SPAN = 60;
constexpr int EMBER_MIN = 2;
constexpr int EMBER_SPAN = 30;
constexpr float EMBER_DRIFT_X = 0.4f;
constexpr float EMBER_DRIFT_Y = 0.1f;
constexpr float EMBER_FRICTION_X = 0.98f;
constexpr float EMBER_FRICTION_Y = 0.97f;
constexpr float FALLING_EMBER_FRICTION = 0.97f;
constexpr float FALLING_EMBER_FRICTION_SCALE = 0.03f;
constexpr float FALLING_EMBER_FALL = 0.15f;
constexpr float FALLING_EMBER_FALL_SPAN = 0.05f;
// The rain drops: the frame they splash on, and the ripple it leaves.
constexpr int RAIN_DROP_SPLASH_FRAME = 13;
constexpr int RAIN_DROP_KINDS = 4;
constexpr int RIPPLE_FROM_RAIN = 1;
// The lights: those of subtype 1 flicker.
constexpr int LIGHT_FLICKER = 1;
constexpr int LIGHT_TOGGLE_ODDS = 24;
constexpr int LIGHT_DIM_ODDS = 100;
constexpr float LIGHT_ALPHA_MIN = 0.6f;
constexpr float LIGHT_ALPHA_SPAN = 0.6f;
// The pieces of the floor rooms place: the broken carpet, the dice floor's faces and the ladder's step distance.
constexpr int CARPET_BROKEN = 1000;
constexpr int DICE_FACE_LAST = 5;
constexpr int DICE_ARM_FRAMES = 15;
constexpr float DICE_REACH = 75;
constexpr int SHOVEL_SHADOW_RENDER_Z = 10000;
constexpr int LADDER_ARM_FRAMES = 5;
constexpr float LADDER_NEAR = 50;
constexpr float LADDER_CLIMB = 21;
template <size_t N>
static bool is_listed(const std::array<int, N>& list, int value)
{
return std::find(list.begin(), list.end(), value) != list.end();
}
// normalize_angle_degrees 00682740: an angle brought into -180 to 180.
static float angle_normalized(float angle)
{
if (std::abs(angle) > FULL_TURN) angle = std::fmod(angle, FULL_TURN);
if (angle > HALF_TURN) return angle - FULL_TURN;
if (angle < -HALF_TURN) angle += FULL_TURN;
return angle;
}
// Vector::Lerp a10210: moves a vector t of the way to a target.
static void vector_lerp(Vector& v, Vector target, float t)
{
v.x = (target.x - v.x) * t + v.x;
v.y = (target.y - v.y) * t + v.y;
}
static float distance_squared(Vector a, Vector b)
{
return vector_length_squared(vector_sub(a, b));
}
// Game::GetNearestPlayer 00703950: the player nearest a position, the first one on a tie.
static Entity_Player* nearest_player_get(Vector position)
{
Entity_Player* nearest = nullptr;
float nearestDistance = 0;
for (Entity_Player* player : g_game->playerManager.playerList)
{
float distance = distance_squared(position, player->pos);
if (nearest && distance >= nearestDistance) continue;
nearest = player;
nearestDistance = distance;
}
return nearest;
}
// Room::GetGridCollisionAtPos 007f0780 and Room::GetGridEntityFromPos 00456620.
static int grid_collision_at(Vector position)
{
Room& room = *g_game->room;
return (int)room.GetGridCollision(room.GetGridIndex(position));
}
static GridEntity* grid_entity_at(Vector position)
{
Room& room = *g_game->room;
return room.GetGridEntity((uint32_t)room.GetGridIndex(position));
}
// What EntityList::QueryRadius 0041a790 looks through: Lua's EntityPartition bits.
enum QueryMask : uint32_t
{
QUERY_FAMILIARS = 1 << 0,
QUERY_PROJECTILES = 1 << 1,
QUERY_TEARS = 1 << 2,
QUERY_ENEMIES = 1 << 3,
QUERY_PICKUPS = 1 << 4,
QUERY_PLAYERS = 1 << 5
};
// The entities of the masked partitions (and the players) touching a position within a radius, in the original's
// partition order, those in their interpolation update left out.
static EntityList_EL entities_near(Vector position, float radius, uint32_t mask)
{
constexpr std::array<std::pair<uint32_t, Partition>, 5> PARTITIONS = {{{QUERY_FAMILIARS, PARTITION_FAMILIARS},
{QUERY_TEARS, PARTITION_SHOTS},
{QUERY_ENEMIES, PARTITION_ENEMIES},
{QUERY_PROJECTILES, PARTITION_PROJECTILES},
{QUERY_PICKUPS, PARTITION_PICKUPS}}};
EntityList& entities = g_game->room->entityList;
EntityList_EL found;
for (auto [bit, partition] : PARTITIONS)
if (mask & bit) entities.partitions[partition].query_box(found, position, vector_make(radius, radius));
if (mask & QUERY_PLAYERS)
for (Entity_Player* player : g_game->playerManager.playerList) found.push_back(player);
std::erase_if(found, [&](Entity* entity) {
float reach = radius + entity->size;
return entity->HasEntityFlags(FLAG_INTERPOLATION_UPDATE) ||
distance_squared(entity->pos, position) >= reach * reach;
});
return found;
}
// Sets a layer to draw additively (BlendMode::SetMode 2).
static void layer_additive_set(LayerState& layer)
{
KAGE::Graphics::BlendMode mode;
mode.SetMode(KAGE::Graphics::BLEND_ADDITIVE);
layer.blendMode = {mode.equation, mode.rgbSource, mode.rgbDest, mode.alphaSource, mode.alphaDest};
}
// A color tinted, with no colorize or offset (Color::Reset and SetTint).
static ColorMod tint_make(float red, float green, float blue, float alpha)
{
return {{red, green, blue, alpha}, {0, 0, 0, 0}, {0, 0, 0}};
}
// Spawns a blood splat of a bug's blood color where it died, at a scale, onto the floor or the wall.
static void bug_splat(Entity_Effect& bug, uint64_t addedFlags)
{
Entity* splat = g_game->Spawn({.position = bug.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT,
.seed = Random()});
splat->SetColor(bug.splatColor, -1, 255, false, true);
static_cast<Entity_Effect*>(splat)->scale = BUG_SPLAT_SCALE;
splat->AddEntityFlags(addedFlags);
splat->Update();
bug.Remove();
}
// Pushes a crawler back to the edge of the grid cell at a point, along the side it entered from, stopping it there.
static void cell_push_out(Entity_Effect& crawler, Vector point)
{
Room& room = *g_game->room;
Vector cell = room.GetGridPosition(room.GetGridIndex(point));
Vector toCell = vector_sub(cell, crawler.pos);
if (std::abs(toCell.x) <= std::abs(toCell.y))
{
crawler.pos.y = toCell.y <= 0 ? cell.y + BUG_CELL_EDGE : cell.y - BUG_CELL_EDGE;
crawler.velocity.y *= BUG_STOPPED_SPEED;
}
else
{
crawler.pos.x = toCell.x <= 0 ? cell.x + BUG_CELL_EDGE : cell.x - BUG_CELL_EDGE;
crawler.velocity.x *= BUG_STOPPED_SPEED;
}
}
// The crawlers and flies: light, colliding with everything, uncolored in the Dross.
static void critter_init(Entity_Effect& effect)
{
effect.mass = 1;
effect.entityCollisionClass = ENTCOLL_ALL;
effect.isUnknown176 = true;
if (g_game->room->backdropType == BACKDROP_DROSS) effect.sprite.color = COLOR_DEFAULT;
}
// A tiny bug crawls on the floor among the door layer's sprites.
static void tiny_bug_init(Entity_Effect& effect)
{
effect.sortingLayer = SORTING_DOOR;
critter_init(effect);
}
// A tiny fly is white in the Cathedral.
static void tiny_fly_init(Entity_Effect& effect)
{
if (RoomConfig::GetStageID((int)g_game->stage, (int)g_game->stageType, (RoomMode)-1) == STAGE_ID_CATHEDRAL)
effect.sprite.Play("White");
critter_init(effect);
}
// A wall bug starts somewhere along the walls (its target position holds its depth and its distance along them) and
// draws over the floor.
static void wall_bug_init(Entity_Effect& effect)
{
effect.sortingLayer = SORTING_BACKGROUND;
effect.renderZOffset = WALL_BUG_RENDER_Z;
float along = random_unit() * WALL_BUG_START_SPAN;
effect.targetPosition = vector_make(random_unit() * WALL_BUG_INSET_SPAN, along);
critter_init(effect);
}
// A tiny bug's frame: it idles or runs in bursts along its heading, which wobbles, flees a player close by, and is
// pushed out of the grid cells it walks into. It splats when a player walks over it or a tear splashes on it.
static void tiny_bug_update(Entity_Effect& bug)
{
Room& room = *g_game->room;
bug.friction *= BUG_FRICTION;
if (bug.state < 1)
{
if (random_below(BUG_BURST_ODDS) == 0) bug.state = random_below(BUG_BURST_SPAN) + BUG_BURST_MIN;
else if (random_below(BUG_STEP_ODDS) == 0)
bug.AddVelocity_divided(vector_scale(vector_from_angle(bug.rotation), random_unit() * BUG_STEP), false);
}
else
{
Vector heading = vector_from_angle(bug.rotation);
bug.AddVelocity_divided(vector_scale(heading, random_unit() * BUG_STEP + BUG_STEP), false);
bug.state--;
}
Entity_Player* player = nearest_player_get(bug.pos);
float playerDistance = distance_squared(bug.pos, player->pos);
if (playerDistance < NEAR_PLAYER_RANGE_SQUARED && random_below(BUG_FLEE_ODDS) == 0)
{
float push = (1 - playerDistance / NEAR_PLAYER_RANGE_SQUARED) * BUG_FLEE_PUSH;
bug.AddVelocity_divided(vector_scale(vector_normalized(vector_sub(bug.pos, player->pos)), push), false);
bug.state = random_below(BUG_FLEE_SPAN) + BUG_FLEE_MIN;
}
bug.rotation = angle_normalized(random_unit() * BUG_TURN_SPAN + bug.rotation - BUG_TURN_BACK);
bug.pos = room.GetClampedPosition(bug.pos, BUG_ROOM_MARGIN);
if (grid_collision_at(bug.pos) != COLLISION_NONE)
{
GridEntity* grid = grid_entity_at(bug.pos);
cell_push_out(bug, bug.pos);
if (grid && grid->type == GRID_PIT && grid_collision_at(bug.pos) != COLLISION_NONE)
{
bug.pos = bug.targetPosition;
bug.rotation = angle_normalized(random_unit() * FULL_TURN);
if (grid_collision_at(bug.pos) == COLLISION_PIT) bug.pos = vector_add(bug.pos, random_direction());
}
}
bug.targetPosition = bug.pos;
if (bug.isDead) bug_splat(bug, 0);
if (playerDistance < BUG_SQUASH_RANGE_SQUARED && vector_length_squared(player->velocity) > 1 && !player->IsFlying())
bug.isDead = true;
for (Entity* tear : entities_near(bug.pos, 1, QUERY_TEARS))
if (tear->type == ENTITY_TEAR && tear->isDead && distance_squared(tear->pos, bug.pos) < BUG_SPLASH_RANGE_SQUARED)
bug.isDead = true;
}
// room_perimeter_to_position 0060ac70: the point a wall bug stands on from its depth into the walls (clamped) and
// its distance along them (wrapped), both written back. The walk runs up the left wall, along the top, down the
// right and back along the bottom.
static Vector wall_position_get(Vector& walk)
{
Room& room = *g_game->room;
Vector topLeft = room.topLeftPos;
Vector bottomRight = room.bottomRightPos;
walk.x = std::min(std::max(walk.x, WALL_INSET_MIN), WALL_DEPTH);
float width = bottomRight.x - topLeft.x;
float height = bottomRight.y - topLeft.y;
float perimeter = width + width + height + height;
walk.y = std::fmod(walk.y, perimeter);
if (walk.y < 0) walk.y += perimeter;
// The corners of the walk at its depth, each between the outer edge of the walls and the floor's.
float depth = walk.x / WALL_DEPTH;
auto inset = [depth](float outer, float inner) { return (inner - outer) * depth + outer; };
float left = inset(topLeft.x - WALL_DEPTH, topLeft.x);
float right = inset(bottomRight.x + WALL_DEPTH, bottomRight.x);
float top = inset(topLeft.y - WALL_DEPTH, topLeft.y);
float bottom = inset(bottomRight.y + WALL_DEPTH, bottomRight.y);
Vector from = vector_make(left, bottom);
Vector to = vector_make(left, top);
float along = walk.y / height;
if (walk.y >= width + height + height)
{
from = vector_make(right, bottom);
to = vector_make(left, bottom);
along = (walk.y - (height + height + width)) / width;
}
else if (walk.y >= width + height)
{
from = vector_make(right, top);
to = vector_make(right, bottom);
along = (walk.y - (width + height)) / height;
}
else if (walk.y >= height)
{
from = vector_make(left, top);
to = vector_make(right, top);
along = (walk.y - height) / width;
}
return vector_make((to.x - from.x) * along + from.x, (to.y - from.y) * along + from.y);
}
// A wall bug's frame: it idles or runs in bursts along the walls with a wobbling heading, turns back from the floor's
// edge and from doors, and splats onto the wall when a tear splashes on it.
static void wall_bug_update(Entity_Effect& bug)
{
bug.velocity = {};
Vector previous = bug.targetPosition;
bug.rotation = angle_normalized(random_unit() * BUG_TURN_SPAN + bug.rotation - BUG_TURN_BACK);
if (bug.state < 1)
{
if (random_below(BUG_BURST_ODDS) == 0) bug.state = random_below(BUG_BURST_SPAN) + BUG_BURST_MIN;
else if (random_below(BUG_STEP_ODDS) == 0)
bug.targetPosition = vector_add(bug.targetPosition, vector_scale(vector_from_angle(bug.rotation), random_unit()));
}
else
{
Vector heading = vector_from_angle(bug.rotation);
bug.targetPosition = vector_add(bug.targetPosition, vector_scale(heading, random_unit() + 1));
bug.state--;
}
float depth = bug.targetPosition.x;
bug.pos = wall_position_get(bug.targetPosition);
if (depth != bug.targetPosition.x)
{
float turn = (depth <= 0) == (bug.rotation <= 0) ? RIGHT_ANGLE : -RIGHT_ANGLE;
bug.rotation = angle_lerp(bug.rotation, bug.rotation + turn, WALL_BUG_TURN_RATE);
}
if (grid_collision_at(bug.pos) == COLLISION_WALL_EXCEPT_PLAYER)
{
bool isTurnLeft = bug.targetPosition.y <= previous.y ? bug.rotation >= -RIGHT_ANGLE : bug.rotation <= RIGHT_ANGLE;
float turn = isTurnLeft ? -RIGHT_ANGLE : RIGHT_ANGLE;
bug.rotation = angle_lerp(bug.rotation, bug.rotation + turn, WALL_BUG_TURN_RATE);
bug.targetPosition = previous;
bug.pos = wall_position_get(bug.targetPosition);
}
if (grid_collision_at(bug.pos) == COLLISION_WALL_EXCEPT_PLAYER) bug.targetPosition.y += WALL_BUG_DOOR_STEP;
if (bug.isDead) bug_splat(bug, FLAG_RENDER_WALL);
for (Entity* tear : entities_near(bug.pos, 1, QUERY_TEARS))
{
if (tear->type != ENTITY_TEAR || !tear->isDead) continue;
bug.isDead = true;
break;
}
}
// Bursts the fly into a small splash of its blood color.
static void tiny_fly_burst(Entity_Effect& fly)
{
fly.isDead = true;
Entity* burst = g_game->Spawn({.position = vector_make(fly.pos.x, fly.pos.y + FLY_BURST_RISE),
.type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()});
burst->SetColor(fly.splatColor, -1, 255, false, true);
burst->sprite.scale = vector_make(FLY_BURST_SCALE, FLY_BURST_SCALE);
burst->Update();
fly.sprite.Stop();
}
// Whether an entity stands within reach of a position.
static bool is_within_reach(Entity& entity, Vector position, float reach)
{
return distance_squared(entity.pos, position) < reach * reach;
}
// A tiny fly's frame: alive it drifts at random, now and then toward its parent or the nearest player, and away
// from a player close by, and bursts on a tear, knife or fire. Dead, it spirals down and splats. It faces its motion
// and stays in the room.
static void tiny_fly_update(Entity_Effect& fly)
{
Entity_Player* player = nearest_player_get(fly.pos);
Vector toPlayer = vector_sub(player->pos, fly.pos);
float distance = vector_length(toPlayer);
Vector direction = vector_scale(toPlayer, 1 / (distance == 0 ? MIN_DISTANCE : distance));
EntityList& entities = g_game->room->entityList;
fly.friction *= FLY_FRICTION;
if (fly.isDead)
{
LayerState& layer = *fly.sprite.GetLayer(0);
if (layer.pos.y <= FLY_FALL_HEIGHT)
{
layer.pos.y += FLY_FALL_STEP;
float side = (float)(fly.index % 2) * 2 - 1;
float angle = (float)g_game->frameCount * FLY_CIRCLE_SPEED * side * DEGREES_TO_RADIANS;
Vector circle = vector_make(std::cos(angle), std::sin(angle));
circle = vector_scale(vector_scale(circle, std::abs(layer.pos.y) / FLY_FALL_HEIGHT), FLY_CIRCLE_RADIUS);
fly.pos = vector_add(fly.pos, circle);
fly.friction *= FLY_DEAD_FRICTION;
}
else
{
Entity* splat = g_game->Spawn({.position = fly.pos, .type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_SPLAT,
.seed = Random()});
splat->SetColor(fly.splatColor, -1, 255, false, true);
splat->sprite.scale = vector_make(FLY_SPLAT_SCALE, FLY_SPLAT_SCALE);
splat->Update();
fly.Remove();
}
}
if (!fly.isDead)
{
if (Random() % FLY_WANDER_ODDS == 0)
{
Vector pull = direction;
if (fly.parent)
{
Vector toParent = vector_sub(fly.parent->pos, fly.pos);
float length = vector_length(toParent);
if (length > 0) toParent = vector_scale(toParent, (length - fly.parent->size) / length);
float resized = vector_length(toParent);
pull = resized > 0 ? vector_scale(toParent, 1 / resized) : toParent;
}
fly.AddVelocity_divided(vector_scale(pull, random_unit() * FLY_PULL), false);
}
if (fly.IsFrame(FLY_JITTER_FRAMES, (int)fly.index))
{
float angle = random_unit() * RANDOM_HALF_TURN * 2;
Vector jitter = vector_make(std::cos(angle), std::sin(angle));
fly.AddVelocity_divided(vector_scale(jitter, random_unit() * FLY_JITTER), false);
}
if (distance < FLY_FLEE_RANGE)
{
float push = (1 - distance * distance / (FLY_FLEE_RANGE * FLY_FLEE_RANGE)) * FLY_FLEE_PUSH;
fly.AddVelocity_divided(vector_scale(direction, push), false);
}
EntityList_EL shots;
entities.partitions[PARTITION_SHOTS].query_box(shots, fly.pos, vector_make(FLY_HIT_RADIUS, FLY_HIT_RADIUS));
bool isShot = std::any_of(shots.begin(), shots.end(), [&fly](Entity* shot) {
return !shot->HasEntityFlags(FLAG_INTERPOLATION_UPDATE) && shot->type == ENTITY_TEAR &&
is_within_reach(*shot, fly.pos, FLY_HIT_RADIUS + shot->size);
});
if (isShot) tiny_fly_burst(fly);
std::vector<Entity*> hazards(entities.updateEL);
for (Entity* hazard : hazards)
{
bool isKnife = hazard->type == ENTITY_KNIFE && is_within_reach(*hazard, fly.pos, hazard->size * FLY_KNIFE_REACH);
bool isFire = hazard->type == ENTITY_FIREPLACE && is_within_reach(*hazard, fly.pos, hazard->size + FLY_FIRE_REACH);
if (isKnife || isFire) tiny_fly_burst(fly);
}
}
fly.sprite.isFlipX = fly.pos.x - fly.targetPosition.x < 0;
fly.pos = g_game->room->GetClampedPosition(fly.pos, FLY_CLAMP_MARGIN);
fly.targetPosition = fly.pos;
}
// A wisp's glow by the stage: yellow in the wombs, red in Sheol and Gehenna, orange in the Mines and blue elsewhere,
// at a random height and size, drawn additively. Its blood color matches.
static void wisp_init(Entity_Effect& wisp)
{
int stageId = g_game->GetStageID();
ColorMod splat = COLOR_DEFAULT;
if (is_listed(WISP_YELLOW_STAGES, stageId))
{
wisp.sprite.Play("White");
wisp.sprite.color = tint_make(1, 0.8f, 0, 1);
splat = tint_make(1, 1, 0.5f, 1);
}
else if (is_listed(WISP_RED_STAGES, stageId))
{
wisp.sprite.Play("Red");
splat = tint_make(1, 0.5f, 0.5f, 1);
}
else if (stageId == WISP_ORANGE_STAGE)
{
wisp.sprite.Play("White");
wisp.sprite.color = tint_make(1, 0.02f, 0, 1);
}
else wisp.sprite.Play("Blue");
wisp.splatColor = splat;
wisp.posOffset.y = random_unit() * WISP_FLOAT_HEIGHT;
float size = random_unit() * WISP_SCALE_SPAN + WISP_SCALE_MIN;
wisp.sprite.scale = vector_make(size, size);
layer_additive_set(*wisp.sprite.GetLayer(0));
}
// A wisp's frame: it drifts at random, follows a moving player close by, keeps away from the walls and floats at a
// wandering height.
static void wisp_update(Entity_Effect& wisp)
{
Room& room = *g_game->room;
wisp.pos = room.GetClampedPosition(wisp.pos, 0);
float driftRate = random_unit() * WISP_DRIFT_RATE_SPAN + WISP_DRIFT_RATE_MIN;
Vector drift = random_direction();
vector_lerp(wisp.velocity, vector_scale(drift, random_unit() * WISP_DRIFT_SPEED), driftRate);
Entity_Player* player = nearest_player_get(wisp.pos);
float playerDistance = distance_squared(player->pos, wisp.pos);
if (playerDistance < NEAR_PLAYER_RANGE_SQUARED && vector_length_squared(player->velocity) > 1)
{
float closeness = 1 - playerDistance / NEAR_PLAYER_RANGE_SQUARED;
vector_lerp(wisp.velocity, player->velocity, (random_unit() * WISP_DRIFT_RATE_SPAN + WISP_DRIFT_RATE_MIN) * closeness);
}
Vector inside = room.GetClampedPosition(wisp.pos, WISP_WALL_MARGIN);
if (wisp.pos.x != inside.x || wisp.pos.y != inside.y)
vector_lerp(wisp.velocity, vector_normalized(vector_sub(Room::GetCenterPos(), wisp.pos)), WISP_CENTER_PULL);
float height = random_unit() * WISP_FLOAT_HEIGHT;
wisp.posOffset.y = (height - wisp.posOffset.y) * WISP_FLOAT_RATE + wisp.posOffset.y;
}
// A water droplet: dank in the Dank Depths, bloody from the Womb on, large and sized at random or small.
static void water_droplet_init(Entity_Effect& drop)
{
int stage = (int)g_game->stage;
if ((stage == STAGE_DEPTHS || stage == STAGE_DEPTHS_2) && (int)g_game->stageType == STAGE_TYPE_AFTERBIRTH)
drop.sprite.ReplaceSpritesheet(0, "gfx/Effects/Effect_DankDroplets.png");
else if (stage >= STAGE_WOMB) drop.sprite.ReplaceSpritesheet(0, "gfx/Effects/Effect_BloodDroplets.png");
drop.state = (int)(Random() % DROPLET_KINDS);
if (drop.state == 0)
{
drop.sprite.Play("LargeDrop");
float size = random_unit() * 0.5f + 0.5f;
drop.sprite.scale = vector_make(size, size);
}
else drop.sprite.Play("SmallDrop");
drop.height = DROPLET_HEIGHT;
drop.sprite.isFlipX = !(Random() & 1);
}
// The floor under a droplet falling in a crawlspace: the cell above the first solid one below the first open cell of
// its column. It is gone when the column has none.
static bool droplet_floor_find(Entity_Effect& drop)
{
Room& room = *g_game->room;
int column = room.GetGridIndex(drop.targetPosition) % room.gridWidth;
int row = 0;
while (row < room.gridHeight && room.GetGridCollision(room.GetGridIndexByTile(column, row)) != COLLISION_NONE) row++;
if (row >= room.gridHeight) return false;
while (row < room.gridHeight && room.GetGridCollision(room.GetGridIndexByTile(column, row)) == COLLISION_NONE) row++;
drop.targetPosition.y = room.GetGridPosition(room.GetGridIndexByTile(column, row - 1)).y + DROPLET_FLOOR_OFFSET;
return true;
}
// A droplet's frame: it picks a random floor height under it, falls there, then splashes in water or stains the
// floor, and goes once that plays out.
static EffectUpdateEnd water_droplet_update(Entity_Effect& drop)
{
Room& room = *g_game->room;
if (drop.FrameCount() == 0)
{
float floor = random_unit() * (room.bottomRightPos.y - room.topLeftPos.y) + room.topLeftPos.y;
drop.targetPosition = vector_make(drop.pos.x, floor);
if (room.roomType == ROOM_DUNGEON && !droplet_floor_find(drop))
{
drop.Remove();
return EFFECT_UPDATE_RETURN;
}
}
if (drop.height >= 0)
{
drop.pos = drop.targetPosition;
drop.velocity = {};
if (drop.sprite.IsFinished()) drop.Remove();
return EFFECT_UPDATE_FINISH;
}
drop.velocity.y += DROPLET_GRAVITY;
drop.velocity.x = 0;
drop.friction *= DROPLET_FRICTION;
if (drop.pos.y + drop.velocity.y <= drop.targetPosition.y) return EFFECT_UPDATE_FINISH;
drop.pos = drop.targetPosition;
drop.height = DROPLET_LANDED_HEIGHT;
if (!room.HasWater()) drop.sprite.Play(drop.state == 0 ? "Spot1" : "Spot2");
else
{
drop.sprite.Play("Splash");
drop.sprite.isFlipY = false;
float pitch = random_unit() * 0.5f + 1;
float volume = random_unit() * 0.5f + 0.5f;
npc_sound_play(SOUND_DROPLET_SPLASH, volume, 2, pitch);
}
drop.velocity = {};
drop.sortingLayer = SORTING_BACKGROUND;
drop.sprite.isFlipX = random_below(2) == 0;
drop.sprite.isFlipY = random_below(2) == 0;
return EFFECT_UPDATE_FINISH;
}
// An ember's frame: it picks its life on the first (glowing embers live longer and draw additively), drifts up and
// sideways, slows, and plays its animation through as it burns out.
static void ember_particle_update(Entity_Effect& ember)
{
if (ember.state == 0)
{
if (ember.subtype == EMBER_GLOWING_SUBTYPE)
{
ember.state = random_below(EMBER_GLOW_SPAN) + EMBER_GLOW_MIN;
layer_additive_set(*ember.sprite.GetLayer(0));
}
else ember.state = random_below(EMBER_SPAN) + EMBER_MIN;
ember.timeout = ember.state - 1;
}
float driftY = random_unit() * EMBER_DRIFT_Y - EMBER_DRIFT_Y / 2;
float driftX = random_unit() * EMBER_DRIFT_X - EMBER_DRIFT_X / 2;
ember.velocity = vector_add(ember.velocity, vector_make(driftX, driftY));
ember.velocity = vector_make(ember.velocity.x * EMBER_FRICTION_X, ember.velocity.y * EMBER_FRICTION_Y);
float burnt = (float)ember.timeout / (float)ember.state;
ember.sprite.SetFrame((float)(int)((float)ember.sprite.animState.GetAnimationLength() * burnt));
if (ember.isDead) ember.Remove();
}
// A falling ember glows additively at a random size.
static void falling_ember_init(Entity_Effect& ember)
{
layer_additive_set(*ember.sprite.GetLayer(0));
float size = ember.dropRNG.RandomFloat() * 0.5f + 0.5f;
ember.sprite.scale = vector_make(size, size);
}
// A falling ember's frame: it picks a floor height on its first, then flutters down to it, the larger ones slower.
static void falling_ember_update(Entity_Effect& ember)
{
Room& room = *g_game->room;
if (ember.FrameCount() == 0)
{
float floor = random_unit() * (room.bottomRightPos.y - room.topLeftPos.y) + room.topLeftPos.y;
ember.targetPosition = vector_make(ember.pos.x, floor);
}
ember.velocity.x += random_unit() - 0.5f;
ember.friction *= FALLING_EMBER_FRICTION - ember.sprite.scale.x * FALLING_EMBER_FRICTION_SCALE;
ember.velocity.y += FALLING_EMBER_FALL - random_unit() * FALLING_EMBER_FALL_SPAN;
if (ember.pos.y > ember.targetPosition.y) ember.Remove();
}
// A rain drop: one of four, partway through when the room has just loaded, tinted like the room's water.
static void rain_drop_init(Entity_Effect& drop)
{
drop.sprite.Play("Drop0" + std::to_string(random_below(RAIN_DROP_KINDS) + 1));
if (g_game->room->GetFrameCount() == 0) drop.sprite.SetFrame((float)random_below(drop.sprite.animState.GetAnimationLength()));
drop.sprite.color = g_game->room->fxLayers.fxParams.waterEffectColor;
}
// A rain drop's frame: it leaves a ripple of its color when it lands and goes when its animation ends.
static void rain_drop_update(Entity_Effect& drop)
{
if (drop.sprite.IsFinished()) drop.Remove();
if (drop.sprite.GetFrame() != RAIN_DROP_SPLASH_FRAME) return;
Entity* ripple = g_game->Spawn({.position = drop.pos, .subType = RIPPLE_FROM_RAIN, .type = ENTITY_EFFECT,
.variant = EFFECT_WATER_RIPPLE, .seed = Random()});
ripple->sprite.color = drop.sprite.color;
}
// A ripple turns with its rotation and goes once its animation ends, as the poofs Update shares its case with do.
static void water_ripple_update(Entity_Effect& ripple)
{
ripple.sprite.rotation = ripple.sprite.isFlipX ? ripple.rotation : -ripple.rotation;
if (ripple.sprite.IsFinished()) ripple.Remove();
}
// Isaac's carpet lies on the floor touching only the players, torn in a barren room.
static void carpet_init(Entity_Effect& carpet)
{
carpet.sortingLayer = SORTING_BACKGROUND;
carpet.entityGridCollisionClass = GRIDCOLL_WALLS;
carpet.entityCollisionClass = ENTCOLL_PLAYERONLY;
if (g_game->room->roomType == ROOM_BARREN_TYPE) carpet.sprite.ReplaceSpritesheet(0, "gfx/Effects/IsaacCarpet_Barren.png");
}
// A carpet of subtype 1000 shows torn.
static void carpet_update(Entity_Effect& carpet)
{
if (carpet.subtype == CARPET_BROKEN) carpet.sprite.Play("Broken");
}
// The dice room's floor shows its face, 1 to 6 by subtype, on the floor.
static void dice_floor_init(Entity_Effect& floor)
{
floor.sprite.Play(std::to_string(std::min(floor.subtype, DICE_FACE_LAST) + 1));
floor.sortingLayer = SORTING_BACKGROUND;
}
// The dice floor's frame: once armed, the first player standing on it rolls its face's dice, once per room.
static void dice_floor_update(Entity_Effect& floor)
{
if (g_game->room->IsSacrificeDone() || floor.FrameCount() <= DICE_ARM_FRAMES) return;
for (Entity_Player* player : g_game->playerManager.playerList)
{
if (player->variant != 0 || player->isCoopGhost || player->entityCollisionClass == ENTCOLL_NONE) continue;
Vector offset = vector_sub(player->pos, floor.pos);
if (std::abs(offset.x) >= DICE_REACH || std::abs(offset.y) >= DICE_REACH) continue;
reconstruction_missing("Entity_Effect::Update 005d4380: the dice floor's roll (Game::Darken, ShakeScreen, "
"the D4, D6, D20 and D100)");
}
}
// The Broken Shovel's shadow draws over everything, until it falls.
static void shovel_shadow_init(Entity_Effect& shadow)
{
shadow.sprite.Play("Idle");
shadow.renderZOffset = SHOVEL_SHADOW_RENDER_Z;
shadow.state = 0;
shadow.AddEntityFlags(FLAG_DONT_OVERWRITE);
}
static void shovel_shadow_update(Entity_Effect& shadow)
{
if (shadow.state != 0) shadow.sprite.Play("Fall");
}
// A spawner holds an entity back (its type the subtype, its variant and subtype the extra data) unseen until it is
// killed.
static void spawner_init(Entity_Effect& spawner)
{
spawner.isVisible = false;
spawner.varData[0] = 0;
spawner.varData[1] = 0;
spawner.state = -1;
spawner.AddEntityFlags(FLAG_DONT_OVERWRITE);
}
// A killed spawner lets its entity out, an enemy as an ambush with the summon sound. When it brings enemies into a
// room that had none, the doors close and the room is no longer clear, losing its reward if it was.
static void spawner_update(Entity_Effect& spawner)
{
if (!spawner.isDead) return;
Room& room = *g_game->room;
int enemiesBefore = room.GetAliveEnemiesCount();
Entity* entity = g_game->Spawn({.position = spawner.pos, .subType = (int)spawner.varData[1], .type = spawner.subtype,
.variant = (int)spawner.varData[0], .seed = spawner.initSeed});
if (entity->IsEnemy())
{
npc_sound_play(SOUND_SPAWNER_SUMMON, 1, 2, 1);
entity->AddEntityFlags(FLAG_AMBUSH);
}
entity->Update();
spawner.Remove();
if (enemiesBefore != 0 || room.GetAliveEnemiesCount() <= 0) return;
for (int slot = 0; slot < DOOR_SLOT_COUNT; slot++)
if (GridEntity_Door* door = room.GetDoor(slot)) door->Close(false);
uint32_t& flags = room.descriptor->flags;
if (flags & ROOM_DESCRIPTOR_FLAG_CLEAR) flags |= ROOM_DESCRIPTOR_FLAG_NO_REWARD;
flags &= ~ROOM_DESCRIPTOR_FLAG_CLEAR;
}
// The pieces the room keeps through overwrites: lights, decorations, door outlines and ladders.
static void kept_init(Entity_Effect& effect)
{
effect.AddEntityFlags(FLAG_DONT_OVERWRITE);
}
// A light starts dark on its default frame. Lighting draws it, never its own Render.
static void light_init(Entity_Effect& light)
{
light.AddEntityFlags(FLAG_DONT_OVERWRITE);
light.scale = 0;
light.sprite.SetFrame("Default", 0);
}
// A backdrop detail on the wall in front of a door is gone (the door's state 7 keeps it).
static bool backdrop_detail_cleared(Entity_Effect& effect)
{
if (!effect.HasEntityFlags(FLAG_BACKDROP_DETAIL) || effect.renderZOffset >= RENDER_Z_DECORATION_LIMIT) return false;
GridEntity* grid = grid_entity_at(effect.pos);
if (!grid || grid->type != GRID_DOOR || grid->state == DOOR_STATE_KEEPS_DECORATIONS) return false;
effect.Remove();
return true;
}
// A light's frame: off a door's wall, flickering for subtype 1 while lit, fading out over its timeout's last
// stretch, gone when dead. A light that lost the parent it followed starts fading in Update's shared part.
static EffectUpdateEnd light_update(Entity_Effect& light)
{
if (backdrop_detail_cleared(light)) return EFFECT_UPDATE_RETURN;
if (light.timeout < 0 || light.state <= light.timeout)
{
if (light.subtype == LIGHT_FLICKER)
{
if (random_below(LIGHT_TOGGLE_ODDS) == 0) light.isVisible = !light.isVisible;
if (random_below(LIGHT_DIM_ODDS) == 0)
{
float dim = random_unit() * LIGHT_ALPHA_SPAN;
light.sprite.color._tint[3] = dim * random_unit() + LIGHT_ALPHA_MIN;
}
}
}
else light.sprite.color._tint[3] = light.color._tint[3] * ((float)light.timeout / (float)light.state);
if (light.isDead) light.Remove();
return EFFECT_UPDATE_FINISH;
}
static EffectUpdateEnd backdrop_decoration_update(Entity_Effect& decoration)
{
return backdrop_detail_cleared(decoration) ? EFFECT_UPDATE_RETURN : EFFECT_UPDATE_FINISH;
}
// Game::GetNearestPlayerEx 00703ab0 for the main players: the nearest one that is no coop ghost, hologram or held
// body and still collides.
static Entity_Player* nearest_main_player_get(Vector position)
{
Entity_Player* nearest = nullptr;
float nearestDistance = 1e10f;
for (Entity_Player* player : g_game->playerManager.playerList)
{
float distance = distance_squared(position, player->pos);
if (distance >= nearestDistance || player->variant != 0 || player->isCoopGhost || player->parent) continue;
if (player->IsHologram() || player->entityCollisionClass == ENTCOLL_NONE) continue;
nearest = player;
nearestDistance = distance;
}
return nearest;
}
// A ladder's frame: it counts the frames no player stands close, and a player climbing it once it is ready leaves.
static void tall_ladder_update(Entity_Effect& ladder)
{
Entity_Player* player = nearest_main_player_get(ladder.pos);
float distance = player ? vector_length(vector_sub(ladder.pos, player->pos)) : 1e9f;
ladder.state = distance < LADDER_NEAR && ladder.state <= LADDER_ARM_FRAMES ? 0 : ladder.state + 1;
if (player && distance < LADDER_CLIMB && ladder.state > LADDER_ARM_FRAMES)
reconstruction_missing("Entity_Effect::Update 005d4380: climbing a ladder out of the room");
}
// The creep: how long it lasts, where it lies, and how it fades when it dies.
constexpr std::array<int, 4> LASTING_CREEPS = {EFFECT_PLAYER_CREEP_LEMON_MISHAP, EFFECT_PLAYER_CREEP_HOLYWATER,
EFFECT_PLAYER_CREEP_LEMON_PARTY, EFFECT_PLAYER_CREEP_PUDDLE_MILK};
constexpr int CREEP_RENDER_Z = 2000;
constexpr int CREEP_FRAMES = 125;
constexpr int LASTING_CREEP_FRAMES = 290;
constexpr int GREEN_CREEP_FRAMES = 25;
constexpr int BACKDROP_WOMB = 10;
constexpr unsigned int CREEP_STATIC_RENDER_FLAG = 0x20;
constexpr float LEMON_MISHAP_PLAYER_SCALE = 1.3f;
constexpr float CREEP_RADIUS_PER_SCALE = 20;
constexpr float CREEP_FADE_SHRINK = 0.98f;
constexpr int CREEP_FADE_FRAMES = 40;
constexpr int CREEP_BLOOD_KINDS = 6;
constexpr int CREEP_DAMAGE_COUNTDOWN = 30;
constexpr int CREEP_RANDOM_TIMEOUT = 30;
constexpr int CREEP_DAMAGE_PERIOD = 3;
constexpr float CREEP_ELLIPSE_SQUASH = 1.75f;
constexpr float CREEP_TEXEL_OPAQUE = 0.5f;
constexpr float SCREEN_SCALE = 0.65f;
// The creep sizes: the spawn scale picks the art, smaller than 0.99, 1.3 and 2.1.
constexpr float CREEP_SMALL = 0.99f;
constexpr float CREEP_BIG = 1.3f;
constexpr float CREEP_BIGGEST = 2.1f;
// Lost Cork grows the players' creep by its multiplier: small creep gains size, larger creep multiplies it.
constexpr uint32_t TRINKET_LOST_CORK = 106;
constexpr std::array<float, 3> CORK_SMALL_GROWTH = {1, 1.25f, 1.5f};
constexpr std::array<float, 3> CORK_GROWTH = {1.65f, 1.9f, 2.15f};
// What spares a player creep: Callus, and the collectible 571 (Evil Charm's immunity is the player's).
constexpr uint32_t TRINKET_CALLUS = 14;
constexpr int COLLECTIBLE_CREEP_IMMUNE = 571;
constexpr uint64_t DAMAGE_ACID = 1 << 4;
constexpr uint64_t DAMAGE_COUNTDOWN = 1 << 6;
// The slowing creep: white slows more than the black and brown, for ten frames past touching it, tinted grey-blue.
constexpr int PLAYER_SLOW_FRAMES = -10;
constexpr int ENEMY_SLOW_FRAMES = -1;
constexpr float WHITE_CREEP_SLOW = 0.75f;
constexpr float CREEP_SLOW = 0.85f;
constexpr float PLAYER_CREEP_SLOW = 0.9f;
constexpr ColorMod CREEP_SLOW_COLOR = {{1, 1, 1.3f, 1}, {0, 0, 0, 0}, {40 / 255.0f, 40 / 255.0f, 40 / 255.0f}};
// The holy water trail's homing: how far ahead it looks, how far it searches, and how fast it follows.
constexpr float HOMING_LOOKAHEAD = 5;
constexpr float HOMING_RANGE = 128;
constexpr float HOMING_NONE = 1e9f;
constexpr float HOMING_HIT_PENALTY = 1000;
constexpr float HOMING_MAX_PULL = 4;
constexpr float HOMING_PULL_DIVISOR = 10;
constexpr int TEAR_FLAG_HOMING = 2;
// The players' lasting creep grows in over its first 15 frames and shrinks away over its last 65. Holy water freezes
// what it burns, now and then.
constexpr float LASTING_GROW_FRAMES = 15;
constexpr float LASTING_SHRINK_FRAMES = 65;
constexpr int PLAYER_CREEP_COUNTDOWN = 10;
constexpr int HOLY_WATER_FREEZE_PERIOD = 10;
constexpr int HOLY_WATER_VERSUS_FREEZE_PERIOD = 60;
constexpr int HOLY_WATER_FREEZE = 10;
constexpr int HOLY_WATER_BOSS_FREEZE = 90;
// Black Powder's pentagram: its reach from its spawn scale, its tiny start, its burn and its fade.
constexpr float PENTAGRAM_REACH = 0.7f;
constexpr float PENTAGRAM_START_SCALE = 0.00390625f;
constexpr float PENTAGRAM_DAMAGE = 10;
constexpr float PENTAGRAM_VERSUS_DAMAGE = 5;
constexpr float PENTAGRAM_FADE = 0.8f;
constexpr int PENTAGRAM_FADE_FRAMES = 10;
// A color with its tint and offset, as the Color constructors build it.
static ColorMod color_make(std::array<float, 4> tint, std::array<float, 3> offset)
{
return {{tint[0], tint[1], tint[2], tint[3]}, {0, 0, 0, 0}, {offset[0], offset[1], offset[2]}};
}
// A spritesheet's texels, read once from its file.
struct Texels
{
std::vector<uint8_t> rgba;
int height = 0;
int width = 0;
};
static const Texels& texels_get(const KAGE::Graphics::ImageBase& image)
{
static std::unordered_map<std::string, Texels> cache;
auto [entry, isNew] = cache.try_emplace(image.path);
if (!isNew) return entry->second;
int channels = 0;
Texels& texels = entry->second;
stbi_uc* data = stbi_load(resource_path(image.path).c_str(), &texels.width, &texels.height, &channels, STBI_rgb_alpha);
if (data) texels.rgba.assign(data, data + (size_t)texels.width * texels.height * 4);
stbi_image_free(data);
return texels;
}
// The texel at a spritesheet position, white off the image.
static KColor texel_read(const KAGE::Graphics::ImageBase& image, int x, int y)
{
const Texels& texels = texels_get(image);
if ((uint32_t)x >= (uint32_t)texels.width || (uint32_t)y >= (uint32_t)texels.height || texels.rgba.empty())
return kcolor_rgba(1, 1, 1, 1);
const uint8_t* texel = &texels.rgba[((size_t)y * texels.width + x) * 4];
return kcolor_rgba(texel[0] / 255.0f, texel[1] / 255.0f, texel[2] / 255.0f, texel[3] / 255.0f);
}
// ANM2::GetTexel 0040b600: the color a sprite drawn at a place shows at a point, from the first layer (by track)
// whose texel there is at least half opaque, tinted and offset by the sprite's, layer's and keyframe's colors. None is
// clear. The original reads the texel back from the texture, this from the spritesheet's file.
static KColor sprite_texel_get(ANM2& sprite, Vector point, Vector place)
{
const AnimationState& state = sprite.animState;
if (!state.animData) return kcolor_rgba(0, 0, 0, 0);
for (size_t track = 0; track < state.animData->animLayers.size(); track++)
{
const AnimationLayer& animLayer = state.animData->animLayers[track];
int frameIndex = state.layerFrames[track];
LayerState* layer = sprite.GetLayer(animLayer.layerId);
if (animLayer.frames.empty() || !layer || frameIndex < 0 || frameIndex >= (int)animLayer.frames.size()) continue;
const AnimationFrame& frame = animLayer.frames[frameIndex];
if (!frame.isVisible || !layer->isVisible || !layer->spriteSheet) continue;
SourceQuad source = AnimationLayer::GetSourceQuad(frame, *layer, SpriteDraw{}, sprite);
DestinationQuad screen = AnimationLayer::GetDestQuad(frame, *layer, SpriteDraw{place, {}, {}}, sprite);
float layerTurn = frame.rotation + layer->rotation;
float spriteTurn = sprite.rotation;
if (spriteTurn != 0 || layerTurn != 0)
{
float scaleX = frame.scale.x * layer->size.x;
float scaleY = frame.scale.y * layer->size.y;
float spriteScaleY = sprite.isFlipY ? -sprite.scale.y : sprite.scale.y;
if ((sprite.scale.x < 0) != (scaleX < 0))
{
if (sprite.scale.x < 0)
{
layerTurn = -layerTurn;
spriteTurn = -spriteTurn;
}
if (scaleX < 0) layerTurn = -layerTurn;
}
if (layer->isFlipY) scaleY = -scaleY;
if ((spriteScaleY < 0) != (scaleY < 0))
{
if (spriteScaleY < 0)
{
layerTurn = -layerTurn;
spriteTurn = -spriteTurn;
}
if (scaleY < 0) layerTurn = -layerTurn;
}
float angle = -(layerTurn + spriteTurn) * DEGREES_TO_RADIANS;
float cosine = std::cos(angle);
float sine = std::sin(angle);
for (Vector* corner : {&screen._topLeft, &screen._topRight, &screen._bottomLeft, &screen._bottomRight})
*corner = vector_make(corner->x * cosine - corner->y * sine, corner->y * cosine + corner->x * sine);
point = vector_make(cosine * point.x - sine * point.y, cosine * point.y + sine * point.x);
}
Vector topLeft = screen._topLeft;
Vector bottomRight = screen._bottomRight;
if (point.x <= topLeft.x || point.x >= bottomRight.x || point.y <= topLeft.y || point.y >= bottomRight.y) continue;
float u = std::clamp((point.x - topLeft.x) / (bottomRight.x - topLeft.x), 0.0f, 1.0f);
float v = std::clamp((point.y - topLeft.y) / (bottomRight.y - topLeft.y), 0.0f, 1.0f);
float x = (source._bottomRight.x - source._topLeft.x) * u + source._topLeft.x;
float y = (source._bottomRight.y - source._topLeft.y) * v + source._topLeft.y;
KColor texel = texel_read(*layer->spriteSheet, (int)x, (int)y);
if (texel._alpha < CREEP_TEXEL_OPAQUE) continue;
std::array<float, 4> tint{};
std::array<float, 3> offset{};
for (int i = 0; i < 4; i++) tint[i] = frame.color._tint[i] * (layer->color._tint[i] * sprite.color._tint[i]);
for (int i = 0; i < 3; i++) offset[i] = frame.color._offset[i] + (layer->color._offset[i] + sprite.color._offset[i]);
return kcolor_rgba(tint[0] * texel._red + offset[0], tint[1] * texel._green + offset[1],
tint[2] * texel._blue + offset[2], tint[3] * texel._alpha);
}
return kcolor_rgba(0, 0, 0, 0);
}
// Lost Cork's multiplier for a creep's owner, 1 to 3, or 0 for none.
static int lost_cork_get(Entity* owner)
{
if (!owner || !owner->is_player()) return 0;
Entity_Player& player = *static_cast<Entity_Player*>(owner);
if (!player.HasTrinket(TRINKET_LOST_CORK)) return 0;
int multiplier = player.GetTrinketMultiplier(TRINKET_LOST_CORK);
return multiplier >= 1 && multiplier <= (int)CORK_GROWTH.size() ? multiplier : 0;
}
// Creep lies on the floor among the floor stains and lasts 125 frames (green 25), the players' lemon, holy water and
// milk 290. Red creep is grey in the Womb, a player's Lemon Mishap larger.
static void creep_init(Entity_Effect& creep)
{
creep.sortingLayer = SORTING_BACKGROUND;
creep.renderZOffset = CREEP_RENDER_Z;
bool isLasting = is_listed(LASTING_CREEPS, creep.variant);
if (isLasting) creep.lifespan = LASTING_CREEP_FRAMES;
creep.timeout = isLasting ? LASTING_CREEP_FRAMES : CREEP_FRAMES;
creep.isUnknown176 = true;
if (creep.variant == EFFECT_CREEP_RED && g_game->room->backdropType == BACKDROP_WOMB)
creep.sprite.color = tint_make(0.5f, 0.5f, 0.5f, 1);
if (creep.variant == EFFECT_CREEP_STATIC) creep.sprite.bitflags |= CREEP_STATIC_RENDER_FLAG;
if (creep.variant == EFFECT_PLAYER_CREEP_GREEN) creep.timeout = GREEN_CREEP_FRAMES;
if (creep.variant == EFFECT_PLAYER_CREEP_LEMON_MISHAP && creep.spawnerEntity && creep.spawnerEntity->is_player())
creep.scale = LEMON_MISHAP_PLAYER_SCALE;
}
// Settles creep on its first frame: its art and radius by the scale it was spawned at (Lost Cork's growth added),
// drawn at its own scale on the game's frame of a random puddle. The players' white, red, green and holy water creep
// and the yellow hold their first frame, the black and Black Powder their third, and the holy water, brown, yellow and
// slippery creep take their colors. Its alpha now is what it fades from.
// The original divides by zero for an animation without frames. This takes the first frame.
static void creep_settle(Entity_Effect& creep)
{
creep.state++;
float spawnScale = creep.sprite.scale.x;
if (int cork = creep.spawnerEntity ? lost_cork_get(creep.spawnerEntity->GetLastSpawner()) : 0)
{
if (spawnScale >= CREEP_BIGGEST) creep.scale *= CORK_GROWTH[cork - 1];
else if (spawnScale >= CREEP_SMALL) spawnScale *= CORK_GROWTH[cork - 1];
else spawnScale += CORK_SMALL_GROWTH[cork - 1];
}
const char* kind = "SmallBlood";
if (spawnScale >= CREEP_SMALL && creep.variant != EFFECT_PLAYER_CREEP_BLACKPOWDER)
kind = spawnScale >= CREEP_BIGGEST ? "BiggestBlood" : spawnScale >= CREEP_BIG ? "BigBlood" : "Blood";
char animation[32];
std::snprintf(animation, sizeof(animation), "%s%02d", kind, random_below(CREEP_BLOOD_KINDS) + 1);
creep.size = spawnScale * CREEP_RADIUS_PER_SCALE * creep.scale;
creep.sprite.scale = vector_make(creep.scale, creep.scale);
creep.sprite.Play(animation);
int length = creep.sprite.animState.GetAnimationLength();
creep.sprite.SetFrame(length > 0 ? (float)(g_game->frameCount % length) : 0.0f);
switch (creep.variant)
{
case EFFECT_PLAYER_CREEP_WHITE:
case EFFECT_PLAYER_CREEP_RED:
case EFFECT_PLAYER_CREEP_GREEN:
case EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL:
case EFFECT_CREEP_BROWN:
case EFFECT_PLAYER_CREEP_YELLOW:
creep.sprite.SetFrame(0.0f);
creep.sprite.Stop();
if (creep.variant == EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL)
{
ColorMod& color = creep.sprite.color;
KColor water = kcolor_rgba(135 / 255.0f, 165 / 255.0f, 201 / 255.0f, 1);
creep.sprite.color = color_make({0, 0, 0, 1}, {color._tint[0] * water._red + color._offset[0],
color._tint[1] * water._green + color._offset[1],
color._tint[2] * water._blue + color._offset[2]});
creep.timeout /= 2;
}
else if (creep.variant == EFFECT_CREEP_BROWN)
creep.sprite.color = color_make({0, 0, 0, 1}, {166 / 255.0f, 104 / 255.0f, 41 / 255.0f});
else if (creep.variant == EFFECT_PLAYER_CREEP_YELLOW)
creep.sprite.color = color_make({0, 0, 0, 1}, {146 / 255.0f, 146 / 255.0f, 10 / 255.0f});
break;
case EFFECT_PLAYER_CREEP_BLACK:
case EFFECT_PLAYER_CREEP_BLACKPOWDER:
creep.sprite.SetFrame(2.0f);
creep.sprite.Stop();
break;
case EFFECT_CREEP_SLIPPERY_BROWN:
creep.sprite.color = color_make({0, 0, 0, 1}, {0.6f, 0.4f, 0});
break;
}
creep.minRadius = creep.sprite.color._tint[3];
}
// Runs touch for each player on the ground the creep's opaque part lies under, and leaves its color on their feet
// unless it is Dogma's.
static void creep_players_touch(Entity_Effect& creep, void (*touch)(Entity_Effect&, Entity_Player&))
{
for (Entity_Player* player : g_game->playerManager.playerList)
{
if (player->isDead || player->entityCollisionClass == ENTCOLL_NONE) continue;
if (player->entityGridCollisionClass != GRIDCOLL_GROUND || player->HasTrinket(TRINKET_CALLUS)) continue;
if (player->HasCollectible(COLLECTIBLE_CREEP_IMMUNE)) continue;
float distance = vector_length(vector_sub(player->pos, creep.pos));
if (distance >= creep.size * creep.sprite.scale.x + player->size) continue;
Vector point = vector_scale(player->pos, SCREEN_SCALE);
KColor texel = sprite_texel_get(creep.sprite, point, vector_scale(creep.pos, SCREEN_SCALE));
if (texel._alpha <= CREEP_TEXEL_OPAQUE) continue;
touch(creep, *player);
if (creep.variant != EFFECT_CREEP_STATIC) player->SetFootprintColor(texel, false);
}
}
// Whether a player shrugs creep off: Evil Charm against its kind, or the collectible 571.
static bool is_creep_immune(Entity_Effect& creep, Entity_Player& player)
{
return player.is_evil_charm_immune(EntityRef(&creep)) || player.HasCollectible(COLLECTIBLE_CREEP_IMMUNE);
}
// Red, green and yellow creep burn a player for a heart, as their parent's.
static void creep_burn(Entity_Effect& creep, Entity_Player& player)
{
if (is_creep_immune(creep, player)) return;
Entity* source = creep.parent ? creep.parent.get() : &creep;
player.TakeDamage(1, DAMAGE_ACID, EntityRef(source), CREEP_DAMAGE_COUNTDOWN);
}
// White, black and brown creep slow a player.
static void creep_slow(Entity_Effect& creep, Entity_Player& player)
{
if (is_creep_immune(creep, player)) return;
float slow = creep.variant == EFFECT_CREEP_WHITE ? WHITE_CREEP_SLOW : CREEP_SLOW;
player.AddSlowing(EntityRef(&creep), PLAYER_SLOW_FRAMES, slow, CREEP_SLOW_COLOR, false);
}
// Slippery creep makes a player slide.
static void creep_slip(Entity_Effect&, Entity_Player& player)
{
player.AddEntityFlags(FLAG_SLIPPERY_PHYSICS);
}
// Whether the players' creep reaches an entity: a vulnerable enemy on the ground that did not spawn it, within the
// creep's radius squashed into a floor ellipse. A player counts unless creep cannot touch them.
static bool is_creep_victim(Entity_Effect& creep, Entity& entity, float radius)
{
if (entity.is_player() && is_creep_immune(creep, *static_cast<Entity_Player*>(&entity))) return false;
if (!entity.IsVulnerableEnemy(nullptr) || entity.IsFlying()) return false;
if (creep.spawnerEntity && creep.spawnerEntity->IsDescendantOf(&entity)) return false;
Vector offset = vector_sub(entity.pos, creep.pos);
offset.y *= CREEP_ELLIPSE_SQUASH;
float reach = radius + entity.size;
return vector_length_squared(offset) < reach * reach;
}
// Burns an enemy with the creep's damage as acid, or raises the acid hit it already takes this frame to it.
static void creep_acid_burn(Entity_Effect& creep, Entity& enemy)
{
if (!(enemy.pendingDamageFlags & DAMAGE_ACID))
{
enemy.TakeDamage(creep.collisionDamage, DAMAGE_ACID, EntityRef(&creep), CREEP_DAMAGE_COUNTDOWN);
return;
}
for (DamageEvent& event : enemy.damageEvents)
{
if (!(event.damageFlags & DAMAGE_ACID)) continue;
event.damage = std::max(event.damage, creep.collisionDamage);
break;
}
}
// The tear flags a holy water trail carries in its extra data.
static TearFlags creep_tear_flags(const Entity_Effect& creep)
{
TearFlags flags;
for (size_t bit = 0; bit < flags.size(); bit++) flags[bit] = (creep.varData[bit / 32] >> (bit % 32)) & 1;
return flags;
}
// A homing holy water trail picks the nearest enemy on the ground ahead of it (with some chance, and ones it hit
// last), and drifts toward its target.
static void holy_water_trail_home(Entity_Effect& trail)
{
if (!trail.target)
{
Entity* best = nullptr;
float bestScore = HOMING_NONE;
Vector ahead = vector_add(trail.pos, vector_scale(trail.velocity, HOMING_LOOKAHEAD));
for (Entity* enemy : entities_near(ahead, HOMING_RANGE, QUERY_ENEMIES))
{
if (!enemy->IsVulnerableEnemy(nullptr)) continue;
if (trail.spawnerEntity && trail.spawnerEntity->IsDescendantOf(enemy)) continue;
if (enemy->HasEntityFlags(FLAG_FRIENDLY) || enemy->entityGridCollisionClass != GRIDCOLL_GROUND) continue;
float score = vector_length(vector_sub(ahead, enemy->pos)) + random_unit() * HOMING_RANGE;
if (EntityList::HitListContains(trail.hitList, *enemy)) score += HOMING_HIT_PENALTY;
if (score >= bestScore) continue;
bestScore = score;
best = enemy;
}
trail.target = best;
}
if (!trail.target) return;
Vector pull = vector_sub(trail.target->pos, trail.pos);
if (vector_length(pull) > HOMING_MAX_PULL) pull = vector_resized(pull, HOMING_MAX_PULL);
trail.velocity = vector_add(trail.velocity, vector_scale(pull, 1 / HOMING_PULL_DIVISOR));
}
// Every third frame the players' red, holy water and yellow creep burn the enemies over them they have not hit, and
// the holy water trail brings its tears' effects and drifts after enemies when it homes.
static void creep_enemies_burn(Entity_Effect& creep)
{
if (g_game->frameCount % CREEP_DAMAGE_PERIOD != 0) return;
float radius = creep.size * creep.sprite.scale.x;
bool isTrail = creep.variant == EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL;
TearFlags flags = creep_tear_flags(creep);
for (Entity* enemy : entities_near(creep.pos, radius, QUERY_ENEMIES))
{
if (EntityList::HitListContains(creep.hitList, *enemy) || !is_creep_victim(creep, *enemy, radius)) continue;
creep_acid_burn(creep, *enemy);
if (isTrail) Entity_Tear::ApplyTearFlagEffects(enemy, creep.pos, flags, &creep, creep.collisionDamage);
}
if (!isTrail) return;
if (flags[TEAR_FLAG_HOMING]) holy_water_trail_home(creep);
else creep.velocity = {};
}
// The creep's frame: settled on its first, it dies with its room's enemies (or in a flooded stage's water) unless it
// is the players'. Alive and not just decoration, enemies' creep burns, slows or trips the players over it, the
// players' slows or burns enemies. Dead, it shrinks and fades out over 40 frames.
static void creep_update(Entity_Effect& creep)
{
Room& room = *g_game->room;
int variant = creep.variant;
if (creep.state == 0) creep_settle(creep);
int stageId = room.waterAmount > 0.1f ? g_game->GetStageID() : 0;
bool isFlooded = stageId == 12 || stageId == 33;
bool isFriendly = creep.HasEntityFlags(FLAG_FRIENDLY);
if (!isFriendly && !Entity_Effect::IsPlayerCreep(variant) && ((room.IsClear() && room.GetAliveEnemiesCount() <= 0) || isFlooded))
creep.isDead = true;
bool isStaticBurning = variant == EFFECT_CREEP_STATIC && !isFriendly;
if (!creep.isDead && !creep.HasEntityFlags(FLAG_NO_BLOOD_SPLASH))
{
bool isSticky = variant == EFFECT_CREEP_WHITE || variant == EFFECT_CREEP_BLACK || variant == EFFECT_CREEP_BROWN;
if ((isSticky || variant == EFFECT_CREEP_SLIPPERY_BROWN) && creep.timeout == 0 && !creep.parent)
creep.timeout = random_below(CREEP_RANDOM_TIMEOUT);
if (variant == EFFECT_CREEP_RED || variant == EFFECT_CREEP_GREEN || variant == EFFECT_CREEP_YELLOW || isStaticBurning)
creep_players_touch(creep, creep_burn);
else if (isSticky) creep_players_touch(creep, creep_slow);
else if (variant == EFFECT_CREEP_SLIPPERY_BROWN) creep_players_touch(creep, creep_slip);
else if (variant == EFFECT_PLAYER_CREEP_WHITE || variant == EFFECT_PLAYER_CREEP_BLACK)
{
float radius = creep.size * creep.sprite.scale.x;
for (Entity* enemy : entities_near(creep.pos, radius, QUERY_ENEMIES))
if (is_creep_victim(creep, *enemy, radius))
enemy->AddSlowing(EntityRef(&creep), ENEMY_SLOW_FRAMES, PLAYER_CREEP_SLOW, CREEP_SLOW_COLOR, false);
}
else if (variant == EFFECT_PLAYER_CREEP_RED || variant == EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL ||
variant == EFFECT_PLAYER_CREEP_YELLOW)
creep_enemies_burn(creep);
else if (variant == EFFECT_PLAYER_CREEP_GREEN)
{
float radius = creep.size * creep.sprite.scale.x;
for (Entity* enemy : entities_near(creep.pos, radius, QUERY_ENEMIES))
if (is_creep_victim(creep, *enemy, radius))
enemy->TakeDamage(creep.collisionDamage, 0, EntityRef(&creep), CREEP_DAMAGE_COUNTDOWN);
}
}
if (!creep.isDead) return;
creep.sprite.scale = vector_scale(creep.sprite.scale, CREEP_FADE_SHRINK);
float fade = std::clamp((float)(CREEP_FADE_FRAMES - creep.state) / CREEP_FADE_FRAMES, 0.0f, 1.0f);
creep.sprite.color._tint[3] = fade * creep.minRadius;
if (++creep.state > CREEP_FADE_FRAMES) creep.Remove();
}
// The players' lasting creep (Lemon Mishap, holy water, Lemon Party, milk): Lost Cork grows it on its first frame. It
// grows in and shrinks out with its timeout (a player's Lemon Mishap holds full size), and all but the milk burn the
// enemies over it, holy water freezing them now and then.
static void lasting_creep_update(Entity_Effect& creep)
{
if (creep.state == 0)
{
Entity* owner = creep.GetLastSpawner();
if (int cork = owner ? lost_cork_get(owner->ToPlayer()) : 0) creep.scale *= CORK_GROWTH[cork - 1];
creep.state++;
}
float growth = 1;
if (creep.timeout > creep.lifespan - (int)LASTING_GROW_FRAMES)
growth = (float)(creep.lifespan - creep.timeout) / LASTING_GROW_FRAMES;
else if (creep.variant == EFFECT_PLAYER_CREEP_LEMON_MISHAP && creep.spawnerEntity && creep.spawnerEntity->is_player())
creep.timeout++;
else if (creep.timeout < (int)LASTING_SHRINK_FRAMES) growth = (float)creep.timeout / LASTING_SHRINK_FRAMES;
creep.sprite.scale = vector_make(growth * creep.scale, growth * creep.scale);
if (creep.variant != EFFECT_PLAYER_CREEP_PUDDLE_MILK)
{
float radius = creep.size * growth * creep.scale;
int freezePeriod = g_game->deathmatchManager.is_active() ? HOLY_WATER_VERSUS_FREEZE_PERIOD : HOLY_WATER_FREEZE_PERIOD;
for (Entity* enemy : entities_near(creep.pos, radius, QUERY_ENEMIES))
{
if (!is_creep_victim(creep, *enemy, radius)) continue;
enemy->TakeDamage(creep.collisionDamage, DAMAGE_COUNTDOWN, EntityRef(&creep), PLAYER_CREEP_COUNTDOWN);
if (creep.variant != EFFECT_PLAYER_CREEP_HOLYWATER || !creep.IsFrame(freezePeriod, 0)) continue;
enemy->AddFreeze(EntityRef(&creep), enemy->IsBoss() ? HOLY_WATER_BOSS_FREEZE : HOLY_WATER_FREEZE, false);
}
}
if (creep.isDead) creep.Remove();
}
// Black Powder's pentagram: it starts as a speck with its reach from its spawn scale and burns the enemies inside it
// until it dies, then fades out over 10 frames.
static void pentagram_update(Entity_Effect& pentagram)
{
if (pentagram.state == 0)
{
pentagram.state++;
pentagram.size = pentagram.sprite.scale.x * pentagram.scale * PENTAGRAM_REACH;
float start = pentagram.scale * PENTAGRAM_START_SCALE;
pentagram.sprite.scale = vector_make(start, start);
pentagram.sprite.Play("Pentagram");
}
if (!pentagram.isDead)
{
float damage = g_game->deathmatchManager.is_active() ? PENTAGRAM_VERSUS_DAMAGE : PENTAGRAM_DAMAGE;
for (Entity* enemy : entities_near(pentagram.pos, pentagram.size, QUERY_ENEMIES))
{
if (!enemy->IsVulnerableEnemy(nullptr) || pentagram.IsDescendantOf(enemy)) continue;
float reach = enemy->size + pentagram.size;
if (distance_squared(enemy->pos, pentagram.pos) >= reach * reach) continue;
enemy->TakeDamage(damage, DAMAGE_ACID | DAMAGE_COUNTDOWN, EntityRef(&pentagram), PLAYER_CREEP_COUNTDOWN);
}
return;
}
pentagram.sprite.color._tint[3] *= PENTAGRAM_FADE;
if (++pentagram.state > PENTAGRAM_FADE_FRAMES) pentagram.Remove();
}
// The Downpour's tadpoles: their swim and its pull by the current, their darts away from the walls and from a player
// close by.
constexpr float TADPOLE_FRICTION = 0.93f;
constexpr float TADPOLE_STROKE = 0.2f;
constexpr float TADPOLE_CURRENT_PULL = 0.3f;
constexpr float TADPOLE_SPEED_ANIMATION = 0.5f;
constexpr float TADPOLE_FASTEST_ANIMATION = 2.5f;
constexpr float TADPOLE_WALL_MARGIN = 40;
constexpr float TADPOLE_WALL_TURN = 0.05f;
constexpr float TADPOLE_WOBBLE = 10;
constexpr float TADPOLE_TIRE_MIN = 0.9f;
constexpr float TADPOLE_TIRE_SPAN = 0.1f;
constexpr float TADPOLE_RESTING = 0.05f;
constexpr int TADPOLE_REST_KICK_ODDS = 15;
constexpr int TADPOLE_KICK_ODDS = 30;
constexpr int TADPOLE_CURRENT_KICK_ODDS = 3;
constexpr float TADPOLE_KICK_JITTER = 0.4f;
constexpr float TADPOLE_CURRENT_KICK = 1.35f;
constexpr float TADPOLE_SLOW = 0.6f;
constexpr float TADPOLE_FLEE_RANGE_SQUARED = 4900;
constexpr int TADPOLE_FLEE_ODDS = 3;
constexpr int TADPOLE_STILL_FLEE_ODDS = 40;
constexpr float TADPOLE_STILL_SPEED_SQUARED = 0.1f;
constexpr float TADPOLE_FLEE_SPREAD = 40;
constexpr float TADPOLE_FLEE_SPEED = 2;
constexpr float TADPOLE_SPLASH_RANGE = 10;
// The lil ghosts: where they appear (away from shots, enemies and players), how long they stay gone, and their drift.
constexpr int GHOST_GONE_MIN = 30;
constexpr int GHOST_GONE_SPAN = 600;
constexpr int GHOST_FIRST_TRIES = 5;
constexpr float GHOST_ROOM_MARGIN = 20;
constexpr float GHOST_SPOT_CLEARANCE = 200;
constexpr float GHOST_SHY_RANGE = 80;
constexpr float GHOST_DRIFT = 0.005f;
constexpr float GHOST_TURN = 10;
constexpr float GHOST_SCALE_SPAN = 0.2f;
constexpr float GHOST_SPEED_SPAN = 0.3f;
constexpr float GHOST_ALPHA_MIN = 0.3f;
constexpr float GHOST_ALPHA_SPAN = 0.3f;
constexpr uint32_t GHOST_SHY_OF = QUERY_PROJECTILES | QUERY_TEARS | QUERY_ENEMIES | QUERY_PLAYERS;
// The backdrops whose lil ghosts are pale violet: the Mausoleum's.
constexpr std::array<int, 5> GHOST_PALE_BACKDROPS = {33, 38, 40, 41, 42};
// The heaven door (subtype 0), Luna's moonlight (1) and the light beam up (2): how close a player steps in, when the
// door is ready, and the sounds.
constexpr int HEAVEN_DOOR_MOONLIGHT = 1;
constexpr int HEAVEN_DOOR_BEAM = 2;
constexpr int ROOM_INDEX_GENESIS = -2;
constexpr float HEAVEN_DOOR_RANGE_SQUARED = 625;
constexpr float MOONLIGHT_RANGE_SQUARED = 900;
constexpr int MOONLIGHT_READY = 60;
constexpr int HEAVEN_DOOR_READY = 41;
constexpr int HEAVEN_DOOR_EARLY = 8;
constexpr int HEAVEN_DOOR_RESET = -10;
constexpr int HEAVEN_DOOR_REOPEN = 25;
constexpr int BEAM_READY = 32;
constexpr int BEAM_FADE = 82;
constexpr int SOUND_POWER_UP = 128;
constexpr int SOUND_HEAVEN_DOOR = 1051;
constexpr int MOONLIGHT_GROUND_LAYER = 2;
constexpr float MOONLIGHT_DEPTH = 10;
// A tadpole swims on the floor, facing a random way.
static void tadpole_init(Entity_Effect& tadpole)
{
tadpole.sprite.Play("Idle");
tadpole.rotation = angle_normalized(random_unit() * FULL_TURN);
tadpole.sprite.GetLayer(0)->rotation = tadpole.rotation + HALF_TURN;
tadpole.height = 0;
tadpole.isUnknown176 = true;
}
// A tadpole's stroke: a new heading from its old one against the current with a jitter, and a burst of speed.
static void tadpole_kick(Entity_Effect& tadpole, Vector current)
{
Vector heading = vector_sub(vector_from_angle(tadpole.rotation), current);
tadpole.rotation = vector_angle(vector_add(heading, vector_scale(random_direction(), TADPOLE_KICK_JITTER)));
tadpole.minRadius = random_unit() + 1;
if (!vector_is_zero(current)) tadpole.minRadius *= TADPOLE_CURRENT_KICK;
}
// A tadpole's frame (its speed is its minimum radius): it swims along its wobbling heading with the current, turns
// from the walls, tires, and kicks off again now and then, more often in a current. Slow, it darts from a player
// close by. It is pushed out of the grid, and splats when stepped on or splashed.
static void tadpole_update(Entity_Effect& tadpole)
{
Room& room = *g_game->room;
Vector current = room.waterCurrent;
tadpole.sortingLayer = SORTING_DOOR;
tadpole.friction *= TADPOLE_FRICTION;
Vector stroke = vector_scale(vector_scale(vector_from_angle(tadpole.rotation), tadpole.minRadius), TADPOLE_STROKE);
tadpole.velocity = vector_add(tadpole.velocity, vector_add(stroke, vector_scale(current, TADPOLE_CURRENT_PULL)));
tadpole.sprite.playbackSpeed = std::min(tadpole.minRadius + TADPOLE_SPEED_ANIMATION, TADPOLE_FASTEST_ANIMATION);
Vector inside = room.GetClampedPosition(tadpole.pos, TADPOLE_WALL_MARGIN);
if (inside.x != tadpole.pos.x || inside.y != tadpole.pos.y)
tadpole.rotation = angle_lerp(tadpole.rotation, vector_angle(vector_sub(inside, tadpole.pos)), TADPOLE_WALL_TURN);
tadpole.rotation = angle_normalized(random_unit() * TADPOLE_WOBBLE + tadpole.rotation - TADPOLE_WOBBLE / 2);
tadpole.minRadius *= random_unit() * TADPOLE_TIRE_SPAN + TADPOLE_TIRE_MIN;
bool isKick = tadpole.minRadius <= TADPOLE_RESTING && random_below(TADPOLE_REST_KICK_ODDS) == 0;
if (!isKick) isKick = random_below(TADPOLE_KICK_ODDS) == 0;
if (!isKick) isKick = !vector_is_zero(current) && random_below(TADPOLE_CURRENT_KICK_ODDS) == 0;
if (isKick) tadpole_kick(tadpole, current);
Entity_Player* player = nearest_player_get(tadpole.pos);
float playerDistance = distance_squared(tadpole.pos, player->pos);
if (tadpole.minRadius <= TADPOLE_SLOW && playerDistance < TADPOLE_FLEE_RANGE_SQUARED &&
random_below(TADPOLE_FLEE_ODDS) == 0)
{
bool isStill = vector_length_squared(player->velocity) <= TADPOLE_STILL_SPEED_SQUARED;
if (!isStill || random_below(TADPOLE_STILL_FLEE_ODDS) == 0)
{
float away = vector_angle(vector_sub(tadpole.pos, player->pos));
tadpole.rotation = away + random_unit() * TADPOLE_FLEE_SPREAD - TADPOLE_FLEE_SPREAD / 2;
tadpole.minRadius = random_unit() + TADPOLE_FLEE_SPEED;
}
}
tadpole.pos = room.GetClampedPosition(tadpole.pos, BUG_ROOM_MARGIN);
Vector next = vector_add(tadpole.pos, tadpole.velocity);
if (grid_collision_at(next) > COLLISION_PIT) cell_push_out(tadpole, next);
tadpole.targetPosition = tadpole.pos;
if (playerDistance < BUG_SQUASH_RANGE_SQUARED && vector_length_squared(player->velocity) > 1 && !player->IsFlying())
tadpole.isDead = true;
for (Entity* tear : entities_near(tadpole.pos, TADPOLE_SPLASH_RANGE, QUERY_TEARS))
{
if (tear->type != ENTITY_TEAR || !tear->isDead) continue;
tadpole.isDead = true;
break;
}
if (tadpole.isDead) bug_splat(tadpole, 0);
tadpole.sprite.GetLayer(0)->rotation = tadpole.rotation + HALF_TURN;
}
// A lil ghost starts where it was spawned with a random heading, size, speed and faintness, pale violet in the dark
// backdrops.
static void lil_ghost_init(Entity_Effect& ghost)
{
ghost.targetPosition = ghost.pos;
ghost.rotation = angle_normalized(random_unit() * FULL_TURN);
ghost.sprite.Play("Idle");
float size = ghost.dropRNG.RandomFloat() * GHOST_SCALE_SPAN + 1;
ghost.sprite.scale = vector_make(size, size);
ghost.sprite.isFlipX = ghost.dropRNG.RandomInt(2) != 0;
ghost.sprite.playbackSpeed = ghost.dropRNG.RandomFloat() * GHOST_SPEED_SPAN + 1;
if (is_listed(GHOST_PALE_BACKDROPS, g_game->room->backdropType)) ghost.sprite.color = tint_make(0.96f, 0.9f, 1, 1);
ghost.sprite.color._tint[3] = ghost.dropRNG.RandomFloat() * GHOST_ALPHA_SPAN + GHOST_ALPHA_MIN;
ghost.isUnknown176 = true;
}
// Picks a quiet spot for a lil ghost, with five tries on its first frames and one after: open floor with nothing
// that shoots or walks within 200. It appears there, or stays gone a frame longer.
static void lil_ghost_spot_find(Entity_Effect& ghost)
{
Room& room = *g_game->room;
int tries = ghost.FrameCount() < 2 ? GHOST_FIRST_TRIES : 1;
for (int i = 0; i < tries; i++)
{
Vector spot = room.GetRandomPosition(GHOST_ROOM_MARGIN);
if (grid_collision_at(spot) != COLLISION_NONE || !entities_near(spot, GHOST_SPOT_CLEARANCE, GHOST_SHY_OF).empty())
continue;
ghost.targetPosition = spot;
ghost.pos = spot;
break;
}
if (vector_is_zero(ghost.targetPosition))
{
ghost.sprite.Play("Disappear");
ghost.sprite.SetLastFrame();
ghost.state = 1;
}
else if (ghost.FrameCount() > 1) ghost.sprite.Play("Appear");
}
// A lil ghost's frame: dead, it vanishes for a while instead. Visible, it drifts around its spot and vanishes when
// anything comes within 80. Gone, it waits out its time, then appears at a new spot.
static void lil_ghost_update(Entity_Effect& ghost)
{
if (ghost.isDead)
{
ghost.isDead = false;
ghost.sprite.Play("Disappear");
ghost.velocity = {};
ghost.state = random_below(GHOST_GONE_SPAN) + GHOST_GONE_MIN;
}
if (ghost.state < 1 && vector_is_zero(ghost.targetPosition)) lil_ghost_spot_find(ghost);
if (ghost.state >= 1)
{
ghost.targetPosition = {};
ghost.state--;
return;
}
if (ghost.sprite.IsFinished()) ghost.sprite.Play("Idle");
Vector wander = vector_scale(vector_from_angle(ghost.rotation), random_unit() * GHOST_DRIFT);
Vector home = vector_scale(vector_sub(ghost.targetPosition, ghost.pos), GHOST_DRIFT);
ghost.velocity = vector_add(ghost.velocity, vector_add(wander, home));
ghost.rotation += GHOST_TURN - random_unit() * GHOST_TURN * 2;
if (ghost.sprite.animState.IsLoopingAnimation() && !entities_near(ghost.pos, GHOST_SHY_RANGE, GHOST_SHY_OF).empty())
ghost.isDead = true;
}
// FUN_007ab0e0: whether a player is free to step into a light: no extra or item animation playing, unless carrying
// their twin.
static bool is_player_free(Entity_Player& player)
{
bool isAnimating = player.isPlayingExtraAnimation || player.isPlayingItemAnimation;
return !isAnimating || (player.heldEntity && player.heldEntity == player.twinPlayer.get());
}
// The heaven door keeps through overwrites. Luna's moonlight glows additively with its ground layer hidden, and
// spawns a copy of itself on the floor that shows that ground layer under everything.
static void heaven_door_init(Entity_Effect& door)
{
door.AddEntityFlags(FLAG_DONT_OVERWRITE);
if (door.subtype != HEAVEN_DOOR_MOONLIGHT) return;
if (door.spawnerType != 0)
{
door.sortingLayer = SORTING_BACKGROUND;
return;
}
for (int layerId : {0, MOONLIGHT_GROUND_LAYER})
{
LayerState& layer = *door.sprite.GetLayer(layerId);
layer.minFilterMode = 1;
layer.magFilterMode = 1;
layer_additive_set(layer);
}
door.sprite.GetLayer(MOONLIGHT_GROUND_LAYER)->isVisible = false;
Entity* ground = g_game->Spawn({.position = door.pos, .spawner = &door, .subType = door.subtype, .type = door.type,
.variant = door.variant, .seed = door.initSeed});
door.child = ground;
ground->parent = &door;
door.renderDepthOffset = MOONLIGHT_DEPTH;
}
// Luna's moonlight: it shines until a player stands in it once it is ready, then fades out with its ground copy. The
// copy stays on it.
static void moonlight_update(Entity_Effect& light)
{
if (light.spawnerType != 0)
{
if (!light.parent) light.Remove();
else light.pos = light.parent->pos;
return;
}
if (light.state < 0)
{
light.sprite.Play("Disappear");
if (!light.sprite.IsFinished()) return;
light.Remove();
if (light.child) light.child->Remove();
return;
}
light.state++;
light.sprite.Play("Appear");
for (Entity_Player* player : g_game->playerManager.playerList)
{
if (player->variant != 0 || player->parent || player->entityCollisionClass == ENTCOLL_NONE) continue;
if (distance_squared(player->pos, light.pos) >= MOONLIGHT_RANGE_SQUARED || light.state <= MOONLIGHT_READY) continue;
light.state = -1;
npc_sound_play(SOUND_POWER_UP, 1, 2, 1);
reconstruction_missing("Entity_Effect::Update 005d4380: Luna's moonlight blessing (Entity_Effect::CreateTimer)");
}
}
// The light beam up: it appears, waits, and once a player free to move stands in it, carries them up.
static void light_beam_update(Entity_Effect& beam)
{
if (beam.state == 0)
{
beam.sprite.Play("Appear");
beam.state++;
}
else if (beam.state < BEAM_READY || (beam.state > BEAM_READY && beam.state < BEAM_FADE)) beam.state++;
else if (beam.state == BEAM_FADE)
{
beam.sprite.Play("Disappear");
beam.state++;
}
else if (beam.state == BEAM_READY)
{
for (Entity_Player* player : g_game->playerManager.playerList)
{
if (player->variant != 0 || player->isCoopGhost || player->entityCollisionClass == ENTCOLL_NONE) continue;
if (distance_squared(player->pos, beam.pos) < HEAVEN_DOOR_RANGE_SQUARED && is_player_free(*player))
reconstruction_missing("Entity_Effect::Update 005d4380: the light beam's travel (AnimateLightTravel)");
}
}
}
// The heaven door: open while the room is clear (in Backasswards only in the starting room or Genesis's), it takes a
// player standing in it once ready up to the next floor. A player stepping in too early closes it again.
static void heaven_door_update(Entity_Effect& door)
{
if (door.subtype == HEAVEN_DOOR_MOONLIGHT) return moonlight_update(door);
if (door.subtype == HEAVEN_DOOR_BEAM) return light_beam_update(door);
int roomIndex = g_game->currentRoomIdx;
bool isBackasswardsAway = (int)g_game->challenge == CHALLENGE_BACKASSWARDS && roomIndex != g_game->startingRoomIdx &&
roomIndex != ROOM_INDEX_GENESIS;
if (!g_game->room->IsClear() || isBackasswardsAway)
{
door.sprite.Play("Disappear");
door.state = 0;
return;
}
door.state++;
door.sprite.Play("Appear");
bool isEntered = false;
for (Entity_Player* player : g_game->playerManager.playerList)
{
if (player->variant != 0 || player->entityCollisionClass == ENTCOLL_NONE) continue;
if (distance_squared(player->pos, door.pos) >= HEAVEN_DOOR_RANGE_SQUARED || !is_player_free(*player)) continue;
if (door.state >= HEAVEN_DOOR_READY)
reconstruction_missing("Entity_Effect::Update 005d4380: the heaven door's travel (StartStageTransition)");
if (door.state < HEAVEN_DOOR_EARLY) door.state = HEAVEN_DOOR_RESET;
npc_sound_play(SOUND_HEAVEN_DOOR, 1, 2, 1);
isEntered = true;
break;
}
if (!isEntered && door.state < 0) door.state = HEAVEN_DOOR_REOPEN;
}
// Luna's moonlight copy draws its parent's ground layer under everything, the rest their own sprite.
static void heaven_door_render(Entity_Effect& door, const Vector&)
{
Entity* parent = door.parent;
if (door.subtype != HEAVEN_DOOR_MOONLIGHT || !parent)
return door.sprite.Render(SpriteDraw{door.renderPosition, {}, {}});
if (parent->sprite.layerStates.size() <= MOONLIGHT_GROUND_LAYER) return;
LayerState& ground = *parent->sprite.GetLayer(MOONLIGHT_GROUND_LAYER);
ground.isVisible = true;
parent->sprite.RenderLayer(MOONLIGHT_GROUND_LAYER, SpriteDraw{door.renderPosition, {}, {}});
ground.isVisible = false;
}
// The beetles: how they crawl in bursts, take off from a player close by and fly about until they land, and what
// knocks them down.
constexpr int BEETLE_FLYING = 1;
constexpr int BEETLE_BURST_ODDS = 40;
constexpr int BEETLE_STEP_ODDS = 10;
constexpr int BEETLE_TAKEOFF_ODDS = 3;
constexpr int BEETLE_STILL_TAKEOFF_ODDS = 40;
constexpr int BEETLE_FLEE_ODDS = 2;
constexpr int BEETLE_LAND_ODDS = 100;
constexpr float BEETLE_STEP = 0.05f;
constexpr float BEETLE_RUN = 0.2f;
constexpr float BEETLE_RUN_MIN = 0.1f;
constexpr float BEETLE_WALK_WOBBLE = 10;
constexpr float BEETLE_RUN_WOBBLE = 30;
constexpr float BEETLE_FLIGHT_WOBBLE = 50;
constexpr float BEETLE_FLIGHT_TURN = 0.4f;
constexpr float BEETLE_FLEE_TURN = 0.2f;
constexpr float BEETLE_FLIGHT_SPEED = 0.4f;
constexpr float BEETLE_FLEE_PUSH = 1.5f;
constexpr float BEETLE_TAKEOFF_RANGE_SQUARED = 4900;
constexpr float BEETLE_FLIGHT_HEIGHT = -20;
constexpr float BEETLE_SHADOW_MIN = 0.5f;
constexpr float BEETLE_SHADOW_FADE = 0.8f;
constexpr float BEETLE_SHADOW_ALPHA_MIN = 0.1f;
constexpr float BEETLE_HIT_RANGE = 5;
constexpr float BEETLE_FIRE_REACH = 3;
constexpr float BEETLE_BURST_SCALE = 0.4f;
constexpr int BEETLE_SHADOW_LAYER = 1;
// A beetle crawls on the floor, facing a random way.
static void beetle_init(Entity_Effect& beetle)
{
beetle.sprite.Play("WalkHori");
beetle.rotation = angle_normalized(random_unit() * FULL_TURN);
beetle.sprite.GetLayer(0)->rotation = beetle.rotation;
beetle.height = 0;
beetle.isUnknown176 = true;
if (g_game->room->backdropType == BACKDROP_DROSS) beetle.sprite.color = COLOR_DEFAULT;
}
// A flying beetle's shadow shrinks and fades with its height.
static void beetle_shadow_set(Entity_Effect& beetle)
{
float lift = beetle.height / BEETLE_FLIGHT_HEIGHT;
LayerState& shadow = *beetle.sprite.GetLayer(BEETLE_SHADOW_LAYER);
shadow.size = vector_make(lift + BEETLE_SHADOW_MIN, lift + BEETLE_SHADOW_MIN);
shadow.color._tint[3] = (1 - lift) * BEETLE_SHADOW_FADE + BEETLE_SHADOW_ALPHA_MIN;
}
// Turns a beetle back from the walls.
static void beetle_wall_turn(Entity_Effect& beetle)
{
Vector inside = g_game->room->GetClampedPosition(beetle.pos, TADPOLE_WALL_MARGIN);
if (inside.x != beetle.pos.x || inside.y != beetle.pos.y)
beetle.rotation = angle_lerp(beetle.rotation, vector_angle(vector_sub(inside, beetle.pos)), TADPOLE_WALL_TURN);
}
// A crawling beetle lands if it was flying, takes off from a player close by (rarely from one standing still), idles
// or runs in bursts with a wobbling heading, turns from the walls, is pushed out of the grid, and splats when stepped
// on or splashed.
static void beetle_crawl(Entity_Effect& beetle)
{
Room& room = *g_game->room;
if (beetle.height >= 0)
{
beetle.sortingLayer = SORTING_DOOR;
beetle.sprite.Play("WalkHori");
}
else
{
beetle.sprite.Play("FlyHori");
beetle.height += 1;
if (beetle.height < 0) beetle_shadow_set(beetle);
else
{
beetle.height = 0;
beetle.state = 0;
}
}
beetle.friction *= BUG_FRICTION;
Entity_Player* player = nearest_player_get(beetle.pos);
float playerDistance = distance_squared(beetle.pos, player->pos);
if (playerDistance < BEETLE_TAKEOFF_RANGE_SQUARED && random_below(BEETLE_TAKEOFF_ODDS) == 0)
{
bool isStill = vector_length_squared(player->velocity) <= TADPOLE_STILL_SPEED_SQUARED;
if (!isStill || random_below(BEETLE_STILL_TAKEOFF_ODDS) == 0) beetle.subtype = BEETLE_FLYING;
}
float wobble = beetle.state < 1 ? BEETLE_WALK_WOBBLE : BEETLE_RUN_WOBBLE;
beetle.rotation = angle_normalized(random_unit() * wobble + beetle.rotation - wobble / 2);
beetle.pos = room.GetClampedPosition(beetle.pos, BUG_ROOM_MARGIN);
if (beetle.state < 1)
{
if (random_below(BEETLE_BURST_ODDS) == 0) beetle.state = random_below(BUG_BURST_SPAN) + BUG_BURST_MIN;
else if (random_below(BEETLE_STEP_ODDS) == 0)
beetle.AddVelocity_divided(vector_scale(vector_from_angle(beetle.rotation), random_unit() * BEETLE_STEP), false);
}
else
{
Vector heading = vector_from_angle(beetle.rotation);
beetle.AddVelocity_divided(vector_scale(heading, random_unit() * BEETLE_RUN + BEETLE_RUN_MIN), false);
beetle.state--;
}
beetle_wall_turn(beetle);
if (grid_collision_at(beetle.pos) != COLLISION_NONE)
{
GridEntity* grid = grid_entity_at(beetle.pos);
cell_push_out(beetle, beetle.pos);
if (grid && grid->type == GRID_PIT && grid_collision_at(beetle.pos) != COLLISION_NONE)
{
beetle.pos = beetle.targetPosition;
beetle.rotation = angle_normalized(random_unit() * FULL_TURN);
if (grid_collision_at(beetle.pos) == COLLISION_PIT) beetle.pos = vector_add(beetle.pos, random_direction());
}
}
beetle.targetPosition = beetle.pos;
if (playerDistance < BUG_SQUASH_RANGE_SQUARED && vector_length_squared(player->velocity) > 1 && !player->IsFlying())
beetle.isDead = true;
for (Entity* tear : entities_near(beetle.pos, BEETLE_HIT_RANGE, QUERY_TEARS))
{
if (tear->type != ENTITY_TEAR || !tear->isDead) continue;
beetle.isDead = true;
break;
}
}
// A flying beetle climbs to its height, flutters about away from the walls, flees a player close by now and then,
// and lands on open floor at random. A tear, knife or fire knocks it out of the air.
static void beetle_fly(Entity_Effect& beetle)
{
Room& room = *g_game->room;
beetle.sortingLayer = SORTING_NORMAL;
if (beetle.height > BEETLE_FLIGHT_HEIGHT)
{
beetle.height -= 1;
beetle_shadow_set(beetle);
}
beetle.friction *= BUG_FRICTION;
float wobble = random_unit() * BEETLE_FLIGHT_WOBBLE + beetle.rotation - BEETLE_FLIGHT_WOBBLE / 2;
beetle.rotation = angle_lerp(beetle.rotation, wobble, BEETLE_FLIGHT_TURN);
beetle.pos = room.GetClampedPosition(beetle.pos, BUG_ROOM_MARGIN);
beetle_wall_turn(beetle);
Vector heading = vector_from_angle(beetle.rotation);
beetle.AddVelocity_divided(vector_scale(heading, random_unit() * BEETLE_FLIGHT_SPEED + BEETLE_FLIGHT_SPEED), false);
Entity_Player* player = nearest_player_get(beetle.pos);
float playerDistance = distance_squared(beetle.pos, player->pos);
if (playerDistance < NEAR_PLAYER_RANGE_SQUARED && random_below(BEETLE_FLEE_ODDS) == 0)
{
float closeness = 1 - playerDistance / NEAR_PLAYER_RANGE_SQUARED;
beetle.rotation = angle_lerp(beetle.rotation, vector_angle(vector_sub(beetle.pos, player->pos)), BEETLE_FLEE_TURN);
beetle.AddVelocity_divided(vector_scale(vector_from_angle(beetle.rotation), closeness * BEETLE_FLEE_PUSH), false);
}
else if (random_below(BEETLE_LAND_ODDS) == 0 && grid_collision_at(beetle.pos) == COLLISION_NONE) beetle.subtype = 0;
beetle.sprite.Play("FlyHori");
EntityList_EL tears = entities_near(beetle.pos, BEETLE_HIT_RANGE, QUERY_TEARS);
bool isHit = std::any_of(tears.begin(), tears.end(), [](Entity* tear) { return tear->type == ENTITY_TEAR; });
for (Entity* entity : g_game->room->entityList.updateEL)
{
if (isHit) break;
if (entity->type == ENTITY_KNIFE) isHit = is_within_reach(*entity, beetle.pos, entity->size * FLY_KNIFE_REACH);
}
for (Entity* entity : g_game->room->entityList.updateEL)
{
if (isHit) break;
if (entity->type == ENTITY_FIREPLACE) isHit = is_within_reach(*entity, beetle.pos, entity->size + BEETLE_FIRE_REACH);
}
if (!isHit) return;
beetle.isDead = true;
beetle.sprite.Stop();
}
// A beetle's frame: it crawls or flies by its subtype. Dead, it splats on the floor or bursts in the air.
static void beetle_update(Entity_Effect& beetle)
{
if (beetle.subtype == 0) beetle_crawl(beetle);
else beetle_fly(beetle);
if (beetle.isDead)
{
if (beetle.sortingLayer == SORTING_DOOR) bug_splat(beetle, 0);
else
{
Entity* burst = g_game->Spawn({.position = vector_make(beetle.pos.x, beetle.pos.y + beetle.height),
.type = ENTITY_EFFECT, .variant = EFFECT_BLOOD_EXPLOSION, .seed = Random()});
burst->sprite.scale = vector_make(BEETLE_BURST_SCALE, BEETLE_BURST_SCALE);
burst->SetColor(beetle.splatColor, -1, 255, false, true);
burst->Update();
beetle.Remove();
}
}
beetle.sprite.GetLayer(0)->rotation = beetle.rotation;
beetle.sprite.GetLayer(0)->pos.y = beetle.height;
}
// The ambient variants by their Init, Update and Render.
constexpr auto AMBIENT_BEHAVIOURS = std::to_array<AmbientBehaviour>({
{EFFECT_TINY_BUG, tiny_bug_init, finishing<tiny_bug_update>, nullptr},
{EFFECT_TINY_FLY, tiny_fly_init, finishing<tiny_fly_update>, nullptr},
{EFFECT_WATER_DROPLET, water_droplet_init, water_droplet_update, nullptr},
{EFFECT_WISP, wisp_init, finishing<wisp_update>, nullptr},
{EFFECT_EMBER_PARTICLE, nullptr, finishing<ember_particle_update>, nullptr},
{EFFECT_WALL_BUG, wall_bug_init, finishing<wall_bug_update>, nullptr},
{EFFECT_ISAACS_CARPET, carpet_init, finishing<carpet_update>, nullptr},
{EFFECT_DICE_FLOOR, dice_floor_init, finishing<dice_floor_update>, nullptr},
{EFFECT_FALLING_EMBER, falling_ember_init, finishing<falling_ember_update>, nullptr},
{EFFECT_BROKEN_SHOVEL_SHADOW, shovel_shadow_init, finishing<shovel_shadow_update>, nullptr},
{EFFECT_SPAWNER, spawner_init, finishing<spawner_update>, nullptr},
{EFFECT_LIGHT, light_init, light_update, nullptr},
{EFFECT_WATER_RIPPLE, nullptr, finishing<water_ripple_update>, nullptr},
{EFFECT_RAIN_DROP, rain_drop_init, finishing<rain_drop_update>, nullptr},
{EFFECT_BACKDROP_DECORATION, kept_init, backdrop_decoration_update, nullptr},
{EFFECT_DOOR_OUTLINE, kept_init, nullptr, nullptr},
{EFFECT_TALL_LADDER, kept_init, finishing<tall_ladder_update>, nullptr},
{EFFECT_HEAVEN_LIGHT_DOOR, heaven_door_init, finishing<heaven_door_update>, heaven_door_render},
{EFFECT_TADPOLE, tadpole_init, finishing<tadpole_update>, nullptr},
{EFFECT_BEETLE, beetle_init, finishing<beetle_update>, nullptr},
{EFFECT_LIL_GHOST, lil_ghost_init, finishing<lil_ghost_update>, nullptr},
{EFFECT_CREEP_RED, creep_init, finishing<creep_update>, nullptr},
{EFFECT_CREEP_GREEN, creep_init, finishing<creep_update>, nullptr},
{EFFECT_CREEP_YELLOW, creep_init, finishing<creep_update>, nullptr},
{EFFECT_CREEP_WHITE, creep_init, finishing<creep_update>, nullptr},
{EFFECT_CREEP_BLACK, creep_init, finishing<creep_update>, nullptr},
{EFFECT_PLAYER_CREEP_WHITE, creep_init, finishing<creep_update>, nullptr},
{EFFECT_PLAYER_CREEP_BLACK, creep_init, finishing<creep_update>, nullptr},
{EFFECT_PLAYER_CREEP_RED, creep_init, finishing<creep_update>, nullptr},
{EFFECT_PLAYER_CREEP_GREEN, creep_init, finishing<creep_update>, nullptr},
{EFFECT_PLAYER_CREEP_HOLYWATER_TRAIL, creep_init, finishing<creep_update>, nullptr},
{EFFECT_CREEP_BROWN, creep_init, finishing<creep_update>, nullptr},
{EFFECT_PLAYER_CREEP_BLACKPOWDER, creep_init, finishing<creep_update>, nullptr},
{EFFECT_CREEP_SLIPPERY_BROWN, creep_init, finishing<creep_update>, nullptr},
{EFFECT_CREEP_STATIC, creep_init, finishing<creep_update>, nullptr},
{EFFECT_PLAYER_CREEP_YELLOW, creep_init, finishing<creep_update>, nullptr},
{EFFECT_PLAYER_CREEP_LEMON_MISHAP, creep_init, finishing<lasting_creep_update>, nullptr},
{EFFECT_PLAYER_CREEP_HOLYWATER, creep_init, finishing<lasting_creep_update>, nullptr},
{EFFECT_PLAYER_CREEP_LEMON_PARTY, creep_init, finishing<lasting_creep_update>, nullptr},
{EFFECT_PLAYER_CREEP_PUDDLE_MILK, creep_init, finishing<lasting_creep_update>, nullptr},
{EFFECT_PENTAGRAM_BLACKPOWDER, creep_init, finishing<pentagram_update>, nullptr},
});
// The behaviours indexed by variant, for the variants up to the last vanilla one.
constexpr int AMBIENT_VARIANT_LIMIT = 256;
constexpr std::array<AmbientBehaviour, AMBIENT_VARIANT_LIMIT> AMBIENT_TABLE = [] {
std::array<AmbientBehaviour, AMBIENT_VARIANT_LIMIT> table{};
for (const AmbientBehaviour& behaviour : AMBIENT_BEHAVIOURS)
if (behaviour.variant >= 0) table[behaviour.variant] = behaviour;
return table;
}();
static const AmbientBehaviour& behaviour_get(int variant)
{
return AMBIENT_TABLE[variant];
}
bool is_ambient_effect(int variant)
{
return variant >= 0 && variant < AMBIENT_VARIANT_LIMIT && AMBIENT_TABLE[variant].variant == variant;
}
void ambient_effect_init(Entity_Effect& effect)
{
if (auto init = behaviour_get(effect.variant).init) init(effect);
}
EffectUpdateEnd ambient_effect_update(Entity_Effect& effect)
{
auto update = behaviour_get(effect.variant).update;
return update ? update(effect) : EFFECT_UPDATE_FINISH;
}
void ambient_effect_render(Entity_Effect& effect, const Vector& offset)
{
if (auto render = behaviour_get(effect.variant).render) return render(effect, offset);
effect.sprite.Render(SpriteDraw{effect.renderPosition, {}, {}});
}