#include "engine/fx_layers.h" #include "engine/data.h" #include "entity/effect/effect.h" #include "entity/player/player.h" #include "game/game.h" #include "engine/log.h" #include "game/manager.h" #include "engine/render_passes.h" #include "level/room.h" #include "engine/seeds.h" #include #include #include #include #include constexpr std::string_view LAYER_TYPE_NAMES[] = {"", "foreground", "background", "behind", "lighting", "underwater", "overlay"}; constexpr std::string_view COLOR_CHANNELS[] = {"r", "g", "b", "a"}; constexpr const char* BACKGROUND_SHADER = "Background"; constexpr const char* COLOR_OFFSET_SHADER = "ColorOffset"; constexpr const char* WRAP_SIZE_UNIFORM = "WrapSize"; constexpr const char* POOP_CLOUDS_PATH = "gfx/backdrop/pooclouds.png"; constexpr const char* RAY_FOLDER = "gfx/"; constexpr const char* VEINS_ANM2 = "gfx/Veins.anm2"; constexpr const char* VEIN_ANIMATIONS[VEIN_SPRITE_COUNT] = {"Vein1", "Vein2"}; // The RNG shift indices of the tiles and the light ray pick (5, 9, 7), of the vein and ray phase generator (2, 7, 25) // and of Delete This's random floor (2, 9, 15). constexpr uint32_t ROOM_RNG_SHIFT = 35; constexpr uint32_t FX_RNG_SHIFT = 13; constexpr uint32_t DELETE_THIS_RNG_SHIFT = 14; // The color an image draw takes to keep its quad's own colors. constexpr KColor COLOR_UNSET = kcolor_rgba(-1, -1, -1, -1); // fxlayers.xml numbers stages by chapter: 1 to 4 the chapters' first floors, then Blue Womb (5) and on. constexpr int CHAPTER_LAST = 4; constexpr int CHAPTER_STAGE_OFFSET = 4; constexpr int STAGE_LAST_IN_CHAPTERS = 8; constexpr int STAGE_ASCENT_LAST = 6; constexpr int STAGE_CHAPTER_TWO = 3; constexpr int GREED_STAGE_SHEOL = 5; constexpr int STAGE_TYPE_COUNT = 5; constexpr uint32_t CURSE_DARKNESS = 1; // A normal room shows its floor's light rays one time in RAY_ODDS (in RAY_ODDS_CHAPTER_ONE on the first chapter). constexpr uint32_t RAY_ODDS = 2; constexpr uint32_t RAY_ODDS_CHAPTER_ONE = 3; constexpr float RAY_PHASE_RANGE = 3.1415927f; constexpr float LIGHTING_ALPHA_SCALE = 0.1f; constexpr float LIGHTING_BRIGHT = 0.9f; constexpr float PLANETARIUM_FADE_FRAMES = 30; constexpr float UNDERWATER_MARGIN = 52; constexpr float PLAYERS_CENTER_EASE = 0.1f; // The poop clouds last POOP_FX_FRAMES, fading in over the first POOP_FADE_IN_FRAMES and out over the last // POOP_FADE_OUT_FRAMES, with POOP_CLOUD_COUNT tiles drifting by speeds in the POOP_SPEED ranges. constexpr int POOP_FX_FRAMES = 180; constexpr float POOP_FADE_IN_FRAMES = 30; constexpr float POOP_FADE_OUT_FRAMES = 150; constexpr int POOP_CLOUD_COUNT = 3; constexpr float POOP_SPEED_X_MAX = 1; constexpr float POOP_SPEED_X_MIN = 0.1f; constexpr float POOP_SPEED_Y_MAX = 0.5f; constexpr float POOP_SPEED_Y_MIN = -0.5f; // The veins sit on the walls facing in (top, right, bottom, left), turn toward the players by VEIN_TURN_RATE a frame // and grow longer and dimmer with distance. Branches sprout at the sprite's nulls up to VEIN_DEPTH_MAX deep. constexpr float VEIN_ROTATION_TOP = 180; constexpr float VEIN_ROTATION_RIGHT = -90; constexpr float VEIN_ROTATION_BOTTOM = 0; constexpr float VEIN_ROTATION_LEFT = 90; constexpr float VEIN_TARGET_EASE = 0.03f; constexpr float VEIN_TURN_RATE = 0.3f; constexpr float VEIN_SCALE_MAX = 10; constexpr float VEIN_SCALE_MIN = 1; constexpr float VEIN_SCALE_PER_DISTANCE = 0.004f; constexpr float VEIN_LENGTH_MAX = 2; constexpr float VEIN_LENGTH_MIN = 0.2f; constexpr float VEIN_LENGTH_PER_DISTANCE = 0.002f; constexpr float VEIN_LENGTH_REACH = 5; constexpr float VEIN_SPEED_MIN = 0.25f; constexpr float VEIN_GROWTH_STEP = 0.05f; constexpr float VEIN_GROWTH_MAX = 1; constexpr float VEIN_GROWTH_MIN = -1; constexpr float VEIN_BRANCH_SCALE = 0.75f; constexpr float VEIN_SPROUT_SCALE = 0.85f; constexpr float VEIN_DEPTH_FADE = 0.25f; constexpr float VEIN_ALPHA_MIN = 0.3f; constexpr float VEIN_ALPHA_RANGE = 0.7f; constexpr int VEIN_DEPTH_MAX = 4; // The vein and ray phase generator, seeded anew by every LoadConfig. static RNG fxRng = {}; // Where a branch of a vein starts and the way it points. struct VeinTip { Vector position{}; float angle = 0; }; static int text_int(std::string_view text) { return std::atoi(text.data()); } static float text_float(std::string_view text) { return (float)std::atof(text.data()); } // The game's bool attribute: "true", "True" or a nonzero number. static bool is_text_true(std::string_view text) { return text == "true" || text == "True" || text_int(text) != 0; } // Calls visit with each attribute's name and text, in document order. template static void attrs_visit(DataNode node, Visit visit) { for (auto [name, text] : node_attrs(node)) visit(name, text); } // Calls visit with the children from the first one tagged tag on, as the game walks them: rapidxml's first_node(tag), // then every next sibling whatever its tag. template static void children_visit(DataNode node, std::string_view tag, Visit visit) { bool isFound = false; for (DataNode child : node_children(node)) { isFound = isFound || node_tag(child) == tag; if (isFound) visit(child); } } // The document's first top-level element tagged tag. static std::optional root_find(const Data& data, std::string_view tag) { if (node_tag(data.root) != DOCUMENT_TAG) return node_tag(data.root) == tag ? std::optional(data.root) : std::nullopt; for (DataNode child : node_children(data.root)) if (node_tag(child) == tag) return child; return std::nullopt; } // The level stage of an fxlayers.xml stage, 0 (any) staying 0. static int level_stage_get(int fxStage) { if (fxStage == 0) return 0; return fxStage <= CHAPTER_LAST ? fxStage * 2 - 1 : fxStage + CHAPTER_STAGE_OFFSET; } static FXLayerType layer_type_find(std::string_view name) { for (size_t i = 0; i < std::size(LAYER_TYPE_NAMES); i++) if (LAYER_TYPE_NAMES[i] == name) return (FXLayerType)i; return FX_LAYER_NONE; } // The channel an r, g, b or a attribute names, or -1. static int channel_find(std::string_view key) { for (size_t i = 0; i < std::size(COLOR_CHANNELS); i++) if (key == COLOR_CHANNELS[i]) return (int)i; return -1; } static void channel_set(KColor& color, int channel, float value) { std::array channels = {&color._red, &color._green, &color._blue, &color._alpha}; if (channel >= 0) *channels[channel] = value; } // The room shape whose gfx variants a room draws: 1x1 for the small ones, 1x2, 2x1 or 2x2 for the long, wide and big // ones (L shapes with the big), none for an unknown shape and 1x1 without a layout. static RoomShape room_shape_group_get(const Room& room) { if (!room.descriptor || !room.descriptor->data) return ROOMSHAPE_1x1; switch (room.descriptor->data->shape) { case ROOMSHAPE_1x1: case ROOMSHAPE_IH: case ROOMSHAPE_IV: return ROOMSHAPE_1x1; case ROOMSHAPE_1x2: case ROOMSHAPE_IIV: return ROOMSHAPE_1x2; case ROOMSHAPE_2x1: case ROOMSHAPE_IIH: return ROOMSHAPE_2x1; case ROOMSHAPE_2x2: case ROOMSHAPE_LTL: case ROOMSHAPE_LTR: case ROOMSHAPE_LBL: case ROOMSHAPE_LBR: return ROOMSHAPE_2x2; default: return ROOMSHAPE_ANY; } } static uint32_t decoration_seed_get(const Room& room) { return room.descriptor ? (uint32_t)room.descriptor->decorationSeed : 0; } // How far the room's renders are shifted: its scroll and the screen shake. static Vector render_offset_get(const Room& room) { return vector_make(room.renderScrollOffset.x + g_game->screenShakeOffset.x, room.renderScrollOffset.y + g_game->screenShakeOffset.y); } static Vector screen_size_get() { return vector_make(g_screenWidth, g_screenHeight); } // A world position on screen, snapped to whole device pixels. static Vector screen_position_get(Vector world) { float scale = g_displayPixelRatio * g_screenPointScale; float viewX = (g_screenWidth - ROOM_VIEW_WIDTH) * HALF; float viewY = (g_screenHeight - ROOM_VIEW_HEIGHT) * HALF; float x = ((world.x - ROOM_ORIGIN_X) * ROOM_SCREEN_SCALE + viewX) * scale + HALF; float y = ((world.y - ROOM_ORIGIN_Y) * ROOM_SCREEN_SCALE + viewY) * scale + HALF; return vector_make(std::floor(x) / scale, std::floor(y) / scale); } static Vector room_center_get(const FXLayers& fx) { return vector_make((fx.roomBottomRight.x + fx.roomTopLeft.x) * HALF, (fx.roomBottomRight.y + fx.roomTopLeft.y) * HALF); } // Whether something turned by angle at position points to target's side of it. static bool is_facing(Vector target, float angle, Vector position) { float radians = (angle - RIGHT_ANGLE_DEGREES) * DEGREES_TO_RADIANS; return sin_float(radians) * (target.y - position.y) + cos_float(radians) * (target.x - position.x) >= 0; } static void shader_use(const char* name) { if (KAGE::Graphics::Shader* shader = KAGE::Graphics::manager.shader_find(name)) KAGE::Graphics::manager.currentShader = shader; } static void tile_velocity_pick(FXTile& tile, const FXLayer& layer, RNG& rng) { tile.velocity.x = rng.RandomFloat() * (layer.xMax - layer.xMin) + layer.xMin; tile.velocity.y = rng.RandomFloat() * (layer.yMax - layer.yMin) + layer.yMin; } // Starts a drifting tile at a random texel of its image, randomly mirrored. static void tile_place(FXTile& tile, const KAGE::Graphics::ImageBase& image, RNG& rng) { tile.position.x = rng.RandomFloat() * (float)image.width; tile.position.y = rng.RandomFloat() * (float)image.height; tile.isFlipX = rng.RandomFloat() < HALF; tile.isFlipY = rng.RandomFloat() < HALF; } // Scrolls a drifting tile by its velocity, wrapping around its image. static void tile_drift(FXTile& tile, const KAGE::Graphics::ImageBase& image) { tile.position.x = std::fmod(tile.position.x - tile.velocity.x, (float)image.width); tile.position.y = std::fmod(tile.velocity.y + tile.position.y, (float)image.height); } // Puts a parallax tile where the screen position of the point the layers follow takes it. static void tile_follow(FXTile& tile, Vector screen, float parallax) { tile.position.x = screen.x * parallax + tile.velocity.x; tile.position.y = screen.y * parallax + tile.velocity.y; } // The texels of a tile's image a quad shows: size of them from the tile's texel less origin, mirrored with the tile. static SourceQuad tile_source_get(const FXTile& tile, Vector origin, Vector size) { if (tile.isFlipX) { origin.x = -origin.x; size.x = -size.x; } if (tile.isFlipY) { origin.y = -origin.y; size.y = -size.y; } return KAGE::Graphics::source_quad_rect(vector_make(tile.position.x - origin.x, tile.position.y - origin.y), size); } // Where a vein's branch at one of its sprite's nulls starts and points: the null unscaled from screen units, turned // and scaled with the vein. static VeinTip vein_tip_get(const FXVein& vein, const NullFrame& frame) { float radians = vein.rotation * DEGREES_TO_RADIANS; float cosine = cos_float(radians); float sine = sin_float(radians); float x = frame.pos.x / ROOM_SCREEN_SCALE; float y = frame.pos.y / ROOM_SCREEN_SCALE; VeinTip tip; tip.angle = normalize_angle_degrees(vein.rotation + frame.rotation); tip.position = vector_make((x * cosine - y * sine) * vein.scale + vein.position.x, (y * cosine + x * sine) * vein.scale + vein.position.y); return tip; } // The null a vein's sprite shows for one of its branches, or null without an animation (where the game crashes). static const NullFrame* vein_null_get(const FXLayers& fx, const FXVein& vein, int branch) { const AnimationState& animation = fx.veinSprites[vein.spriteIndex].animState; return animation.animData ? animation.GetNullFrameById(branch) : nullptr; } static void load_failure_log(const std::string& path) { std::string message = "[warn] failed to load " + path + "\n"; KAGE_LogMessage(LOG_INFO, (uint8_t*)message.data()); } // Whether a rayGroup's stages (comma separated fxlayers.xml stages, an a suffix for stage type 1) hold the floor. // A b suffix marks the group for nothing that reads it, and is dropped first. static bool is_stage_listed(const FXLayers& fx, std::string_view stages) { for (size_t start = 0; start < stages.size();) { size_t end = std::min(stages.find(',', start), stages.size()); std::string stage(stages.substr(start, end - start)); int stageType = 0; start = end + 1; if (!stage.empty() && stage.back() == 'b') stage.pop_back(); if (!stage.empty() && stage.back() == 'a') { stage.pop_back(); stageType = STAGETYPE_WOTL; } if (fx.is_stage_shown(level_stage_get(std::atoi(stage.c_str())), 1u << stageType)) return true; } return false; } // Applies a color child of a params node (colorModifier, waterColor, shadowColor, lightColor or waterEffectColor). static void color_node_parse(FXParams& params, DataNode node) { std::string_view tag = node_tag(node); attrs_visit(node, [&](std::string_view key, std::string_view text) { float value = text_float(text); int channel = channel_find(key); if (tag == "colorModifier") { channel_set(params.roomColor, channel, value); if (key == "brightness") params.brightness = value; else if (key == "contrast") params.contrast = value; } else if (tag == "waterColor") { channel_set(params.waterColor, channel, value); if (key == "rMul") params.waterColorMultiplier._red = value; else if (key == "gMul") params.waterColorMultiplier._green = value; else if (key == "bMul") params.waterColorMultiplier._blue = value; } else if (tag == "shadowColor") channel_set(params.shadowColor, channel, value); else if (tag == "lightColor") channel_set(params.lightColor, channel, value); else if (tag == "waterEffectColor" && channel >= 0) params.waterEffectColor._tint[channel] = value; }); } // 0098fa60 Applies the params nodes of fxParams that suit the floor and the room's backdrop to the floor's look, in // order: water and shadow alpha from their attributes, the colors from their children. static void fx_params_parse(FXLayers& fx, DataNode root) { children_visit(root, "params", [&](DataNode node) { int backdrop = 0; int layerStage = 0; uint32_t stageTypes = UINT32_MAX; attrs_visit(node, [&](std::string_view key, std::string_view text) { if (key == "stage") layerStage = level_stage_get(text_int(text)); else if (key == "altStages") stageTypes = text_int(text); else if (key == "backdrop") backdrop = text_int(text); }); if (!fx.is_stage_shown(layerStage, stageTypes) || (backdrop && backdrop != fx.backdropType)) return; attrs_visit(node, [&](std::string_view key, std::string_view text) { if (key == "waterv2") fx.fxParams.isWaterV2 = is_text_true(text); else if (key == "shadowAlpha") fx.fxParams.shadowAlpha = text_float(text); }); for (DataNode child : node_children(node)) color_node_parse(fx.fxParams, child); }); } // Adds the fx layers that show on the floor and the room's backdrop, each with its image (a random one of its gfx // variants for the room's shape when it has them) and its tiles laid out by the room's decoration seed. // The game reuses one layer for every fx node without resetting its type and parallax, so a node lacking them keeps // the previous node's. static void layers_load(FXLayers& fx, DataNode root, int stageId) { Room& room = *g_game->room; std::string gfxRoot(node_attr(root, "gfxroot")); RoomShape shapeGroup = room_shape_group_get(room); FXLayerType type = FX_LAYER_NONE; float parallax = 0; children_visit(root, "fx", [&](DataNode node) { FXLayer layer; std::string path; std::vector paths; int numLayers = 1; layer.type = type; layer.parallax = parallax; attrs_visit(node, [&](std::string_view key, std::string_view text) { if (key == "id") layer.id = text_int(text); else if (key == "path") path = gfxRoot + std::string(text); else if (key == "numLayers") numLayers = text_int(text); else if (key == "xMin") layer.xMin = text_float(text); else if (key == "xMax") layer.xMax = text_float(text); else if (key == "yMin") layer.yMin = text_float(text); else if (key == "yMax") layer.yMax = text_float(text); else if (key == "layer") layer.type = layer_type_find(text); else if (key == "stage") layer.stage = level_stage_get(text_int(text)); else if (key == "altStages") layer.altStages = text_int(text); else if (key == "onlyDefaultBackdrop") layer.isOnlyDefaultBackdrop = is_text_true(text); else if (key == "backdrop") layer.backdrop = text_int(text); else if (key == "blendMode") layer.blendMode = text_int(text); else if (key == "useBGShader") layer.isBGShader = is_text_true(text); else if (key == "parallax") { layer.motion = FX_MOTION_PARALLAX; layer.parallax = text_float(text); } }); type = layer.type; parallax = layer.parallax; children_visit(node, "gfx", [&](DataNode gfx) { std::string gfxPath; int shape = ROOMSHAPE_1x1; attrs_visit(gfx, [&](std::string_view key, std::string_view text) { if (key == "path") gfxPath = gfxRoot + std::string(text); else if (key == "roomshape") shape = text_int(text); }); if (shape == shapeGroup) paths.push_back(gfxPath); }); if (paths.empty()) paths.push_back(path); bool isBackdropShown = !layer.backdrop || layer.backdrop == fx.backdropType; if (!fx.is_stage_shown(layer.stage, layer.altStages) || !isBackdropShown) return; if (layer.isOnlyDefaultBackdrop && g_game->roomConfig.stages[stageId].backdrop != fx.backdropType) return; RNG rng = {}; rng.SetSeed(decoration_seed_get(room), ROOM_RNG_SHIFT); FXLayer& added = fx.layers.emplace_back(std::move(layer)); std::string imagePath = paths[rng.RandomInt((uint32_t)paths.size())]; added.image = Manager::LoadImage(imagePath); if (!added.image) return load_failure_log(imagePath); KAGE::Graphics::ImageBase& image = *added.image; bool isFiltered = image.minFilter == FILTER_LINEAR && image.magFilter == FILTER_LINEAR; if (image.wrapS != WRAP_REPEAT || image.wrapT != WRAP_REPEAT) image.wrap_set(WRAP_REPEAT, WRAP_REPEAT); if (!added.isBGShader && added.parallax != 0 && !isFiltered) image.filter_set(FILTER_LINEAR, FILTER_LINEAR); added.tiles.resize(std::max(numLayers, 0)); for (FXTile& tile : added.tiles) { tile_velocity_pick(tile, added, rng); if (added.motion == FX_MOTION_PARALLAX) { tile.velocity = Vector{}; tile_follow(tile, screen_position_get(fx.playersCenter), added.parallax); } else if (!added.isBGShader) tile_place(tile, image, rng); } }); } // Adds the light ray groups that show on the floor, loading the ray images of every group. // The game reuses one group for every rayGroup node without resetting its perspective, so a node lacking one keeps the // previous node's. static void ray_groups_load(FXLayers& fx, DataNode root) { float perspective = 0; children_visit(root, "rayGroup", [&](DataNode node) { FXRayGroup group; std::string_view stages; group.perspective = perspective; attrs_visit(node, [&](std::string_view key, std::string_view text) { if (key == "xMin") group.xMin = text_float(text); else if (key == "xMax") group.xMax = text_float(text); else if (key == "topParallax") group.topParallax = text_float(text); else if (key == "bottomParallax") group.bottomParallax = text_float(text); else if (key == "rayLength") group.rayLength = text_float(text); else if (key == "raySpacing") group.raySpacing = text_float(text); else if (key == "perspective") group.perspective = text_float(text); else if (key == "stages") stages = text; }); perspective = group.perspective; bool isShown = is_stage_listed(fx, stages); children_visit(node, "fxRay", [&](DataNode rayNode) { FXRay& ray = group.rays.emplace_back(); std::string path; ray.phase = fxRng.RandomFloat() * RAY_PHASE_RANGE; attrs_visit(rayNode, [&](std::string_view key, std::string_view text) { if (key == "path") path = RAY_FOLDER + std::string(text); else if (key == "opacity") ray.opacity = text_float(text); else if (key == "animationSpeed") ray.animationSpeed = text_float(text); }); ray.image = Manager::LoadImage(path); if (ray.image && (ray.image->wrapS != WRAP_CLAMP || ray.image->wrapT != WRAP_CLAMP)) ray.image->wrap_set(WRAP_CLAMP, WRAP_CLAMP); }); if (isShown) fx.rayGroups.push_back(std::move(group)); }); } // Lays Hush's veins out round the room's walls from its top left corner, evenly spaced and facing in, and grows their // branches in Hush's room (the boss room of Blue Womb). static void veins_place(FXLayers& fx) { Vector topLeft = fx.roomTopLeft; Vector bottomRight = fx.roomBottomRight; float width = bottomRight.x - topLeft.x; float height = bottomRight.y - topLeft.y; float doubleWidth = width + width; for (int i = 0; i < VEIN_COUNT; i++) { FXVein& vein = fx.veins[i]; float along = (height + height + doubleWidth) * ((float)i / VEIN_COUNT); if (along < width) { vein.position = vector_make(along / width * width + topLeft.x, topLeft.y); vein.baseRotation = VEIN_ROTATION_TOP; } else if (along < height + width) { vein.position = vector_make(bottomRight.x, (along - width) / height * height + topLeft.y); vein.baseRotation = VEIN_ROTATION_RIGHT; } else if (along < height + doubleWidth) { vein.position = vector_make((along - width - height) / width * width + topLeft.x, bottomRight.y); vein.baseRotation = VEIN_ROTATION_BOTTOM; } else { vein.position = vector_make(topLeft.x, (along - doubleWidth - height) / height * height + topLeft.y); vein.baseRotation = VEIN_ROTATION_LEFT; } vein.spriteIndex = fxRng.Next() & 1; for (std::unique_ptr& branch : vein.branches) branch.reset(); if (fx.stage == STAGE_BLUE_WOMB && fx.stageType == 0 && g_game->room->roomType == ROOM_BOSS) fx.vein_branches_grow(vein); } } // How wounded the first Hush the room updates is, 0 at full health to 1, or 0 without one. static float hush_wound_get(Room& room) { for (Entity* entity : room.entityList.updateEL) { if (entity->type == ENTITY_HUSH && entity->variant == 0) return std::min(1.0f, std::max(0.0f, 1 - entity->health / entity->maxHitPoints)); } return 0; } // Draws the sprite trails the Beast leaves, which its arena shows under the room's layers. static void beast_trails_render(Room& room) { for (Entity* entity : room.entityList.updateEL) { bool isBeastTrail = entity->variant == EFFECT_SPRITE_TRAIL && entity->spawnerType == ENTITY_BEAST; if (entity->type == ENTITY_EFFECT && isBeastTrail) entity->Render(g_game->room->renderScrollOffset); } } // Draws the poop clouds over the screen in their color, fading in over their first frames and out over their last. static void poop_clouds_render(const FXLayers& fx) { const FXLayer& clouds = fx.poopLayer; float countdown = (float)fx.poopFxCountdown; float alpha = fx.poopFxCountdown <= POOP_FADE_OUT_FRAMES ? countdown / POOP_FADE_OUT_FRAMES : (countdown - POOP_FX_FRAMES) / -POOP_FADE_IN_FRAMES; KAGE::Graphics::manager.blend_set(KAGE::Graphics::BLEND_NORMAL); for (const FXTile& tile : clouds.tiles) { SourceQuad source = tile_source_get(tile, render_offset_get(*g_game->room), screen_size_get()); KAGE::Graphics::ColorQuad quad = KAGE::Graphics::color_quad_rect({}, screen_size_get(), WHITE); shader_use(COLOR_OFFSET_SHADER); apply_sprite_shader_params(fx.poopFxColor, SPRITE_SHADER_COLOR_APPLY, *clouds.image); clouds.image->Render(source, quad, kcolor_rgba(1, 1, 1, alpha)); } } // Whether light rays show: lighting is on and the floor has no Curse of Darkness. static bool is_lit() { if (!g_manager->optionsConfig.render.isLightingEnabled) return false; uint32_t curses = g_game->debugCurses | g_game->curses | Seeds::GetForcedCurses(); return !(curses & ~Seeds::GetPreventedCurses() & CURSE_DARKNESS); } // Draws a ray's image into quad with the pulse's share of alpha, then its mirror image with the rest. static void ray_render(const FXRay& ray, const KAGE::Graphics::ColorQuad& quad, float alpha) { float pulse = (sin_float(ray.phase) + 1) * HALF; std::array alphas = {pulse * alpha, (1 - pulse) * alpha}; std::array sources = {KAGE::Graphics::source_quad_rect({}, vector_make(1, 1)), KAGE::Graphics::source_quad_rect(vector_make(1, 0), vector_make(-1, 1))}; for (size_t i = 0; i < sources.size(); i++) { ColorMod color = COLOR_DEFAULT; color._tint[3] = alphas[i]; sources[i]._coordinateSpace = KAGE::Graphics::COORDINATES_NORMALIZED; apply_sprite_shader_params(color, SPRITE_SHADER_COLOR_APPLY, *ray.image); ray.image->Render(sources[i], quad, kcolor_rgba(1, 1, 1, alphas[i])); } } // Draws the room's light ray group from the top of the screen down, spread over its width, leaning and fading as the // players leave the room's center, then advances the rays' pulses. static void rays_render(FXLayers& fx) { Room& room = *g_game->room; FXRayGroup& group = fx.rayGroups[fx.rayGroupIndex]; Vector center = screen_position_get(room_center_get(fx)); Vector players = screen_position_get(fx.playersCenter); float top = g_game->screenShakeOffset.y + room.renderScrollOffset.y; center.x += room.renderScrollOffset.x; center.y += room.renderScrollOffset.y; float leanX = players.x - center.x + room.renderScrollOffset.x; float leanY = players.y - center.y + room.renderScrollOffset.y; float count = (float)group.rays.size(); float width = (group.xMax - group.xMin - (float)(group.rays.size() - 1) * group.raySpacing) / count; float halfWidth = width * HALF; float fadeX = std::max(0.0f, 1 - std::abs(leanX) / center.x); float fadeY = std::max(0.0f, 1 - std::abs(leanY) / center.y); KAGE::Graphics::manager.blend_set(KAGE::Graphics::BLEND_ADDITIVE); shader_use(COLOR_OFFSET_SHADER); for (size_t i = 0; i < group.rays.size(); i++) { FXRay& ray = group.rays[i]; float offset = (width + group.raySpacing) * (float)i + group.xMin; float topX = center.x + offset; float topShift = leanX * group.topParallax; float bottomX = (halfWidth + offset) * group.perspective + center.x; float bottomShift = leanX * group.bottomParallax; float bottomY = leanY * group.bottomParallax + group.rayLength; DestinationQuad corners; corners._topLeft = vector_make(topShift + topX, top); corners._topRight = vector_make(topX + width + topShift, top); corners._bottomLeft = vector_make(bottomX - halfWidth + bottomShift, bottomY); corners._bottomRight = vector_make(bottomX + halfWidth + bottomShift, bottomY); if (ray.image) ray_render(ray, KAGE::Graphics::ColorQuad(corners, WHITE), fadeX * fadeY * ray.opacity); ray.phase = ray.animationSpeed + ray.phase; } } // 00990a40 Loads fxlayers.xml for the floor and the current room: the layers and light rays that show, the floor's look // and Hush's veins. Greed floors count as the normal floors of their chapter, the Mausoleum's exit to Corpse as Womb, // and Delete This picks a random floor by the run's seed. void FXLayers::LoadConfig(std::string_view path, int levelStage, int levelStageType) { Room& room = *g_game->room; Level& level = *g_game; stage = levelStage; stageType = levelStageType; fxRng.SetSeed(Random(), FX_RNG_SHIFT); roomTopLeft = room.topLeftPos; roomBottomRight = room.bottomRightPos; int stageId = RoomConfig::GetStageID(stage, stageType, ROOM_MODE_CURRENT); if (g_game->difficulty == DIFFICULTY_GREED || g_game->difficulty == DIFFICULTY_GREEDIER) stage = levelStage <= CHAPTER_LAST ? levelStage * 2 - 1 : (levelStage == GREED_STAGE_SHEOL ? STAGE_SHEOL : 0); backdropType = room.backdropType; if (level.get_secret_exit_kind() == SECRET_EXIT_MOMS_HEART && g_game->currentRoomIdx == ROOM_SECRET_EXIT_IDX) { stage = STAGE_WOMB_I; stageType = 0; } else if (level.IsMausoleumHeartStage()) backdropType = BACKDROP_CORPSE_ENTRANCE; if (g_game->challenge == CHALLENGE_DELETE_THIS) { RNG rng = {}; rng.SetSeed(g_game->dungeonPlacementSeed, DELETE_THIS_RNG_SHIFT); if ((uint32_t)(stage - 1) < DELETE_THIS_STAGES) stage = rng.Next() % DELETE_THIS_STAGES + 1; stageType = rng.Next() % STAGE_TYPE_COUNT; if (stageType == STAGETYPE_GREEDMODE) stageType = STAGETYPE_REPENTANCE; } clear(); playersCenter = Vector{}; Data data; data_load(data, path); if (!data.isLoaded) return; if (std::optional root = root_find(data, "fxLayers")) layers_load(*this, *root, stageId); if (std::optional root = root_find(data, "fxRays")) ray_groups_load(*this, *root); RNG rng = {}; rng.SetSeed(decoration_seed_get(room), ROOM_RNG_SHIFT); rayGroupIndex = rayGroups.empty() ? -1 : (int)rng.RandomInt((uint32_t)rayGroups.size()); uint32_t rayOdds = stage < STAGE_CHAPTER_TWO ? RAY_ODDS_CHAPTER_ONE : RAY_ODDS; bool isRayless = room.roomType == ROOM_DEFAULT && rng.RandomInt(rayOdds); if (isRayless && (stage != STAGE_SHEOL || g_game->stageType == 0)) rayGroupIndex = -1; fxParams = FXParams(); if (std::optional root = root_find(data, "fxParams")) fx_params_parse(*this, *root); for (int i = 0; i < VEIN_SPRITE_COUNT; i++) { veinSprites[i].Load(VEINS_ANM2, GRAPHICS_LOAD); veinSprites[i].GetLayer(0)->minFilterMode = FILTER_LINEAR; veinSprites[i].GetLayer(0)->magFilterMode = FILTER_LINEAR; veinSprites[i].Play(VEIN_ANIMATIONS[i]); } veinTarget = room_center_get(*this); veins_place(*this); poopFxCountdown = 0; poopFxColor = COLOR_DEFAULT; isLoaded = true; } // 00993840 Drops the layers and light rays with their images and Hush's veins, and resets the floor's look. void FXLayers::clear() { isLoaded = false; rayGroups.clear(); layers.clear(); for (FXVein& vein : veins) for (std::unique_ptr& branch : vein.branches) branch.reset(); fxParams = FXParams(); } // 0098f9d0 Whether a layer of layerStage (0 for any) and the stage types stageTypeMask has a bit for shows on the // floor. Stages up to Womb II match both floors of their chapter. On the Ascent, Blue Womb layers with the Repentance // stage type show on every floor. bool FXLayers::is_stage_shown(int layerStage, uint32_t stageTypeMask) const { bool isAscent = g_game->stage >= 1 && g_game->stage <= STAGE_ASCENT_LAST && (g_game->gameStateFlags & 1ull << GAME_STATE_BACKWARDS_PATH); bool isStageMatch = stage == layerStage; if (isAscent && layerStage == STAGE_BLUE_WOMB) { if (stageTypeMask & 1u << STAGETYPE_REPENTANCE) return true; } else if (layerStage == 0) return true; else if (layerStage <= STAGE_LAST_IN_CHAPTERS) isStageMatch = (stage - 1) / 2 == (layerStage - 1) / 2; return isStageMatch && (stageTypeMask & 1u << (stageType & 31)); } // 009960b0 Spreads poop clouds over the screen in color for POOP_FX_FRAMES, or brings back clouds that are fading out. // Poop pills, bombs and farts call it (Lua's FXLayers:AddPoopFx). // The game lays the clouds out on a missing pooclouds.png and crashes. Here it stops after the warning. void FXLayers::AddPoopFx(const ColorMod& color) { poopFxColor = color; if (poopFxCountdown > 0) { if (poopFxCountdown < POOP_FADE_OUT_FRAMES) { float fade = (float)poopFxCountdown / POOP_FADE_OUT_FRAMES; poopFxCountdown = (int)(POOP_FX_FRAMES - fade * POOP_FADE_IN_FRAMES); } return; } RNG rng = {}; poopFxCountdown = POOP_FX_FRAMES; poopLayer.motion = FX_MOTION_DRIFT; poopLayer.xMin = POOP_SPEED_X_MIN; poopLayer.xMax = POOP_SPEED_X_MAX; poopLayer.yMin = POOP_SPEED_Y_MIN; poopLayer.yMax = POOP_SPEED_Y_MAX; rng.SetSeed(decoration_seed_get(*g_game->room), ROOM_RNG_SHIFT); if (!poopLayer.image) { poopLayer.image = Manager::LoadImage(POOP_CLOUDS_PATH); if (!poopLayer.image) { poopFxCountdown = 0; KAGE_LogMessage(LOG_INFO, (uint8_t*)"[warn] failed to load pooclouds.png\n"); return; } if (poopLayer.image->wrapS != WRAP_REPEAT || poopLayer.image->wrapT != WRAP_REPEAT) poopLayer.image->wrap_set(WRAP_REPEAT, WRAP_REPEAT); } poopLayer.tiles.resize(POOP_CLOUD_COUNT); for (FXTile& tile : poopLayer.tiles) { tile_velocity_pick(tile, poopLayer, rng); tile_place(tile, *poopLayer.image, rng); } } // 00993a70 Moves everything on a frame: drifting tiles scroll, parallax tiles follow the players, the poop clouds count // down, Hush's veins turn, grow and dim with Hush's health, then the point the layers follow eases toward the players' // center, or snaps to it. // A layer whose image failed to load stays put, where the game crashes. void FXLayers::Update(PlayerFollow follow) { if (!isLoaded) return; Vector screen = screen_position_get(playersCenter); for (FXLayer& layer : layers) for (FXTile& tile : layer.tiles) { if (layer.motion == FX_MOTION_PARALLAX) tile_follow(tile, screen, layer.parallax); else if (layer.image) tile_drift(tile, *layer.image); } if (poopFxCountdown > 0) { poopFxCountdown--; for (FXTile& tile : poopLayer.tiles) tile_drift(tile, *poopLayer.image); } if (veins[0].branches[0]) { float wound = hush_wound_get(*g_game->room); float woundSquared = wound * wound; veinTarget.y = (playersCenter.y - veinTarget.y) * VEIN_TARGET_EASE + veinTarget.y; veinTarget.x = (playersCenter.x - veinTarget.x) * VEIN_TARGET_EASE + veinTarget.x; for (FXVein& vein : veins) { float dy = veinTarget.y - vein.position.y; float dx = veinTarget.x - vein.position.x; float distance = std::sqrt(dy * dy + dx * dx); float reach = (distance - VEIN_LENGTH_REACH) * VEIN_LENGTH_PER_DISTANCE; float angle = normalize_angle_degrees(atan2_float(dy, dx) * RADIANS_TO_DEGREES + RIGHT_ANGLE_DEGREES); vein.scale = std::min(VEIN_SCALE_MAX, std::max(VEIN_SCALE_MIN, distance * VEIN_SCALE_PER_DISTANCE)); vein.rotation = angle_lerp(vein.baseRotation, angle, VEIN_TURN_RATE); vein.growth = VEIN_GROWTH_MAX; vein.length = std::min(VEIN_LENGTH_MAX, std::max(VEIN_LENGTH_MIN, reach)) * woundSquared; vein_update(vein); } for (ANM2& sprite : veinSprites) { sprite.playbackSpeed = std::max(VEIN_SPEED_MIN, wound); sprite.Update(); } } if ((playersCenter.x != 0 || playersCenter.y != 0) && follow == PLAYER_FOLLOW_EASE) { Vector center = g_game->playerManager.players_center_position(CENTER_CACHED); playersCenter.x = (center.x - playersCenter.x) * PLAYERS_CENTER_EASE + playersCenter.x; playersCenter.y = (center.y - playersCenter.y) * PLAYERS_CENTER_EASE + playersCenter.y; } else playersCenter = g_game->playerManager.players_center_position(CENTER_FRESH); } // 00996b30 Grows a vein's branches at load, fully grown, at the nulls of its sprite that point to the players' side, // and theirs in turn below VEIN_DEPTH_MAX. void FXLayers::vein_branches_grow(FXVein& vein) { for (int i = 0; i < VEIN_BRANCHES; i++) { std::unique_ptr& branch = vein.branches[i]; const NullFrame* frame = vein_null_get(*this, vein, i); branch.reset(); if (vein.depth > VEIN_DEPTH_MAX || !frame) continue; VeinTip tip = vein_tip_get(vein, *frame); if (!is_facing(veinTarget, tip.angle, vein.position)) continue; branch = std::make_unique(); branch->spriteIndex = fxRng.Next() & 1; branch->rotation = tip.angle; branch->position = tip.position; branch->baseRotation = vein.baseRotation; branch->scale = vein.scale * VEIN_BRANCH_SCALE; branch->length = vein.length; branch->growth = VEIN_GROWTH_MAX; branch->depth = vein.depth + 1; vein_branches_grow(*branch); } } // 00996e90 Grows a vein while it points to the players' side, letting its branches grow too. Pointing away it has its // branches retract, or withers once it has none. Then it moves its branches to its sprite's nulls and updates them, // sprouts new ones from a grown vein toward the players, and drops the withered ones. void FXLayers::vein_update(FXVein& vein) { bool isBranched = std::any_of(vein.branches.begin(), vein.branches.end(), [](auto& branch) { return !!branch; }); if (!vein.isRetracting && is_facing(veinTarget, vein.rotation, vein.position)) { vein.growth = std::min(vein.growth + VEIN_GROWTH_STEP, VEIN_GROWTH_MAX); for (std::unique_ptr& branch : vein.branches) if (branch) branch->isRetracting = false; } else if (isBranched) { for (std::unique_ptr& branch : vein.branches) if (branch) branch->isRetracting = true; } else vein.growth = std::max(vein.growth - VEIN_GROWTH_STEP, VEIN_GROWTH_MIN); for (int i = 0; i < VEIN_BRANCHES; i++) { std::unique_ptr& branch = vein.branches[i]; const NullFrame* frame = vein_null_get(*this, vein, i); if (!frame) continue; VeinTip tip = vein_tip_get(vein, *frame); if (branch && branch->growth < 0) branch.reset(); else if (branch) { branch->position = tip.position; branch->rotation = tip.angle; branch->scale = vein.scale * VEIN_BRANCH_SCALE; branch->length = vein.length; vein_update(*branch); } else if (vein.depth < VEIN_DEPTH_MAX && vein.growth >= VEIN_GROWTH_MAX && is_facing(veinTarget, tip.angle, tip.position)) { branch = std::make_unique(); branch->spriteIndex = fxRng.Next() & 1; branch->position = tip.position; branch->rotation = tip.angle; branch->scale = vein.scale * VEIN_SPROUT_SCALE; branch->length = vein.length; branch->depth = vein.depth + 1; } } } // 009948f0 Draws the Beast's sprite trails in its arena, then the foreground layers, the poop clouds and, with lighting // on and no Curse of Darkness, the room's light rays. It ends on the plain texture shader. void FXLayers::Render() { KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; Room& room = *g_game->room; if (room.backdropType == BACKDROP_DUNGEON_BEAST) beast_trails_render(room); if (!isLoaded) return; KAGE::Graphics::BlendMode blendMode = graphics.blendMode; layers_render(FX_LAYER_FOREGROUND); if (poopFxCountdown > 0) poop_clouds_render(*this); if (is_lit() && rayGroupIndex >= 0) rays_render(*this); graphics.blendMode = blendMode; graphics.shader_default_set(); } // 00994120 Draws a layer's tiles over the screen: an overlay stretches its whole image, the others show a screen of it // from each tile's texel, centered on the room. Background shader layers give the shader their wrap size (Planetarium // ones fading in over their room's first second), and parallax layers draw half transparent in bright rooms. void FXLayers::layer_render(const FXLayer& layer) { KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; KAGE::Graphics::ImageBase& image = *layer.image; Room& room = *g_game->room; float lightingAlpha = room.GetLightingAlpha() * LIGHTING_ALPHA_SCALE; KAGE::Graphics::Shader* previousShader = graphics.currentShader; if (layer.isBGShader) shader_use(BACKGROUND_SHADER); Vector center = screen_position_get(room_center_get(*this)); Vector offset = render_offset_get(room); Vector imageSize = vector_make((float)image.width, (float)image.height); Vector origin = vector_make(offset.x - imageSize.x * HALF + center.x, offset.y - imageSize.y * HALF + center.y); for (const FXTile& tile : layer.tiles) { SourceQuad source = layer.type == FX_LAYER_OVERLAY ? KAGE::Graphics::source_quad_rect({}, imageSize) : tile_source_get(tile, origin, screen_size_get()); KAGE::Graphics::ColorQuad quad = KAGE::Graphics::color_quad_rect({}, screen_size_get(), WHITE); KColor color = COLOR_UNSET; if (layer.isBGShader) { std::array wrapSize = {imageSize.x / (float)image.textureWidth, imageSize.y / (float)image.textureHeight}; color = WHITE; if (layer.backdrop == BACKDROP_PLANETARIUM) { float fade = std::min(1.0f, std::max(0.0f, (float)room.GetFrameCount() / PLANETARIUM_FADE_FRAMES)); color = kcolor_rgba(fade, fade, fade, 1); } if (graphics.currentShader) graphics.currentShader->set_uniform(WRAP_SIZE_UNIFORM, KAGE::Graphics::UNIFORM_VEC2, wrapSize.data()); } else if (layer.parallax != 0 && lightingAlpha > LIGHTING_BRIGHT) color = kcolor_rgba(1, 1, 1, HALF); image.Render(source, quad, color); } if (previousShader && previousShader->isLoaded) graphics.currentShader = previousShader; } // The layers of one pass, each in its blend mode, the blend mode put back after. A layer without an image is skipped // where the game crashes. void FXLayers::layers_render(FXLayerType type) { KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager; KAGE::Graphics::BlendMode blendMode = graphics.blendMode; if (isLoaded) for (const FXLayer& layer : layers) { if (layer.type != type || !layer.image) continue; graphics.blend_set((KAGE::Graphics::BlendType)layer.blendMode); layer_render(layer); } graphics.blendMode = blendMode; } // 00994670 Draws the behind layers, under the room's backdrop. void FXLayers::behind_layers_render() { layers_render(FX_LAYER_BEHIND); } // 009947b0 Draws the background layers, over the backdrop and under the entities. void FXLayers::background_layers_render() { layers_render(FX_LAYER_BACKGROUND); } // 00995e00 Draws the overlay layers, over everything of the room. void FXLayers::overlay_layers_render() { layers_render(FX_LAYER_OVERLAY); } // 009956e0 Draws the lighting layers over the screen in color, the room's light, into the lighting target. Without a // lighting tile it fills the screen with color instead. void FXLayers::lighting_layers_render(const KColor& color) { if (!isLoaded) return; KAGE::Graphics::ColorQuad quad = KAGE::Graphics::color_quad_rect({}, screen_size_get(), color); bool isDrawn = false; for (const FXLayer& layer : layers) { if (layer.type != FX_LAYER_LIGHTING || !layer.image) continue; Vector center = screen_position_get(room_center_get(*this)); Vector offset = render_offset_get(*g_game->room); Vector origin = vector_make(offset.x - ((float)layer.image->width * HALF - center.x), offset.y - ((float)layer.image->height * HALF - center.y)); for (const FXTile& tile : layer.tiles) { isDrawn = true; layer.image->Render(tile_source_get(tile, origin, screen_size_get()), quad, COLOR_UNSET); } } if (!isDrawn) render_color_shader_pass(quad); } // 00995af0 Draws the underwater layers into the water: the room's floor on screen and a margin round it. void FXLayers::underwater_layers_render() { if (!isLoaded) return; Room& room = *g_game->room; Vector topLeft = room.floorScreenTopLeft; Vector bottomRight = room.floorScreenBottomRight; Vector size = vector_make(bottomRight.x - topLeft.x, bottomRight.y - topLeft.y); Vector center = vector_make((topLeft.x + bottomRight.x) * HALF, (topLeft.y + bottomRight.y) * HALF); Vector quadAt = vector_make(topLeft.x - UNDERWATER_MARGIN, topLeft.y - UNDERWATER_MARGIN); Vector quadSize = vector_make(size.x + UNDERWATER_MARGIN * 2, size.y + UNDERWATER_MARGIN * 2); KAGE::Graphics::ColorQuad quad = KAGE::Graphics::color_quad_rect(quadAt, quadSize, WHITE); KAGE::Graphics::manager.blend_set(KAGE::Graphics::BLEND_NORMAL); for (const FXLayer& layer : layers) { if (layer.type != FX_LAYER_UNDERWATER || !layer.image) continue; Vector origin = vector_make((float)layer.image->width * HALF + center.x, (float)layer.image->height * HALF + center.y); for (const FXTile& tile : layer.tiles) layer.image->Render(tile_source_get(tile, origin, size), quad, COLOR_UNSET); } } // 00996580 Draws Hush's veins, once they have grown. void FXLayers::veins_render() { if (!veins[0].branches[0]) return; for (const FXVein& vein : veins) vein_render(&vein); } // 009968b0 Draws a vein and its branches, each faded in by its growth and dimmed by its depth and by Hush's health. void FXLayers::vein_render(const FXVein* vein) { if (!vein) return; ANM2& sprite = veinSprites[vein->spriteIndex]; Room& room = *g_game->room; float size = vein->scale * vein->growth; float depthAlpha = (1 - (float)vein->depth * VEIN_DEPTH_FADE) * VEIN_ALPHA_RANGE + VEIN_ALPHA_MIN; float alpha = depthAlpha * vein->length * vein->growth; Vector screen = screen_position_get(vein->position); SpriteDraw draw; sprite.scale = vector_make(size, size); sprite.rotation = vein->rotation; sprite.color = COLOR_DEFAULT; sprite.color._tint[3] = alpha; draw.position = vector_make(screen.x + room.renderScrollOffset.x + g_game->screenShakeOffset.x, screen.y + room.renderScrollOffset.y + g_game->screenShakeOffset.y); sprite.Render(draw); for (const std::unique_ptr& branch : vein->branches) vein_render(branch.get()); }