Files
isaac-port/src/anm2.cpp
T

1755 lines
66 KiB
C++

#include "anm2.h"
#include "game.h"
#include "kage_graphics.h"
#include "data.h"
#include "manager.h"
#include "log.h"
#include "render_passes.h"
#include "room.h"
#include "texture_cache.h"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <filesystem>
#include <unordered_map>
// 00a15640 A value's place between inMin and inMax carried between outMin and outMax, logging an empty range.
float lerp_range(float value, const LerpRange& range)
{
if (range.inMin == range.inMax)
KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"Start and End parameters cannot be the same!");
float t = (value - range.inMin) / (range.inMax - range.inMin);
if (range.isClamped) t = std::clamp(t, 0.0f, 1.0f);
return (range.outMax - range.outMin) * t + range.outMin;
}
using simdjson::dom::array;
using simdjson::dom::element;
using simdjson::dom::object;
constexpr int LOG_MESSAGE_SIZE = 1024;
constexpr int FRAME_INDEX_UNSET = -1;
constexpr uint32_t EVENT_BIT_MASK = 31;
constexpr float CHANNEL = 255;
constexpr float PERCENT = 100;
constexpr float DEGREES_HALF_TURN = 180;
constexpr float DEGREES_TURN = 360;
constexpr float RADIANS_PER_DEGREE = 0.017453292f;
constexpr float GLITCH_TURN = 90;
constexpr int SHIMMER_STEPS = 256;
constexpr std::string_view SHADOW_LAYER_NAME = "shadow";
constexpr std::string_view APPEAR_ANIMATION = "Appear";
constexpr std::string_view IDLE_ANIMATION = "Idle";
constexpr std::string_view CHAMPION_COLOR_UNIFORM = "ChampionColor";
constexpr std::string_view COLOR_OFFSET_SHADER = "ColorOffset";
constexpr std::string_view COLOR_OFFSET_CHAMPION_SHADER = "ColorOffsetChampion";
constexpr std::string_view COLOR_OFFSET_DOGMA_SHADER = "ColorOffsetDogma";
constexpr std::string_view COLOR_OFFSET_GOLD_SHADER = "ColorOffsetGold";
// Delirium's forms swap a boss's or monster's spritesheets for the ones under DELIRIUM_FORMS_FOLDER.
constexpr int DELIRIUM_TYPE = 412;
constexpr std::string_view GFX_FOLDER = "gfx/";
constexpr std::string_view BOSSES_FOLDER = "bosses";
constexpr std::string_view MONSTERS_FOLDER = "monsters";
constexpr std::string_view DELIRIUM_FORMS_FOLDER = "Bosses/AfterbirthPlus/DeliriumForms";
// The xorshift the glitch jitter draws from, and the one a procedural item's layer turns by.
constexpr uint32_t GLITCH_SEED = 0x9e3779b9;
constexpr uint32_t PROCEDURAL_SHIFTS[] = {5, 9, 7};
// What reading one .anm2 needs at hand: its path for messages and its spritesheets' regions as keyframes.
struct Anm2Parse
{
std::string path;
std::vector<std::vector<AnimationFrame>> regions;
std::vector<int> layerSheets;
};
static std::unordered_map<std::string, std::shared_ptr<const AnmFileData>> cacheFiles;
static const std::string EMPTY_NAME;
// Formats a message for KAGE_LogMessage, whose declaration takes nothing to format with.
static void log_print(LogLevel level, const char* format, ...)
{
char message[LOG_MESSAGE_SIZE];
va_list arguments;
va_start(arguments, format);
vsnprintf(message, sizeof(message), format, arguments);
va_end(arguments);
KAGE_LogMessage(level, (uint8_t*)message);
}
static bool is_prefix_case_insensitive(std::string_view text, std::string_view prefix)
{
auto isSame = [](char a, char b) { return std::tolower((unsigned char)a) == std::tolower((unsigned char)b); };
return text.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), text.begin(), isSame);
}
// The position of a name in a file's list, or -1.
static int name_index(const std::vector<std::string>* names, std::string_view name)
{
if (!names) return -1;
auto found = std::find(names->begin(), names->end(), name);
return found == names->end() ? -1 : (int)(found - names->begin());
}
// KAGE's render pass flags, which the graphics layer owns.
static bool is_reflection_pass()
{
return DAT_00c7977d != 0;
}
static bool is_light_pass()
{
return DAT_00c7977e != 0;
}
static bool is_procedural_item_pass()
{
return DAT_00c7977f != 0;
}
static bool is_screen_shake_applied()
{
return DAT_00c33910 != 0;
}
// A colour a fraction t of the way to another, every channel, as Color::Lerp does.
ColorMod color_lerp(const ColorMod& from, const ColorMod& to, float t)
{
float rest = 1 - t;
ColorMod color;
for (int i = 0; i < 4; i++) color._tint[i] = from._tint[i] * rest + to._tint[i] * t;
for (int i = 0; i < 4; i++) color._colorize[i] = from._colorize[i] * rest + to._colorize[i] * t;
for (int i = 0; i < 3; i++) color._offset[i] = from._offset[i] * rest + to._offset[i] * t;
return color;
}
// Tints a colour by another, as Color's *= does: tints multiply, offsets add and colorizes average.
void color_multiply(ColorMod& color, const ColorMod& other)
{
for (int i = 0; i < 4; i++) color._tint[i] = other._tint[i] * color._tint[i];
if (other._colorize[0] + other._colorize[1] + other._colorize[2] != 0)
{
bool isColorized = color._colorize[0] + color._colorize[1] + color._colorize[2] != 0;
for (int i = 0; i < 4; i++)
color._colorize[i] = isColorized ? (color._colorize[i] + other._colorize[i]) * HALF : other._colorize[i];
}
for (int i = 0; i < 3; i++) color._offset[i] = other._offset[i] + color._offset[i];
}
// An angle brought into [-180, 180] degrees.
static float angle_wrap(float angle)
{
if (std::fabs(angle) > DEGREES_TURN) angle = (float)std::fmod((double)angle, (double)DEGREES_TURN);
if (angle > DEGREES_HALF_TURN) return angle - DEGREES_TURN;
if (angle < -DEGREES_HALF_TURN) return angle + DEGREES_TURN;
return angle;
}
// 006828b0 An angle in degrees a fraction t of the way to another, the short way round.
float angle_lerp(float from, float to, float t)
{
from = angle_wrap(from);
to = angle_wrap(to);
if (std::fabs(to - from) > DEGREES_HALF_TURN)
{
if (to > from) from += DEGREES_TURN;
else to += DEGREES_TURN;
}
return angle_wrap((to - from) * t + from);
}
// Moves a keyframe's position, scale, colour and rotation a fraction t of the way between two keyframes.
static void frame_lerp(NullFrame& frame, const NullFrame& from, const NullFrame& to, float t)
{
frame.pos.x = (to.pos.x - from.pos.x) * t + from.pos.x;
frame.pos.y = (to.pos.y - from.pos.y) * t + from.pos.y;
frame.scale.x = (to.scale.x - from.scale.x) * t + from.scale.x;
frame.scale.y = (to.scale.y - from.scale.y) * t + from.scale.y;
frame.color = color_lerp(from.color, to.color, t);
frame.rotation = angle_lerp(from.rotation, to.rotation, t);
}
// 00415170 Bakes a track's interpolation, as InterpolateLayerFrames and InterpolateNullFrames (00414e00) do.
// An interpolated keyframe but the last becomes one keyframe per tick, linear toward the next whatever the easing.
// t steps by 1 / duration added up in floats, as the game adds it.
template <class Frame> static std::vector<Frame> track_interpolate(const std::vector<Frame>& frames)
{
std::vector<Frame> baked;
int tick = 0;
for (size_t i = 0; i < frames.size(); i++)
{
const Frame& from = frames[i];
if (i + 1 == frames.size() || !from.isInterpolated)
{
Frame& frame = baked.emplace_back(from);
frame.startFrame = tick;
frame.endFrame = tick + from.duration;
tick += from.duration;
continue;
}
if (i + 1 >= ANM2_FRAME_LIMIT) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"too many frames after interpolation\n");
float step = 1.0f / (float)from.duration;
float t = 0;
for (int k = 0; k < from.duration; k++)
{
Frame& frame = baked.emplace_back(from);
frame_lerp(frame, from, frames[i + 1], t);
frame.duration = 1;
frame.startFrame = tick;
frame.endFrame = ++tick;
t = step + t;
}
}
return baked;
}
// Multiplies the root track into a track, cutting its keyframes wherever a root keyframe ends.
// A piece keeps its source's duration, only its end is right. The root does not turn positions.
// The original applies a stale root keyframe when an animation has none. Here that root changes nothing.
template <class Frame> static std::vector<Frame> track_root_apply(std::vector<Frame>& frames,
const std::vector<NullFrame>& root,
const std::string& path)
{
static const NullFrame ROOT_NONE;
std::vector<Frame> baked;
size_t rootIndex = 0;
int tick = 0;
for (Frame& source : frames)
{
source.startFrame = tick;
for (int k = 0; k < source.duration; k++)
{
size_t previous = rootIndex;
bool isRootEnded = false;
tick++;
if (rootIndex + 1 < root.size())
{
while (tick >= root[rootIndex].endFrame && ++rootIndex + 1 < root.size()) {}
isRootEnded = rootIndex > previous;
}
if (!isRootEnded && k != source.duration - 1) continue;
if (baked.size() >= ANM2_FRAME_LIMIT)
log_print(LOG_ASSERT, "%s: too many frames after interpolation/root frame adjustment\n", path.c_str());
const NullFrame& rootFrame = root.empty() ? ROOT_NONE : root[previous];
Frame& frame = baked.emplace_back(source);
frame.pos.x = frame.pos.x * rootFrame.scale.x + rootFrame.pos.x;
frame.pos.y = rootFrame.scale.y * frame.pos.y + rootFrame.pos.y;
frame.isVisible = frame.isVisible && rootFrame.isVisible;
frame.scale.x = frame.scale.x * rootFrame.scale.x;
frame.scale.y = rootFrame.scale.y * frame.scale.y;
color_multiply(frame.color, rootFrame.color);
frame.rotation = rootFrame.rotation + frame.rotation;
frame.endFrame = tick;
source.startFrame = tick;
}
}
return baked;
}
static float number_get(object source, std::string_view key, float fallback)
{
double value;
return source[key].get(value) ? fallback : (float)value;
}
static bool is_get(object source, std::string_view key, bool fallback)
{
bool value;
return source[key].get(value) ? fallback : value;
}
static std::string_view text_get(object source, std::string_view key)
{
std::string_view value;
return source[key].get(value) ? std::string_view() : value;
}
// A list of numbers read into values, each keeping its fallback where the list stops short.
template <size_t COUNT> static void numbers_get(object source, std::string_view key, float (&values)[COUNT])
{
array list;
if (source[key].get(list)) return;
for (size_t i = 0; i < COUNT; i++)
{
double value;
if (!list.at(i).get(value)) values[i] = (float)value;
}
}
// A keyframe of Anm2Ed's JSON, a region of its spritesheet too, converted as the game converts its XML.
// Any easing plays as the game's linear interpolation. The game has no alpha offset.
static AnimationFrame frame_read(object source, const std::vector<AnimationFrame>* regions)
{
AnimationFrame frame;
float crop[2] = {};
float offset[3] = {};
float pivot[2] = {};
float pos[2] = {};
float scale[2] = {PERCENT, PERCENT};
float size[2] = {};
float tint[4] = {CHANNEL, CHANNEL, CHANNEL, CHANNEL};
int64_t region;
numbers_get(source, "crop", crop);
numbers_get(source, "offset", offset);
numbers_get(source, "pivot", pivot);
numbers_get(source, "pos", pos);
numbers_get(source, "scale", scale);
numbers_get(source, "size", size);
numbers_get(source, "tint", tint);
frame.crop = vector_make(crop[0], crop[1]);
frame.width = size[0];
frame.height = size[1];
frame.pivot = vector_make(pivot[0], pivot[1]);
std::string_view origin = text_get(source, "origin");
if (origin == "topLeft") frame.pivot = Vector{};
if (origin == "center") frame.pivot = vector_make(frame.width * HALF, frame.height * HALF);
if (regions && !source["region"].get(region) && region >= 0 && region < (int64_t)regions->size())
{
const AnimationFrame& shown = (*regions)[region];
frame.crop = shown.crop;
frame.pivot = shown.pivot;
frame.width = shown.width;
frame.height = shown.height;
}
for (int i = 0; i < 4; i++) frame.color._tint[i] = tint[i] / CHANNEL;
for (int i = 0; i < 3; i++) frame.color._offset[i] = offset[i] / CHANNEL;
frame.pos = vector_make(pos[0], pos[1]);
frame.scale = vector_make(scale[0] / PERCENT, scale[1] / PERCENT);
frame.rotation = number_get(source, "rotation", 0);
frame.duration = (int)number_get(source, "delay", 1);
frame.isVisible = is_get(source, "visible", true);
frame.isInterpolated = !text_get(source, "interpolation").empty();
return frame;
}
template <class Frame> static std::vector<Frame> frames_read(object source, std::string_view key,
const std::vector<AnimationFrame>* regions)
{
std::vector<Frame> frames;
array list;
if (source[key].get(list)) return frames;
for (element entry : list)
{
object fields;
if (!entry.get(fields)) frames.push_back(frame_read(fields, regions));
}
return frames;
}
// An animation's layer tracks in drawing order, a group's among them in its place.
// The game has no groups, so a group's root transform is left out.
static void layer_tracks_read(object source, const Anm2Parse& parse, AnimationData& animation,
const std::vector<NullFrame>& root)
{
array tracks;
if (source["layers"].get(tracks)) return;
for (element entry : tracks)
{
object fields;
if (entry.get(fields)) continue;
if (!fields["group"].error())
{
layer_tracks_read(fields, parse, animation, root);
continue;
}
if (animation.animLayers.size() >= ANM2_LAYER_LIMIT)
log_print(LOG_ASSERT, "%s: too many animation layers\n", parse.path.c_str());
int layerId = (int)number_get(fields, "layer", -1);
bool isKnown = layerId >= 0 && layerId < (int)parse.layerSheets.size();
int sheet = isKnown ? parse.layerSheets[layerId] : -1;
bool isSheet = sheet >= 0 && sheet < (int)parse.regions.size();
const std::vector<AnimationFrame>* regions = isSheet ? &parse.regions[sheet] : nullptr;
auto frames = track_interpolate(frames_read<AnimationFrame>(fields, "frames", regions));
animation.animLayers.push_back(
{track_root_apply(frames, root, parse.path), layerId, is_get(fields, "visible", true)});
}
}
static void null_tracks_read(object source, const Anm2Parse& parse, AnimationData& animation,
const std::vector<NullFrame>& root)
{
array tracks;
if (source["nulls"].get(tracks)) return;
for (element entry : tracks)
{
object fields;
if (entry.get(fields)) continue;
if (animation.nullLayers.size() >= ANM2_LAYER_LIMIT)
log_print(LOG_ASSERT, "%s: too many null layers\n", parse.path.c_str());
auto frames = track_interpolate(frames_read<NullFrame>(fields, "frames", nullptr));
animation.nullLayers.push_back({track_root_apply(frames, root, parse.path),
(int)number_get(fields, "null", -1), is_get(fields, "visible", true)});
}
}
// A trigger fires each of its events on its frame, one game trigger per event.
static void triggers_read(object source, const Anm2Parse& parse, AnimationData& animation)
{
array triggers;
if (source["triggers"].get(triggers)) return;
for (element entry : triggers)
{
object fields;
array events;
if (entry.get(fields) || fields["events"].get(events)) continue;
for (element event : events)
{
double eventId;
if (event.get(eventId)) continue;
if (animation.eventTriggers.size() >= ANM2_TRIGGER_LIMIT)
log_print(LOG_ASSERT, "%s: too many triggers\n", parse.path.c_str());
animation.eventTriggers.push_back({(int)number_get(fields, "at", 0), (uint32_t)eventId});
}
}
}
// Every animation of a list in file order, a group's among them in its place.
static void animations_read(object list, const Anm2Parse& parse, AnmFileData& file)
{
for (auto [name, value] : list)
{
object fields;
object group;
if (value.get(fields)) continue;
if (!fields["animations"].get(group))
{
animations_read(group, parse, file);
continue;
}
AnimationData& animation = file.animations.emplace_back();
animation.name = name;
animation.index = (int)file.animations.size() - 1;
animation.length = (int)number_get(fields, "length", 1);
animation.isLooping = is_get(fields, "loop", true);
auto root = track_interpolate(frames_read<NullFrame>(fields, "root", nullptr));
layer_tracks_read(fields, parse, animation, root);
null_tracks_read(fields, parse, animation, root);
triggers_read(fields, parse, animation);
for (size_t i = 0; i < animation.animLayers.size(); i++)
{
int layerId = animation.animLayers[i].layerId;
if (layerId >= 0 && layerId < ANM2_LAYER_LIMIT) animation.layerMap[layerId] = (int)i;
}
}
}
// The names of a list of objects, or of plain strings.
static std::vector<std::string> names_read(object document, std::string_view key)
{
std::vector<std::string> names;
array list;
if (document[key].get(list)) return names;
for (element entry : list)
{
object fields;
std::string_view name;
if (!entry.get(fields)) name = text_get(fields, "name");
else if (entry.is_string()) name = entry.get_string().value_unsafe();
names.emplace_back(name);
}
return names;
}
// 0040ed50 Parses an .anm2, Anm2Ed's JSON document (its docs/json_format.md), into what the game plays.
// Ids are indices into their lists. Spritesheet paths become relative to resources/, from the .anm2's folder.
static std::shared_ptr<const AnmFileData> file_parse(const std::string& path)
{
static simdjson::dom::parser parser;
auto file = std::make_shared<AnmFileData>();
Anm2Parse parse = {path, {}, {}};
std::vector<std::string> sheetPaths;
object document;
array list;
std::string redirected = g_manager ? g_manager->modManager.TryRedirectPath(path) : path;
if (parser.load(resource_path(redirected)).get(document) || document["anm2ed"].error())
{
log_print(LOG_INFO, "ERROR Could not open %s\n", path.c_str());
return nullptr;
}
if (!document["spritesheets"].get(list))
for (element entry : list)
{
object fields;
if (entry.get(fields)) continue;
std::string relative(text_get(fields, "path"));
std::replace(relative.begin(), relative.end(), '\\', '/');
auto resolved = std::filesystem::path(path).parent_path() / relative;
sheetPaths.push_back(resolved.lexically_normal().generic_string());
parse.regions.push_back(frames_read<AnimationFrame>(fields, "regions", nullptr));
}
if (!document["layers"].get(list))
for (element entry : list)
{
object fields;
LayerData& layer = file->layers.emplace_back();
bool isRead = !entry.get(fields);
layer.id = (int)file->layers.size() - 1;
layer.name = isRead ? text_get(fields, "name") : "";
layer.spriteSheetId = isRead ? (int)number_get(fields, "sheet", 0) : 0;
if (layer.id >= ANM2_LAYER_LIMIT)
log_print(LOG_ASSERT, "%s: invalid layer id %d\n", path.c_str(), layer.id);
if (layer.spriteSheetId >= 0 && layer.spriteSheetId < (int)sheetPaths.size())
layer.spriteSheetPath = sheetPaths[layer.spriteSheetId];
else log_print(LOG_ASSERT, "%s: invalid spritesheet id %d\n", path.c_str(), layer.spriteSheetId);
parse.layerSheets.push_back(layer.spriteSheetId);
}
if (file->layers.empty()) log_print(LOG_ASSERT, "%s: no layers\n", path.c_str());
file->nullLayerNames = names_read(document, "nulls");
if (file->nullLayerNames.size() > ANM2_LAYER_LIMIT)
log_print(LOG_ASSERT, "%s: invalid Null ID %d\n", path.c_str(), ANM2_LAYER_LIMIT);
file->eventNames = names_read(document, "events");
if (file->eventNames.size() > ANM2_EVENT_LIMIT)
log_print(LOG_ASSERT, "%s: invalid Event ID %d\n", path.c_str(), ANM2_EVENT_LIMIT);
file->defaultAnimation = text_get(document, "defaultAnimation");
object animations;
if (!document["animations"].get(animations)) animations_read(animations, parse, *file);
return file;
}
// 0040db90 Gives a sprite the parsed file at its path, parsing it on first use, with fresh layer states.
// A file that fails to load leaves the sprite as it was. The original's reload flag is set by nothing, so a cached
// file is never parsed again.
void AnmCache::Load(ANM2& sprite)
{
if (sprite.filename.empty()) return;
std::string key = resource_path(sprite.filename);
auto found = cacheFiles.find(key);
std::shared_ptr<const AnmFileData> file = found != cacheFiles.end() ? found->second : file_parse(sprite.filename);
if (!file)
{
log_print(LOG_INFO, "AnmCache failed to load %s\n", sprite.filename.c_str());
return;
}
cacheFiles[key] = file;
sprite.file = file;
sprite.animState.file = file.get();
sprite.overlayAnimState.file = file.get();
sprite.layerStates.assign(file->layers.size(), LayerState());
for (size_t i = 0; i < file->layers.size(); i++) sprite.layerStates[i].Init(&file->layers[i]);
}
// 0040ea50 Parses an .anm2 ahead of time, and loads each spritesheet the texture cache lacks.
void AnmCache::Preload(std::string_view path)
{
if (path.empty()) return;
std::string key = resource_path(path);
if (!cacheFiles.contains(key))
{
auto file = file_parse(std::string(path));
if (!file) return;
cacheFiles[key] = file;
}
for (const LayerData& layer : cacheFiles[key]->layers) TextureCache::Preload(layer.spriteSheetPath);
}
// 0040e470 Drops every file no sprite holds.
void AnmCache::Clear()
{
std::erase_if(cacheFiles, [](const auto& entry)
{
if (entry.second.use_count() > 1) return false;
log_print(LOG_INFO, "AnmCache: Clear %s.\n", entry.first.c_str());
return true;
});
}
// 0040d4c0 Logs what the cached files' animations take.
void AnmCache::LogMemoryUsage()
{
size_t bytes = 0;
for (const auto& [path, file] : cacheFiles)
for (const AnimationData& animation : file->animations)
{
bytes += sizeof(AnimationData);
for (const AnimationLayer& layer : animation.animLayers)
bytes += sizeof(AnimationLayer) + layer.frames.size() * sizeof(AnimationFrame);
for (const AnimationNullLayer& layer : animation.nullLayers)
bytes += sizeof(AnimationNullLayer) + layer.frames.size() * sizeof(NullFrame);
}
log_print(LOG_INFO, "AnmCache memory usage: %u bytes in %u entries.\n", (unsigned)bytes,
(unsigned)cacheFiles.size());
}
// 00408830 Starts over on an animation, or none, with every track before its first keyframe and no events.
void AnimationState::SetAnimationData(const AnimationData* data)
{
animData = data;
layerFrames.assign(data ? data->animLayers.size() : 0, FRAME_INDEX_UNSET);
nullLayerFrames.assign(data ? data->nullLayers.size() : 0, FRAME_INDEX_UNSET);
animFrame = ANIMATION_FRAME_UNSET;
isPlaying = false;
currentlyTriggeredEvents = 0;
previouslyTriggeredEvents = 0;
}
// 00408970 Switches animation, keeping the frame, play state, events and each shared track's keyframe.
// The original copies the old count of indices, overflowing a smaller array, and stores new null indices in the layer
// slot, so the next update crashes. Here each array keeps the indices both animations have.
void AnimationState::ChangeAnimationKeepFrame(const AnimationData* data)
{
layerFrames.resize(data ? data->animLayers.size() : 0, FRAME_INDEX_UNSET);
nullLayerFrames.resize(data ? data->nullLayers.size() : 0, FRAME_INDEX_UNSET);
animData = data;
}
// Moves a track's keyframe forward to the one holding a frame, never back.
template <class Frame> static void track_advance(const std::vector<Frame>& frames, int& index, float targetFrame)
{
while (index >= 0 && index + 1 < (int)frames.size() && !(targetFrame < (float)frames[index].endFrame)) index++;
}
// 00408b90 Moves a layer track forward to the keyframe holding a frame.
// The original logs a bad track and reads it anyway. Here it stops after the log.
void AnimationState::AdvanceLayerPosition(int layerId, float targetFrame)
{
if (!animData || layerId < 0 || layerId >= (int)animData->animLayers.size())
{
KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"id out of bounds\n");
return;
}
track_advance(animData->animLayers[layerId].frames, layerFrames[layerId], targetFrame);
}
// 00408c10 Moves a null track forward to the keyframe holding a frame.
// The original logs a bad track and reads it anyway. Here it stops after the log.
void AnimationState::AdvanceNullLayerPosition(int nullLayerId, float targetFrame)
{
if (!animData || nullLayerId < 0 || nullLayerId >= (int)animData->nullLayers.size())
{
KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"id out of bounds\n");
return;
}
track_advance(animData->nullLayers[nullLayerId].frames, nullLayerFrames[nullLayerId], targetFrame);
}
// 00408c90 Fires the event of every trigger exactly on the current frame, into both event masks.
// The original logs a missing animation and crashes. Here it returns after the log.
void AnimationState::FireTriggersAtCurrentFrame()
{
if (!animData)
{
KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"AnimationData is NULL\n");
return;
}
for (const AnimationData_EventTrigger& trigger : animData->eventTriggers)
{
if ((float)trigger.animationFrame != animFrame) continue;
uint32_t bit = 1u << (trigger.eventId & EVENT_BIT_MASK);
currentlyTriggeredEvents |= bit;
previouslyTriggeredEvents |= bit;
}
}
// 00408d00 Steps whole frames up to a target, firing each one's triggers, then brings every track up to it.
// Without an animation it does nothing, where the original crashes.
void AnimationState::AdvancePosition(int targetFrame)
{
if (!animData) return;
int currentFrame = (int)std::floor(animFrame);
if (targetFrame < currentFrame)
log_print(LOG_ASSERT, "Animation::AdvancePosition cannot go backward (new: %d, cur: %d)\n", targetFrame,
currentFrame);
float target = (float)targetFrame;
currentlyTriggeredEvents = 0;
while (animFrame < target)
{
animFrame = std::floor(animFrame) + 1;
FireTriggersAtCurrentFrame();
}
for (int i = 0; i < (int)layerFrames.size(); i++) AdvanceLayerPosition(i, target);
for (int i = 0; i < (int)nullLayerFrames.size(); i++) AdvanceNullLayerPosition(i, target);
}
// 00408e00 Jumps to a frame clamped below the animation's length, firing only its triggers.
// The tracks restart and catch up to the unclamped frame. Without an animation it does nothing, where the original
// crashes.
void AnimationState::SetFrameFloat(float frame)
{
if (!animData) return;
float lastFrame = std::nextafter((float)animData->length, 0.0f);
currentlyTriggeredEvents = 0;
animFrame = frame <= lastFrame ? frame : lastFrame;
FireTriggersAtCurrentFrame();
for (int i = 0; i < (int)layerFrames.size(); i++)
{
layerFrames[i] = 0;
AdvanceLayerPosition(i, frame);
}
for (int i = 0; i < (int)nullLayerFrames.size(); i++)
{
nullLayerFrames[i] = 0;
AdvanceNullLayerPosition(i, frame);
}
}
// The track an animation keys a layer id with, or -1. Logs a layer id outside the sprite's layers.
static int layer_track_get(const AnimationState& state, int layerId)
{
int layerCount = state.file ? (int)state.file->layers.size() : 0;
if (layerId < 0 || layerId >= layerCount)
{
KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"LayerId out of bounds\n");
return -1;
}
if (!state.animData || layerId >= ANM2_LAYER_LIMIT) return -1;
return state.animData->layerMap[layerId];
}
// 00408ef0 Puts a layer's track back to its keyframe holding a frame.
// The original logs a layer the animation does not key and writes before its array. Here it stops after the log.
void AnimationState::SetLayerFrame(int layerId, int frame)
{
int layerCount = file ? (int)file->layers.size() : 0;
if (layerId < 0 || layerId >= layerCount)
{
KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"LayerId out of bounds\n");
return;
}
int track = layer_track_get(*this, layerId);
if (track < 0 || track >= (int)layerFrames.size())
{
KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"id out of bounds\n");
return;
}
layerFrames[track] = 0;
AdvanceLayerPosition(track, (float)frame);
}
// 00408f70 The keyframe index a layer's track is on, 0 for a layer outside the sprite.
// The original reads before its array for a layer the animation does not key. Here that is -1.
int AnimationState::GetLayerFrameIdx(int layerId) const
{
int layerCount = file ? (int)file->layers.size() : 0;
if (layerId < 0 || layerId >= layerCount)
{
KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"LayerId out of bounds\n");
return 0;
}
int track = layer_track_get(*this, layerId);
return track >= 0 ? layerFrames[track] : FRAME_INDEX_UNSET;
}
// 00408fc0 Puts a null track back to its keyframe holding a frame.
// The original logs a bad track and writes it anyway. Here it stops after the log.
void AnimationState::SetNullLayerFrame(int nullLayerId, int frame)
{
int nullCount = file ? (int)file->nullLayerNames.size() : 0;
if (nullLayerId < 0 || nullLayerId >= nullCount) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"layerId out of bounds\n");
if (nullLayerId < 0 || nullLayerId >= (int)nullLayerFrames.size())
{
KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"id out of bounds\n");
return;
}
nullLayerFrames[nullLayerId] = 0;
AdvanceNullLayerPosition(nullLayerId, (float)frame);
}
// 00409030 Plays on by the sprite's playback speed, looping or stopping on the last frame at the end.
// A loop restarts without stepping the frames it skips, so a fast loop can miss an event near its end.
void AnimationState::Update(float playbackSpeed)
{
if (!animData || !isPlaying) return;
float nextFrame = animFrame + playbackSpeed;
int nextWholeFrame = (int)std::floor(nextFrame);
if (nextWholeFrame < animData->length)
{
AdvancePosition(nextWholeFrame);
animFrame = nextFrame;
return;
}
if (animData->isLooping)
{
Rewind();
return;
}
int lastFrame = animData->length - 1;
if ((int)std::floor(animFrame) <= lastFrame) AdvancePosition(lastFrame);
isPlaying = false;
}
// 0040a1b0 Goes back to frame 0 with only its events fired and every track on its first keyframe.
void AnimationState::Rewind()
{
animFrame = 0;
currentlyTriggeredEvents = 0;
previouslyTriggeredEvents = 0;
FireTriggersAtCurrentFrame();
std::fill(layerFrames.begin(), layerFrames.end(), 0);
std::fill(nullLayerFrames.begin(), nullLayerFrames.end(), 0);
}
// 0040a030 Draws every layer track on its current keyframe, bottom first.
void AnimationState::Render(const SpriteDraw& draw, const ANM2& animation) const
{
if (!animData) return;
for (size_t i = 0; i < animData->animLayers.size(); i++)
animData->animLayers[i].RenderFrame(draw, layerFrames[i], animation);
}
// 0040a080 Draws one layer on its current keyframe, if the animation keys it.
void AnimationState::RenderLayer(int layerId, const SpriteDraw& draw, const ANM2& animation) const
{
if (!animData || layerId < 0 || layerId >= (int)animation.layerStates.size() || layerId >= ANM2_LAYER_LIMIT) return;
int track = animData->layerMap[layerId];
if (track >= 0) animData->animLayers[track].RenderFrame(draw, layerFrames[track], animation);
}
// 0040a220 The keyframe a layer shows now, or null.
// Like the original it lets a layer id equal to the layer count through, but never one past the layer map.
const AnimationFrame* AnimationState::GetLayerFrame(int layerId) const
{
int layerCount = file ? (int)file->layers.size() : 0;
if (!animData) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"AnimationData is NULL\n");
if (layerId < 0 || layerId >= layerCount) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"LayerId out of bounds\n");
if (!animData || layerId < 0 || layerId > layerCount || layerId >= ANM2_LAYER_LIMIT) return nullptr;
int track = animData->layerMap[layerId];
if (track < 0 || track >= (int)animData->animLayers.size()) return nullptr;
const std::vector<AnimationFrame>& frames = animData->animLayers[track].frames;
int index = layerFrames[track];
return index >= 0 && index < (int)frames.size() ? &frames[index] : nullptr;
}
// 0040ac70 The keyframe the first track of a null shows now, or null.
// The original logs a missing animation and crashes. Here it returns null after the log.
const NullFrame* AnimationState::GetNullFrameById(int nullLayerId) const
{
if (!animData)
{
KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"AnimationData is NULL\n");
return nullptr;
}
for (size_t i = 0; i < animData->nullLayers.size(); i++)
{
const AnimationNullLayer& layer = animData->nullLayers[i];
int index = nullLayerFrames[i];
if (layer.nullLayerId == nullLayerId && index >= 0 && index < (int)layer.frames.size())
return &layer.frames[index];
}
return nullptr;
}
// 0040ace0 The keyframe a null shows now, by name.
const NullFrame* AnimationState::GetNullFrame(std::string_view nullLayerName) const
{
if (!animData) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"AnimationData is NULL\n");
int index = name_index(file ? &file->nullLayerNames : nullptr, nullLayerName);
return index < 0 ? nullptr : GetNullFrameById(index);
}
// The mask bit an event of the file fires, or 0 for an event it lacks.
static uint32_t event_bit_get(const AnimationState& state, std::string_view eventName)
{
if (!state.animData) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"AnimationData is NULL\n");
int index = name_index(state.file ? &state.file->eventNames : nullptr, eventName);
return index < 0 ? 0 : 1u << (index & EVENT_BIT_MASK);
}
// 0040add0 Whether an event fired on the last step.
bool AnimationState::IsEventTriggered(std::string_view eventName) const
{
return (currentlyTriggeredEvents & event_bit_get(*this, eventName)) != 0;
}
// 0040ae70 Whether an event fired since the animation started.
bool AnimationState::WasEventTriggered(std::string_view eventName) const
{
return (previouslyTriggeredEvents & event_bit_get(*this, eventName)) != 0;
}
// 0040af10 The nearest frame after the current one, truncated, an event fires on, or -1.
// The original crashes without an animation. Here that is -1.
int AnimationState::NextEventTrigger(std::string_view eventName) const
{
if (!animData) KAGE_LogMessage(LOG_ASSERT, (uint8_t*)"AnimationData is NULL\n");
int eventId = name_index(file ? &file->eventNames : nullptr, eventName);
int nextFrame = -1;
int nearest = -1;
if (eventId < 0 || !animData) return nextFrame;
for (const AnimationData_EventTrigger& trigger : animData->eventTriggers)
{
int distance = trigger.animationFrame - (int)animFrame;
if (trigger.eventId != (uint32_t)eventId || distance <= 0 || (nearest >= 0 && distance >= nearest)) continue;
nearest = distance;
nextFrame = trigger.animationFrame;
}
return nextFrame;
}
// 00452bf0 The name of the animation shown, or an empty one.
const std::string& AnimationState::GetAnimation() const
{
return animData ? animData->name : EMPTY_NAME;
}
// 0040bc90 The animation's position in its file, or -1.
int AnimationState::GetAnimationIndex() const
{
return animData ? animData->index : -1;
}
// 00440e30 The animation's length in frames, or 0.
int AnimationState::GetAnimationLength() const
{
return animData ? animData->length : 0;
}
// 004073b0 Whether the animation shown loops.
bool AnimationState::IsLoopingAnimation() const
{
return animData && animData->isLooping;
}
// Whether an animation plays, the named one if a name is given.
bool AnimationState::is_playing(std::string_view name) const
{
return animData && isPlaying && (name.empty() || animData->name == name);
}
// Whether an animation stopped, the named one if a name is given. With none shown, only for no name.
bool AnimationState::is_finished(std::string_view name) const
{
if (!animData) return name.empty();
return !isPlaying && (name.empty() || animData->name == name);
}
// 004081d0 A layer with no layer data, no spritesheet and the default look.
LayerState::LayerState()
{
Init(nullptr);
}
// 00408310 Points a layer at its layer data and resets its spritesheet, transform, colour, blending and render flags.
void LayerState::Init(const LayerData* data)
{
bool isPremultiplied = KAGE::Graphics::manager.isPremultipliedAlpha;
layerData = data;
spriteSheetPath = data ? data->spriteSheetPath : "";
spriteSheet = nullptr;
isSpriteSheetLoaded = false;
isUnknown31 = false;
isFlipX = false;
isFlipY = false;
size = vector_make(1, 1);
rotation = 0;
pos = Vector{};
color = COLOR_DEFAULT;
isVisible = true;
blendMode[BLEND_EQUATION] = BLEND_EQUATION_ADD;
blendMode[BLEND_RGB_SOURCE] = isPremultiplied ? BLEND_FACTOR_ONE : BLEND_FACTOR_SRC_ALPHA;
blendMode[BLEND_RGB_DEST] = BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
blendMode[BLEND_ALPHA_SOURCE] = BLEND_FACTOR_ONE;
blendMode[BLEND_ALPHA_DEST] = BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
minFilterMode = DAT_00c3799c;
magFilterMode = DAT_00c379a0;
wrapSMode = DAT_00c379a4;
wrapTMode = DAT_00c379a8;
bitflags = 0;
cropOffset = Vector{};
}
// A rectangle's corners: top left, top right, bottom left, bottom right.
static void quad_set(DestinationQuad& quad, float left, float top, float right, float bottom)
{
quad._topLeft = vector_make(left, top);
quad._topRight = vector_make(right, top);
quad._bottomLeft = vector_make(left, bottom);
quad._bottomRight = vector_make(right, bottom);
}
// Scales a quad about a pivot, as Quad::scale does.
static void quad_scale(DestinationQuad& quad, Vector pivot, Vector scale)
{
if (scale.x == 1 && scale.y == 1) return;
for (Vector* corner : {&quad._topLeft, &quad._topRight, &quad._bottomLeft, &quad._bottomRight})
*corner = vector_make((corner->x - pivot.x) * scale.x + pivot.x, (corner->y - pivot.y) * scale.y + pivot.y);
}
// Quad::rotate: turns a quad about a pivot by radians.
void quad_rotate(DestinationQuad& quad, Vector pivot, float angle)
{
if (angle == 0) return;
float cosine = std::cos(angle);
float sine = std::sin(angle);
for (Vector* corner : {&quad._topLeft, &quad._topRight, &quad._bottomLeft, &quad._bottomRight})
{
float x = corner->x - pivot.x;
float y = corner->y - pivot.y;
*corner = vector_make(x * cosine - y * sine + pivot.x, y * cosine + x * sine + pivot.y);
}
}
static void quad_columns_swap(DestinationQuad& quad)
{
std::swap(quad._topLeft, quad._topRight);
std::swap(quad._bottomLeft, quad._bottomRight);
}
static void quad_rows_swap(DestinationQuad& quad)
{
std::swap(quad._topLeft, quad._bottomLeft);
std::swap(quad._topRight, quad._bottomRight);
}
// The KAGE random the glitch jitter draws from.
// The original shares KAGE's global render RNG (00c33914), which classes.h does not declare yet.
static RNG& glitch_rng()
{
static RNG rng = []
{
RNG seeded;
seeded.SetSeed(GLITCH_SEED, 0);
return seeded;
}();
return rng;
}
// 004098a0 The spritesheet rectangle a layer keyframe shows, clamped and mirrored as the sprite and layer flip.
SourceQuad AnimationLayer::GetSourceQuad(const AnimationFrame& frame, const LayerState& layer, const SpriteDraw& draw,
const ANM2& animation)
{
bool isFlipY = animation.isFlipY != is_reflection_pass();
float width = frame.scale.x * layer.size.x;
float height = frame.scale.y * layer.size.y;
float spriteScaleX = animation.isFlipX ? -animation.scale.x : animation.scale.x;
float spriteScaleY = isFlipY ? -animation.scale.y : animation.scale.y;
SourceQuad quad;
quad_set(quad, draw.topLeftClamp.x / width + frame.crop.x, draw.topLeftClamp.y / height + frame.crop.y,
(frame.crop.x + frame.width) - draw.bottomRightClamp.x / width,
(frame.crop.y + frame.height) - draw.bottomRightClamp.y / height);
quad._coordinateSpace = 1;
if ((spriteScaleX < 0) != ((layer.isFlipX ? -width : width) < 0)) quad_columns_swap(quad);
if ((spriteScaleY < 0) != ((layer.isFlipY ? -height : height) < 0)) quad_rows_swap(quad);
if ((animation.bitflags | layer.bitflags) & ANIM_RENDER_GLITCH)
{
float shiftY = (glitch_rng().RandomFloat() - HALF) * (quad._bottomLeft.y - quad._topLeft.y);
float shiftX = (glitch_rng().RandomFloat() - HALF) * (quad._topRight.x - quad._topLeft.x);
for (Vector* corner : {&quad._topLeft, &quad._topRight, &quad._bottomLeft, &quad._bottomRight})
*corner = vector_make(corner->x + shiftX, corner->y + shiftY);
}
for (Vector* corner : {&quad._topLeft, &quad._topRight, &quad._bottomLeft, &quad._bottomRight})
*corner = vector_make(layer.cropOffset.x + corner->x, layer.cropOffset.y + corner->y);
return quad;
}
// 00409cb0 Where a layer keyframe lands on screen: scaled and turned about the layer's place, then the sprite's.
// A flipped sprite or layer mirrors its pivot and turns the other way.
DestinationQuad AnimationLayer::GetDestQuad(const AnimationFrame& frame, const LayerState& layer,
const SpriteDraw& draw, const ANM2& animation)
{
bool isFlipY = animation.isFlipY != is_reflection_pass();
Vector layerScale = vector_make(frame.scale.x * layer.size.x, frame.scale.y * layer.size.y);
Vector spriteScale = animation.scale;
Vector shake = is_screen_shake_applied() && g_game ? g_game->screenShakeOffset : Vector{};
float layerRotation = frame.rotation + layer.rotation;
float spriteRotation = animation.rotation;
float pivotX = frame.pivot.x;
float pivotY = frame.pivot.y;
float x = frame.pos.x + layer.pos.x + animation.offset.x;
float y = frame.pos.y + layer.pos.y + animation.offset.y;
DestinationQuad quad;
if ((animation.bitflags | layer.bitflags) & ANIM_RENDER_SIZE_WITH_SPRITE)
{
spriteScale = vector_make(layer.size.x * animation.scale.x, layer.size.y * animation.scale.y);
layerScale = frame.scale;
}
if (layer.isFlipX) layerScale.x = -layerScale.x;
if (animation.isFlipX) spriteScale.x = -spriteScale.x;
if (spriteScale.x < 0)
{
spriteScale.x = -spriteScale.x;
layerRotation = -layerRotation;
spriteRotation = -spriteRotation;
x = -x;
pivotX = frame.width - frame.pivot.x;
}
if (layerScale.x < 0)
{
layerScale.x = -layerScale.x;
pivotX = frame.width - pivotX;
}
if (layer.isFlipY) layerScale.y = -layerScale.y;
if (isFlipY) spriteScale.y = -spriteScale.y;
if (spriteScale.y < 0)
{
spriteScale.y = -spriteScale.y;
pivotY = frame.height - frame.pivot.y;
layerRotation = -layerRotation;
spriteRotation = -spriteRotation;
y = -y;
}
if (layerScale.y < 0)
{
layerScale.y = -layerScale.y;
pivotY = frame.height - pivotY;
}
float originX = shake.x + draw.position.x;
float originY = shake.y + draw.position.y;
Vector layerOrigin = vector_make(originX + x, originY + y);
Vector spriteOrigin = vector_make(originX + animation.offset.x, originY + animation.offset.y);
float left = layerOrigin.x - pivotX;
float top = layerOrigin.y - pivotY;
quad_set(quad, draw.topLeftClamp.x / layerScale.x + left, draw.topLeftClamp.y / layerScale.y + top,
(left + frame.width) - draw.bottomRightClamp.x / layerScale.x,
(top + frame.height) - draw.bottomRightClamp.y / layerScale.y);
quad_scale(quad, layerOrigin, layerScale);
quad_scale(quad, spriteOrigin, spriteScale);
quad_rotate(quad, layerOrigin, layerRotation * RADIANS_PER_DEGREE);
quad_rotate(quad, spriteOrigin, spriteRotation * RADIANS_PER_DEGREE);
return quad;
}
// The colour a layer keyframe draws in: the sprite's, layer's and keyframe's together, the top of KAGE's colour
// stack instead while one is pushed, or the layer's and keyframe's alone for an untinted layer.
static ColorMod layer_color_get(const AnimationFrame& frame, const LayerState& layer, const ANM2& animation,
unsigned int flags)
{
ColorMod color = (flags & ANIM_RENDER_UNTINTED) ? layer.color : animation.color;
if (flags & ANIM_RENDER_UNTINTED) color_multiply(color, frame.color);
else if (g_colorStackSize != 0) color = *(const ColorMod*)(uintptr_t)FUN_0040c6f0();
else
{
color_multiply(color, layer.color);
color_multiply(color, frame.color);
}
if (is_reflection_pass())
{
color._tint[3] *= HALF;
if (g_game) color._tint[3] *= g_game->room->waterAmount;
}
return color;
}
// A procedural item's layer turns its spritesheet rectangle a quarter about its middle, either way, and may mirror it,
// the same way every frame for a sprite.
static void procedural_item_turn(SourceQuad& source, const AnimationFrame& frame, const LayerState& layer,
const ANM2& animation)
{
RNG rng;
Vector center = vector_make(frame.width * HALF + frame.crop.x, frame.height * HALF + frame.crop.y);
rng._seed = (uint32_t)(uintptr_t)&animation;
rng._shift1 = PROCEDURAL_SHIFTS[0];
rng._shift2 = PROCEDURAL_SHIFTS[1];
rng._shift3 = PROCEDURAL_SHIFTS[2];
if (layer.spriteSheet == g_game->proceduralItemManager.renderTarget)
center = vector_make(center.x + layer.cropOffset.x, center.y + layer.cropOffset.y);
quad_rotate(source, center, (rng.RandomInt(2) == 0 ? GLITCH_TURN : -GLITCH_TURN) * RADIANS_PER_DEGREE);
if (rng.RandomInt(2) != 0) quad_columns_swap(source);
}
// A layer's blend mode as KAGE draws with it.
static KAGE::Graphics::BlendMode layer_blend_get(const LayerState& layer)
{
using Factor = KAGE::Graphics::BlendFactor;
const std::array<int, BLEND_PART_COUNT>& mode = layer.blendMode;
return {(KAGE::Graphics::BlendEquation)mode[BLEND_EQUATION], (Factor)mode[BLEND_RGB_SOURCE],
(Factor)mode[BLEND_RGB_DEST], (Factor)mode[BLEND_ALPHA_SOURCE], (Factor)mode[BLEND_ALPHA_DEST]};
}
// 00682260 Makes the shader a layer's render flags ask for current, when it is loaded.
// A layer keeping its shader sets none and returns false.
static bool layer_shader_select(unsigned int flags)
{
std::string_view name = COLOR_OFFSET_SHADER;
if (flags & ANIM_RENDER_COLOROFFSET_CHAMPION) name = COLOR_OFFSET_CHAMPION_SHADER;
else if (flags & ANIM_RENDER_STATIC) name = COLOR_OFFSET_DOGMA_SHADER;
else if (flags & ANIM_RENDER_GOLDEN) name = COLOR_OFFSET_GOLD_SHADER;
else if (flags & ANIM_RENDER_SHADER_KEPT) return false;
KAGE::Graphics::Shader* shader = KAGE::Graphics::manager.shader_find(name);
if (shader) KAGE::Graphics::manager.currentShader = shader;
return true;
}
// 00409120 Draws one keyframe of a layer track with the layer's spritesheet, colour, blending and shader.
// The original reads past the sprite's layers for a track keying a missing layer. Here it draws nothing.
void AnimationLayer::RenderFrame(const SpriteDraw& draw, int frameIndex, const ANM2& animation) const
{
if (!isVisible || frameIndex < 0 || frameIndex >= (int)frames.size()) return;
const AnimationFrame& frame = frames[frameIndex];
if (!frame.isVisible || layerId < 0 || layerId >= (int)animation.layerStates.size()) return;
const LayerState& layer = animation.layerStates[layerId];
unsigned int flags = animation.bitflags | layer.bitflags;
if (!layer.isVisible || !layer.spriteSheet || ((flags & ANIM_RENDER_LIGHT_PASS_ONLY) && !is_light_pass())) return;
KAGE::Graphics::Manager& graphics = KAGE::Graphics::manager;
KAGE::Graphics::BlendMode savedBlend = graphics.blendMode;
graphics.blendMode = layer_blend_get(layer);
ColorMod color = layer_color_get(frame, layer, animation, flags);
SourceQuad source = GetSourceQuad(frame, layer, draw, animation);
DestinationQuad dest = GetDestQuad(frame, layer, draw, animation);
if (is_procedural_item_pass()) procedural_item_turn(source, frame, layer, animation);
bool isChampion = flags & ANIM_RENDER_COLOROFFSET_CHAMPION;
bool isShimmering = !isChampion && (flags & (ANIM_RENDER_STATIC | ANIM_RENDER_GOLDEN));
if (isShimmering)
{
bool isGameTime = !(flags & ANIM_RENDER_IGNORE_GAME_TIME);
int frameCount = isGameTime ? g_game->frameCount : (int)(g_manager->framecount / 2);
color._colorize[3] = (float)(frameCount % SHIMMER_STEPS) / SHIMMER_STEPS;
}
KColor tint;
tint._red = color._tint[0];
tint._green = color._tint[1];
tint._blue = color._tint[2];
tint._alpha = color._tint[3];
tint._unk = 0;
if (layer_shader_select(flags)) apply_sprite_shader_params(color, SPRITE_SHADER_COLOR_APPLY, *layer.spriteSheet);
if (isChampion)
KAGE::Graphics::manager.currentShader->set_uniform(CHAMPION_COLOR_UNIFORM, KAGE::Graphics::UNIFORM_VEC4,
&animation.championColor);
layer.spriteSheet->Render(source, KAGE::Graphics::ColorQuad(dest, tint), tint);
graphics.blendMode = savedBlend;
graphics.shader_default_set();
}
// 00407690 Copies a sprite, sharing its file and spritesheets. The copy starts with no offset and no render flags.
ANM2::ANM2(const ANM2& other)
{
*this = other;
}
// 00407e90 Assigns a copy, made as the copy constructor makes one.
ANM2& ANM2::operator=(const ANM2& other)
{
ANM2Base::operator=(other);
offset = Vector{};
bitflags = 0;
return *this;
}
// 00407f10 Unloads the sprite and puts every setting back to its default.
void ANM2::Reset()
{
ANM2Base::operator=(ANM2Base());
}
// 0040bd50 Loads an .anm2 through the cache, then finds the shadow layer and flags the lit layers and nulls.
// Like the original it counts as loaded even when the file failed to load.
void ANM2::Load(std::string_view path, GraphicsLoad graphics)
{
filename = path;
AnmCache::Load(*this);
if (graphics == GRAPHICS_LOAD) LoadGraphics();
animState.SetAnimationData(nullptr);
overlayAnimState.SetAnimationData(nullptr);
isLoaded = true;
shadowLayerIndex = NO_SHADOW_LAYER;
for (int i = 0; i < (int)layerStates.size(); i++)
{
LayerState& layer = layerStates[i];
std::string_view name = layer.layerData ? std::string_view(layer.layerData->name) : std::string_view();
if (name == SHADOW_LAYER_NAME) shadowLayerIndex = i;
else if (name.starts_with(LIGHT_LAYER_PREFIX))
{
layer.bitflags |= ANIM_RENDER_UNTINTED | ANIM_RENDER_LIGHT_PASS_ONLY;
bitflags |= ANIM_RENDER_ENABLE_LAYER_LIGHTING;
}
}
if (!file) return;
for (const std::string& name : file->nullLayerNames)
if (name.starts_with(LIGHT_LAYER_PREFIX)) bitflags |= ANIM_RENDER_ENABLE_NULL_LAYER_LIGHTING;
}
// 0040bea0 Loads the file again with fresh layer states, then their spritesheets.
void ANM2::Reload()
{
if (filename.empty()) return;
AnmCache::Load(*this);
LoadGraphics();
}
// 0040c000, 0040bff0 Loads the spritesheet of every layer that lacks it, sharing images through KAGE's image cache.
void ANM2::LoadGraphics()
{
for (LayerState& layer : layerStates)
{
if (layer.isSpriteSheetLoaded) continue;
layer.spriteSheet = Manager::LoadImage(layer.spriteSheetPath);
layer.isSpriteSheetLoaded = layer.spriteSheet && layer.spriteSheet->isLoaded;
layer.isUnknown31 = false;
}
}
// 0040bf30 Points a layer at another spritesheet for the next LoadGraphics, false when the layer or path stays.
bool ANM2::ReplaceSpritesheet(int layerId, std::string_view path)
{
if (layerId < 0 || layerId >= (int)layerStates.size() || layerStates[layerId].spriteSheetPath == path) return false;
layerStates[layerId].spriteSheetPath = path;
layerStates[layerId].isSpriteSheetLoaded = false;
return true;
}
// 004a5d10 Dresses a sprite as Delirium's form of an entity: each boss or monster spritesheet that has a Delirium
// version swaps for it, then the default animation stops on its first frame.
// Where the original asks the file system for the swapped sheet, this looks under resources/.
void ANM2::LoadDeliriumForm(ANM2& sprite, int type, int variant, bool isReloadAnm2)
{
EntityConfig_Entity* entity = isReloadAnm2 ? g_manager->entityConfig.GetEntity(type, variant, 0) : nullptr;
if (entity) sprite.Load(entity->anm2Path, GRAPHICS_DEFER);
for (int i = 0; i < (int)sprite.layerStates.size() && type != DELIRIUM_TYPE; i++)
{
std::string path = sprite.layerStates[i].spriteSheetPath;
if (path.size() < GFX_FOLDER.size()) continue;
std::string_view folder = std::string_view(path).substr(GFX_FOLDER.size());
size_t replaced = is_prefix_case_insensitive(folder, BOSSES_FOLDER) ? BOSSES_FOLDER.size()
: is_prefix_case_insensitive(folder, MONSTERS_FOLDER) ? MONSTERS_FOLDER.size()
: 0;
if (!replaced) continue;
path.replace(GFX_FOLDER.size(), replaced, DELIRIUM_FORMS_FOLDER);
if (std::filesystem::exists(resource_path(path))) sprite.ReplaceSpritesheet(i, path);
}
sprite.LoadGraphics();
sprite.SetFrame(sprite.GetDefaultAnimationName(), 0);
}
// 00409100 Plays both animations on by the playback speed.
void ANM2::Update()
{
if (!isLoaded) return;
animState.Update(playbackSpeed);
overlayAnimState.Update(playbackSpeed);
}
// 0040a0d0 Draws the main animation and the overlay, the overlay first when it renders first.
void ANM2::Render(const SpriteDraw& draw) const
{
if (!isLoaded) return;
const AnimationState& first = isOverlayRenderFirst ? overlayAnimState : animState;
const AnimationState& second = isOverlayRenderFirst ? animState : overlayAnimState;
first.Render(draw, *this);
second.Render(draw, *this);
}
// 0040a140 Draws one layer of both animations, in the order Render draws them.
void ANM2::RenderLayer(int layerId, const SpriteDraw& draw) const
{
if (!isLoaded) return;
const AnimationState& first = isOverlayRenderFirst ? overlayAnimState : animState;
const AnimationState& second = isOverlayRenderFirst ? animState : overlayAnimState;
first.RenderLayer(layerId, draw, *this);
second.RenderLayer(layerId, draw, *this);
}
// Selects a named animation on a state, from its start or keeping the frame, false when the sprite has none.
static bool state_select(const ANM2& sprite, AnimationState& state, std::string_view name, AnimationSwitch mode)
{
const AnimationData* data = sprite.GetAnimationData(name);
if (!data)
{
log_print(LOG_INFO, "[warn] no animation named %.*s\n", (int)name.size(), name.data());
return false;
}
if (mode == SWITCH_RESET) state.SetAnimationData(data);
else state.ChangeAnimationKeepFrame(data);
return true;
}
// Plays an animation from its start. Unforced, the one shown stays as it is unless it loops and has stopped.
static void state_play(const ANM2& sprite, AnimationState& state, std::string_view name, PlayMode mode)
{
const AnimationData* data = state.animData;
bool isShown = data && data->name == name;
if (mode == PLAY_UNFORCED && isShown && (!data->isLooping || state.isPlaying)) return;
if (!state_select(sprite, state, name, SWITCH_RESET)) return;
state.Rewind();
state.isPlaying = true;
}
// 0040a380, 0040a360 Plays an animation from its start, as state_play decides.
void ANM2::Play(std::string_view name, PlayMode mode)
{
state_play(*this, animState, name, mode);
}
// 0040a2b0 Plays the animation a seed picks, unforced.
void ANM2::PlayRandom(uint32_t seed)
{
if (!file || file->animations.empty())
{
KAGE_LogMessage(LOG_INFO, (uint8_t*)"[warn] PlayRandom: no animations\n");
return;
}
Play(file->animations[seed % (uint32_t)file->animations.size()].name);
}
// 0040a400 Plays the animation at a position in the file, unforced.
void ANM2::PlayIndex(int index)
{
if (!file || index < 0 || index >= (int)file->animations.size())
{
KAGE_LogMessage(LOG_INFO, (uint8_t*)"[warn] Animation index out of range!\n");
return;
}
Play(file->animations[index].name);
}
// 0040a5d0, 0040a5b0 Selects an animation on the main state, false when there is none of that name.
bool ANM2::SetAnimation(std::string_view name, AnimationSwitch mode)
{
return state_select(*this, animState, name, mode);
}
// 0040a690, 0040a6e0 Shows a frame of an animation, stopped.
void ANM2::SetFrame(std::string_view name, int frame)
{
if (!SetAnimation(name) || !animState.animData) return;
animState.SetFrameFloat((float)frame);
animState.isPlaying = false;
}
// 0040a740, 0040a720 Jumps the main animation to a frame, still playing if it was.
void ANM2::SetFrame(float frame)
{
if (animState.animData) animState.SetFrameFloat(frame);
}
// 0040a760 Steps to the last frame, firing the events on the way, still playing if it was.
void ANM2::SetLastFrame()
{
if (animState.animData) animState.AdvancePosition(animState.animData->length - 1);
}
// 0040a780 The whole frame the main animation is on, or -1.
int ANM2::GetFrame() const
{
return animState.animData ? (int)std::floor(animState.animFrame) : -1;
}
// 0040a910 Stops the main animation where it is.
void ANM2::Stop()
{
if (animState.animData) animState.isPlaying = false;
}
// 0040a4d0, 0040a4b0 Whether the main animation plays, the named one if a name is given.
bool ANM2::IsPlaying(std::string_view name) const
{
return animState.is_playing(name);
}
// 0040a550, 0040a530 Whether the main animation stopped, the named one if a name is given.
bool ANM2::IsFinished(std::string_view name) const
{
return animState.is_finished(name);
}
// 0085db20 The main animation's name, or an empty one.
const std::string& ANM2::GetAnimation() const
{
return animState.GetAnimation();
}
// 004a5cf0 The file's default animation, or an empty name.
const std::string& ANM2::GetDefaultAnimationName() const
{
return file ? file->defaultAnimation : EMPTY_NAME;
}
// 0040bcd0, 0040bcb0 The animation with a name, or null.
const AnimationData* ANM2::GetAnimationData(std::string_view name) const
{
if (!file) return nullptr;
for (const AnimationData& animation : file->animations)
if (animation.name == name) return &animation;
return nullptr;
}
// 0040a940, 0040a920 Plays an overlay animation from its start, as state_play decides.
void ANM2::PlayOverlay(std::string_view name, PlayMode mode)
{
state_play(*this, overlayAnimState, name, mode);
}
// 0040aaf0, 0040aad0 Selects an animation on the overlay state, false when there is none of that name.
bool ANM2::SetOverlayAnimation(std::string_view name, AnimationSwitch mode)
{
return state_select(*this, overlayAnimState, name, mode);
}
// 0040abf0, 0040abb0 Shows a frame of an overlay animation, still playing if it was.
void ANM2::SetOverlayFrame(std::string_view name, int frame)
{
if (SetOverlayAnimation(name) && overlayAnimState.animData) overlayAnimState.SetFrameFloat((float)frame);
}
// 0040ac30 Jumps the overlay to a frame.
void ANM2::SetOverlayFrame(int frame)
{
if (overlayAnimState.animData) overlayAnimState.SetFrameFloat((float)frame);
}
// 0040ac50 The frame the overlay is on, truncated, or -1.
int ANM2::GetOverlayFrame() const
{
return overlayAnimState.animData ? (int)overlayAnimState.animFrame : -1;
}
// 0040a9c0 Stops the overlay where it is.
void ANM2::StopOverlay()
{
if (overlayAnimState.animData) overlayAnimState.isPlaying = false;
}
// 0040ac60 Takes the overlay off.
void ANM2::RemoveOverlay()
{
overlayAnimState.SetAnimationData(nullptr);
}
// 0040a9f0, 0040a9d0 Whether the overlay plays, the named one if a name is given.
bool ANM2::IsOverlayPlaying(std::string_view name) const
{
return overlayAnimState.is_playing(name);
}
// 0040aa70, 0040aa50 Whether the overlay stopped, the named one if a name is given.
bool ANM2::IsOverlayFinished(std::string_view name) const
{
return overlayAnimState.is_finished(name);
}
// 0085db70 The overlay's name, or an empty one.
const std::string& ANM2::GetOverlayAnimation() const
{
return overlayAnimState.GetAnimation();
}
// 0040b030, 0040b000 Whether an event fired on the main animation's last step.
bool ANM2::IsEventTriggered(std::string_view eventName) const
{
return animState.animData && animState.IsEventTriggered(eventName);
}
// 0040b090, 0040b060 Whether an event fired since the main animation started.
bool ANM2::WasEventTriggered(std::string_view eventName) const
{
return animState.animData && animState.WasEventTriggered(eventName);
}
// 0040b220, 0040b200 A layer by id, or a shared default layer for an id outside the sprite.
LayerState* ANM2::GetLayer(int layerId)
{
static LayerState layerNone;
if (layerId >= 0 && layerId < (int)layerStates.size()) return &layerStates[layerId];
log_print(LOG_ASSERT, "%s: No layer with Id %d\n", filename.c_str(), layerId);
return &layerNone;
}
// 0040b430, 0040b310 A layer by name, or null.
LayerState* ANM2::GetLayer(std::string_view name)
{
for (LayerState& layer : layerStates)
if ((layer.layerData ? std::string_view(layer.layerData->name) : std::string_view()) == name) return &layer;
return nullptr;
}
// 0040a7e0 Puts a layer's track back to its keyframe holding a frame.
void ANM2::SetLayerFrame(int layerId, int frame)
{
if (animState.animData) animState.SetLayerFrame(layerId, frame);
}
// 0040a860 Puts a named layer's track back to its keyframe holding a frame.
void ANM2::SetLayerFrame(std::string_view layerName, int frame)
{
LayerState* layer = GetLayer(layerName);
if (!layer || !layer->layerData)
{
log_print(LOG_WARN, "[warn] no layer named %.*s\n", (int)layerName.size(), layerName.data());
return;
}
SetLayerFrame(layer->layerData->id, frame);
}
// 0040a8a0 The keyframe index a layer's track is on, or -1 without an animation.
int ANM2::GetLayerFrameIdx(int layerId) const
{
return animState.animData ? animState.GetLayerFrameIdx(layerId) : -1;
}
// 0040b1d0 The keyframe a null shows now on the main animation, by name.
const NullFrame* ANM2::GetNullFrame(std::string_view nullLayerName) const
{
return animState.animData ? animState.GetNullFrame(nullLayerName) : nullptr;
}
// 0040b0c0 A null's baked keyframe at an index in any animation, the last null of that name, or null.
const NullFrame* ANM2::GetNullFrame(std::string_view animName, std::string_view nullLayerName, int frame) const
{
const AnimationData* animation = GetAnimationData(animName);
if (!animation || file->nullLayerNames.empty()) return nullptr;
auto found = std::find(file->nullLayerNames.rbegin(), file->nullLayerNames.rend(), nullLayerName);
if (found == file->nullLayerNames.rend()) return nullptr;
int nullLayerId = (int)(file->nullLayerNames.rend() - found) - 1;
for (const AnimationNullLayer& layer : animation->nullLayers)
if (layer.nullLayerId == nullLayerId && frame >= 0 && frame < (int)layer.frames.size())
return &layer.frames[frame];
log_print(LOG_INFO, "[warn] ANM2::GetNullFrame frame number %d out of bounds.\n", frame);
return nullptr;
}
// 0040b1a0 The keyframe a null shows now on the main animation, by id.
const NullFrame* ANM2::GetNullFrameById(int nullLayerId) const
{
return animState.animData ? animState.GetNullFrameById(nullLayerId) : nullptr;
}
// 0040b4d0 A null's name by id.
// The original logs an id outside the file and reads past its names. Here that is an empty name.
const std::string& ANM2::GetNullLayerName(int nullLayerId) const
{
if (file && nullLayerId >= 0 && nullLayerId < (int)file->nullLayerNames.size())
return file->nullLayerNames[nullLayerId];
log_print(LOG_ASSERT, "%s: No null with Id %d\n", filename.c_str(), nullLayerId);
return EMPTY_NAME;
}
// 0040b520 A null's id by name, or -1.
int ANM2::null_index_get(std::string_view name) const
{
return name_index(file ? &file->nullLayerNames : nullptr, name);
}
// 0078b3b0 Puts another loaded sprite on this one's animations and frames, playing as they play.
void ANM2::animation_copy(ANM2& dest) const
{
if (!isLoaded || !dest.isLoaded) return;
if (!animState.animData || !animState.isPlaying) dest.SetFrame(GetAnimation(), GetFrame());
else
{
if (dest.SetAnimation(GetAnimation()))
{
dest.animState.Rewind();
dest.animState.isPlaying = true;
}
dest.SetFrame((float)GetFrame());
}
if (!overlayAnimState.animData)
{
if (dest.overlayAnimState.animData) dest.RemoveOverlay();
}
else if (!overlayAnimState.isPlaying) dest.SetOverlayFrame(GetOverlayAnimation(), GetOverlayFrame());
else
{
if (dest.SetOverlayAnimation(GetOverlayAnimation()))
{
dest.overlayAnimState.Rewind();
dest.overlayAnimState.isPlaying = true;
}
dest.SetOverlayFrame(GetOverlayFrame());
}
}
// 00837210 Plays on, then plays Idle once Appear has finished.
void ANM2::appear_update()
{
Update();
if (animState.animData && !animState.isPlaying && animState.animData->name == APPEAR_ANIMATION)
Play(IDLE_ANIMATION);
}