AVA2 cross-platform client parity baseline

This commit is contained in:
shen
2026-10-06 00:53:42 -07:00
commit 9f748eb05a
3271 changed files with 1275528 additions and 0 deletions
+340
View File
@@ -0,0 +1,340 @@
#include "EffectData.h"
#include <fstream>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <filesystem>
namespace ava2 {
float InterpolateTimeEvent(const std::vector<TimeEvent>& events, float time, float defaultValue) {
if (events.empty()) return defaultValue;
if (events.size() == 1 || time <= events.front().time) return events.front().value;
if (time >= events.back().time) return events.back().value;
for (size_t i = 0; i + 1 < events.size(); ++i) {
if (time >= events[i].time && time <= events[i + 1].time) {
float dt = events[i + 1].time - events[i].time;
if (dt < 1e-6f) return events[i].value;
float t = (time - events[i].time) / dt;
return events[i].value + t * (events[i + 1].value - events[i].value);
}
}
return events.back().value;
}
EffectData::EffectData() = default;
EffectData::~EffectData() = default;
static std::string NormalizePath(std::string path) {
for (char& c : path) {
if (c == '\\') c = '/';
}
if (path.size() >= 3 && (path[0] == 'd' || path[0] == 'D') && path[1] == ':' && path[2] == '/') {
path = path.substr(3);
}
if (!path.empty() && path[0] == '/') {
path = path.substr(1);
}
return path;
}
static std::vector<std::string> TokenizeScript(const std::string& content) {
std::vector<std::string> tokens;
size_t i = 0;
size_t n = content.size();
while (i < n) {
// Skip whitespace
while (i < n && (content[i] == ' ' || content[i] == '\t' || content[i] == '\r' || content[i] == '\n')) {
i++;
}
if (i >= n) break;
// Skip line comment
if (i + 1 < n && content[i] == '/' && content[i + 1] == '/') {
while (i < n && content[i] != '\n') i++;
continue;
}
// Single character tokens: '{', '}'
if (content[i] == '{' || content[i] == '}') {
tokens.push_back(std::string(1, content[i]));
i++;
continue;
}
// Quoted string
if (content[i] == '"') {
i++;
size_t start = i;
while (i < n && content[i] != '"') {
i++;
}
tokens.push_back(content.substr(start, i - start));
if (i < n && content[i] == '"') i++;
continue;
}
// Normal word
size_t start = i;
while (i < n && content[i] != ' ' && content[i] != '\t' && content[i] != '\r' && content[i] != '\n' &&
content[i] != '{' && content[i] != '}' && content[i] != '"') {
i++;
}
tokens.push_back(content.substr(start, i - start));
}
return tokens;
}
static std::string ToLower(std::string str) {
std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { return std::tolower(c); });
return str;
}
bool EffectData::LoadScript(const std::string& filepath) {
m_filename = NormalizePath(filepath);
m_particles.clear();
std::ifstream file(filepath, std::ios::binary);
if (!file.is_open()) {
// Try normalized or relative to workspace
file.open(m_filename, std::ios::binary);
if (!file.is_open()) {
return false;
}
}
std::stringstream buffer;
buffer << file.rdbuf();
std::string content = buffer.str();
std::string effectDir = "";
size_t lastSlash = filepath.find_last_of("/\\");
if (lastSlash != std::string::npos) {
effectDir = filepath.substr(0, lastSlash + 1);
}
auto tokens = TokenizeScript(content);
size_t idx = 0;
size_t numTokens = tokens.size();
auto ReadTimeEvents = [&](std::vector<TimeEvent>& outEvents) {
if (idx < numTokens && tokens[idx] == "{") {
idx++;
while (idx < numTokens && tokens[idx] != "}") {
float t = std::stof(tokens[idx++]);
if (idx < numTokens && tokens[idx] != "}") {
float v = std::stof(tokens[idx++]);
outEvents.push_back({t, v});
}
}
if (idx < numTokens && tokens[idx] == "}") idx++;
}
};
while (idx < numTokens) {
std::string tokenLower = ToLower(tokens[idx]);
if (tokenLower == "boundingsphereradius" && idx + 1 < numTokens) {
idx++;
m_bounding_sphere_radius = std::stof(tokens[idx++]);
} else if (tokenLower == "boundingsphereposition" && idx + 3 < numTokens) {
idx++;
m_bounding_sphere_position[0] = std::stof(tokens[idx++]);
m_bounding_sphere_position[1] = std::stof(tokens[idx++]);
m_bounding_sphere_position[2] = std::stof(tokens[idx++]);
} else if (tokenLower == "group" && idx + 1 < numTokens && ToLower(tokens[idx + 1]) == "particle") {
idx += 2;
if (idx < numTokens && tokens[idx] == "{") idx++;
ParticleElement pe;
int depth = 1;
while (idx < numTokens && depth > 0) {
if (tokens[idx] == "{") {
depth++;
idx++;
continue;
}
if (tokens[idx] == "}") {
depth--;
idx++;
continue;
}
std::string pKey = ToLower(tokens[idx++]);
if (pKey == "starttime" && idx < numTokens) {
pe.start_time = std::stof(tokens[idx++]);
} else if (pKey == "list" && idx + 1 < numTokens && ToLower(tokens[idx]) == "timeeventposition") {
idx++; // skip timeeventposition
if (idx < numTokens && tokens[idx] == "{") {
idx++;
while (idx < numTokens && tokens[idx] != "}") {
// format: time "MOVING_TYPE_DIRECT" x y z
idx++; // time
if (idx < numTokens && tokens[idx] != "}") idx++; // moving type string
if (idx + 2 < numTokens && tokens[idx] != "}") {
float mx = std::stof(tokens[idx++]);
float my = std::stof(tokens[idx++]);
float mz = std::stof(tokens[idx++]);
// Map Metin2 3ds Max Z-up (X:right, Y:forward, Z:up) to Ava2 Y-up (X:right, Y:up, Z:forward)
pe.position[0] = mx;
pe.position[1] = mz;
pe.position[2] = my;
}
}
if (idx < numTokens && tokens[idx] == "}") idx++;
}
} else if (pKey == "group" && idx < numTokens && ToLower(tokens[idx]) == "emitterproperty") {
idx++; // skip emitterproperty
if (idx < numTokens && tokens[idx] == "{") idx++;
int emitterDepth = 1;
while (idx < numTokens && emitterDepth > 0) {
if (tokens[idx] == "{") { emitterDepth++; idx++; continue; }
if (tokens[idx] == "}") { emitterDepth--; idx++; continue; }
std::string eKey = ToLower(tokens[idx++]);
if (eKey == "maxemissioncount" && idx < numTokens) {
pe.emitter.max_emission_count = std::stoul(tokens[idx++]);
} else if (eKey == "cyclelength" && idx < numTokens) {
pe.emitter.cycle_length = std::stof(tokens[idx++]);
} else if (eKey == "cycleloopenable" && idx < numTokens) {
pe.emitter.cycle_loop_enable = (std::stoi(tokens[idx++]) != 0);
} else if (eKey == "loopcount" && idx < numTokens) {
pe.emitter.loop_count = std::stoi(tokens[idx++]);
} else if (eKey == "emittershape" && idx < numTokens) {
pe.emitter.emitter_shape = static_cast<uint8_t>(std::stoi(tokens[idx++]));
} else if (eKey == "emittingradius" && idx < numTokens) {
pe.emitter.emitting_radius = std::stof(tokens[idx++]);
} else if (eKey == "emittingdirection" && idx + 2 < numTokens) {
float ex = std::stof(tokens[idx++]);
float ey = std::stof(tokens[idx++]);
float ez = std::stof(tokens[idx++]);
pe.emitter.emitting_direction[0] = ex;
pe.emitter.emitting_direction[1] = ez;
pe.emitter.emitting_direction[2] = ey;
} else if (eKey == "list" && idx < numTokens) {
std::string listName = ToLower(tokens[idx++]);
if (listName == "timeeventemittingvelocity") ReadTimeEvents(pe.emitter.time_emitting_velocity);
else if (listName == "timeeventemissioncountpersecond") ReadTimeEvents(pe.emitter.time_emission_count_per_second);
else if (listName == "timeeventlifetime") ReadTimeEvents(pe.emitter.time_life_time);
else if (listName == "timeeventsizex") ReadTimeEvents(pe.emitter.time_size_x);
else if (listName == "timeeventsizey") ReadTimeEvents(pe.emitter.time_size_y);
else if (listName == "timeeventemittingdirectionx") ReadTimeEvents(pe.emitter.time_emitting_dir_x);
else if (listName == "timeeventemittingdirectiony") ReadTimeEvents(pe.emitter.time_emitting_dir_z);
else if (listName == "timeeventemittingdirectionz") ReadTimeEvents(pe.emitter.time_emitting_dir_y);
else if (listName == "timeeventemittingangularvelocity") ReadTimeEvents(pe.emitter.time_emitting_angular_velocity);
else {
// Skip unknown list
if (idx < numTokens && tokens[idx] == "{") {
int lDepth = 1; idx++;
while (idx < numTokens && lDepth > 0) {
if (tokens[idx] == "{") lDepth++;
else if (tokens[idx] == "}") lDepth--;
idx++;
}
}
}
}
}
} else if (pKey == "group" && idx < numTokens && ToLower(tokens[idx]) == "particleproperty") {
idx++; // skip particleproperty
if (idx < numTokens && tokens[idx] == "{") idx++;
int partDepth = 1;
while (idx < numTokens && partDepth > 0) {
if (tokens[idx] == "{") { partDepth++; idx++; continue; }
if (tokens[idx] == "}") { partDepth--; idx++; continue; }
std::string prKey = ToLower(tokens[idx++]);
if (prKey == "srcblendtype" && idx < numTokens) {
pe.particle.src_blend_type = static_cast<uint8_t>(std::stoi(tokens[idx++]));
} else if (prKey == "destblendtype" && idx < numTokens) {
pe.particle.dest_blend_type = static_cast<uint8_t>(std::stoi(tokens[idx++]));
} else if (prKey == "coloroperationtype" && idx < numTokens) {
pe.particle.color_op_type = static_cast<uint8_t>(std::stoi(tokens[idx++]));
} else if (prKey == "billboardtype" && idx < numTokens) {
pe.particle.billboard_type = static_cast<uint8_t>(std::stoi(tokens[idx++]));
} else if (prKey == "rotationtype" && idx < numTokens) {
pe.particle.rotation_type = static_cast<uint8_t>(std::stoi(tokens[idx++]));
} else if (prKey == "rotationspeed" && idx < numTokens) {
pe.particle.rotation_speed = std::stof(tokens[idx++]);
} else if (prKey == "rotationrandomstartingbegin" && idx < numTokens) {
pe.particle.rotation_random_begin = std::stoi(tokens[idx++]);
} else if (prKey == "rotationrandomstartingend" && idx < numTokens) {
pe.particle.rotation_random_end = std::stoi(tokens[idx++]);
} else if (prKey == "attachenable" && idx < numTokens) {
pe.particle.attach_enable = (std::stoi(tokens[idx++]) != 0);
} else if (prKey == "stretchenable" && idx < numTokens) {
pe.particle.stretch_enable = (std::stoi(tokens[idx++]) != 0);
} else if (prKey == "texanitype" && idx < numTokens) {
pe.particle.tex_ani_type = static_cast<uint8_t>(std::stoi(tokens[idx++]));
} else if (prKey == "texanidelay" && idx < numTokens) {
pe.particle.tex_ani_delay = std::stof(tokens[idx++]);
} else if (prKey == "texanirandomstartframeenable" && idx < numTokens) {
pe.particle.tex_ani_random_start_frame = (std::stoi(tokens[idx++]) != 0);
} else if (prKey == "list" && idx < numTokens) {
std::string listName = ToLower(tokens[idx++]);
if (listName == "timeeventscalex") ReadTimeEvents(pe.particle.time_scale_x);
else if (listName == "timeeventscaley") ReadTimeEvents(pe.particle.time_scale_y);
else if (listName == "timeeventcolorred") ReadTimeEvents(pe.particle.time_color_r);
else if (listName == "timeeventcolorgreen") ReadTimeEvents(pe.particle.time_color_g);
else if (listName == "timeeventcolorblue") ReadTimeEvents(pe.particle.time_color_b);
else if (listName == "timeeventalpha") ReadTimeEvents(pe.particle.time_alpha);
else if (listName == "timeeventrotation") ReadTimeEvents(pe.particle.time_rotation);
else if (listName == "timeeventgravity") ReadTimeEvents(pe.particle.time_gravity);
else if (listName == "timeeventairresistance") ReadTimeEvents(pe.particle.time_air_resistance);
else if (listName == "texturefiles") {
if (idx < numTokens && tokens[idx] == "{") {
idx++;
while (idx < numTokens && tokens[idx] != "}") {
std::string rawTex = NormalizePath(tokens[idx++]);
// Resolve relative to effect directory if needed
std::string resolvedTex = rawTex;
if (!std::filesystem::exists(resolvedTex) && !effectDir.empty()) {
std::string candidate = NormalizePath(effectDir + rawTex);
if (std::filesystem::exists(candidate)) {
resolvedTex = candidate;
}
}
pe.particle.texture_files.push_back(resolvedTex);
}
if (idx < numTokens && tokens[idx] == "}") idx++;
}
} else {
// Skip unknown list
if (idx < numTokens && tokens[idx] == "{") {
int lDepth = 1; idx++;
while (idx < numTokens && lDepth > 0) {
if (tokens[idx] == "{") lDepth++;
else if (tokens[idx] == "}") lDepth--;
idx++;
}
}
}
}
}
}
}
m_particles.push_back(pe);
} else {
idx++;
}
}
// Check for bound sound file
std::string stem = m_filename;
size_t extDot = stem.find_last_of('.');
if (extDot != std::string::npos) stem = stem.substr(0, extDot);
std::string soundCandidate = "sound/" + stem + ".mss";
if (std::filesystem::exists(soundCandidate)) {
m_sound_filename = soundCandidate;
}
return true;
}
} // namespace ava2
+99
View File
@@ -0,0 +1,99 @@
#pragma once
#include <string>
#include <vector>
#include <memory>
#include <cstdint>
namespace ava2 {
struct TimeEvent {
float time = 0.0f;
float value = 0.0f;
};
float InterpolateTimeEvent(const std::vector<TimeEvent>& events, float time, float defaultValue = 0.0f);
struct EmitterProperty {
uint32_t max_emission_count = 1;
float cycle_length = 0.5f;
bool cycle_loop_enable = false;
int loop_count = 0;
uint8_t emitter_shape = 0; // 0: Point, 1: Ellipse, 2: Box
uint8_t emitter_advanced_type = 0;
bool emit_from_edge_flag = false;
float emitting_radius = 0.0f;
float emitting_direction[3] = {0.0f, 0.0f, 0.0f};
std::vector<TimeEvent> time_emitting_velocity;
std::vector<TimeEvent> time_emission_count_per_second;
std::vector<TimeEvent> time_life_time;
std::vector<TimeEvent> time_size_x;
std::vector<TimeEvent> time_size_y;
std::vector<TimeEvent> time_emitting_dir_x;
std::vector<TimeEvent> time_emitting_dir_y;
std::vector<TimeEvent> time_emitting_dir_z;
std::vector<TimeEvent> time_emitting_angular_velocity;
};
struct ParticleProperty {
uint8_t src_blend_type = 5; // D3DBLEND_SRCALPHA
uint8_t dest_blend_type = 2; // D3DBLEND_ONE (Additive) or 5 (D3DBLEND_INVSRCALPHA)
uint8_t color_op_type = 4; // D3DTOP_MODULATE
uint8_t billboard_type = 1; // 0: None, 1: All/Camera, 2: Y-axis, 3: Lie flat, 4: 2Face, 5: 3Face
uint8_t rotation_type = 0;
float rotation_speed = 0.0f;
int rotation_random_begin = 0;
int rotation_random_end = 0;
bool attach_enable = false;
bool stretch_enable = false;
uint8_t tex_ani_type = 0;
float tex_ani_delay = 0.03f;
bool tex_ani_random_start_frame = false;
std::vector<TimeEvent> time_gravity;
std::vector<TimeEvent> time_air_resistance;
std::vector<TimeEvent> time_scale_x;
std::vector<TimeEvent> time_scale_y;
std::vector<TimeEvent> time_color_r;
std::vector<TimeEvent> time_color_g;
std::vector<TimeEvent> time_color_b;
std::vector<TimeEvent> time_alpha;
std::vector<TimeEvent> time_rotation;
std::vector<std::string> texture_files;
};
struct ParticleElement {
float start_time = 0.0f;
float position[3] = {0.0f, 0.0f, 0.0f};
EmitterProperty emitter;
ParticleProperty particle;
};
class EffectData {
public:
EffectData();
~EffectData();
bool LoadScript(const std::string& filepath);
const std::string& GetFileName() const { return m_filename; }
float GetBoundingSphereRadius() const { return m_bounding_sphere_radius; }
const float* GetBoundingSpherePosition() const { return m_bounding_sphere_position; }
const std::vector<ParticleElement>& GetParticles() const { return m_particles; }
const std::string& GetSoundFileName() const { return m_sound_filename; }
private:
std::string m_filename;
float m_bounding_sphere_radius = 100.0f;
float m_bounding_sphere_position[3] = {0.0f, 0.0f, 0.0f};
std::vector<ParticleElement> m_particles;
std::string m_sound_filename;
};
} // namespace ava2
+356
View File
@@ -0,0 +1,356 @@
#include "EffectInstance.h"
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <unordered_map>
namespace ava2 {
static float RandomFloat(float minVal, float maxVal) {
if (minVal >= maxVal) return minVal;
float r = static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX);
return minVal + r * (maxVal - minVal);
}
EffectInstance::EffectInstance(std::shared_ptr<EffectData> data)
: m_data(std::move(data)) {
if (m_data) {
m_emitters.resize(m_data->GetParticles().size());
}
}
EffectInstance::~EffectInstance() = default;
void EffectInstance::SetPosition(float x, float y, float z) {
m_position[0] = x;
m_position[1] = y;
m_position[2] = z;
m_matrix[12] = x;
m_matrix[13] = y;
m_matrix[14] = z;
}
void EffectInstance::SetRotation(float yaw, float pitch, float roll) {
m_rotation[0] = yaw;
m_rotation[1] = pitch;
m_rotation[2] = roll;
MakeTransformMatrix(yaw, m_position[0], m_position[1], m_position[2], 1.0f, m_matrix);
}
void EffectInstance::SetGlobalMatrix(const float* mat16) {
if (mat16) {
for (int i = 0; i < 16; ++i) {
m_matrix[i] = mat16[i];
}
m_position[0] = mat16[12];
m_position[1] = mat16[13];
m_position[2] = mat16[14];
m_hasCustomMatrix = true;
}
}
void EffectInstance::Update(float dt) {
if (!m_isAlive || !m_data) return;
m_age += dt;
const auto& peList = m_data->GetParticles();
bool hasActiveElements = false;
for (size_t i = 0; i < peList.size(); ++i) {
const auto& pe = peList[i];
auto& inst = m_emitters[i];
if (m_age < pe.start_time) {
hasActiveElements = true;
continue;
}
float localTime = m_age - pe.start_time;
float cycleLength = pe.emitter.cycle_length > 0.001f ? pe.emitter.cycle_length : 0.5f;
float cycleTime = localTime;
bool cycleExpired = false;
if (pe.emitter.cycle_loop_enable) {
cycleTime = std::fmod(localTime, cycleLength);
hasActiveElements = true;
} else {
if (localTime >= cycleLength) {
cycleTime = cycleLength;
cycleExpired = true;
} else {
hasActiveElements = true;
}
}
inst.local_time = cycleTime;
// Determine particle spawning
float emissionRate = InterpolateTimeEvent(pe.emitter.time_emission_count_per_second, cycleTime, 20.0f);
uint32_t maxEmission = pe.emitter.max_emission_count > 0 ? pe.emitter.max_emission_count : 1;
if (!cycleExpired || pe.emitter.cycle_loop_enable) {
inst.emission_accumulator += emissionRate * dt;
int toSpawn = static_cast<int>(inst.emission_accumulator);
inst.emission_accumulator -= toSpawn;
// Cap to remaining emission allowance in cycle
if (inst.emitted_count + toSpawn > maxEmission && !pe.emitter.cycle_loop_enable) {
toSpawn = static_cast<int>(maxEmission) - static_cast<int>(inst.emitted_count);
}
for (int s = 0; s < toSpawn && s < 20; ++s) {
ParticleState p;
p.life = 0.0f;
p.max_life = InterpolateTimeEvent(pe.emitter.time_life_time, cycleTime, 0.5f);
if (p.max_life < 0.05f) p.max_life = 0.05f;
// Position offset
float offset[3] = {pe.position[0], pe.position[1], pe.position[2]};
if (pe.emitter.emitter_shape == 1 && pe.emitter.emitting_radius > 0.0f) {
float angle = RandomFloat(0.0f, 6.2831853f);
float r = RandomFloat(0.0f, pe.emitter.emitting_radius);
offset[0] += std::cos(angle) * r;
offset[1] += std::sin(angle) * r;
}
// Transform offset into world space using m_matrix
p.pos[0] = offset[0] * m_matrix[0] + offset[1] * m_matrix[4] + offset[2] * m_matrix[8] + m_matrix[12];
p.pos[1] = offset[0] * m_matrix[1] + offset[1] * m_matrix[5] + offset[2] * m_matrix[9] + m_matrix[13];
p.pos[2] = offset[0] * m_matrix[2] + offset[1] * m_matrix[6] + offset[2] * m_matrix[10] + m_matrix[14];
p.last_pos[0] = p.pos[0];
p.last_pos[1] = p.pos[1];
p.last_pos[2] = p.pos[2];
// Velocity
float speed = InterpolateTimeEvent(pe.emitter.time_emitting_velocity, cycleTime, 0.0f);
float dirX = InterpolateTimeEvent(pe.emitter.time_emitting_dir_x, cycleTime, pe.emitter.emitting_direction[0]);
float dirY = InterpolateTimeEvent(pe.emitter.time_emitting_dir_y, cycleTime, pe.emitter.emitting_direction[1]);
float dirZ = InterpolateTimeEvent(pe.emitter.time_emitting_dir_z, cycleTime, pe.emitter.emitting_direction[2]);
float dirLen = std::sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ);
if (dirLen > 1e-4f) {
dirX /= dirLen; dirY /= dirLen; dirZ /= dirLen;
}
// Transform velocity vector by rotation matrix
float worldDirX = dirX * m_matrix[0] + dirY * m_matrix[4] + dirZ * m_matrix[8];
float worldDirY = dirX * m_matrix[1] + dirY * m_matrix[5] + dirZ * m_matrix[9];
float worldDirZ = dirX * m_matrix[2] + dirY * m_matrix[6] + dirZ * m_matrix[10];
p.vel[0] = worldDirX * speed;
p.vel[1] = worldDirY * speed;
p.vel[2] = worldDirZ * speed;
// Rotation
p.rot = RandomFloat(static_cast<float>(pe.particle.rotation_random_begin),
static_cast<float>(pe.particle.rotation_random_end));
p.rot_speed = pe.particle.rotation_speed;
inst.particles.push_back(p);
inst.emitted_count++;
}
}
// Update active particles
for (auto it = inst.particles.begin(); it != inst.particles.end();) {
it->life += dt;
if (it->life >= it->max_life) {
it = inst.particles.erase(it);
continue;
}
float t = it->life / it->max_life;
it->last_pos[0] = it->pos[0];
it->last_pos[1] = it->pos[1];
it->last_pos[2] = it->pos[2];
it->pos[0] += it->vel[0] * dt;
it->pos[1] += it->vel[1] * dt;
it->pos[2] += it->vel[2] * dt;
// Gravity
float grav = InterpolateTimeEvent(pe.particle.time_gravity, t, 0.0f);
it->vel[1] -= grav * 9.8f * dt;
// Air resistance
float airRes = InterpolateTimeEvent(pe.particle.time_air_resistance, t, 0.0f);
if (airRes > 0.0f) {
float drag = std::max(0.0f, 1.0f - airRes * dt);
it->vel[0] *= drag;
it->vel[1] *= drag;
it->vel[2] *= drag;
}
it->rot += it->rot_speed * dt;
// Color & Alpha interpolation
it->color[0] = InterpolateTimeEvent(pe.particle.time_color_r, t, 1.0f);
it->color[1] = InterpolateTimeEvent(pe.particle.time_color_g, t, 1.0f);
it->color[2] = InterpolateTimeEvent(pe.particle.time_color_b, t, 1.0f);
it->color[3] = InterpolateTimeEvent(pe.particle.time_alpha, t, 1.0f);
// Scale interpolation
it->scale[0] = InterpolateTimeEvent(pe.particle.time_scale_x, t, 1.0f);
it->scale[1] = InterpolateTimeEvent(pe.particle.time_scale_y, t, 1.0f);
// Texture animation
if (pe.particle.texture_files.size() > 1 && pe.particle.tex_ani_delay > 0.001f) {
it->frame_index = static_cast<uint8_t>(std::fmod(it->life / pe.particle.tex_ani_delay, pe.particle.texture_files.size()));
}
++it;
}
if (!inst.particles.empty()) {
hasActiveElements = true;
}
}
if (!hasActiveElements) {
m_isAlive = false;
}
}
void EffectInstance::BuildDrawCommands(const float* viewMatrix, const float* projMatrix, const float* cameraPos, std::vector<Render3DDraw>& outDraws) {
if (!m_isAlive || !m_data) return;
// Camera basis vectors
float camRight[3] = {viewMatrix[0], viewMatrix[4], viewMatrix[8]};
float camUp[3] = {viewMatrix[1], viewMatrix[5], viewMatrix[9]};
float camDir[3] = {viewMatrix[2], viewMatrix[6], viewMatrix[10]};
// Normalize basis
auto Normalize = [](float* v) {
float len = std::sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
if (len > 1e-5f) { v[0] /= len; v[1] /= len; v[2] /= len; }
};
Normalize(camRight);
Normalize(camUp);
Normalize(camDir);
const auto& peList = m_data->GetParticles();
for (size_t i = 0; i < peList.size(); ++i) {
const auto& pe = peList[i];
const auto& inst = m_emitters[i];
if (inst.particles.empty()) continue;
// Group particles by texture
std::unordered_map<std::string, std::vector<size_t>> texGroups;
for (size_t pIdx = 0; pIdx < inst.particles.size(); ++pIdx) {
const auto& p = inst.particles[pIdx];
std::string tex = "";
if (!pe.particle.texture_files.empty()) {
size_t frame = p.frame_index % pe.particle.texture_files.size();
tex = pe.particle.texture_files[frame];
}
texGroups[tex].push_back(pIdx);
}
float baseSizeX = InterpolateTimeEvent(pe.emitter.time_size_x, inst.local_time, 32.0f);
float baseSizeY = InterpolateTimeEvent(pe.emitter.time_size_y, inst.local_time, 32.0f);
for (const auto& [texPath, pIndices] : texGroups) {
Render3DDraw draw;
draw.texture0 = texPath;
draw.lighting = false;
draw.z_enable = true;
draw.z_write = false;
draw.cull_mode = 1; // D3DCULL_NONE
draw.alpha_blend = true;
draw.blend_mode = (pe.particle.dest_blend_type == 2 ? 1 : 0); // 1 = Additive (D3DBLEND_ONE)
for (int m = 0; m < 16; ++m) {
draw.view[m] = viewMatrix[m];
draw.proj[m] = projMatrix[m];
draw.world[m] = (m % 5 == 0) ? 1.0f : 0.0f; // Identity world matrix
}
uint32_t vertexOffset = 0;
for (size_t pIdx : pIndices) {
const auto& p = inst.particles[pIdx];
if (p.color[3] <= 0.001f) continue;
float hx = baseSizeX * p.scale[0] * 0.5f;
float hy = baseSizeY * p.scale[1] * 0.5f;
float right[3] = {camRight[0], camRight[1], camRight[2]};
float up[3] = {camUp[0], camUp[1], camUp[2]};
if (pe.particle.billboard_type == 3) {
// BILLBOARD_TYPE_LIE: Horizontal XZ plane (ground flat)
float rad = p.rot * 3.14159265f / 180.0f;
float c = std::cos(rad), s = std::sin(rad);
right[0] = c; right[1] = 0.0f; right[2] = -s;
up[0] = s; up[1] = 0.0f; up[2] = c;
} else if (pe.particle.billboard_type == 2) {
// BILLBOARD_TYPE_Y: Cylindrical billboard facing camera around Y
up[0] = 0.0f; up[1] = 1.0f; up[2] = 0.0f;
float dirXZ[2] = {camDir[0], camDir[2]};
float dLen = std::sqrt(dirXZ[0]*dirXZ[0] + dirXZ[1]*dirXZ[1]);
if (dLen > 1e-4f) { dirXZ[0] /= dLen; dirXZ[1] /= dLen; }
right[0] = -dirXZ[1]; right[1] = 0.0f; right[2] = dirXZ[0];
} else if (pe.particle.stretch_enable) {
// Stretched along velocity
float vDir[3] = {p.vel[0], p.vel[1], p.vel[2]};
float vLen = std::sqrt(vDir[0]*vDir[0] + vDir[1]*vDir[1] + vDir[2]*vDir[2]);
if (vLen > 1e-4f) {
float stretch = 1.0f + std::log(1.0f + vLen * 0.01f);
up[0] = (vDir[0] / vLen) * stretch;
up[1] = (vDir[1] / vLen) * stretch;
up[2] = (vDir[2] / vLen) * stretch;
right[0] = up[1] * camDir[2] - up[2] * camDir[1];
right[1] = up[2] * camDir[0] - up[0] * camDir[2];
right[2] = up[0] * camDir[1] - up[1] * camDir[0];
Normalize(right);
}
} else if (p.rot != 0.0f) {
// Billboard rotated in camera plane
float rad = p.rot * 3.14159265f / 180.0f;
float c = std::cos(rad), s = std::sin(rad);
float rotRight[3] = {right[0]*c - up[0]*s, right[1]*c - up[1]*s, right[2]*c - up[2]*s};
float rotUp[3] = {right[0]*s + up[0]*c, right[1]*s + up[1]*c, right[2]*s + up[2]*c};
right[0] = rotRight[0]; right[1] = rotRight[1]; right[2] = rotRight[2];
up[0] = rotUp[0]; up[1] = rotUp[1]; up[2] = rotUp[2];
}
// 4 Quad vertices
float p0[3] = {p.pos[0] - right[0]*hx - up[0]*hy, p.pos[1] - right[1]*hx - up[1]*hy, p.pos[2] - right[2]*hx - up[2]*hy};
float p1[3] = {p.pos[0] + right[0]*hx - up[0]*hy, p.pos[1] + right[1]*hx - up[1]*hy, p.pos[2] + right[2]*hx - up[2]*hy};
float p2[3] = {p.pos[0] + right[0]*hx + up[0]*hy, p.pos[1] + right[1]*hx + up[1]*hy, p.pos[2] + right[2]*hx + up[2]*hy};
float p3[3] = {p.pos[0] - right[0]*hx + up[0]*hy, p.pos[1] - right[1]*hx + up[0]*hy, p.pos[2] - right[2]*hx + up[2]*hy};
uint8_t cr = static_cast<uint8_t>(std::clamp(p.color[0] * 255.0f, 0.0f, 255.0f));
uint8_t cg = static_cast<uint8_t>(std::clamp(p.color[1] * 255.0f, 0.0f, 255.0f));
uint8_t cb = static_cast<uint8_t>(std::clamp(p.color[2] * 255.0f, 0.0f, 255.0f));
uint8_t ca = static_cast<uint8_t>(std::clamp(p.color[3] * 255.0f, 0.0f, 255.0f));
uint32_t diff = (static_cast<uint32_t>(ca) << 24) | (static_cast<uint32_t>(cr) << 16) | (static_cast<uint32_t>(cg) << 8) | static_cast<uint32_t>(cb);
// Add vertices: 0, 1, 2, 3
draw.positions.insert(draw.positions.end(), {p0[0], p0[1], p0[2]});
draw.positions.insert(draw.positions.end(), {p1[0], p1[1], p1[2]});
draw.positions.insert(draw.positions.end(), {p2[0], p2[1], p2[2]});
draw.positions.insert(draw.positions.end(), {p3[0], p3[1], p3[2]});
draw.uv0.insert(draw.uv0.end(), {0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f});
draw.diffuse.insert(draw.diffuse.end(), {diff, diff, diff, diff});
// Two triangles: (0, 1, 2) and (0, 2, 3)
draw.indices.push_back(vertexOffset + 0);
draw.indices.push_back(vertexOffset + 1);
draw.indices.push_back(vertexOffset + 2);
draw.indices.push_back(vertexOffset + 0);
draw.indices.push_back(vertexOffset + 2);
draw.indices.push_back(vertexOffset + 3);
vertexOffset += 4;
}
if (!draw.indices.empty()) {
outDraws.push_back(std::move(draw));
}
}
}
}
} // namespace ava2
+65
View File
@@ -0,0 +1,65 @@
#pragma once
#include "EffectData.h"
#include "eter_render/RenderCommands3D.h"
#include <vector>
#include <memory>
#include <cstdint>
namespace ava2 {
struct ParticleState {
float pos[3] = {0.0f, 0.0f, 0.0f};
float last_pos[3] = {0.0f, 0.0f, 0.0f};
float vel[3] = {0.0f, 0.0f, 0.0f};
float life = 0.0f;
float max_life = 1.0f;
float rot = 0.0f;
float rot_speed = 0.0f;
float scale[2] = {1.0f, 1.0f};
float color[4] = {1.0f, 1.0f, 1.0f, 1.0f}; // RGBA [0..1]
uint8_t frame_index = 0;
};
struct EmitterInstance {
float local_time = 0.0f;
uint32_t emitted_count = 0;
float emission_accumulator = 0.0f;
std::vector<ParticleState> particles;
};
class EffectInstance {
public:
EffectInstance(std::shared_ptr<EffectData> data);
~EffectInstance();
void SetPosition(float x, float y, float z);
void SetRotation(float yaw, float pitch, float roll);
void SetGlobalMatrix(const float* mat16);
void Update(float dt);
void BuildDrawCommands(const float* viewMatrix, const float* projMatrix, const float* cameraPos, std::vector<Render3DDraw>& outDraws);
bool IsAlive() const { return m_isAlive; }
void Kill() { m_isAlive = false; }
std::shared_ptr<EffectData> GetData() const { return m_data; }
private:
std::shared_ptr<EffectData> m_data;
bool m_isAlive = true;
float m_age = 0.0f;
float m_position[3] = {0.0f, 0.0f, 0.0f};
float m_rotation[3] = {0.0f, 0.0f, 0.0f};
float m_matrix[16] = {
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f
};
bool m_hasCustomMatrix = false;
std::vector<EmitterInstance> m_emitters;
};
} // namespace ava2
+126
View File
@@ -0,0 +1,126 @@
#include "EffectManager.h"
#include <algorithm>
namespace ava2 {
EffectManager& EffectManager::Instance() {
static EffectManager s_instance;
return s_instance;
}
uint32_t EffectManager::ComputeCRC(const std::string& str) {
uint32_t crc = 0xFFFFFFFF;
for (char c : str) {
char lower = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
if (lower == '\\') lower = '/';
crc ^= static_cast<uint8_t>(lower);
for (int i = 0; i < 8; ++i) {
crc = (crc >> 1) ^ (0xEDB88320 & (-(crc & 1)));
}
}
return ~crc;
}
bool EffectManager::RegisterEffect(const std::string& filename, uint32_t* outId) {
uint32_t id = ComputeCRC(filename);
if (outId) *outId = id;
if (m_dataCache.find(id) != m_dataCache.end()) {
return true;
}
auto data = std::make_shared<EffectData>();
if (!data->LoadScript(filename)) {
return false;
}
m_dataCache[id] = data;
m_fileToId[filename] = id;
return true;
}
uint32_t EffectManager::CreateEffect(const std::string& filename, float x, float y, float z, float yaw) {
uint32_t id = 0;
if (!RegisterEffect(filename, &id)) {
return 0;
}
return CreateEffect(id, x, y, z, yaw);
}
uint32_t EffectManager::CreateEffect(uint32_t effectId, float x, float y, float z, float yaw) {
auto it = m_dataCache.find(effectId);
if (it == m_dataCache.end()) {
return 0;
}
auto instance = std::make_shared<EffectInstance>(it->second);
instance->SetPosition(x, y, z);
if (yaw != 0.0f) {
instance->SetRotation(yaw, 0.0f, 0.0f);
}
uint32_t instId = m_nextInstanceId++;
m_instances[instId] = instance;
return instId;
}
bool EffectManager::DestroyEffectInstance(uint32_t instanceId) {
auto it = m_instances.find(instanceId);
if (it != m_instances.end()) {
it->second->Kill();
m_instances.erase(it);
return true;
}
return false;
}
void EffectManager::DeleteAllInstances() {
m_instances.clear();
}
bool EffectManager::IsAliveEffect(uint32_t instanceId) const {
auto it = m_instances.find(instanceId);
return (it != m_instances.end()) && it->second->IsAlive();
}
void EffectManager::SetEffectInstancePosition(uint32_t instanceId, float x, float y, float z) {
auto it = m_instances.find(instanceId);
if (it != m_instances.end()) {
it->second->SetPosition(x, y, z);
}
}
void EffectManager::SetEffectInstanceRotation(uint32_t instanceId, float yaw, float pitch, float roll) {
auto it = m_instances.find(instanceId);
if (it != m_instances.end()) {
it->second->SetRotation(yaw, pitch, roll);
}
}
void EffectManager::SetEffectInstanceGlobalMatrix(uint32_t instanceId, const float* mat16) {
auto it = m_instances.find(instanceId);
if (it != m_instances.end()) {
it->second->SetGlobalMatrix(mat16);
}
}
void EffectManager::Update(float dt) {
for (auto it = m_instances.begin(); it != m_instances.end();) {
it->second->Update(dt);
if (!it->second->IsAlive()) {
it = m_instances.erase(it);
} else {
++it;
}
}
}
void EffectManager::BuildDrawCommands(const float* viewMatrix, const float* projMatrix, const float* cameraPos, std::vector<Render3DDraw>& outDraws) {
for (const auto& [id, instance] : m_instances) {
if (instance && instance->IsAlive()) {
instance->BuildDrawCommands(viewMatrix, projMatrix, cameraPos, outDraws);
}
}
}
} // namespace ava2
+46
View File
@@ -0,0 +1,46 @@
#pragma once
#include "EffectData.h"
#include "EffectInstance.h"
#include "eter_render/RenderCommands3D.h"
#include <unordered_map>
#include <string>
#include <memory>
#include <vector>
namespace ava2 {
class EffectManager {
public:
static EffectManager& Instance();
bool RegisterEffect(const std::string& filename, uint32_t* outId = nullptr);
uint32_t CreateEffect(const std::string& filename, float x = 0.0f, float y = 0.0f, float z = 0.0f, float yaw = 0.0f);
uint32_t CreateEffect(uint32_t effectId, float x = 0.0f, float y = 0.0f, float z = 0.0f, float yaw = 0.0f);
bool DestroyEffectInstance(uint32_t instanceId);
void DeleteAllInstances();
bool IsAliveEffect(uint32_t instanceId) const;
void SetEffectInstancePosition(uint32_t instanceId, float x, float y, float z);
void SetEffectInstanceRotation(uint32_t instanceId, float yaw, float pitch, float roll);
void SetEffectInstanceGlobalMatrix(uint32_t instanceId, const float* mat16);
void Update(float dt);
void BuildDrawCommands(const float* viewMatrix, const float* projMatrix, const float* cameraPos, std::vector<Render3DDraw>& outDraws);
size_t GetActiveInstanceCount() const { return m_instances.size(); }
private:
EffectManager() = default;
~EffectManager() = default;
uint32_t ComputeCRC(const std::string& str);
std::unordered_map<uint32_t, std::shared_ptr<EffectData>> m_dataCache;
std::unordered_map<std::string, uint32_t> m_fileToId;
std::unordered_map<uint32_t, std::shared_ptr<EffectInstance>> m_instances;
uint32_t m_nextInstanceId = 1;
};
} // namespace ava2
+127
View File
@@ -0,0 +1,127 @@
#include "FlyTrace.h"
#include <cmath>
#include <algorithm>
namespace ava2 {
FlyTrace::FlyTrace() = default;
FlyTrace::~FlyTrace() = default;
void FlyTrace::Create(uint32_t color, float tailLength, float tailSize, bool rectShape) {
m_color = color;
m_tailLength = tailLength > 0.01f ? tailLength : 0.25f;
m_tailSize = tailSize > 0.1f ? tailSize : 10.0f;
m_rectShape = rectShape;
m_history.clear();
}
void FlyTrace::Clear() {
m_history.clear();
}
void FlyTrace::UpdateNewPosition(float x, float y, float z, float currentTime) {
TraceNode node;
node.time = currentTime;
node.pos[0] = x;
node.pos[1] = y;
node.pos[2] = z;
m_history.push_front(node);
while (!m_history.empty() && (currentTime - m_history.back().time) > m_tailLength) {
m_history.pop_back();
}
}
void FlyTrace::BuildDrawCommands(const float* viewMatrix, const float* projMatrix, float currentTime, std::vector<Render3DDraw>& outDraws) {
if (m_history.size() < 2) return;
Render3DDraw draw;
draw.lighting = false;
draw.z_enable = true;
draw.z_write = false;
draw.cull_mode = 1; // D3DCULL_NONE
draw.alpha_blend = true;
draw.blend_mode = 1; // Additive (D3DBLEND_ONE)
for (int m = 0; m < 16; ++m) {
draw.view[m] = viewMatrix[m];
draw.proj[m] = projMatrix[m];
draw.world[m] = (m % 5 == 0) ? 1.0f : 0.0f;
}
float camDir[3] = {viewMatrix[2], viewMatrix[6], viewMatrix[10]};
float camLen = std::sqrt(camDir[0]*camDir[0] + camDir[1]*camDir[1] + camDir[2]*camDir[2]);
if (camLen > 1e-5f) { camDir[0] /= camLen; camDir[1] /= camLen; camDir[2] /= camLen; }
uint32_t vertexOffset = 0;
for (size_t i = 0; i + 1 < m_history.size(); ++i) {
const auto& n0 = m_history[i];
const auto& n1 = m_history[i + 1];
float age0 = currentTime - n0.time;
float age1 = currentTime - n1.time;
float rate0 = std::clamp(1.0f - age0 / m_tailLength, 0.0f, 1.0f);
float rate1 = std::clamp(1.0f - age1 / m_tailLength, 0.0f, 1.0f);
float s0 = m_rectShape ? m_tailSize : m_tailSize * rate0;
float s1 = m_rectShape ? m_tailSize : m_tailSize * rate1;
// Ribbon segment direction
float seg[3] = {n1.pos[0] - n0.pos[0], n1.pos[1] - n0.pos[1], n1.pos[2] - n0.pos[2]};
float segLen = std::sqrt(seg[0]*seg[0] + seg[1]*seg[1] + seg[2]*seg[2]);
if (segLen < 1e-4f) continue;
// Normal perpendicular to segment and camera look
float norm[3] = {
seg[1] * camDir[2] - seg[2] * camDir[1],
seg[2] * camDir[0] - seg[0] * camDir[2],
seg[0] * camDir[1] - seg[1] * camDir[0]
};
float normLen = std::sqrt(norm[0]*norm[0] + norm[1]*norm[1] + norm[2]*norm[2]);
if (normLen > 1e-5f) {
norm[0] /= normLen; norm[1] /= normLen; norm[2] /= normLen;
}
// Vertices for this quad segment
float v0[3] = {n0.pos[0] + norm[0] * s0, n0.pos[1] + norm[1] * s0, n0.pos[2] + norm[2] * s0};
float v1[3] = {n0.pos[0] - norm[0] * s0, n0.pos[1] - norm[1] * s0, n0.pos[2] - norm[2] * s0};
float v2[3] = {n1.pos[0] - norm[0] * s1, n1.pos[1] - norm[1] * s1, n1.pos[2] - norm[2] * s1};
float v3[3] = {n1.pos[0] + norm[0] * s1, n1.pos[1] + norm[1] * s1, n1.pos[2] + norm[2] * s1};
uint8_t baseA = (m_color >> 24) & 0xFF;
uint8_t baseR = (m_color >> 16) & 0xFF;
uint8_t baseG = (m_color >> 8) & 0xFF;
uint8_t baseB = m_color & 0xFF;
uint8_t a0 = static_cast<uint8_t>(baseA * rate0);
uint8_t a1 = static_cast<uint8_t>(baseA * rate1);
uint32_t diff0 = (static_cast<uint32_t>(a0) << 24) | (static_cast<uint32_t>(baseR) << 16) | (static_cast<uint32_t>(baseG) << 8) | baseB;
uint32_t diff1 = (static_cast<uint32_t>(a1) << 24) | (static_cast<uint32_t>(baseR) << 16) | (static_cast<uint32_t>(baseG) << 8) | baseB;
draw.positions.insert(draw.positions.end(), {v0[0], v0[1], v0[2]});
draw.positions.insert(draw.positions.end(), {v1[0], v1[1], v1[2]});
draw.positions.insert(draw.positions.end(), {v2[0], v2[1], v2[2]});
draw.positions.insert(draw.positions.end(), {v3[0], v3[1], v3[2]});
draw.diffuse.insert(draw.diffuse.end(), {diff0, diff0, diff1, diff1});
draw.uv0.insert(draw.uv0.end(), {0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f});
draw.indices.push_back(vertexOffset + 0);
draw.indices.push_back(vertexOffset + 1);
draw.indices.push_back(vertexOffset + 2);
draw.indices.push_back(vertexOffset + 0);
draw.indices.push_back(vertexOffset + 2);
draw.indices.push_back(vertexOffset + 3);
vertexOffset += 4;
}
if (!draw.indices.empty()) {
outDraws.push_back(std::move(draw));
}
}
} // namespace ava2
+37
View File
@@ -0,0 +1,37 @@
#pragma once
#include "eter_render/RenderCommands3D.h"
#include <deque>
#include <vector>
#include <cstdint>
namespace ava2 {
class FlyTrace {
public:
FlyTrace();
~FlyTrace();
void Create(uint32_t color, float tailLength, float tailSize, bool rectShape = false);
void UpdateNewPosition(float x, float y, float z, float currentTime);
void Clear();
void BuildDrawCommands(const float* viewMatrix, const float* projMatrix, float currentTime, std::vector<Render3DDraw>& outDraws);
bool IsEmpty() const { return m_history.size() < 2; }
private:
struct TraceNode {
float time = 0.0f;
float pos[3] = {0.0f, 0.0f, 0.0f};
};
uint32_t m_color = 0xFFFFFFFF;
float m_tailLength = 0.25f;
float m_tailSize = 10.0f;
bool m_rectShape = false;
std::deque<TraceNode> m_history;
};
} // namespace ava2
+345
View File
@@ -0,0 +1,345 @@
#include "FlyingManager.h"
#include <fstream>
#include <sstream>
#include <cmath>
#include <algorithm>
#include <filesystem>
namespace ava2 {
static std::string NormalizePath(std::string path) {
for (char& c : path) {
if (c == '\\') c = '/';
}
if (path.size() >= 3 && (path[0] == 'd' || path[0] == 'D') && path[1] == ':' && path[2] == '/') {
path = path.substr(3);
}
if (!path.empty() && path[0] == '/') {
path = path.substr(1);
}
return path;
}
static std::vector<std::string> TokenizeScript(const std::string& content) {
std::vector<std::string> tokens;
size_t i = 0;
size_t n = content.size();
while (i < n) {
while (i < n && (content[i] == ' ' || content[i] == '\t' || content[i] == '\r' || content[i] == '\n')) i++;
if (i >= n) break;
if (i + 1 < n && content[i] == '/' && content[i + 1] == '/') {
while (i < n && content[i] != '\n') i++;
continue;
}
if (content[i] == '{' || content[i] == '}') {
tokens.push_back(std::string(1, content[i]));
i++;
continue;
}
if (content[i] == '"') {
i++;
size_t start = i;
while (i < n && content[i] != '"') i++;
tokens.push_back(content.substr(start, i - start));
if (i < n && content[i] == '"') i++;
continue;
}
size_t start = i;
while (i < n && content[i] != ' ' && content[i] != '\t' && content[i] != '\r' && content[i] != '\n' &&
content[i] != '{' && content[i] != '}' && content[i] != '"') {
i++;
}
tokens.push_back(content.substr(start, i - start));
}
return tokens;
}
static std::string ToLower(std::string str) {
std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c) { return std::tolower(c); });
return str;
}
FlyingData::FlyingData() = default;
FlyingData::~FlyingData() = default;
bool FlyingData::LoadScriptFile(const std::string& filepath) {
std::ifstream file(filepath, std::ios::binary);
if (!file.is_open()) {
file.open(NormalizePath(filepath), std::ios::binary);
if (!file.is_open()) return false;
}
std::stringstream buffer;
buffer << file.rdbuf();
std::string content = buffer.str();
std::string dir = "";
size_t lastSlash = filepath.find_last_of("/\\");
if (lastSlash != std::string::npos) {
dir = filepath.substr(0, lastSlash + 1);
}
auto tokens = TokenizeScript(content);
size_t idx = 0;
size_t numTokens = tokens.size();
while (idx < numTokens) {
std::string key = ToLower(tokens[idx++]);
if (key == "initialvelocity" && idx < numTokens) {
initial_velocity = std::stof(tokens[idx++]);
} else if (key == "gravity" && idx < numTokens) {
gravity = std::stof(tokens[idx++]);
} else if (key == "acceleration" && idx + 2 < numTokens) {
acceleration[0] = std::stof(tokens[idx++]);
acceleration[1] = std::stof(tokens[idx++]);
acceleration[2] = std::stof(tokens[idx++]);
} else if (key == "bombrange" && idx < numTokens) {
bomb_range = std::stof(tokens[idx++]);
} else if (key == "bombeffect" && idx < numTokens) {
std::string eff = NormalizePath(tokens[idx++]);
if (!dir.empty() && !std::filesystem::exists(eff)) {
std::string candidate = NormalizePath(dir + eff);
if (std::filesystem::exists(candidate)) eff = candidate;
}
bomb_effect = eff;
} else if (key == "homingflag" && idx < numTokens) {
homing_flag = (std::stoi(tokens[idx++]) != 0);
} else if (key == "homingmaxangle" && idx < numTokens) {
homing_max_angle = std::stof(tokens[idx++]);
} else if (key == "range" && idx < numTokens) {
range = std::stof(tokens[idx++]);
} else if (key == "group" && idx < numTokens && ToLower(tokens[idx]) == "attachdata") {
idx++; // skip attachdata
if (idx < numTokens && tokens[idx] == "{") idx++;
int aDepth = 1;
while (idx < numTokens && aDepth > 0) {
if (tokens[idx] == "{") { aDepth++; idx++; continue; }
if (tokens[idx] == "}") { aDepth--; idx++; continue; }
std::string aKey = ToLower(tokens[idx++]);
if (aKey == "type" && idx < numTokens) {
attach.type = std::stoi(tokens[idx++]);
} else if (aKey == "flytype" && idx < numTokens) {
attach.fly_type = std::stoi(tokens[idx++]);
} else if (aKey == "attachfile" && idx < numTokens) {
std::string att = NormalizePath(tokens[idx++]);
if (!dir.empty() && !std::filesystem::exists(att)) {
std::string candidate = NormalizePath(dir + att);
if (std::filesystem::exists(candidate)) att = candidate;
}
attach.attach_file = att;
} else if (aKey == "tailflag" && idx < numTokens) {
attach.has_tail = (std::stoi(tokens[idx++]) != 0);
} else if (aKey == "tailcolor" && idx < numTokens) {
std::string cStr = tokens[idx++];
if (!cStr.empty() && (cStr.back() == 'd' || cStr.back() == 'D')) {
cStr.pop_back();
}
attach.tail_color = static_cast<uint32_t>(std::stoul(cStr));
} else if (aKey == "taillength" && idx < numTokens) {
attach.tail_length = std::stof(tokens[idx++]);
} else if (aKey == "tailsize" && idx < numTokens) {
attach.tail_size = std::stof(tokens[idx++]);
} else if (aKey == "tailshaperect" && idx < numTokens) {
attach.rect_shape = (std::stoi(tokens[idx++]) != 0);
}
}
}
}
return true;
}
FlyingInstance::FlyingInstance(std::shared_ptr<FlyingData> data, const float* startPos, const float* targetPos)
: m_data(std::move(data)) {
if (startPos) {
m_position[0] = startPos[0];
m_position[1] = startPos[1];
m_position[2] = startPos[2];
}
if (targetPos) {
m_targetPosition[0] = targetPos[0];
m_targetPosition[1] = targetPos[1];
m_targetPosition[2] = targetPos[2];
}
float dir[3] = {
m_targetPosition[0] - m_position[0],
m_targetPosition[1] - m_position[1],
m_targetPosition[2] - m_position[2]
};
float len = std::sqrt(dir[0]*dir[0] + dir[1]*dir[1] + dir[2]*dir[2]);
float speed = m_data ? m_data->initial_velocity : 1000.0f;
if (speed < 100.0f) speed = 1000.0f;
if (len > 1e-4f) {
m_velocity[0] = (dir[0] / len) * speed;
m_velocity[1] = (dir[1] / len) * speed;
m_velocity[2] = (dir[2] / len) * speed;
} else {
m_velocity[0] = speed;
m_velocity[1] = 0.0f;
m_velocity[2] = 0.0f;
}
if (m_data) {
if (!m_data->attach.attach_file.empty()) {
m_attachedEffectId = EffectManager::Instance().CreateEffect(m_data->attach.attach_file, m_position[0], m_position[1], m_position[2]);
}
if (m_data->attach.has_tail) {
m_tail.Create(m_data->attach.tail_color, m_data->attach.tail_length, m_data->attach.tail_size, m_data->attach.rect_shape);
}
}
}
FlyingInstance::~FlyingInstance() {
if (m_attachedEffectId != 0) {
EffectManager::Instance().DestroyEffectInstance(m_attachedEffectId);
m_attachedEffectId = 0;
}
}
bool FlyingInstance::Update(float dt, float currentTime) {
if (!m_isAlive) return false;
m_age += dt;
// Move
m_position[0] += m_velocity[0] * dt;
m_position[1] += m_velocity[1] * dt;
m_position[2] += m_velocity[2] * dt;
if (m_data) {
m_velocity[0] += m_data->acceleration[0] * dt;
m_velocity[1] += m_data->acceleration[1] * dt;
m_velocity[2] += (m_data->acceleration[2] - m_data->gravity * 9.8f) * dt;
if (m_data->homing_flag) {
float toTarget[3] = {
m_targetPosition[0] - m_position[0],
m_targetPosition[1] - m_position[1],
m_targetPosition[2] - m_position[2]
};
float tLen = std::sqrt(toTarget[0]*toTarget[0] + toTarget[1]*toTarget[1] + toTarget[2]*toTarget[2]);
if (tLen > 1e-4f) {
float curSpeed = std::sqrt(m_velocity[0]*m_velocity[0] + m_velocity[1]*m_velocity[1] + m_velocity[2]*m_velocity[2]);
float steer = std::min(1.0f, m_data->homing_max_angle * dt * 0.5f);
m_velocity[0] = m_velocity[0] * (1.0f - steer) + (toTarget[0] / tLen) * curSpeed * steer;
m_velocity[1] = m_velocity[1] * (1.0f - steer) + (toTarget[1] / tLen) * curSpeed * steer;
m_velocity[2] = m_velocity[2] * (1.0f - steer) + (toTarget[2] / tLen) * curSpeed * steer;
}
}
}
if (m_attachedEffectId != 0) {
EffectManager::Instance().SetEffectInstancePosition(m_attachedEffectId, m_position[0], m_position[1], m_position[2]);
}
m_tail.UpdateNewPosition(m_position[0], m_position[1], m_position[2], currentTime);
// Distance check to target
float d[3] = {m_targetPosition[0] - m_position[0], m_targetPosition[1] - m_position[1], m_targetPosition[2] - m_position[2]};
float dist = std::sqrt(d[0]*d[0] + d[1]*d[1] + d[2]*d[2]);
float hitThreshold = m_data ? std::max(m_data->bomb_range, 25.0f) : 25.0f;
if (dist <= hitThreshold || m_age > 5.0f) {
// Hit target
m_isAlive = false;
if (m_data && !m_data->bomb_effect.empty()) {
EffectManager::Instance().CreateEffect(m_data->bomb_effect, m_position[0], m_position[1], m_position[2]);
}
if (m_attachedEffectId != 0) {
EffectManager::Instance().DestroyEffectInstance(m_attachedEffectId);
m_attachedEffectId = 0;
}
if (m_hitCallback) {
m_hitCallback(m_position);
}
return false;
}
return true;
}
void FlyingInstance::BuildDrawCommands(const float* viewMatrix, const float* projMatrix, float currentTime, std::vector<Render3DDraw>& outDraws) {
if (!m_tail.IsEmpty()) {
m_tail.BuildDrawCommands(viewMatrix, projMatrix, currentTime, outDraws);
}
}
FlyingManager& FlyingManager::Instance() {
static FlyingManager s_instance;
return s_instance;
}
uint32_t FlyingManager::ComputeCRC(const std::string& str) {
uint32_t crc = 0xFFFFFFFF;
for (char c : str) {
char lower = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
if (lower == '\\') lower = '/';
crc ^= static_cast<uint8_t>(lower);
for (int i = 0; i < 8; ++i) {
crc = (crc >> 1) ^ (0xEDB88320 & (-(crc & 1)));
}
}
return ~crc;
}
bool FlyingManager::RegisterFlyingData(const std::string& filename, uint32_t* outId) {
uint32_t id = ComputeCRC(filename);
if (outId) *outId = id;
if (m_dataCache.find(id) != m_dataCache.end()) return true;
auto data = std::make_shared<FlyingData>();
if (!data->LoadScriptFile(filename)) return false;
m_dataCache[id] = data;
m_fileToId[filename] = id;
return true;
}
uint32_t FlyingManager::CreateFlyingInstance(const std::string& filename, const float* startPos, const float* targetPos, std::function<void(const float*)> hitCb) {
uint32_t id = 0;
if (!RegisterFlyingData(filename, &id)) return 0;
return CreateFlyingInstance(id, startPos, targetPos, std::move(hitCb));
}
uint32_t FlyingManager::CreateFlyingInstance(uint32_t flyId, const float* startPos, const float* targetPos, std::function<void(const float*)> hitCb) {
auto it = m_dataCache.find(flyId);
if (it == m_dataCache.end()) return 0;
auto inst = std::make_shared<FlyingInstance>(it->second, startPos, targetPos);
if (hitCb) inst->SetHitCallback(std::move(hitCb));
m_instances.push_back(inst);
return static_cast<uint32_t>(m_instances.size());
}
void FlyingManager::Update(float dt, float currentTime) {
for (auto it = m_instances.begin(); it != m_instances.end();) {
if (!(*it)->Update(dt, currentTime)) {
it = m_instances.erase(it);
} else {
++it;
}
}
}
void FlyingManager::BuildDrawCommands(const float* viewMatrix, const float* projMatrix, float currentTime, std::vector<Render3DDraw>& outDraws) {
for (const auto& inst : m_instances) {
if (inst && inst->IsAlive()) {
inst->BuildDrawCommands(viewMatrix, projMatrix, currentTime, outDraws);
}
}
}
void FlyingManager::DeleteAllInstances() {
m_instances.clear();
}
} // namespace ava2
+124
View File
@@ -0,0 +1,124 @@
#pragma once
#include "FlyTrace.h"
#include "EffectManager.h"
#include "eter_render/RenderCommands3D.h"
#include <string>
#include <vector>
#include <memory>
#include <unordered_map>
#include <functional>
namespace ava2 {
struct FlyingAttachData {
int type = 1;
int fly_type = 1;
std::string attach_file;
bool has_tail = false;
uint32_t tail_color = 0xFFFFFFFF;
float tail_length = 0.2f;
float tail_size = 8.0f;
bool rect_shape = false;
};
class FlyingData {
public:
FlyingData();
~FlyingData();
bool LoadScriptFile(const std::string& filepath);
float initial_velocity = 2000.0f;
float gravity = 0.0f;
float acceleration[3] = {0.0f, 0.0f, 0.0f};
float bomb_range = 10.0f;
std::string bomb_effect;
bool homing_flag = false;
float homing_max_angle = 3.0f;
float range = 10000.0f;
FlyingAttachData attach;
};
class FlyingInstance {
public:
FlyingInstance(std::shared_ptr<FlyingData> data, const float* startPos, const float* targetPos);
~FlyingInstance();
bool Update(float dt, float currentTime);
void BuildDrawCommands(const float* viewMatrix, const float* projMatrix, float currentTime, std::vector<Render3DDraw>& outDraws);
bool IsAlive() const { return m_isAlive; }
const float* GetPosition() const { return m_position; }
void SetHitCallback(std::function<void(const float*)> cb) { m_hitCallback = std::move(cb); }
private:
std::shared_ptr<FlyingData> m_data;
bool m_isAlive = true;
float m_age = 0.0f;
float m_position[3] = {0.0f, 0.0f, 0.0f};
float m_velocity[3] = {0.0f, 0.0f, 0.0f};
float m_targetPosition[3] = {0.0f, 0.0f, 0.0f};
uint32_t m_attachedEffectId = 0;
FlyTrace m_tail;
std::function<void(const float*)> m_hitCallback;
};
class FlyingManager {
public:
static FlyingManager& Instance();
enum EIndexFlyType {
INDEX_FLY_TYPE_NORMAL = 0,
INDEX_FLY_TYPE_FIRE_CRACKER = 1,
INDEX_FLY_TYPE_AUTO_FIRE = 2,
};
enum {
FLY_NONE = 0,
FLY_EXP = 1,
FLY_HP_MEDIUM = 2,
FLY_HP_BIG = 3,
FLY_SP_SMALL = 4,
FLY_SP_MEDIUM = 5,
FLY_SP_BIG = 6,
FLY_FIREWORK1 = 7,
FLY_FIREWORK2 = 8,
FLY_FIREWORK3 = 9,
FLY_FIREWORK4 = 10,
FLY_FIREWORK5 = 11,
FLY_FIREWORK6 = 12,
FLY_FIREWORK_XMAS = 13,
FLY_CHAIN_LIGHTNING = 14,
FLY_HP_SMALL = 15,
FLY_SKILL_MUYEONG = 16,
FLY_QUIVER_ATTACK_NORMAL = 17,
FLY_CONQUEROR_EXP = 18
};
bool RegisterFlyingData(const std::string& filename, uint32_t* outId = nullptr);
uint32_t CreateFlyingInstance(uint32_t flyId, const float* startPos, const float* targetPos, std::function<void(const float*)> hitCb = nullptr);
uint32_t CreateFlyingInstance(const std::string& filename, const float* startPos, const float* targetPos, std::function<void(const float*)> hitCb = nullptr);
void Update(float dt, float currentTime);
void BuildDrawCommands(const float* viewMatrix, const float* projMatrix, float currentTime, std::vector<Render3DDraw>& outDraws);
void DeleteAllInstances();
size_t GetActiveInstanceCount() const { return m_instances.size(); }
private:
FlyingManager() = default;
~FlyingManager() = default;
uint32_t ComputeCRC(const std::string& str);
std::unordered_map<uint32_t, std::shared_ptr<FlyingData>> m_dataCache;
std::unordered_map<std::string, uint32_t> m_fileToId;
std::vector<std::shared_ptr<FlyingInstance>> m_instances;
};
} // namespace ava2
+46
View File
@@ -0,0 +1,46 @@
#include "GrpDevice.h"
CGraphicDevice::CGraphicDevice()
: m_pRenderer(nullptr), m_clearColor{0.0f, 0.0f, 0.0f, 1.0f}
{
}
CGraphicDevice::~CGraphicDevice()
{
}
void CGraphicDevice::Init(SDL_Renderer* pRenderer)
{
m_pRenderer = pRenderer;
}
void CGraphicDevice::SetClearColor(float r, float g, float b, float a)
{
m_clearColor = { r, g, b, a };
}
void CGraphicDevice::Clear()
{
if (m_pRenderer)
{
SDL_SetRenderDrawColorFloat(m_pRenderer, m_clearColor.r, m_clearColor.g, m_clearColor.b, m_clearColor.a);
SDL_RenderClear(m_pRenderer);
}
}
void CGraphicDevice::BeginScene(bool bClear)
{
if (bClear && m_pRenderer)
{
SDL_SetRenderDrawColorFloat(m_pRenderer, m_clearColor.r, m_clearColor.g, m_clearColor.b, m_clearColor.a);
SDL_RenderClear(m_pRenderer);
}
}
void CGraphicDevice::EndScene(bool bPresent)
{
if (bPresent && m_pRenderer)
{
SDL_RenderPresent(m_pRenderer);
}
}
+23
View File
@@ -0,0 +1,23 @@
#pragma once
#include <SDL3/SDL.h>
#include "shared/common/Singleton.h"
class CGraphicDevice : public CSingleton<CGraphicDevice>
{
public:
CGraphicDevice();
virtual ~CGraphicDevice();
void Init(SDL_Renderer* pRenderer);
SDL_Renderer* GetRenderer() const { return m_pRenderer; }
void SetClearColor(float r, float g, float b, float a = 1.0f);
void Clear();
void BeginScene(bool bClear = true);
void EndScene(bool bPresent = true);
private:
SDL_Renderer* m_pRenderer;
SDL_FColor m_clearColor;
};
+132
View File
@@ -0,0 +1,132 @@
#pragma once
#include "GrpImageInstance.h"
class CGraphicExpandedImageInstance : public CGraphicImageInstance
{
public:
static DWORD Type()
{
static DWORD s_dwType = GetCRC32("CGraphicExpandedImageInstance", strlen("CGraphicExpandedImageInstance"));
return s_dwType;
}
static void DeleteExpandedImageInstance(CGraphicExpandedImageInstance* pkInstance)
{
Delete(pkInstance);
}
enum ERenderingMode
{
RENDERING_MODE_NORMAL,
RENDERING_MODE_SCREEN,
RENDERING_MODE_COLOR_DODGE,
RENDERING_MODE_MODULATE,
};
CGraphicExpandedImageInstance()
{
Initialize();
}
virtual ~CGraphicExpandedImageInstance()
{
Destroy();
}
void Destroy()
{
CGraphicImageInstance::Destroy();
}
void SetDepth(float fDepth) { m_fDepth = fDepth; }
void SetOrigin() { m_v2Origin.x = 0.0f; m_v2Origin.y = 0.0f; }
void SetOrigin(float fx, float fy) { m_v2Origin.x = fx; m_v2Origin.y = fy; }
void SetRotation(float fRotation) { m_fRotation = fRotation; }
float GetRotation() const { return m_fRotation; }
void SetRenderingRect(float fLeft, float fTop, float fRight, float fBottom)
{
m_RenderingRectFraction.left = fLeft;
m_RenderingRectFraction.top = fTop;
m_RenderingRectFraction.right = fRight;
m_RenderingRectFraction.bottom = fBottom;
UpdateRenderingRect();
}
void UpdateRenderingRect()
{
if (IsEmpty())
return;
float fWidth = float(GetWidth());
float fHeight = float(GetHeight());
m_RenderingRect.left = fWidth * m_RenderingRectFraction.left;
m_RenderingRect.top = fHeight * m_RenderingRectFraction.top;
m_RenderingRect.right = fWidth * m_RenderingRectFraction.right;
m_RenderingRect.bottom = fHeight * m_RenderingRectFraction.bottom;
}
void OnSetImagePointer() override
{
CGraphicImageInstance::OnSetImagePointer();
SetOrigin(float(GetWidth()) / 2.0f, float(GetHeight()) / 2.0f);
UpdateRenderingRect();
}
void SetRenderingMode(int iMode) { m_iRenderingMode = iMode; }
protected:
void Initialize()
{
CGraphicImageInstance::Initialize();
m_fDepth = 0.0f;
m_v2Origin = D3DXVECTOR2(0.0f, 0.0f);
m_fRotation = 0.0f;
m_iRenderingMode = RENDERING_MODE_NORMAL;
m_RenderingRectFraction.left = 0.0f;
m_RenderingRectFraction.top = 0.0f;
m_RenderingRectFraction.right = 0.0f;
m_RenderingRectFraction.bottom = 0.0f;
m_RenderingRect.left = 0.0f;
m_RenderingRect.top = 0.0f;
m_RenderingRect.right = 0.0f;
m_RenderingRect.bottom = 0.0f;
}
BOOL OnIsType(DWORD dwType) override
{
if (CGraphicExpandedImageInstance::Type() == dwType)
return TRUE;
return CGraphicImageInstance::OnIsType(dwType);
}
void OnRender() override;
protected:
struct RECT_FLOAT
{
float left, top, right, bottom;
};
float m_fDepth;
D3DXVECTOR2 m_v2Origin;
float m_fRotation;
int m_iRenderingMode;
RECT_FLOAT m_RenderingRect;
RECT_FLOAT m_RenderingRectFraction;
public:
static void CreateSystem(UINT uCapacity) { ms_kExpandedPool.Create(uCapacity); }
static void DestroySystem() { ms_kExpandedPool.Destroy(); }
static CGraphicExpandedImageInstance* New()
{
return ms_kExpandedPool.Alloc();
}
static void Delete(CGraphicExpandedImageInstance* pkImgInst)
{
if (pkImgInst)
{
pkImgInst->Destroy();
ms_kExpandedPool.Free(pkImgInst);
}
}
static CDynamicPool<CGraphicExpandedImageInstance> ms_kExpandedPool;
};
+105
View File
@@ -0,0 +1,105 @@
#pragma once
#include "src/eter_resource/Resource.h"
#include "GrpImageTexture.h"
#include "src/eter_resource/texture_decode.h"
#include <cstring>
#include <fstream>
class CGraphicImage : public CResource
{
public:
typedef CRef<CGraphicImage> TRef;
static TType Type()
{
static TType s_type = StringToType("CGraphicImage");
return s_type;
}
CGraphicImage(const char* c_szFileName, DWORD dwFilter = 0)
: CResource(c_szFileName), m_dwFilter(dwFilter)
{
std::memset(&m_rect, 0, sizeof(m_rect));
}
virtual ~CGraphicImage()
{
OnClear();
}
virtual bool CreateDeviceObjects() { return true; }
virtual void DestroyDeviceObjects() {}
int GetWidth() const { return m_rect.right - m_rect.left; }
int GetHeight() const { return m_rect.bottom - m_rect.top; }
const RECT& GetRectReference() const { return m_rect; }
const CGraphicTexture& GetTextureReference() const { return m_imageTexture; }
CGraphicTexture* GetTexturePointer() { return &m_imageTexture; }
bool LoadFile(const char* c_szFileName)
{
if (!c_szFileName || !*c_szFileName)
return false;
SetFileName(c_szFileName);
std::ifstream file(c_szFileName, std::ios::binary | std::ios::ate);
if (!file.is_open())
return false;
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<uint8_t> buffer(size);
if (!file.read(reinterpret_cast<char*>(buffer.data()), size))
return false;
return OnLoad(static_cast<int>(buffer.size()), buffer.data());
}
protected:
bool OnLoad(int iSize, const void* c_pvBuf) override
{
if (!c_pvBuf || iSize <= 0)
return false;
m_imageTexture.SetFileName(GetFileName());
auto img = mt_host::decode_texture_bytes(reinterpret_cast<const uint8_t*>(c_pvBuf), static_cast<size_t>(iSize));
if (!img.ok())
return false;
m_imageTexture.SetPixels(img.w, img.h, std::move(img.rgba));
m_rect.left = 0;
m_rect.top = 0;
m_rect.right = img.w;
m_rect.bottom = img.h;
return true;
}
void OnClear() override
{
m_imageTexture.Destroy();
std::memset(&m_rect, 0, sizeof(m_rect));
}
bool OnIsEmpty() const override
{
return m_imageTexture.GetWidth() == 0 || m_imageTexture.GetHeight() == 0;
}
bool OnIsType(TType type) override
{
if (CGraphicImage::Type() == type)
return true;
return CResource::OnIsType(type);
}
protected:
CGraphicImageTexture m_imageTexture;
RECT m_rect;
DWORD m_dwFilter;
};
+167
View File
@@ -0,0 +1,167 @@
#include "GrpImageInstance.h"
#include "GrpExpandedImageInstance.h"
#include "GrpMarkInstance.h"
#include "GrpDevice.h"
#include <SDL3/SDL.h>
#include <mutex>
#include <unordered_map>
#include <cstdint>
static std::mutex s_imageHandleMutex;
static uint32_t s_nextImageHandle = 1;
static std::unordered_map<CGraphicImage*, uint32_t> s_imageToHandle;
static std::unordered_map<uint32_t, CGraphicImage*> s_handleToImage;
uint32_t GrpRegisterImageHandle(CGraphicImage* pImage)
{
if (!pImage)
return 0;
std::lock_guard<std::mutex> lock(s_imageHandleMutex);
auto it = s_imageToHandle.find(pImage);
if (it != s_imageToHandle.end())
return it->second;
uint32_t handle = s_nextImageHandle++;
s_imageToHandle[pImage] = handle;
s_handleToImage[handle] = pImage;
return handle;
}
CGraphicImage* GrpGetImagePointer(uint32_t handle)
{
if (handle == 0)
return nullptr;
std::lock_guard<std::mutex> lock(s_imageHandleMutex);
auto it = s_handleToImage.find(handle);
if (it != s_handleToImage.end())
return it->second;
return nullptr;
}
CDynamicPool<CGraphicImageInstance> CGraphicImageInstance::ms_kPool;
CDynamicPool<CGraphicExpandedImageInstance> CGraphicExpandedImageInstance::ms_kExpandedPool;
CDynamicPool<CGraphicMarkInstance> CGraphicMarkInstance::ms_kPool;
void CGraphicTexture::Destroy()
{
if (m_pSDLTexture)
{
SDL_DestroyTexture(m_pSDLTexture);
m_pSDLTexture = nullptr;
}
m_width = 0;
m_height = 0;
m_pixels.clear();
}
void CGraphicTexture::SetPixels(int w, int h, std::vector<uint8_t> pixels)
{
if (m_pSDLTexture)
{
SDL_DestroyTexture(m_pSDLTexture);
m_pSDLTexture = nullptr;
}
m_width = w;
m_height = h;
m_pixels = std::move(pixels);
}
SDL_Texture* CGraphicTexture::GetSDLTexture(SDL_Renderer* renderer)
{
if (!m_pSDLTexture && renderer && !m_pixels.empty() && m_width > 0 && m_height > 0)
{
m_pSDLTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STATIC, m_width, m_height);
if (m_pSDLTexture)
{
SDL_UpdateTexture(m_pSDLTexture, nullptr, m_pixels.data(), m_width * 4);
}
}
return m_pSDLTexture;
}
void CGraphicImageInstance::OnRender()
{
CGraphicDevice* pDevice = CGraphicDevice::InstancePtr();
if (!pDevice) return;
SDL_Renderer* renderer = pDevice->GetRenderer();
if (!renderer) return;
CGraphicImage* pImage = m_roImage.GetPointer();
if (!pImage) return;
CGraphicTexture* pTexture = pImage->GetTexturePointer();
if (!pTexture) return;
SDL_Texture* tex = pTexture->GetSDLTexture(renderer);
if (!tex) return;
const RECT& r = pImage->GetRectReference();
float rw = static_cast<float>(r.right - r.left);
float rh = static_cast<float>(r.bottom - r.top);
if (rw <= 0.0f || rh <= 0.0f) return;
SDL_FRect srcRect{ static_cast<float>(r.left), static_cast<float>(r.top), rw, rh };
SDL_FRect dstRect{ m_v2Position.x, m_v2Position.y, rw * m_v2Scale.x, rh * m_v2Scale.y };
SDL_SetTextureColorModFloat(tex, m_DiffuseColor.r, m_DiffuseColor.g, m_DiffuseColor.b);
SDL_SetTextureAlphaModFloat(tex, m_DiffuseColor.a);
SDL_SetTextureBlendMode(tex, SDL_BLENDMODE_BLEND);
SDL_FlipMode flip = m_bLeftRightReverse ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
SDL_RenderTextureRotated(renderer, tex, &srcRect, &dstRect, 0.0, nullptr, flip);
}
void CGraphicExpandedImageInstance::OnRender()
{
CGraphicDevice* pDevice = CGraphicDevice::InstancePtr();
if (!pDevice) return;
SDL_Renderer* renderer = pDevice->GetRenderer();
if (!renderer) return;
CGraphicImage* pImage = m_roImage.GetPointer();
if (!pImage) return;
CGraphicTexture* pTexture = pImage->GetTexturePointer();
if (!pTexture) return;
SDL_Texture* tex = pTexture->GetSDLTexture(renderer);
if (!tex) return;
UpdateRenderingRect();
const RECT& r = pImage->GetRectReference();
float imgWidth = static_cast<float>(r.right - r.left);
float imgHeight = static_cast<float>(r.bottom - r.top);
if (imgWidth <= 0.0f || imgHeight <= 0.0f) return;
float left_x = m_v2Position.x - m_RenderingRect.left;
float top_y = m_v2Position.y - m_RenderingRect.top;
float dst_w = (imgWidth * m_v2Scale.x) + m_RenderingRect.left + m_RenderingRect.right;
float dst_h = (imgHeight * m_v2Scale.y) + m_RenderingRect.top + m_RenderingRect.bottom;
if (dst_w <= 0.0f || dst_h <= 0.0f) return;
SDL_FRect dstRect{ left_x, top_y, dst_w, dst_h };
SDL_SetTextureColorModFloat(tex, m_DiffuseColor.r, m_DiffuseColor.g, m_DiffuseColor.b);
SDL_SetTextureAlphaModFloat(tex, m_DiffuseColor.a);
switch (m_iRenderingMode) {
case RENDERING_MODE_SCREEN:
case RENDERING_MODE_COLOR_DODGE:
SDL_SetTextureBlendMode(tex, SDL_BLENDMODE_ADD);
break;
case RENDERING_MODE_MODULATE:
SDL_SetTextureBlendMode(tex, SDL_BLENDMODE_MOD);
break;
default:
SDL_SetTextureBlendMode(tex, SDL_BLENDMODE_BLEND);
break;
}
if ((dst_w > imgWidth * m_v2Scale.x || dst_h > imgHeight * m_v2Scale.y) && m_fRotation == 0.0f) {
SDL_FRect baseSrcRect{ static_cast<float>(r.left), static_cast<float>(r.top), imgWidth, imgHeight };
SDL_RenderTextureTiled(renderer, tex, &baseSrcRect, m_v2Scale.x, &dstRect);
} else {
float src_w = std::min(imgWidth, dst_w / m_v2Scale.x);
float src_h = std::min(imgHeight, dst_h / m_v2Scale.y);
SDL_FRect srcRect{ static_cast<float>(r.left), static_cast<float>(r.top), src_w, src_h };
SDL_FPoint center{ m_v2Origin.x, m_v2Origin.y };
SDL_FlipMode flip = m_bLeftRightReverse ? SDL_FLIP_HORIZONTAL : SDL_FLIP_NONE;
SDL_RenderTextureRotated(renderer, tex, &srcRect, &dstRect, m_fRotation, &center, flip);
}
}
+164
View File
@@ -0,0 +1,164 @@
#pragma once
#include "GrpImage.h"
#include "shared/common/DynamicPool.h"
class CGraphicImageInstance
{
public:
static DWORD Type()
{
static DWORD s_dwType = GetCRC32("CGraphicImageInstance", strlen("CGraphicImageInstance"));
return s_dwType;
}
BOOL IsType(DWORD dwType)
{
return OnIsType(dwType);
}
CGraphicImageInstance()
{
Initialize();
}
virtual ~CGraphicImageInstance()
{
Destroy();
}
void Destroy()
{
m_roImage.Clear();
}
void Render()
{
if (IsEmpty())
return;
OnRender();
}
void SetDiffuseColor(float fr, float fg, float fb, float fa)
{
m_DiffuseColor.r = fr;
m_DiffuseColor.g = fg;
m_DiffuseColor.b = fb;
m_DiffuseColor.a = fa;
}
void SetScale(float fx, float fy)
{
m_v2Scale.x = fx;
m_v2Scale.y = fy;
}
void SetPosition(float fx, float fy)
{
m_v2Position.x = fx;
m_v2Position.y = fy;
}
void SetImagePointer(CGraphicImage* pImage)
{
m_roImage = pImage;
OnSetImagePointer();
}
void ReloadImagePointer(CGraphicImage* pImage)
{
SetImagePointer(pImage);
}
bool IsEmpty() const
{
if (m_roImage.IsNull())
return true;
return m_roImage->IsEmpty();
}
int GetWidth()
{
if (IsEmpty())
return 0;
return m_roImage->GetWidth();
}
int GetHeight()
{
if (IsEmpty())
return 0;
return m_roImage->GetHeight();
}
void LeftRightReverse()
{
m_bLeftRightReverse = true;
}
CGraphicTexture* GetTexturePointer()
{
CGraphicImage* pkImage = m_roImage.GetPointer();
return pkImage ? pkImage->GetTexturePointer() : nullptr;
}
const CGraphicTexture& GetTextureReference() const
{
return m_roImage->GetTextureReference();
}
CGraphicImage* GetGraphicImagePointer()
{
return m_roImage.GetPointer();
}
bool operator == (const CGraphicImageInstance& rhs) const
{
return m_roImage.GetPointer() == rhs.m_roImage.GetPointer();
}
protected:
void Initialize()
{
m_bLeftRightReverse = false;
m_DiffuseColor = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
m_v2Position = D3DXVECTOR2(0.0f, 0.0f);
m_v2Scale = D3DXVECTOR2(1.0f, 1.0f);
m_vScale = 1.0f;
}
virtual void OnRender();
virtual void OnSetImagePointer() {}
virtual BOOL OnIsType(DWORD dwType)
{
return CGraphicImageInstance::Type() == dwType;
}
protected:
bool m_bLeftRightReverse;
D3DXCOLOR m_DiffuseColor;
D3DXVECTOR2 m_v2Position;
D3DXVECTOR2 m_v2Scale;
float m_vScale;
CGraphicImage::TRef m_roImage;
public:
static void CreateSystem(UINT uCapacity) { ms_kPool.Create(uCapacity); }
static void DestroySystem() { ms_kPool.Destroy(); }
static CGraphicImageInstance* New() { return ms_kPool.Alloc(); }
static void Delete(CGraphicImageInstance* pkImgInst)
{
if (pkImgInst)
{
pkImgInst->Destroy();
ms_kPool.Free(pkImgInst);
}
}
static CDynamicPool<CGraphicImageInstance> ms_kPool;
};
uint32_t GrpRegisterImageHandle(CGraphicImage* pImage);
CGraphicImage* GrpGetImagePointer(uint32_t handle);
+66
View File
@@ -0,0 +1,66 @@
#pragma once
#include "shared/common/Win32Types.h"
#include "shared/common/ReferenceObject.h"
#include "shared/common/Ref.h"
#include <string>
#include <vector>
struct SDL_Texture;
struct SDL_Renderer;
class CGraphicTexture : public CReferenceObject
{
public:
CGraphicTexture() : m_width(0), m_height(0), m_pSDLTexture(nullptr) {}
virtual ~CGraphicTexture() { Destroy(); }
virtual void Destroy();
int GetWidth() const { return m_width; }
int GetHeight() const { return m_height; }
const std::vector<uint8_t>& GetPixels() const { return m_pixels; }
void SetDimensions(int w, int h)
{
m_width = w;
m_height = h;
}
void SetPixels(int w, int h, std::vector<uint8_t> pixels);
SDL_Texture* GetSDLTexture(SDL_Renderer* renderer);
protected:
int m_width;
int m_height;
std::vector<uint8_t> m_pixels;
SDL_Texture* m_pSDLTexture;
};
class CGraphicImageTexture : public CGraphicTexture
{
public:
CGraphicImageTexture() {}
virtual ~CGraphicImageTexture() {}
void SetFileName(const char* c_szFileName)
{
if (c_szFileName) m_stFileName = c_szFileName;
}
const std::string& GetFileName() const { return m_stFileName; }
void CreateFromTexturePointer(const CGraphicTexture* c_pSrcTexture)
{
if (c_pSrcTexture)
{
m_width = c_pSrcTexture->GetWidth();
m_height = c_pSrcTexture->GetHeight();
m_pixels = c_pSrcTexture->GetPixels();
}
}
protected:
std::string m_stFileName;
};
+144
View File
@@ -0,0 +1,144 @@
#pragma once
#include "src/eter_image/GrpImage.h"
#include "src/eter_image/GrpImageInstance.h"
#include "src/eter_image/GrpDevice.h"
#include "src/eter_resource/ResourceManager.h"
#include "shared/common/DynamicPool.h"
#include <SDL3/SDL.h>
class CGraphicMarkInstance
{
public:
static DWORD Type()
{
static DWORD s_dwType = GetCRC32("CGraphicMarkInstance", strlen("CGraphicMarkInstance"));
return s_dwType;
}
CGraphicMarkInstance()
{
Initialize();
}
virtual ~CGraphicMarkInstance()
{
Destroy();
}
void Destroy()
{
m_roImage.Clear();
}
void SetImageFileName(const char* c_szFileName)
{
if (c_szFileName) m_stImageFileName = c_szFileName;
}
const std::string& GetImageFileName() const
{
return m_stImageFileName;
}
void Load()
{
if (m_stImageFileName.empty())
return;
CResource* pRes = CResourceManager::Instance().GetResourcePointer(m_stImageFileName.c_str());
if (pRes && pRes->IsType(CGraphicImage::Type()))
{
SetImagePointer(static_cast<CGraphicImage*>(pRes));
}
}
void SetImagePointer(CGraphicImage* pImage)
{
m_roImage = pImage;
}
void SetScale(float fScale) { m_fScale = fScale; }
void SetIndex(UINT uIndex) { m_uIndex = uIndex; }
int GetWidth() { return m_roImage.IsNull() ? 0 : m_roImage->GetWidth(); }
int GetHeight() { return m_roImage.IsNull() ? 0 : m_roImage->GetHeight(); }
void SetDiffuseColor(float fr, float fg, float fb, float fa)
{
m_DiffuseColor.r = fr;
m_DiffuseColor.g = fg;
m_DiffuseColor.b = fb;
m_DiffuseColor.a = fa;
}
void SetPosition(float fx, float fy)
{
m_v2Position.x = fx;
m_v2Position.y = fy;
}
void Render() { OnRender(); }
virtual void OnRender()
{
CGraphicDevice* pDevice = CGraphicDevice::InstancePtr();
if (!pDevice) return;
SDL_Renderer* renderer = pDevice->GetRenderer();
if (!renderer) return;
CGraphicImage* pImage = m_roImage.GetPointer();
if (!pImage) return;
CGraphicTexture* pTexture = pImage->GetTexturePointer();
if (!pTexture) return;
SDL_Texture* tex = pTexture->GetSDLTexture(renderer);
if (!tex) return;
int imgWidth = pImage->GetWidth();
if (imgWidth <= 0) imgWidth = 512;
UINT uColCount = imgWidth / 16;
if (uColCount == 0) return;
UINT uCol = m_uIndex % uColCount;
UINT uRow = m_uIndex / uColCount;
float su = static_cast<float>(uCol * 16);
float sv = static_cast<float>(uRow * 12);
float rw = 16.0f;
float rh = 12.0f;
SDL_FRect srcRect{ su, sv, rw, rh };
SDL_FRect dstRect{ m_v2Position.x, m_v2Position.y, rw * m_fScale, rh * m_fScale };
SDL_SetTextureColorModFloat(tex, m_DiffuseColor.r, m_DiffuseColor.g, m_DiffuseColor.b);
SDL_SetTextureAlphaModFloat(tex, m_DiffuseColor.a);
SDL_SetTextureBlendMode(tex, SDL_BLENDMODE_BLEND);
SDL_RenderTexture(renderer, tex, &srcRect, &dstRect);
}
protected:
void Initialize()
{
m_stImageFileName.clear();
m_fScale = 1.0f;
m_uIndex = 0;
m_DiffuseColor = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f);
m_v2Position = D3DXVECTOR2(0.0f, 0.0f);
}
protected:
std::string m_stImageFileName;
float m_fScale;
UINT m_uIndex;
D3DXCOLOR m_DiffuseColor;
D3DXVECTOR2 m_v2Position;
CGraphicImage::TRef m_roImage;
public:
static void CreateSystem(UINT uCapacity) { ms_kPool.Create(uCapacity); }
static void DestroySystem() { ms_kPool.Destroy(); }
static CGraphicMarkInstance* New() { return ms_kPool.Alloc(); }
static void Delete(CGraphicMarkInstance* pkInst)
{
if (pkInst)
{
pkInst->Destroy();
ms_kPool.Free(pkInst);
}
}
static CDynamicPool<CGraphicMarkInstance> ms_kPool;
};
+73
View File
@@ -0,0 +1,73 @@
#pragma once
#include "GrpImage.h"
class CGraphicSubImage : public CGraphicImage
{
public:
typedef CRef<CGraphicImage> TRef;
static TType Type()
{
static TType s_type = StringToType("CGraphicSubImage");
return s_type;
}
CGraphicSubImage(const char* c_szFileName) : CGraphicImage(c_szFileName)
{
}
virtual ~CGraphicSubImage()
{
m_roImage = nullptr;
}
void SetImagePointer(CGraphicImage* pImage)
{
m_roImage = pImage;
if (m_roImage.GetPointer())
{
m_imageTexture.CreateFromTexturePointer(m_roImage->GetTexturePointer());
}
}
void SetRectPosition(int left, int top, int right, int bottom)
{
m_rect.left = left;
m_rect.top = top;
m_rect.right = right;
m_rect.bottom = bottom;
}
void SetRectReference(const RECT& c_rRect)
{
m_rect = c_rRect;
}
protected:
void OnClear() override
{
m_roImage = nullptr;
std::memset(&m_rect, 0, sizeof(m_rect));
}
bool OnIsEmpty() const override
{
if (!m_roImage.IsNull())
if (!m_roImage->IsEmpty())
return false;
return true;
}
bool OnIsType(TType type) override
{
if (CGraphicSubImage::Type() == type)
return true;
return CGraphicImage::OnIsType(type);
}
protected:
CGraphicImage::TRef m_roImage;
};
+507
View File
@@ -0,0 +1,507 @@
#include "MarkManager.h"
#include <cstdio>
#include <cstring>
#include <fstream>
#include <iostream>
#include <filesystem>
#include <algorithm>
namespace ava2 {
namespace {
// CRC32 calculation table
uint32_t CalculateCRC32(const uint8_t* data, size_t length) {
uint32_t crc = 0xFFFFFFFF;
for (size_t i = 0; i < length; ++i) {
crc ^= data[i];
for (int k = 0; k < 8; ++k) {
crc = (crc >> 1) ^ (0xEDB88320 & (-(crc & 1)));
}
}
return ~crc;
}
std::string FindMarkFile(const std::string& relPath) {
std::vector<std::string> candidates = {
relPath,
"build/dev/" + relPath,
"../" + relPath,
"/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/" + relPath
};
for (const auto& c : candidates) {
if (std::filesystem::exists(c)) return c;
}
return relPath;
}
} // namespace
GuildMark::GuildMark() {
Clear();
}
void GuildMark::Clear() {
std::fill(std::begin(pixels), std::end(pixels), 0x00000000);
}
bool GuildMark::IsEmpty() const {
for (int i = 0; i < SIZE; ++i) {
if ((pixels[i] & 0xFF000000) != 0) return false;
}
return true;
}
void GuildMark::SetPixel(int x, int y, uint32_t argb) {
if (x >= 0 && x < WIDTH && y >= 0 && y < HEIGHT) {
pixels[y * WIDTH + x] = argb;
}
}
uint32_t GuildMark::GetPixel(int x, int y) const {
if (x >= 0 && x < WIDTH && y >= 0 && y < HEIGHT) {
return pixels[y * WIDTH + x];
}
return 0;
}
GuildMarkBlock::GuildMarkBlock() {
std::fill(std::begin(pixels), std::end(pixels), 0x00000000);
crc = 0;
}
void GuildMarkBlock::ComputeCRC() {
crc = CalculateCRC32(reinterpret_cast<const uint8_t*>(pixels), sizeof(pixels));
}
// -----------------------------------------------------------------------------
// GuildMarkImage (512x512 Atlas)
// -----------------------------------------------------------------------------
GuildMarkImage::GuildMarkImage() {
m_pixels.assign(WIDTH * HEIGHT, 0x00000000);
}
GuildMarkImage::~GuildMarkImage() {
InvalidateTexture();
}
void GuildMarkImage::InvalidateTexture() {
if (m_texture) {
SDL_DestroyTexture(m_texture);
m_texture = nullptr;
}
m_cachedRenderer = nullptr;
}
bool GuildMarkImage::LoadTGA(const std::string& filepath) {
std::string resolved = FindMarkFile(filepath);
std::ifstream file(resolved, std::ios::binary);
if (!file.is_open()) {
return false;
}
uint8_t header[18];
file.read(reinterpret_cast<char*>(header), 18);
if (!file) return false;
uint8_t idLength = header[0];
uint8_t imageType = header[2]; // 2 = uncompressed RGB/RGBA, 10 = RLE
int w = header[12] | (header[13] << 8);
int h = header[14] | (header[15] << 8);
int bpp = header[16]; // 24 or 32
uint8_t descriptor = header[17];
bool flipY = (descriptor & 0x20) == 0; // standard TGA origin is bottom-left
if (idLength > 0) {
file.seekg(idLength, std::ios::cur);
}
m_pixels.assign(WIDTH * HEIGHT, 0x00000000);
if (imageType == 2) {
// Uncompressed True-Color
int bytesPerPixel = bpp / 8;
if (bytesPerPixel < 3 || bytesPerPixel > 4) return false;
std::vector<uint8_t> rawData(w * h * bytesPerPixel);
file.read(reinterpret_cast<char*>(rawData.data()), rawData.size());
for (int y = 0; y < std::min(h, (int)HEIGHT); ++y) {
int srcY = flipY ? (h - 1 - y) : y;
for (int x = 0; x < std::min(w, (int)WIDTH); ++x) {
int srcIdx = (srcY * w + x) * bytesPerPixel;
uint8_t b = rawData[srcIdx + 0];
uint8_t g = rawData[srcIdx + 1];
uint8_t r = rawData[srcIdx + 2];
uint8_t a = (bytesPerPixel == 4) ? rawData[srcIdx + 3] : 255;
m_pixels[y * WIDTH + x] = (static_cast<uint32_t>(a) << 24) |
(static_cast<uint32_t>(r) << 16) |
(static_cast<uint32_t>(g) << 8) |
static_cast<uint32_t>(b);
}
}
m_isModified = true;
return true;
} else if (imageType == 10) {
// Run-length encoded (RLE) True-Color
int bytesPerPixel = bpp / 8;
if (bytesPerPixel < 3 || bytesPerPixel > 4) return false;
std::vector<uint32_t> tempPixels(w * h, 0);
int totalPixels = w * h;
int currentPixel = 0;
while (currentPixel < totalPixels && file) {
uint8_t packetHeader = 0;
file.read(reinterpret_cast<char*>(&packetHeader), 1);
int count = (packetHeader & 0x7F) + 1;
if (packetHeader & 0x80) {
// RLE packet
uint8_t pixelBuf[4] = {0, 0, 0, 255};
file.read(reinterpret_cast<char*>(pixelBuf), bytesPerPixel);
uint32_t col = (static_cast<uint32_t>(bytesPerPixel == 4 ? pixelBuf[3] : 255) << 24) |
(static_cast<uint32_t>(pixelBuf[2]) << 16) |
(static_cast<uint32_t>(pixelBuf[1]) << 8) |
static_cast<uint32_t>(pixelBuf[0]);
for (int i = 0; i < count && currentPixel < totalPixels; ++i) {
tempPixels[currentPixel++] = col;
}
} else {
// Raw packet
for (int i = 0; i < count && currentPixel < totalPixels; ++i) {
uint8_t pixelBuf[4] = {0, 0, 0, 255};
file.read(reinterpret_cast<char*>(pixelBuf), bytesPerPixel);
uint32_t col = (static_cast<uint32_t>(bytesPerPixel == 4 ? pixelBuf[3] : 255) << 24) |
(static_cast<uint32_t>(pixelBuf[2]) << 16) |
(static_cast<uint32_t>(pixelBuf[1]) << 8) |
static_cast<uint32_t>(pixelBuf[0]);
tempPixels[currentPixel++] = col;
}
}
}
for (int y = 0; y < std::min(h, (int)HEIGHT); ++y) {
int srcY = flipY ? (h - 1 - y) : y;
for (int x = 0; x < std::min(w, (int)WIDTH); ++x) {
m_pixels[y * WIDTH + x] = tempPixels[srcY * w + x];
}
}
m_isModified = true;
return true;
}
return false;
}
bool GuildMarkImage::SaveTGA(const std::string& filepath) const {
std::filesystem::path p(filepath);
if (p.has_parent_path()) {
std::filesystem::create_directories(p.parent_path());
}
std::ofstream file(filepath, std::ios::binary);
if (!file.is_open()) return false;
uint8_t header[18] = {0};
header[2] = 2; // Uncompressed True-Color
header[12] = WIDTH & 0xFF;
header[13] = (WIDTH >> 8) & 0xFF;
header[14] = HEIGHT & 0xFF;
header[15] = (HEIGHT >> 8) & 0xFF;
header[16] = 32; // 32 bpp
header[17] = 0x20; // Top-left origin flag
file.write(reinterpret_cast<const char*>(header), 18);
// Write pixels as BGRA
std::vector<uint8_t> raw(WIDTH * HEIGHT * 4);
for (size_t i = 0; i < m_pixels.size(); ++i) {
uint32_t argb = m_pixels[i];
raw[i * 4 + 0] = argb & 0xFF; // B
raw[i * 4 + 1] = (argb >> 8) & 0xFF; // G
raw[i * 4 + 2] = (argb >> 16) & 0xFF; // R
raw[i * 4 + 3] = (argb >> 24) & 0xFF; // A
}
file.write(reinterpret_cast<const char*>(raw.data()), raw.size());
return true;
}
bool GuildMarkImage::GetMark(uint32_t slotIdx, GuildMark& outMark) const {
if (slotIdx >= MARK_TOTAL_COUNT) return false;
uint32_t col = slotIdx % MARK_COL_COUNT;
uint32_t row = slotIdx / MARK_COL_COUNT;
uint32_t startX = col * GuildMark::WIDTH;
uint32_t startY = row * GuildMark::HEIGHT;
for (int y = 0; y < GuildMark::HEIGHT; ++y) {
for (int x = 0; x < GuildMark::WIDTH; ++x) {
uint32_t pixel = m_pixels[(startY + y) * WIDTH + (startX + x)];
outMark.SetPixel(x, y, pixel);
}
}
return true;
}
bool GuildMarkImage::PutMark(uint32_t slotIdx, const GuildMark& mark) {
if (slotIdx >= MARK_TOTAL_COUNT) return false;
uint32_t col = slotIdx % MARK_COL_COUNT;
uint32_t row = slotIdx / MARK_COL_COUNT;
uint32_t startX = col * GuildMark::WIDTH;
uint32_t startY = row * GuildMark::HEIGHT;
for (int y = 0; y < GuildMark::HEIGHT; ++y) {
for (int x = 0; x < GuildMark::WIDTH; ++x) {
m_pixels[(startY + y) * WIDTH + (startX + x)] = mark.GetPixel(x, y);
}
}
m_isModified = true;
return true;
}
void GuildMarkImage::GetMarkUV(uint32_t slotIdx, float& u0, float& v0, float& u1, float& v1) const {
if (slotIdx >= MARK_TOTAL_COUNT) {
u0 = v0 = u1 = v1 = 0.0f;
return;
}
uint32_t col = slotIdx % MARK_COL_COUNT;
uint32_t row = slotIdx / MARK_COL_COUNT;
float startX = static_cast<float>(col * GuildMark::WIDTH);
float startY = static_cast<float>(row * GuildMark::HEIGHT);
u0 = startX / static_cast<float>(WIDTH);
v0 = startY / static_cast<float>(HEIGHT);
u1 = (startX + static_cast<float>(GuildMark::WIDTH)) / static_cast<float>(WIDTH);
v1 = (startY + static_cast<float>(GuildMark::HEIGHT)) / static_cast<float>(HEIGHT);
}
SDL_Texture* GuildMarkImage::GetOrCreateSDLTexture(SDL_Renderer* renderer) {
if (!renderer) return nullptr;
if (m_texture && m_cachedRenderer == renderer && !m_isModified) {
return m_texture;
}
if (m_texture && m_cachedRenderer != renderer) {
InvalidateTexture();
}
if (!m_texture) {
m_texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_STREAMING, WIDTH, HEIGHT);
m_cachedRenderer = renderer;
if (m_texture) {
SDL_SetTextureBlendMode(m_texture, SDL_BLENDMODE_BLEND);
}
}
if (m_texture && m_isModified) {
SDL_UpdateTexture(m_texture, nullptr, m_pixels.data(), WIDTH * sizeof(uint32_t));
m_isModified = false;
}
return m_texture;
}
// -----------------------------------------------------------------------------
// GuildMarkManager (Singleton)
// -----------------------------------------------------------------------------
GuildMarkManager& GuildMarkManager::Instance() {
static GuildMarkManager s_instance;
return s_instance;
}
GuildMarkManager::GuildMarkManager() {
Clear();
}
GuildMarkManager::~GuildMarkManager() {
Clear();
}
void GuildMarkManager::Clear() {
m_guildToMark.clear();
m_images.clear();
m_freeMarkIDs.clear();
for (uint32_t i = 0; i < TOTAL_MAX_MARKS; ++i) {
m_freeMarkIDs.insert(i);
}
}
void GuildMarkManager::SetMarkPathPrefix(const std::string& prefix) {
m_pathPrefix = prefix;
}
bool GuildMarkManager::GetMarkImageFilename(uint32_t imgIdx, std::string& outPath) const {
if (imgIdx >= MAX_IMAGE_COUNT) return false;
outPath = "mark/" + m_pathPrefix + "_" + std::to_string(imgIdx) + ".tga";
return true;
}
bool GuildMarkManager::LoadMarkIndex() {
std::string relPath = "mark/" + m_pathPrefix + "_index";
std::string resolved = FindMarkFile(relPath);
std::ifstream file(resolved);
if (!file.is_open()) {
return false;
}
uint32_t guildID = 0, markID = 0;
while (file >> guildID >> markID) {
AddMarkIDByGuildID(guildID, markID);
}
LoadMarkImages();
return true;
}
bool GuildMarkManager::SaveMarkIndex() {
std::string relPath = "mark/" + m_pathPrefix + "_index";
std::filesystem::path p(relPath);
if (p.has_parent_path()) {
std::filesystem::create_directories(p.parent_path());
}
std::ofstream file(relPath);
if (!file.is_open()) return false;
for (const auto& [gID, mID] : m_guildToMark) {
file << gID << " " << mID << "\n";
}
return true;
}
void GuildMarkManager::LoadMarkImages() {
std::vector<bool> needed(MAX_IMAGE_COUNT, false);
for (const auto& [gID, mID] : m_guildToMark) {
if (mID < TOTAL_MAX_MARKS) {
needed[mID / MARKS_PER_IMAGE] = true;
}
}
for (uint32_t i = 0; i < MAX_IMAGE_COUNT; ++i) {
if (needed[i] || i == 0) {
GetImage(i);
}
}
}
bool GuildMarkManager::SaveMarkImage(uint32_t imgIdx) {
if (imgIdx >= MAX_IMAGE_COUNT) return false;
auto it = m_images.find(imgIdx);
if (it == m_images.end() || !it->second) return false;
std::string filename;
GetMarkImageFilename(imgIdx, filename);
return it->second->SaveTGA(filename);
}
uint32_t GuildMarkManager::GetMarkID(uint32_t guildID) const {
auto it = m_guildToMark.find(guildID);
if (it != m_guildToMark.end()) {
return it->second;
}
return INVALID_MARK_ID;
}
bool GuildMarkManager::HasMark(uint32_t guildID) const {
return GetMarkID(guildID) != INVALID_MARK_ID;
}
bool GuildMarkManager::AddMarkIDByGuildID(uint32_t guildID, uint32_t markID) {
if (markID >= TOTAL_MAX_MARKS) return false;
m_guildToMark[guildID] = markID;
m_freeMarkIDs.erase(markID);
return true;
}
uint32_t GuildMarkManager::AllocateNextMarkID(uint32_t guildID) {
auto it = m_guildToMark.find(guildID);
if (it != m_guildToMark.end()) {
return it->second;
}
if (m_freeMarkIDs.empty()) return INVALID_MARK_ID;
uint32_t nextID = *m_freeMarkIDs.begin();
m_freeMarkIDs.erase(m_freeMarkIDs.begin());
m_guildToMark[guildID] = nextID;
return nextID;
}
GuildMarkImage* GuildMarkManager::GetImage(uint32_t imgIdx) {
if (imgIdx >= MAX_IMAGE_COUNT) return nullptr;
auto it = m_images.find(imgIdx);
if (it != m_images.end()) {
return it->second.get();
}
auto img = std::make_unique<GuildMarkImage>();
std::string filename;
GetMarkImageFilename(imgIdx, filename);
img->LoadTGA(FindMarkFile(filename));
GuildMarkImage* ptr = img.get();
m_images[imgIdx] = std::move(img);
return ptr;
}
bool GuildMarkManager::SaveMark(uint32_t guildID, const GuildMark& mark) {
uint32_t markID = AllocateNextMarkID(guildID);
if (markID == INVALID_MARK_ID) return false;
uint32_t imgIdx = markID / MARKS_PER_IMAGE;
uint32_t slotIdx = markID % MARKS_PER_IMAGE;
GuildMarkImage* img = GetImage(imgIdx);
if (!img) return false;
if (!img->PutMark(slotIdx, mark)) return false;
SaveMarkIndex();
SaveMarkImage(imgIdx);
return true;
}
bool GuildMarkManager::GetGuildMark(uint32_t guildID, GuildMark& outMark) {
uint32_t markID = GetMarkID(guildID);
if (markID == INVALID_MARK_ID) return false;
uint32_t imgIdx = markID / MARKS_PER_IMAGE;
uint32_t slotIdx = markID % MARKS_PER_IMAGE;
GuildMarkImage* img = GetImage(imgIdx);
if (!img) return false;
return img->GetMark(slotIdx, outMark);
}
bool GuildMarkManager::GetMarkUV(uint32_t guildID, float& u0, float& v0, float& u1, float& v1, uint32_t& imgIdx) {
uint32_t markID = GetMarkID(guildID);
if (markID == INVALID_MARK_ID) {
u0 = v0 = u1 = v1 = 0.0f;
imgIdx = 0;
return false;
}
imgIdx = markID / MARKS_PER_IMAGE;
uint32_t slotIdx = markID % MARKS_PER_IMAGE;
GuildMarkImage* img = GetImage(imgIdx);
if (!img) return false;
img->GetMarkUV(slotIdx, u0, v0, u1, v1);
return true;
}
SDL_Texture* GuildMarkManager::GetSDLTexture(uint32_t imgIdx, SDL_Renderer* renderer) {
GuildMarkImage* img = GetImage(imgIdx);
if (!img) return nullptr;
return img->GetOrCreateSDLTexture(renderer);
}
} // namespace ava2
+142
View File
@@ -0,0 +1,142 @@
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include <unordered_map>
#include <map>
#include <memory>
#include <set>
#include <SDL3/SDL.h>
namespace ava2 {
constexpr uint32_t INVALID_MARK_ID = 0xFFFFFFFF;
// 16x12 pixel individual guild mark (official Metin2 SGuildMark)
struct GuildMark {
enum {
WIDTH = 16,
HEIGHT = 12,
SIZE = WIDTH * HEIGHT // 192 pixels
};
uint32_t pixels[SIZE]; // 0xAARRGGBB
GuildMark();
void Clear();
bool IsEmpty() const;
void SetPixel(int x, int y, uint32_t argb);
uint32_t GetPixel(int x, int y) const;
};
// 4x4 marks block (64x48 pixels) for delta synchronization
struct GuildMarkBlock {
enum {
MARK_PER_BLOCK_WIDTH = 4,
MARK_PER_BLOCK_HEIGHT = 4,
WIDTH = GuildMark::WIDTH * MARK_PER_BLOCK_WIDTH, // 64
HEIGHT = GuildMark::HEIGHT * MARK_PER_BLOCK_HEIGHT, // 48
SIZE = WIDTH * HEIGHT // 3072 pixels
};
uint32_t pixels[SIZE];
uint32_t crc = 0;
GuildMarkBlock();
void ComputeCRC();
};
// 512x512 Guild Mark Atlas Image (official Metin2 CGuildMarkImage)
class GuildMarkImage {
public:
enum {
WIDTH = 512,
HEIGHT = 512,
BLOCK_ROW_COUNT = 10,
BLOCK_COL_COUNT = 8,
BLOCK_TOTAL_COUNT = BLOCK_ROW_COUNT * BLOCK_COL_COUNT, // 80
MARK_ROW_COUNT = 40,
MARK_COL_COUNT = 32,
MARK_TOTAL_COUNT = MARK_ROW_COUNT * MARK_COL_COUNT // 1280 marks per image
};
GuildMarkImage();
~GuildMarkImage();
bool LoadTGA(const std::string& filepath);
bool SaveTGA(const std::string& filepath) const;
bool GetMark(uint32_t slotIdx, GuildMark& outMark) const;
bool PutMark(uint32_t slotIdx, const GuildMark& mark);
void GetMarkUV(uint32_t slotIdx, float& u0, float& v0, float& u1, float& v1) const;
const uint32_t* GetPixels() const { return m_pixels.data(); }
uint32_t* GetPixels() { return m_pixels.data(); }
bool IsModified() const { return m_isModified; }
void SetModified(bool mod) { m_isModified = mod; }
SDL_Texture* GetOrCreateSDLTexture(SDL_Renderer* renderer);
void InvalidateTexture();
private:
std::vector<uint32_t> m_pixels; // 512 * 512 ARGB pixels
bool m_isModified = false;
SDL_Texture* m_texture = nullptr;
SDL_Renderer* m_cachedRenderer = nullptr;
};
// Guild Mark Manager (modeled after 40250 CGuildMarkManager)
class GuildMarkManager {
public:
enum {
MAX_IMAGE_COUNT = 5,
MARKS_PER_IMAGE = GuildMarkImage::MARK_TOTAL_COUNT, // 1280
TOTAL_MAX_MARKS = MAX_IMAGE_COUNT * MARKS_PER_IMAGE // 6400
};
static GuildMarkManager& Instance();
GuildMarkManager();
~GuildMarkManager();
void SetMarkPathPrefix(const std::string& prefix);
const std::string& GetMarkPathPrefix() const { return m_pathPrefix; }
bool LoadMarkIndex();
bool SaveMarkIndex();
void LoadMarkImages();
bool SaveMarkImage(uint32_t imgIdx);
bool GetMarkImageFilename(uint32_t imgIdx, std::string& outPath) const;
uint32_t GetMarkID(uint32_t guildID) const;
bool HasMark(uint32_t guildID) const;
bool AddMarkIDByGuildID(uint32_t guildID, uint32_t markID);
uint32_t AllocateNextMarkID(uint32_t guildID);
bool SaveMark(uint32_t guildID, const GuildMark& mark);
bool GetGuildMark(uint32_t guildID, GuildMark& outMark);
bool GetMarkUV(uint32_t guildID, float& u0, float& v0, float& u1, float& v1, uint32_t& imgIdx);
GuildMarkImage* GetImage(uint32_t imgIdx);
SDL_Texture* GetSDLTexture(uint32_t imgIdx, SDL_Renderer* renderer);
size_t GetGuildCount() const { return m_guildToMark.size(); }
void Clear();
private:
std::string m_pathPrefix = "10";
std::unordered_map<uint32_t, uint32_t> m_guildToMark; // guildID -> markID
std::unordered_map<uint32_t, std::unique_ptr<GuildMarkImage>> m_images; // imgIdx -> GuildMarkImage
std::set<uint32_t> m_freeMarkIDs;
};
} // namespace ava2
+346
View File
@@ -0,0 +1,346 @@
#include "NetworkActorManager.h"
#include "eter_render/TextTailManager.h"
#include <cmath>
#include <filesystem>
#include <iostream>
namespace ava2 {
namespace {
std::string ResolveModelPath(const std::string& rel) {
if (std::filesystem::exists(rel)) return rel;
if (std::filesystem::exists("build/dev/" + rel)) return "build/dev/" + rel;
if (std::filesystem::exists("../" + rel)) return "../" + rel;
return rel;
}
std::string GetRaceModelPath(uint32_t race) {
switch (race) {
case 0: return ResolveModelPath("ymir work/pc/warrior/warrior_assasin1.gr2");
case 1: return ResolveModelPath("ymir work/pc/assassin/assassin_halloween1_lod_01.gr2");
case 2: return ResolveModelPath("ymir work/pc/sura/sura_soccer1_germany_lod_02.gr2");
case 3: return ResolveModelPath("ymir work/pc/shaman/shaman_fencing1_germany_lod_02.gr2");
case 4: return ResolveModelPath("ymir work/pc/plechito/summer2020_costume/warrior_w.gr2");
case 5: return ResolveModelPath("ymir work/pc/plechito/summer2020_costume/assassin_m.gr2");
case 6: return ResolveModelPath("ymir work/pc/plechito/summer2020_costume/sura_w.gr2");
case 7: return ResolveModelPath("ymir work/pc/plechito/summer2020_costume/shaman_m.gr2");
case 101: return ResolveModelPath("ymir work/npc_mount/christmas_2017_sleddog/christmas_2017_sleddog.gr2");
case 102: return ResolveModelPath("ymir work/monster/plechi_golden_frog/plechi_golden_frog.gr2");
case 103: return ResolveModelPath("ymir work/monster/plechi_slime_monster1/plechi_slime_monster1.gr2");
case 2018: return ResolveModelPath("ymir work/npc_mount/halloween_2018_cerberos/halloween_2018_cerberos.gr2");
case 8001: case 8002: case 8003: return ResolveModelPath("ymir work/monster/metinstone_02/metinstone_10.gr2");
case 20001: case 20016: return ResolveModelPath("ymir work/npc/12zi_statue_rabbit_npc/12zi_statue_rabbit_npc.gr2");
default: return ResolveModelPath("ymir work/pc/warrior/warrior_assasin1.gr2");
}
}
std::string GetWeaponModelPath(uint32_t weapon) {
if (weapon > 0) {
return ResolveModelPath("ymir work/item/weapon/set_11_sword.gr2");
}
return "";
}
std::string GetHairModelPath(uint32_t hair) {
if (hair > 0) {
return ResolveModelPath("ymir work/pc/plechito/summer2020_costume/hair/warrior_m.gr2");
}
return "";
}
std::string GetAlignmentTitle(int16_t alignment, uint32_t& titleColor) {
if (alignment >= 12000) { titleColor = 0xFF00BFFF; return "Chivalric"; }
if (alignment >= 8000) { titleColor = 0xFF1E90FF; return "Noble"; }
if (alignment >= 4000) { titleColor = 0xFF6495ED; return "Good"; }
if (alignment >= 1000) { titleColor = 0xFF87CEEB; return "Friendly"; }
if (alignment > -1000) { titleColor = 0xFFFFFFFF; return ""; }
if (alignment > -4000) { titleColor = 0xFFFF8C00; return "Aggressive"; }
if (alignment > -8000) { titleColor = 0xFFFF4500; return "Fraudulent"; }
if (alignment > -12000) { titleColor = 0xFFFF0000; return "Malicious"; }
titleColor = 0xFF8B0000; return "Cruel";
}
} // namespace
NetworkActorManager& NetworkActorManager::Instance() {
static NetworkActorManager s_instance;
return s_instance;
}
NetworkActorManager::NetworkActorManager() = default;
void NetworkActorManager::SetMainActorVID(uint32_t vid) {
m_mainVID = vid;
}
void NetworkActorManager::AppendActor(const SNetworkActorData& data) {
auto& actorData = m_actors[data.m_dwVID];
actorData = data;
// Instantiate 3D ActorInstance
auto actor = std::make_shared<ActorInstance>();
actor->SetVID(data.m_dwVID);
actor->SetName(data.m_stName);
actor->SetYaw(data.m_fRot);
actor->SetSpeed(static_cast<float>(data.m_dwMovSpd > 0 ? data.m_dwMovSpd : 100));
actor->SetScale(0.8f);
// World position: Metin2 coordinates X, Y(Z in 3D), Z(Y in 3D)
float worldX = static_cast<float>(data.m_lCurX);
float worldY = static_cast<float>(data.m_lCurZ); // height
float worldZ = static_cast<float>(data.m_lCurY);
actor->SetPosition(worldX, worldY, worldZ);
std::string modelPath = GetRaceModelPath(data.m_dwRace);
if (!modelPath.empty()) {
actor->SetModel(modelPath);
}
if (data.m_dwWeapon > 0) {
std::string weaponPath = GetWeaponModelPath(data.m_dwWeapon);
if (!weaponPath.empty()) {
actor->SetWeapon(weaponPath, "equip_right_hand");
}
}
if (data.m_dwHair > 0) {
std::string hairPath = GetHairModelPath(data.m_dwHair);
if (!hairPath.empty()) {
actor->AttachPart(hairPath);
}
}
// AVA2 InstanceBase::SetAffect(AFFECT_STUN=5) controls the sleep action flag.
actor->SetSleep((data.m_affectFlags[0] & (1u<<5))!=0);
actorData.m_pActorInstance = actor;
// Register TextTail overhead display
auto& tt = TextTailManager::Instance();
uint32_t nameColor = (data.m_bType == 0) ? 0xFFFF4444 : 0xFFFFFFFF; // Red for mobs, white for players
tt.RegisterCharacterTextTail(data.m_dwGuildID, data.m_dwVID, nameColor);
tt.SetCharacterName(data.m_dwVID, data.m_stName);
tt.SetCharacterPosition(data.m_dwVID, worldX, worldY, worldZ);
if (data.m_dwLevel > 0) {
tt.AttachLevel(data.m_dwVID, "Lv " + std::to_string(data.m_dwLevel));
}
if (!data.m_stGuildName.empty()) {
tt.SetGuildName(data.m_dwVID, data.m_stGuildName);
}
if (data.m_sAlignment != 0) {
uint32_t titleColor = 0xFFFFFFFF;
std::string title = GetAlignmentTitle(data.m_sAlignment, titleColor);
if (!title.empty()) {
tt.AttachTitle(data.m_dwVID, title, titleColor);
}
}
if (IsMainActorVID(data.m_dwVID)) {
m_mainPosX = data.m_lCurX;
m_mainPosY = data.m_lCurY;
}
}
void NetworkActorManager::RemoveActor(uint32_t vid) {
auto it = m_actors.find(vid);
if (it != m_actors.end()) {
m_actors.erase(it);
}
TextTailManager::Instance().DeleteCharacterTextTail(vid);
}
void NetworkActorManager::UpdateActor(const SNetworkUpdateActorData& data) {
auto it = m_actors.find(data.m_dwVID);
if (it == m_actors.end()) return;
auto& actorData = it->second;
actorData.m_dwSash = data.m_dwSash;
actorData.m_dwArrowType = data.m_dwArrowType;
actorData.m_dwConquerorLevel = data.m_dwConquerorLevel;
actorData.m_dwStateFlags = data.m_dwStateFlags;
std::copy_n(data.m_affectFlags, 2, actorData.m_affectFlags);
std::copy_n(data.m_shining, CHR_SHINING_NUM, actorData.m_shining);
actorData.m_dwArmor = data.m_dwArmor;
actorData.m_dwWeapon = data.m_dwWeapon;
actorData.m_dwHair = data.m_dwHair;
actorData.m_dwGuildID = data.m_dwGuildID;
actorData.m_sAlignment = data.m_sAlignment;
actorData.m_byPKMode = data.m_byPKMode;
actorData.m_dwMountVnum = data.m_dwMountVnum;
actorData.m_dwMovSpd = data.m_dwMovSpd;
actorData.m_dwAtkSpd = data.m_dwAtkSpd;
if (actorData.m_pActorInstance) {
actorData.m_pActorInstance->SetSleep((data.m_affectFlags[0] & (1u<<5))!=0);
if (data.m_dwWeapon > 0) {
std::string weaponPath = GetWeaponModelPath(data.m_dwWeapon);
if (!weaponPath.empty()) {
actorData.m_pActorInstance->SetWeapon(weaponPath, "equip_right_hand");
}
}
if (data.m_dwHair > 0) {
std::string hairPath = GetHairModelPath(data.m_dwHair);
if (!hairPath.empty()) {
actorData.m_pActorInstance->AttachPart(hairPath);
}
}
if (data.m_dwMovSpd > 0) {
actorData.m_pActorInstance->SetSpeed(static_cast<float>(data.m_dwMovSpd));
}
}
auto& tt = TextTailManager::Instance();
if (data.m_sAlignment != 0) {
uint32_t titleColor = 0xFFFFFFFF;
std::string title = GetAlignmentTitle(data.m_sAlignment, titleColor);
if (!title.empty()) {
tt.AttachTitle(data.m_dwVID, title, titleColor);
}
}
}
void NetworkActorManager::MoveActor(const SNetworkMoveActorData& data) {
auto it = m_actors.find(data.m_dwVID);
if (it == m_actors.end()) return;
auto& actorData = it->second;
actorData.m_lDstX = data.m_lPosX;
actorData.m_lDstY = data.m_lPosY;
actorData.m_fRot = data.m_fRot;
actorData.m_dwDuration = data.m_dwDuration;
actorData.m_moveElapsed = 0.0f;
if (actorData.m_pActorInstance) {
actorData.m_pActorInstance->SetYaw(data.m_fRot);
if (data.m_dwFunc == 0) { // Stop
actorData.m_isMoving = false;
actorData.m_pActorInstance->PlayMotion(MotionType::Wait);
} else { // Move
actorData.m_isMoving = true;
actorData.m_pActorInstance->PlayMotion(MotionType::Run);
}
}
}
void NetworkActorManager::SyncActor(uint32_t vid, int32_t lPosX, int32_t lPosY) {
auto it = m_actors.find(vid);
if (it == m_actors.end()) return;
auto& actorData = it->second;
actorData.m_lCurX = lPosX;
actorData.m_lCurY = lPosY;
actorData.m_lDstX = lPosX;
actorData.m_lDstY = lPosY;
actorData.m_isMoving = false;
if (actorData.m_pActorInstance) {
actorData.m_pActorInstance->SetPosition(static_cast<float>(lPosX),
static_cast<float>(actorData.m_lCurZ),
static_cast<float>(lPosY));
}
TextTailManager::Instance().SetCharacterPosition(vid,
static_cast<float>(lPosX),
static_cast<float>(actorData.m_lCurZ),
static_cast<float>(lPosY));
if (IsMainActorVID(vid)) {
m_mainPosX = lPosX;
m_mainPosY = lPosY;
}
}
void NetworkActorManager::SetActorOwner(uint32_t ownerVID, uint32_t victimVID) {
auto it = m_actors.find(victimVID);
if (it != m_actors.end()) {
it->second.m_dwOwnerVID = ownerVID;
}
}
void NetworkActorManager::Update(float dt, const TerrainHeightmap* terrain) {
for (auto& [vid, actorData] : m_actors) {
if (!actorData.m_pActorInstance) continue;
if (actorData.m_isMoving) {
float curX = static_cast<float>(actorData.m_lCurX);
float curZ = static_cast<float>(actorData.m_lCurY);
float dstX = static_cast<float>(actorData.m_lDstX);
float dstZ = static_cast<float>(actorData.m_lDstY);
float dx = dstX - curX;
float dz = dstZ - curZ;
float dist = std::sqrt(dx * dx + dz * dz);
float speed = actorData.m_pActorInstance->GetSpeed();
if (speed <= 0.0f) speed = 250.0f;
float step = speed * dt;
if (dist <= step || dist < 1.0f) {
actorData.m_lCurX = actorData.m_lDstX;
actorData.m_lCurY = actorData.m_lDstY;
actorData.m_isMoving = false;
actorData.m_pActorInstance->PlayMotion(MotionType::Wait);
} else {
float nx = dx / dist;
float nz = dz / dist;
actorData.m_lCurX += static_cast<int32_t>(nx * step);
actorData.m_lCurY += static_cast<int32_t>(nz * step);
}
float finalX = static_cast<float>(actorData.m_lCurX);
float finalZ = static_cast<float>(actorData.m_lCurY);
float finalY = terrain ? terrain->GetHeightAtWorld(finalX, finalZ) : static_cast<float>(actorData.m_lCurZ);
actorData.m_lCurZ = static_cast<int32_t>(finalY);
actorData.m_pActorInstance->SetPosition(finalX, finalY, finalZ);
TextTailManager::Instance().SetCharacterPosition(vid, finalX, finalY, finalZ);
if (IsMainActorVID(vid)) {
m_mainPosX = actorData.m_lCurX;
m_mainPosY = actorData.m_lCurY;
}
}
actorData.m_pActorInstance->Update(dt, terrain);
}
}
void NetworkActorManager::Clear() {
m_actors.clear();
m_mainVID = 0;
m_mainPosX = 0;
m_mainPosY = 0;
}
SNetworkActorData* NetworkActorManager::GetActorData(uint32_t vid) {
auto it = m_actors.find(vid);
return (it != m_actors.end()) ? &it->second : nullptr;
}
const SNetworkActorData* NetworkActorManager::GetActorData(uint32_t vid) const {
auto it = m_actors.find(vid);
return (it != m_actors.end()) ? &it->second : nullptr;
}
std::shared_ptr<ActorInstance> NetworkActorManager::GetActorInstance(uint32_t vid) {
auto it = m_actors.find(vid);
return (it != m_actors.end()) ? it->second.m_pActorInstance : nullptr;
}
std::vector<Render3DDraw> NetworkActorManager::BuildDrawCommands(float animTime) {
(void)animTime;
std::vector<Render3DDraw> allDraws;
for (auto& [vid, actorData] : m_actors) {
if (!actorData.m_pActorInstance) continue;
auto actorDraws = actorData.m_pActorInstance->BuildDrawCommands();
for (auto& d : actorDraws) {
allDraws.push_back(std::move(d));
}
}
return allDraws;
}
} // namespace ava2
+132
View File
@@ -0,0 +1,132 @@
#pragma once
#include "Packet.h"
#include "eter_render/ActorInstance.h"
#include <string>
#include <unordered_map>
#include <memory>
#include <vector>
namespace ava2 {
struct SNetworkActorData {
uint32_t m_dwVID = 0;
std::string m_stName;
uint8_t m_bType = 0; // 0=Mob, 1=NPC, 6=PC
uint32_t m_dwRace = 0;
uint32_t m_dwLevel = 0;
uint32_t m_dwGuildID = 0;
std::string m_stGuildName;
uint32_t m_dwEmpireID = 0;
float m_fRot = 0.0f;
int32_t m_lCurX = 0;
int32_t m_lCurY = 0;
int32_t m_lCurZ = 0;
int32_t m_lDstX = 0;
int32_t m_lDstY = 0;
uint32_t m_dwServerSrcTime = 0;
uint32_t m_dwClientSrcTime = 0;
uint32_t m_dwDuration = 0;
uint32_t m_dwArmor = 0;
uint32_t m_dwWeapon = 0;
uint32_t m_dwHair = 0;
uint32_t m_dwSash = 0;
uint32_t m_dwArrowType = 0;
uint32_t m_dwConquerorLevel = 0;
uint8_t m_language = 0;
uint32_t m_dwStateFlags = 0;
uint32_t m_affectFlags[2] = {};
uint32_t m_shining[CHR_SHINING_NUM] = {};
uint32_t m_dwMovSpd = 100;
uint32_t m_dwAtkSpd = 100;
int16_t m_sAlignment = 0;
uint8_t m_byPKMode = 0;
uint32_t m_dwMountVnum = 0;
uint32_t m_dwOwnerVID = 0;
bool m_duelMode = false;
bool m_isMoving = false;
float m_moveElapsed = 0.0f;
std::shared_ptr<ActorInstance> m_pActorInstance;
};
struct SNetworkMoveActorData {
uint32_t m_dwVID = 0;
uint32_t m_dwTime = 0;
int32_t m_lPosX = 0;
int32_t m_lPosY = 0;
float m_fRot = 0.0f;
uint32_t m_dwFunc = 0; // 0=Wait, 1=Move
uint32_t m_dwArg = 0;
uint32_t m_dwDuration = 0;
};
struct SNetworkUpdateActorData {
uint32_t m_dwVID = 0;
uint32_t m_dwArmor = 0;
uint32_t m_dwWeapon = 0;
uint32_t m_dwHair = 0;
uint32_t m_dwSash = 0;
uint32_t m_dwArrowType = 0;
uint32_t m_dwConquerorLevel = 0;
uint32_t m_dwStateFlags = 0;
uint32_t m_affectFlags[2] = {};
uint32_t m_shining[CHR_SHINING_NUM] = {};
uint32_t m_dwGuildID = 0;
int16_t m_sAlignment = 0;
uint8_t m_byPKMode = 0;
uint32_t m_dwMountVnum = 0;
uint32_t m_dwMovSpd = 0;
uint32_t m_dwAtkSpd = 0;
};
/**
* NetworkActorManager:
* Partial cross-platform implementation of AVA2 CNetworkActorManager.
* Manages dynamic spawning, visibility, interpolation, orientation,
* weapon/armor attachment, TextTail synchronization, and removal of network entities.
*/
class NetworkActorManager {
public:
static NetworkActorManager& Instance();
NetworkActorManager();
~NetworkActorManager() = default;
void SetMainActorVID(uint32_t vid);
uint32_t GetMainActorVID() const { return m_mainVID; }
bool IsMainActorVID(uint32_t vid) const { return vid == m_mainVID; }
void AppendActor(const SNetworkActorData& data);
void RemoveActor(uint32_t vid);
void UpdateActor(const SNetworkUpdateActorData& data);
void MoveActor(const SNetworkMoveActorData& data);
void SyncActor(uint32_t vid, int32_t lPosX, int32_t lPosY);
void SetActorOwner(uint32_t ownerVID, uint32_t victimVID);
void Update(float dt, const TerrainHeightmap* terrain = nullptr);
void Clear();
SNetworkActorData* GetActorData(uint32_t vid);
const SNetworkActorData* GetActorData(uint32_t vid) const;
std::shared_ptr<ActorInstance> GetActorInstance(uint32_t vid);
const std::unordered_map<uint32_t, SNetworkActorData>& GetActorDict() const { return m_actors; }
// Helpers to build 3D rendering draw calls for all visible network actors
std::vector<Render3DDraw> BuildDrawCommands(float animTime);
private:
uint32_t m_mainVID = 0;
int32_t m_mainPosX = 0;
int32_t m_mainPosY = 0;
std::unordered_map<uint32_t, SNetworkActorData> m_actors;
};
} // namespace ava2
+706
View File
@@ -0,0 +1,706 @@
#pragma once
#include <cstdint>
#include <cstring>
#include <string>
#include <vector>
namespace ava2 {
constexpr size_t CHARACTER_NAME_MAX_LEN = 24;
constexpr size_t MUSIC_NAME_MAX_LEN = 24;
constexpr size_t SKILL_MAX_NUM=255;
constexpr size_t CHR_EQUIPPART_ARMOR = 0;
constexpr size_t CHR_EQUIPPART_WEAPON = 1;
constexpr size_t CHR_EQUIPPART_HEAD = 2;
constexpr size_t CHR_EQUIPPART_HAIR = 3;
constexpr size_t CHR_EQUIPPART_SASH = 4;
constexpr size_t CHR_PART_ARROW_TYPE = 5;
constexpr size_t CHR_EQUIPPART_NUM = 6;
constexpr size_t CHR_SHINING_NUM = 3;
constexpr size_t ITEM_SOCKET_SLOT_MAX_NUM = 8;
constexpr size_t ITEM_ATTRIBUTE_SLOT_MAX_NUM = 15;
constexpr size_t GLOVE_ATTR_MAX_NUM = 7;
constexpr size_t MAX_ELEMENTS_SPELL = 3;
constexpr size_t EXCHANGE_ITEM_MAX_NUM = 12;
#pragma pack(push,1)
struct TPlayerItemAttribute {
uint8_t bType = 0;
int16_t sValue = 0;
};
#pragma pack(pop)
struct TItemData {
uint32_t vnum = 0;
uint32_t count = 0;
uint32_t flags = 0;
uint32_t anti_flags = 0;
int32_t alSockets[ITEM_SOCKET_SLOT_MAX_NUM] = {0};
TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_SLOT_MAX_NUM] = {};
TPlayerItemAttribute randomAttr[GLOVE_ATTR_MAX_NUM] = {};
uint32_t bind = 0;
uint8_t grade_element = 0;
uint32_t attack_element[MAX_ELEMENTS_SPELL] = {0};
uint8_t element_type_bonus = 0;
int16_t elements_value_bonus[MAX_ELEMENTS_SPELL] = {0};
char name[32] = "^";
};
// Packet Headers Aligned 1:1 with AVA2 / Metin2 Wire Protocol
enum EPacketCG {
HEADER_CG_HANDSHAKE = 0xff,
HEADER_CG_PONG = 0xfe,
HEADER_CG_TIME_SYNC = 0xfc,
HEADER_CG_LOGIN = 1,
HEADER_CG_ATTACK = 225,
HEADER_CG_CHAT = 231,
HEADER_CG_CHARACTER_CREATE = 4,
HEADER_CG_CHARACTER_DELETE = 5,
HEADER_CG_CHARACTER_SELECT = 6,
HEADER_CG_MOVE = 7,
HEADER_CG_SYNC_POSITION = 8,
HEADER_CG_ENTERGAME = 10,
HEADER_CG_ITEM_USE = 11,
HEADER_CG_ITEM_DROP = 224,
HEADER_CG_ITEM_MOVE = 13,
HEADER_CG_ITEM_PICKUP = 15,
HEADER_CG_QUICKSLOT_ADD = 16,
HEADER_CG_QUICKSLOT_DEL = 17,
HEADER_CG_QUICKSLOT_SWAP = 18,
HEADER_CG_WHISPER = 19,
HEADER_CG_ITEM_DROP2 = 20,
HEADER_CG_ON_CLICK = 26,
HEADER_CG_EXCHANGE = 27,
HEADER_CG_CHARACTER_POSITION = 28,
HEADER_CG_TARGET = 61,
HEADER_CG_FLY_TARGETING = 51,
HEADER_CG_ADD_FLY_TARGETING = 53,
HEADER_CG_USE_SKILL = 233,
HEADER_CG_WARP = 65,
HEADER_CG_MALL_CHECKOUT = 69,
HEADER_CG_SAFEBOX_CHECKIN = 70,
HEADER_CG_SAFEBOX_CHECKOUT = 71,
HEADER_CG_SAFEBOX_ITEM_MOVE = 77,
HEADER_CG_ITEM_USE_TO_ITEM = 60,
HEADER_CG_SCRIPT_ANSWER = 29,
HEADER_CG_SCRIPT_BUTTON = 66,
HEADER_CG_QUEST_INPUT_STRING = 30,
HEADER_CG_QUEST_CONFIRM = 31,
HEADER_CG_GIVE_ITEM = 83,
HEADER_CG_REFINE = 96,
HEADER_CG_CLIENT_VERSION2 = 241,
};
enum EPacketGC {
HEADER_GC_CHARACTER_ADD = 1,
HEADER_GC_CHARACTER_DEL = 2,
HEADER_GC_CHARACTER_MOVE = 3,
HEADER_GC_CHAT = 4,
HEADER_GC_SYNC_POSITION = 5,
HEADER_GC_LOGIN_SUCCESS3 = 6,
HEADER_GC_LOGIN_FAILURE = 7,
HEADER_GC_CHARACTER_CREATE_SUCCESS = 8,
HEADER_GC_CHARACTER_CREATE_FAILURE = 9,
HEADER_GC_CHARACTER_DELETE_SUCCESS = 10,
HEADER_GC_STUN = 13,
HEADER_GC_DEAD = 14,
HEADER_GC_MAIN_CHARACTER = 15,
HEADER_GC_PLAYER_POINTS = 16,
HEADER_GC_PLAYER_POINT_CHANGE = 17,
HEADER_GC_CHANGE_SPEED = 18,
HEADER_GC_CHARACTER_UPDATE = 19,
HEADER_GC_CHARACTER_UPDATE2 = 117,
HEADER_GC_CHARACTER_ADD2 = 120,
HEADER_GC_ITEM_SET = 20,
HEADER_GC_ITEM_SET2 = 21,
HEADER_GC_ITEM_USE = 22,
HEADER_GC_ITEM_DROP = 23,
HEADER_GC_ITEM_UPDATE = 25,
HEADER_GC_ITEM_GROUND_ADD = 26,
HEADER_GC_ITEM_GROUND_DEL = 27,
HEADER_GC_QUICKSLOT_ADD = 28,
HEADER_GC_QUICKSLOT_DEL = 29,
HEADER_GC_QUICKSLOT_SWAP = 30,
HEADER_GC_ITEM_OWNERSHIP = 31,
HEADER_GC_WHISPER = 34,
HEADER_GC_MOTION = 36,
HEADER_GC_SHOP = 38,
HEADER_GC_DUEL_START = 40,
HEADER_GC_EXCHANGE = 42,
HEADER_GC_DAMAGE_INFO = 135,
HEADER_GC_WARP = 65,
HEADER_GC_FLY_TARGETING = 71,
HEADER_GC_ADD_FLY_TARGETING = 69,
HEADER_GC_CREATE_FLY = 70,
HEADER_GC_SAFEBOX_MONEY_CHANGE = 84,
HEADER_GC_SAFEBOX_SET = 85,
HEADER_GC_SAFEBOX_DEL = 86,
HEADER_GC_SAFEBOX_WRONG_PASSWORD = 87,
HEADER_GC_SAFEBOX_SIZE = 88,
HEADER_GC_MAIN_CHARACTER2_EMPIRE = 113,
HEADER_GC_MALL_OPEN = 122,
HEADER_GC_MALL_SET = 128,
HEADER_GC_MALL_DEL = 129,
HEADER_GC_CHAR_ADDITIONAL_INFO = 136,
HEADER_GC_MAIN_CHARACTER3_BGM = 137,
HEADER_GC_MAIN_CHARACTER4_BGM_VOL = 138,
HEADER_GC_AFFECT_ADD=126,
HEADER_GC_AFFECT_REMOVE=127,
HEADER_GC_SKILL_LEVEL=72,
HEADER_GC_SKILL_LEVEL_NEW=76,
HEADER_GC_TIME = 106,
HEADER_GC_PHASE = 0xfd,
HEADER_GC_HANDSHAKE = 0xff,
};
enum EExchangeSubheaderCG {
EXCHANGE_SUBHEADER_CG_START = 0, // arg1 == vid of target
EXCHANGE_SUBHEADER_CG_ITEM_ADD = 1, // arg1 == pos of item
EXCHANGE_SUBHEADER_CG_ITEM_DEL = 2, // arg1 == pos of item
EXCHANGE_SUBHEADER_CG_ELK_ADD = 3, // arg1 == elk amount
EXCHANGE_SUBHEADER_CG_ACCEPT = 4,
EXCHANGE_SUBHEADER_CG_CANCEL = 5,
};
enum EExchangeSubheaderGC {
EXCHANGE_SUBHEADER_GC_START = 0, // arg1 == vid
EXCHANGE_SUBHEADER_GC_ITEM_ADD = 1, // arg1 == vnum, arg2 == pos, arg3 == count
EXCHANGE_SUBHEADER_GC_ITEM_DEL = 2, // arg1 == pos
EXCHANGE_SUBHEADER_GC_ELK_ADD = 3, // arg1 == elk
EXCHANGE_SUBHEADER_GC_ACCEPT = 4, // arg1 == accept (0/1)
EXCHANGE_SUBHEADER_GC_END = 5,
EXCHANGE_SUBHEADER_GC_ALREADY = 6,
EXCHANGE_SUBHEADER_GC_LESS_ELK = 7,
};
enum EPhase {
PHASE_CLOSE = 0,
PHASE_OFFLINE = PHASE_CLOSE,
PHASE_HANDSHAKE = 1,
PHASE_LOGIN = 2,
PHASE_SELECT = 3,
PHASE_LOADING = 4,
PHASE_GAME = 5,
PHASE_DEAD = 6,
PHASE_DBCLIENT_CONNECTING = 7,
PHASE_DBCLIENT = 8,
PHASE_P2P = 9,
PHASE_AUTH = 10,
};
enum EChatType {
CHAT_TYPE_TALKING = 0,
CHAT_TYPE_INFO = 1,
CHAT_TYPE_NOTICE = 2,
CHAT_TYPE_PARTY = 3,
CHAT_TYPE_GUILD = 4,
CHAT_TYPE_COMMAND = 5,
CHAT_TYPE_SHOUT = 6,
CHAT_TYPE_WHISPER = 7,
CHAT_TYPE_BIG_NOTICE = 8,
};
#pragma pack(push, 1)
struct TItemPos {
uint8_t window_type;
uint16_t cell;
};
struct TQuickSlot {
uint8_t Type;
uint8_t Position;
};
// ── Client to Server Wire Packets ──
struct TPacketCGAttack {
uint8_t header;
uint8_t bType;
uint32_t dwVictimVID;
uint8_t bCRCMagicCubeProc;
uint8_t bCRCMagicCubeFile;
};
struct TPacketCGMove {
uint8_t bHeader;
uint8_t bFunc;
uint8_t bArg;
uint8_t bRot;
int32_t lX;
int32_t lY;
uint32_t dwTime;
};
struct TPacketCGItemUse {
uint8_t header;
TItemPos Cell;
};
struct TPacketCGItemMove {
uint8_t header;
TItemPos Cell;
TItemPos CellTo;
uint32_t count;
};
struct TPacketCGItemPickUp {
uint8_t header;
uint32_t vid;
};
struct TPacketCGItemDrop {
uint8_t header;
TItemPos Cell;
uint32_t elk;
};
struct TPacketCGItemDrop2 {
uint8_t header;
TItemPos Cell;
uint32_t gold;
uint32_t count;
};
struct TPacketCGChat {
uint8_t header;
uint16_t size;
uint8_t type;
};
struct TPacketCGWhisper {
uint8_t header;
uint16_t size;
char szNameTo[CHARACTER_NAME_MAX_LEN + 1];
};
struct TPacketCGOnClick {
uint8_t header;
uint32_t vid;
};
struct TPacketCGEnterGame {
uint8_t header;
uint8_t lang;
};
struct TPacketCGWarp {
uint8_t header;
};
struct TPacketCGFlyTargeting {
uint8_t bHeader;
uint32_t dwTargetVID;
int32_t x;
int32_t y;
};
// 1:1 upstream SPacketCGRefine (Locale_inc.h: ENABLE_MULTI_REFINE_WORLDARD on,
// ENABLE_FEATURES_REFINE_SYSTEM off) -> 5 bytes.
struct TPacketCGRefine {
uint8_t header;
uint8_t pos;
uint8_t type;
uint8_t special_storage;
uint8_t index;
};
struct TPacketCGItemUseToItem {
uint8_t header;
TItemPos source_pos;
TItemPos target_pos;
};
struct TPacketCGGiveItem {
uint8_t byHeader;
uint32_t dwTargetVID;
TItemPos ItemPos;
uint32_t byItemCount; // upstream: DWORD
};
struct TPacketCGScriptAnswer {
uint8_t header;
uint8_t answer;
};
struct TPacketCGScriptButton {
uint8_t header;
uint32_t idx;
};
// ── Server to Client Wire Packets ──
struct TPacketGCPhase {
uint8_t header;
uint8_t phase;
};
struct TPacketGCTime { uint8_t bHeader;int32_t time; };
struct TPacketGCPoints { uint8_t header;int64_t points[255]; };
struct TPacketGCMainCharacter {
uint8_t header;
uint32_t dwVID;
uint16_t wRaceNum;
char szName[CHARACTER_NAME_MAX_LEN + 1];
int32_t lX, lY, lZ;
uint8_t bySkillGroup;
};
struct TPacketGCMainCharacter2Empire {
uint8_t header;
uint32_t dwVID;
uint16_t wRaceNum;
char szName[CHARACTER_NAME_MAX_LEN + 1];
int32_t lX, lY, lZ;
uint8_t byEmpire;
uint8_t bySkillGroup;
};
struct TPacketGCMainCharacter3BGM {
uint8_t header;
uint32_t dwVID;
uint16_t wRaceNum;
char szUserName[CHARACTER_NAME_MAX_LEN + 1];
char szBGMName[MUSIC_NAME_MAX_LEN + 1];
int32_t lX, lY, lZ;
uint8_t byEmpire;
uint8_t bySkillGroup;
};
struct TPacketGCMainCharacter4BGMVolume {
uint8_t header;uint32_t dwVID;uint16_t wRaceNum;
char szUserName[CHARACTER_NAME_MAX_LEN+1],szBGMName[MUSIC_NAME_MAX_LEN+1];
float fBGMVol;int32_t lX,lY,lZ;uint8_t byEmpire,bySkillGroup;
};
struct TPacketAffectElement {
uint32_t dwType;uint8_t bPointIdxApplyOn;int32_t lApplyValue;uint32_t dwFlag;int32_t lDuration,lSPCost;
};
struct TPacketGCAffectAdd {uint8_t bHeader;TPacketAffectElement elem;};
struct TPacketGCAffectRemove {uint8_t bHeader;uint32_t dwType;uint8_t bApplyOn;};
struct TPlayerSkill { uint8_t bMasterType,bLevel; int32_t tNextRead; };
struct TPacketGCSkillLevel { uint8_t bHeader; uint8_t abSkillLevels[SKILL_MAX_NUM]; };
struct TPacketGCSkillLevelNew { uint8_t bHeader; TPlayerSkill skills[SKILL_MAX_NUM]; };
struct TPacketGCCharacterAdd {
uint8_t header;
uint32_t dwVID;
float angle;
int32_t x;
int32_t y;
int32_t z;
uint8_t bType;
uint16_t wRaceNum;
int16_t bMovingSpeed;
uint8_t bAttackSpeed;
uint8_t bStateFlag;
uint32_t dwAffectFlag[2];
};
struct TPacketGCCharacterAdd2 {
uint8_t header;
uint32_t dwVID;
char name[CHARACTER_NAME_MAX_LEN + 1];
float angle;
int32_t x;
int32_t y;
int32_t z;
uint8_t bType;
uint16_t wRaceNum;
uint16_t awPart[CHR_EQUIPPART_NUM];
int16_t bMovingSpeed;
uint8_t bAttackSpeed;
uint8_t bStateFlag;
uint32_t dwAffectFlag[2];
uint8_t bEmpire;
uint32_t dwGuild;
int16_t sAlignment;
uint8_t bPKMode;
uint32_t dwMountVnum;
};
struct TPacketGCCharacterAdditionalInfo {
uint8_t header;
uint32_t dwVID;
char name[CHARACTER_NAME_MAX_LEN + 1];
uint16_t awPart[CHR_EQUIPPART_NUM];
uint8_t bEmpire;
uint32_t dwGuildID;
uint32_t dwLevel;
uint32_t dwConquerorLevel;
int16_t sAlignment;
uint8_t bPKMode;
uint32_t dwMountVnum;
uint8_t language;
uint32_t adwShining[CHR_SHINING_NUM];
};
struct TPacketGCCharacterUpdate {
uint8_t header;
uint32_t dwVID;
uint16_t awPart[CHR_EQUIPPART_NUM];
int16_t bMovingSpeed;
uint8_t bAttackSpeed;
uint8_t bStateFlag;
uint32_t dwAffectFlag[2];
uint32_t dwGuildID;
int16_t sAlignment;
uint32_t dwConquerorLevel;
uint8_t bPKMode;
uint32_t dwMountVnum;
uint32_t adwShining[CHR_SHINING_NUM];
};
struct TPacketGCCharacterUpdate2 {
uint8_t header;
uint32_t dwVID;
uint16_t awPart[CHR_EQUIPPART_NUM];
int16_t bMovingSpeed;
uint8_t bAttackSpeed;
uint8_t bStateFlag;
uint32_t dwAffectFlag[2];
uint32_t dwGuildID;
int16_t sAlignment;
uint8_t bPKMode;
uint32_t dwMountVnum;
uint32_t adwShining[CHR_SHINING_NUM];
};
struct TPacketGCCharacterDelete {
uint8_t header;
uint32_t dwVID;
};
struct TPacketGCMove {
uint8_t bHeader;
uint8_t bFunc;
uint8_t bArg;
uint8_t bRot;
uint32_t dwVID;
int32_t lX;
int32_t lY;
uint32_t dwTime;
uint32_t dwDuration;
};
struct TPacketGCSyncPosition {
uint8_t bHeader;
uint16_t wSize;
struct Element {
uint32_t dwVID;
int32_t lX;
int32_t lY;
};
};
struct TPacketGCChat {
uint8_t header;
uint16_t size;
uint8_t type;
uint32_t dwVID;
uint8_t bEmpire;
};
struct TPacketGCWhisper {
uint8_t bHeader;
uint16_t wSize;
uint8_t bType;
char szNameFrom[CHARACTER_NAME_MAX_LEN + 1];
};
struct TPacketGCDamageInfo {
uint8_t header;
uint32_t dwVID;
uint8_t flag;
int32_t damage;
};
enum EReviveTypes { REVIVE_TYPE_HERE, REVIVE_TYPE_TOWN, REVIVE_TYPE_AUTO_TOWN, REVIVE_TYPE_MAX };
struct TPacketGCDead {
uint8_t header;
uint32_t vid;
uint8_t t_d[REVIVE_TYPE_MAX];
};
struct TPacketGCStun {
uint8_t header;
uint32_t vid;
};
struct TPacketGCPointChange {
int32_t header;
uint32_t dwVID;
uint8_t Type;
int64_t amount;
int64_t value;
};
// AVA2 Windows non-GAIDEN profile: GLOVE and NEW_NAME enabled; SOULBIND/ELEMENT disabled.
struct TPacketGCItemSet {
uint8_t header; TItemPos Cell; uint32_t vnum, count;
int32_t alSockets[ITEM_SOCKET_SLOT_MAX_NUM];
TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_SLOT_MAX_NUM];
TPlayerItemAttribute randomAttr[GLOVE_ATTR_MAX_NUM];
char name[25];
};
struct TPacketGCItemSet2 {
uint8_t header; TItemPos Cell; uint32_t vnum, count, flags, anti_flags;
uint8_t highlight;
int32_t alSockets[ITEM_SOCKET_SLOT_MAX_NUM];
TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_SLOT_MAX_NUM];
TPlayerItemAttribute randomAttr[GLOVE_ATTR_MAX_NUM];
char name[25];
};
struct TPacketGCItemUpdate {
uint8_t header; TItemPos Cell; uint32_t count;
int32_t alSockets[ITEM_SOCKET_SLOT_MAX_NUM];
TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_SLOT_MAX_NUM];
TPlayerItemAttribute randomAttr[GLOVE_ATTR_MAX_NUM];
char name[25];
};
struct TPacketGCItemDel {
uint8_t header;
uint8_t pos;
};
struct TPacketGCItemUse {
uint8_t header;
TItemPos Cell;
uint32_t ch_vid;
uint32_t victim_vid;
uint32_t vnum;
};
struct TPacketGCItemGroundAdd {
uint8_t bHeader;
int32_t lX;
int32_t lY;
int32_t lZ;
uint32_t dwVID;
uint32_t dwVnum;
int32_t alSockets[ITEM_SOCKET_SLOT_MAX_NUM];
TPlayerItemAttribute aAttrs[ITEM_ATTRIBUTE_SLOT_MAX_NUM];
uint16_t itemCount;
int32_t ownerTime;
};
struct TPacketGCItemGroundDel {
uint8_t header;
uint32_t vid;
};
struct TPacketGCItemOwnership {
uint8_t bHeader;
uint32_t dwVID;
char szName[CHARACTER_NAME_MAX_LEN + 1];
};
struct TPacketGCQuickSlotAdd {
uint8_t header;
uint8_t pos;
TQuickSlot slot;
};
struct TPacketGCQuickSlotDel {
uint8_t header;
uint8_t pos;
};
struct TPacketGCQuickSlotSwap {
uint8_t header;
uint8_t pos;
uint8_t change_pos;
};
struct TPacketGCCreateFly {
uint8_t bHeader;
uint8_t bType;
uint32_t dwStartVID;
uint32_t dwEndVID;
};
struct TPacketGCWarp {
uint8_t bHeader;
int32_t lX;
int32_t lY;
int32_t lAddr;
uint16_t wPort;
};
struct TPacketCGExchange {
uint8_t header;
uint8_t subheader;
int64_t arg1;
uint8_t arg2;
TItemPos Pos;
};
struct TPacketGCExchange {
uint8_t header;
uint8_t subheader;
uint8_t is_me;
int64_t arg1;
TItemPos arg2;
uint32_t arg3;
TItemPos arg4;
int32_t alValues[ITEM_SOCKET_SLOT_MAX_NUM];
TPlayerItemAttribute aAttr[ITEM_ATTRIBUTE_SLOT_MAX_NUM];
TPlayerItemAttribute randomAttr[GLOVE_ATTR_MAX_NUM];
char name[25];
};
struct TPacketCGSafeboxCheckin {
uint8_t header;
uint8_t bSafeBoxPos;
TItemPos ItemPos;
};
struct TPacketCGSafeboxCheckout {
uint8_t header;
uint8_t bSafeBoxPos;
TItemPos ItemPos;
};
struct TPacketCGSafeboxItemMove {
uint8_t header;
uint8_t bSourcePos;
uint8_t bTargetPos;
uint8_t bCount;
};
struct TPacketCGSafeboxMoney {
uint8_t header;
uint8_t bState;
uint32_t dwMoney;
};
struct TPacketGCSafeboxSize {
uint8_t bHeader;
uint8_t bSize;
};
struct TPacketGCSafeboxMoneyChange {
uint8_t bHeader;
uint32_t dwMoney;
};
struct TPacketGCSafeboxWrongPassword {
uint8_t bHeader;
};
#pragma pack(pop)
static_assert(sizeof(TPacketCGRefine) == 5, "TPacketCGRefine must match upstream");
static_assert(sizeof(TPacketCGItemUseToItem) == 7, "TPacketCGItemUseToItem must match upstream");
static_assert(sizeof(TPacketCGGiveItem) == 12, "TPacketCGGiveItem must match upstream");
static_assert(sizeof(TPacketCGScriptAnswer) == 2, "TPacketCGScriptAnswer must match upstream");
static_assert(sizeof(TPacketCGScriptButton) == 5, "TPacketCGScriptButton must match upstream");
} // namespace ava2
+257
View File
@@ -0,0 +1,257 @@
#include "PythonExchange.h"
#include <cstring>
#include <algorithm>
namespace ava2 {
CPythonExchange& CPythonExchange::Instance() {
static CPythonExchange s_instance;
return s_instance;
}
CPythonExchange::CPythonExchange() {
Clear();
m_isTrading = false;
m_elkMode = false;
}
void CPythonExchange::Clear() {
m_self = TradeData{};
m_victim = TradeData{};
for (size_t i = 0; i < EXCHANGE_ITEM_MAX_NUM; ++i) {
m_self.item_name[i] = "^";
m_victim.item_name[i] = "^";
}
}
void CPythonExchange::Start() {
m_isTrading = true;
}
void CPythonExchange::End() {
m_isTrading = false;
}
void CPythonExchange::SetSelfName(const char* name) {
if (!name) return;
std::strncpy(m_self.name, name, CHARACTER_NAME_MAX_LEN);
m_self.name[CHARACTER_NAME_MAX_LEN] = '\0';
}
void CPythonExchange::SetTargetName(const char* name) {
if (!name) return;
std::strncpy(m_victim.name, name, CHARACTER_NAME_MAX_LEN);
m_victim.name[CHARACTER_NAME_MAX_LEN] = '\0';
}
void CPythonExchange::SetItemToSelf(uint32_t pos, uint32_t vnum, uint32_t count) {
if (pos >= EXCHANGE_ITEM_MAX_NUM) return;
m_self.item_vnum[pos] = vnum;
m_self.item_count[pos] = count;
}
void CPythonExchange::SetItemToTarget(uint32_t pos, uint32_t vnum, uint32_t count) {
if (pos >= EXCHANGE_ITEM_MAX_NUM) return;
m_victim.item_vnum[pos] = vnum;
m_victim.item_count[pos] = count;
}
uint32_t CPythonExchange::GetItemVnumFromSelf(uint32_t pos) const {
if (pos >= EXCHANGE_ITEM_MAX_NUM) return 0;
return m_self.item_vnum[pos];
}
uint32_t CPythonExchange::GetItemVnumFromTarget(uint32_t pos) const {
if (pos >= EXCHANGE_ITEM_MAX_NUM) return 0;
return m_victim.item_vnum[pos];
}
uint32_t CPythonExchange::GetItemCountFromSelf(uint32_t pos) const {
if (pos >= EXCHANGE_ITEM_MAX_NUM) return 0;
return m_self.item_count[pos];
}
uint32_t CPythonExchange::GetItemCountFromTarget(uint32_t pos) const {
if (pos >= EXCHANGE_ITEM_MAX_NUM) return 0;
return m_victim.item_count[pos];
}
void CPythonExchange::SetItemMetinSocketToSelf(uint32_t pos, int socketPos, int32_t vnum) {
if (pos >= EXCHANGE_ITEM_MAX_NUM || socketPos < 0 || socketPos >= static_cast<int>(ITEM_SOCKET_SLOT_MAX_NUM)) return;
m_self.item_metin[pos][socketPos] = vnum;
}
void CPythonExchange::SetItemMetinSocketToTarget(uint32_t pos, int socketPos, int32_t vnum) {
if (pos >= EXCHANGE_ITEM_MAX_NUM || socketPos < 0 || socketPos >= static_cast<int>(ITEM_SOCKET_SLOT_MAX_NUM)) return;
m_victim.item_metin[pos][socketPos] = vnum;
}
int32_t CPythonExchange::GetItemMetinSocketFromSelf(uint32_t pos, int socketPos) const {
if (pos >= EXCHANGE_ITEM_MAX_NUM || socketPos < 0 || socketPos >= static_cast<int>(ITEM_SOCKET_SLOT_MAX_NUM)) return 0;
return m_self.item_metin[pos][socketPos];
}
int32_t CPythonExchange::GetItemMetinSocketFromTarget(uint32_t pos, int socketPos) const {
if (pos >= EXCHANGE_ITEM_MAX_NUM || socketPos < 0 || socketPos >= static_cast<int>(ITEM_SOCKET_SLOT_MAX_NUM)) return 0;
return m_victim.item_metin[pos][socketPos];
}
void CPythonExchange::SetItemAttributeToSelf(uint32_t pos, int attrPos, uint8_t type, int16_t val) {
if (pos >= EXCHANGE_ITEM_MAX_NUM || attrPos < 0 || attrPos >= static_cast<int>(ITEM_ATTRIBUTE_SLOT_MAX_NUM)) return;
m_self.item_attr[pos][attrPos].bType = type;
m_self.item_attr[pos][attrPos].sValue = val;
}
void CPythonExchange::SetItemAttributeToTarget(uint32_t pos, int attrPos, uint8_t type, int16_t val) {
if (pos >= EXCHANGE_ITEM_MAX_NUM || attrPos < 0 || attrPos >= static_cast<int>(ITEM_ATTRIBUTE_SLOT_MAX_NUM)) return;
m_victim.item_attr[pos][attrPos].bType = type;
m_victim.item_attr[pos][attrPos].sValue = val;
}
void CPythonExchange::GetItemAttributeFromSelf(uint32_t pos, int attrPos, uint8_t* pType, int16_t* pVal) const {
if (!pType || !pVal) return;
if (pos >= EXCHANGE_ITEM_MAX_NUM || attrPos < 0 || attrPos >= static_cast<int>(ITEM_ATTRIBUTE_SLOT_MAX_NUM)) {
*pType = 0; *pVal = 0; return;
}
*pType = m_self.item_attr[pos][attrPos].bType;
*pVal = m_self.item_attr[pos][attrPos].sValue;
}
void CPythonExchange::GetItemAttributeFromTarget(uint32_t pos, int attrPos, uint8_t* pType, int16_t* pVal) const {
if (!pType || !pVal) return;
if (pos >= EXCHANGE_ITEM_MAX_NUM || attrPos < 0 || attrPos >= static_cast<int>(ITEM_ATTRIBUTE_SLOT_MAX_NUM)) {
*pType = 0; *pVal = 0; return;
}
*pType = m_victim.item_attr[pos][attrPos].bType;
*pVal = m_victim.item_attr[pos][attrPos].sValue;
}
void CPythonExchange::SetItemRandomAttributeToSelf(uint32_t pos, int attrPos, uint8_t type, int16_t val) {
if (pos >= EXCHANGE_ITEM_MAX_NUM || attrPos < 0 || attrPos >= static_cast<int>(GLOVE_ATTR_MAX_NUM)) return;
m_self.item_random_attr[pos][attrPos].bType = type;
m_self.item_random_attr[pos][attrPos].sValue = val;
}
void CPythonExchange::SetItemRandomAttributeToTarget(uint32_t pos, int attrPos, uint8_t type, int16_t val) {
if (pos >= EXCHANGE_ITEM_MAX_NUM || attrPos < 0 || attrPos >= static_cast<int>(GLOVE_ATTR_MAX_NUM)) return;
m_victim.item_random_attr[pos][attrPos].bType = type;
m_victim.item_random_attr[pos][attrPos].sValue = val;
}
void CPythonExchange::GetItemRandomAttributeFromSelf(uint32_t pos, int attrPos, uint8_t* pType, int16_t* pVal) const {
if (!pType || !pVal) return;
if (pos >= EXCHANGE_ITEM_MAX_NUM || attrPos < 0 || attrPos >= static_cast<int>(GLOVE_ATTR_MAX_NUM)) {
*pType = 0; *pVal = 0; return;
}
*pType = m_self.item_random_attr[pos][attrPos].bType;
*pVal = m_self.item_random_attr[pos][attrPos].sValue;
}
void CPythonExchange::GetItemRandomAttributeFromTarget(uint32_t pos, int attrPos, uint8_t* pType, int16_t* pVal) const {
if (!pType || !pVal) return;
if (pos >= EXCHANGE_ITEM_MAX_NUM || attrPos < 0 || attrPos >= static_cast<int>(GLOVE_ATTR_MAX_NUM)) {
*pType = 0; *pVal = 0; return;
}
*pType = m_victim.item_random_attr[pos][attrPos].bType;
*pVal = m_victim.item_random_attr[pos][attrPos].sValue;
}
void CPythonExchange::DelItemOfSelf(uint32_t pos) {
if (pos >= EXCHANGE_ITEM_MAX_NUM) return;
m_self.item_vnum[pos] = 0;
m_self.item_count[pos] = 0;
}
void CPythonExchange::DelItemOfTarget(uint32_t pos) {
if (pos >= EXCHANGE_ITEM_MAX_NUM) return;
m_victim.item_vnum[pos] = 0;
m_victim.item_count[pos] = 0;
}
void CPythonExchange::SetItemNewName(uint32_t pos, const char* name, bool bSelf) {
if (pos >= EXCHANGE_ITEM_MAX_NUM) return;
if (bSelf) {
m_self.item_name[pos] = name ? name : "^";
} else {
m_victim.item_name[pos] = name ? name : "^";
}
}
const char* CPythonExchange::GetItemNewName(uint32_t pos, bool bSelf) const {
if (pos >= EXCHANGE_ITEM_MAX_NUM) return "^";
return bSelf ? m_self.item_name[pos].c_str() : m_victim.item_name[pos].c_str();
}
void CPythonExchange::SetItemElementToSelf(uint32_t pos, uint8_t grade, uint8_t typeBonus) {
if (pos >= EXCHANGE_ITEM_MAX_NUM) return;
m_self.item_grade_element[pos] = grade;
m_self.item_element_type_bonus[pos] = typeBonus;
}
void CPythonExchange::SetItemElementAttackToSelf(uint32_t pos, uint32_t idx, uint32_t atk) {
if (pos >= EXCHANGE_ITEM_MAX_NUM || idx >= MAX_ELEMENTS_SPELL) return;
m_self.item_attack_element[pos][idx] = atk;
}
void CPythonExchange::SetItemElementValueToSelf(uint32_t pos, uint32_t idx, int16_t val) {
if (pos >= EXCHANGE_ITEM_MAX_NUM || idx >= MAX_ELEMENTS_SPELL) return;
m_self.item_elements_value_bonus[pos][idx] = val;
}
uint8_t CPythonExchange::GetItemElementGradeFromSelf(uint32_t pos) const {
if (pos >= EXCHANGE_ITEM_MAX_NUM) return 0;
return m_self.item_grade_element[pos];
}
uint32_t CPythonExchange::GetItemElementAttackFromSelf(uint32_t pos, uint32_t idx) const {
if (pos >= EXCHANGE_ITEM_MAX_NUM || idx >= MAX_ELEMENTS_SPELL) return 0;
return m_self.item_attack_element[pos][idx];
}
uint8_t CPythonExchange::GetItemElementTypeFromSelf(uint32_t pos) const {
if (pos >= EXCHANGE_ITEM_MAX_NUM) return 0;
return m_self.item_element_type_bonus[pos];
}
int16_t CPythonExchange::GetItemElementValueFromSelf(uint32_t pos, uint32_t idx) const {
if (pos >= EXCHANGE_ITEM_MAX_NUM || idx >= MAX_ELEMENTS_SPELL) return 0;
return m_self.item_elements_value_bonus[pos][idx];
}
void CPythonExchange::SetItemElementToTarget(uint32_t pos, uint8_t grade, uint8_t typeBonus) {
if (pos >= EXCHANGE_ITEM_MAX_NUM) return;
m_victim.item_grade_element[pos] = grade;
m_victim.item_element_type_bonus[pos] = typeBonus;
}
void CPythonExchange::SetItemElementAttackToTarget(uint32_t pos, uint32_t idx, uint32_t atk) {
if (pos >= EXCHANGE_ITEM_MAX_NUM || idx >= MAX_ELEMENTS_SPELL) return;
m_victim.item_attack_element[pos][idx] = atk;
}
void CPythonExchange::SetItemElementValueToTarget(uint32_t pos, uint32_t idx, int16_t val) {
if (pos >= EXCHANGE_ITEM_MAX_NUM || idx >= MAX_ELEMENTS_SPELL) return;
m_victim.item_elements_value_bonus[pos][idx] = val;
}
uint8_t CPythonExchange::GetItemElementGradeFromTarget(uint32_t pos) const {
if (pos >= EXCHANGE_ITEM_MAX_NUM) return 0;
return m_victim.item_grade_element[pos];
}
uint32_t CPythonExchange::GetItemElementAttackFromTarget(uint32_t pos, uint32_t idx) const {
if (pos >= EXCHANGE_ITEM_MAX_NUM || idx >= MAX_ELEMENTS_SPELL) return 0;
return m_victim.item_attack_element[pos][idx];
}
uint8_t CPythonExchange::GetItemElementTypeFromTarget(uint32_t pos) const {
if (pos >= EXCHANGE_ITEM_MAX_NUM) return 0;
return m_victim.item_element_type_bonus[pos];
}
int16_t CPythonExchange::GetItemElementValueFromTarget(uint32_t pos, uint32_t idx) const {
if (pos >= EXCHANGE_ITEM_MAX_NUM || idx >= MAX_ELEMENTS_SPELL) return 0;
return m_victim.item_elements_value_bonus[pos][idx];
}
} // namespace ava2
+125
View File
@@ -0,0 +1,125 @@
#pragma once
#include "Packet.h"
#include <string>
#include <vector>
#include <cstring>
namespace ava2 {
/**
* CPythonExchange:
* Cross-platform reproduction of Metin2 / AVA2 CPythonExchange singleton.
* Manages peer-to-peer trade state machine (both player's and partner's offer slots,
* gold, accept confirmation, socket stones, and attribute sets).
*/
class CPythonExchange {
public:
static constexpr size_t EXCHANGE_ITEM_MAX_NUM = 12;
struct TradeData {
char name[CHARACTER_NAME_MAX_LEN + 1] = {0};
uint32_t level = 0;
uint32_t item_vnum[EXCHANGE_ITEM_MAX_NUM] = {0};
uint32_t item_count[EXCHANGE_ITEM_MAX_NUM] = {0};
int32_t item_metin[EXCHANGE_ITEM_MAX_NUM][ITEM_SOCKET_SLOT_MAX_NUM] = {{0}};
TPlayerItemAttribute item_attr[EXCHANGE_ITEM_MAX_NUM][ITEM_ATTRIBUTE_SLOT_MAX_NUM] = {};
TPlayerItemAttribute item_random_attr[EXCHANGE_ITEM_MAX_NUM][GLOVE_ATTR_MAX_NUM] = {};
std::string item_name[EXCHANGE_ITEM_MAX_NUM];
uint8_t accept = 0;
int64_t elk = 0;
uint8_t item_grade_element[EXCHANGE_ITEM_MAX_NUM] = {0};
uint32_t item_attack_element[EXCHANGE_ITEM_MAX_NUM][MAX_ELEMENTS_SPELL] = {{0}};
uint8_t item_element_type_bonus[EXCHANGE_ITEM_MAX_NUM] = {0};
int16_t item_elements_value_bonus[EXCHANGE_ITEM_MAX_NUM][MAX_ELEMENTS_SPELL] = {{0}};
};
static CPythonExchange& Instance();
CPythonExchange();
~CPythonExchange() = default;
void Clear();
void Start();
void End();
bool isTrading() const { return m_isTrading; }
void SetSelfName(const char* name);
void SetTargetName(const char* name);
const char* GetNameFromSelf() const { return m_self.name; }
const char* GetNameFromTarget() const { return m_victim.name; }
void SetSelfLevel(uint32_t level) { m_self.level = level; }
void SetTargetLevel(uint32_t level) { m_victim.level = level; }
uint32_t GetLevelFromSelf() const { return m_self.level; }
uint32_t GetLevelFromTarget() const { return m_victim.level; }
void SetElkToSelf(int64_t elk) { m_self.elk = elk; }
void SetElkToTarget(int64_t elk) { m_victim.elk = elk; }
int64_t GetElkFromSelf() const { return m_self.elk; }
int64_t GetElkFromTarget() const { return m_victim.elk; }
void SetItemToSelf(uint32_t pos, uint32_t vnum, uint32_t count);
void SetItemToTarget(uint32_t pos, uint32_t vnum, uint32_t count);
uint32_t GetItemVnumFromSelf(uint32_t pos) const;
uint32_t GetItemVnumFromTarget(uint32_t pos) const;
uint32_t GetItemCountFromSelf(uint32_t pos) const;
uint32_t GetItemCountFromTarget(uint32_t pos) const;
void SetItemMetinSocketToSelf(uint32_t pos, int socketPos, int32_t vnum);
void SetItemMetinSocketToTarget(uint32_t pos, int socketPos, int32_t vnum);
int32_t GetItemMetinSocketFromSelf(uint32_t pos, int socketPos) const;
int32_t GetItemMetinSocketFromTarget(uint32_t pos, int socketPos) const;
void SetItemAttributeToSelf(uint32_t pos, int attrPos, uint8_t type, int16_t val);
void SetItemAttributeToTarget(uint32_t pos, int attrPos, uint8_t type, int16_t val);
void GetItemAttributeFromSelf(uint32_t pos, int attrPos, uint8_t* pType, int16_t* pVal) const;
void GetItemAttributeFromTarget(uint32_t pos, int attrPos, uint8_t* pType, int16_t* pVal) const;
void SetItemRandomAttributeToSelf(uint32_t pos, int attrPos, uint8_t type, int16_t val);
void SetItemRandomAttributeToTarget(uint32_t pos, int attrPos, uint8_t type, int16_t val);
void GetItemRandomAttributeFromSelf(uint32_t pos, int attrPos, uint8_t* pType, int16_t* pVal) const;
void GetItemRandomAttributeFromTarget(uint32_t pos, int attrPos, uint8_t* pType, int16_t* pVal) const;
void DelItemOfSelf(uint32_t pos);
void DelItemOfTarget(uint32_t pos);
void SetAcceptToSelf(uint8_t accept) { m_self.accept = accept ? 1 : 0; }
void SetAcceptToTarget(uint8_t accept) { m_victim.accept = accept ? 1 : 0; }
bool GetAcceptFromSelf() const { return m_self.accept != 0; }
bool GetAcceptFromTarget() const { return m_victim.accept != 0; }
bool GetElkMode() const { return m_elkMode; }
void SetElkMode(bool mode) { m_elkMode = mode; }
void SetItemNewName(uint32_t pos, const char* name, bool bSelf);
const char* GetItemNewName(uint32_t pos, bool bSelf) const;
// Element attributes
void SetItemElementToSelf(uint32_t pos, uint8_t grade, uint8_t typeBonus);
void SetItemElementAttackToSelf(uint32_t pos, uint32_t idx, uint32_t atk);
void SetItemElementValueToSelf(uint32_t pos, uint32_t idx, int16_t val);
uint8_t GetItemElementGradeFromSelf(uint32_t pos) const;
uint32_t GetItemElementAttackFromSelf(uint32_t pos, uint32_t idx) const;
uint8_t GetItemElementTypeFromSelf(uint32_t pos) const;
int16_t GetItemElementValueFromSelf(uint32_t pos, uint32_t idx) const;
void SetItemElementToTarget(uint32_t pos, uint8_t grade, uint8_t typeBonus);
void SetItemElementAttackToTarget(uint32_t pos, uint32_t idx, uint32_t atk);
void SetItemElementValueToTarget(uint32_t pos, uint32_t idx, int16_t val);
uint8_t GetItemElementGradeFromTarget(uint32_t pos) const;
uint32_t GetItemElementAttackFromTarget(uint32_t pos, uint32_t idx) const;
uint8_t GetItemElementTypeFromTarget(uint32_t pos) const;
int16_t GetItemElementValueFromTarget(uint32_t pos, uint32_t idx) const;
const TradeData& GetSelfData() const { return m_self; }
const TradeData& GetTargetData() const { return m_victim; }
private:
bool m_isTrading = false;
bool m_elkMode = false;
TradeData m_self;
TradeData m_victim;
};
} // namespace ava2
File diff suppressed because it is too large Load Diff
+214
View File
@@ -0,0 +1,214 @@
#pragma once
#include "Packet.h"
#include "NetworkActorManager.h"
#include <Python.h>
#include <cstdint>
#include <string>
#include <vector>
#include <deque>
#include <memory>
#include <functional>
namespace ava2 {
/**
* PythonNetworkStream:
* Partial AVA2 game-phase packet model and dispatch bridge.
* Encrypted socket integration covers supported packets; full Windows parity remains pending:
* - Phase transitions (PHASE_LOGIN, PHASE_SELECT, PHASE_LOADING, PHASE_GAME)
* - Wire packet parser with fixed & dynamic length packet dispatching
* - Full GamePhase() processor for entity updates, combat, inventory, chat, and skills
* - Integration with Python callbacks, TextTailManager, SoundManager, EffectManager, FlyingManager
*/
class PythonNetworkStream {
public:
static PythonNetworkStream& Instance();
PythonNetworkStream();
~PythonNetworkStream();
// ── Phase Management ──
void SetPhaseWindow(int phase, PyObject* poWindow);
void ClearPhaseWindow(int phase, PyObject* poWindow);
void SetHandler(PyObject* poHandler);
void SetPhase(EPhase phase);
EPhase GetPhase() const { return m_phase; }
bool IsGamePhase() const { return m_phase == PHASE_GAME; }
void StartGame();
void ResetConnection();
void SetClientFilename(std::string name) { m_clientFilename=std::move(name); }
// ── Main Actor Attributes ──
void SetMainActorVID(uint32_t vid);
uint32_t GetMainActorVID() const { return m_dwMainActorVID; }
uint16_t GetMainActorRace() const { return m_wMainActorRace; }
uint8_t GetMainActorEmpire() const { return m_byMainActorEmpire; }
uint8_t GetMainActorSkillGroup() const { return m_byMainActorSkillGroup; }
const std::string& GetMainActorName() const { return m_strMainActorName; }
const std::string& GetFieldMusicFileName() const { return m_strFieldMusicFileName; }
float GetFieldMusicVolume() const { return m_fFieldMusicVolume; }
// ── Wire Ingestion & Dispatch ──
void PushRecvData(const uint8_t* data, size_t len);
void PushRecvData(const std::vector<uint8_t>& bytes);
bool ProcessRecvData();
// ── Client-to-Server Sending API ──
bool SendEnterGamePacket();
bool SendShopPacket(uint8_t operation,uint8_t window=0,uint8_t slot=0,uint32_t count=0);
bool SendOfflineShopPacket(bool buy,uint32_t owner=0,uint8_t position=0);
bool SendOfflineShopManagement(uint8_t operation,uint8_t position=0,uint32_t owner=0);
bool SendQuickSlotAddPacket(uint8_t index,uint8_t type,uint8_t pos);
bool SendQuickSlotDelPacket(uint8_t index);
bool SendQuickSlotMovePacket(uint8_t source,uint8_t target);
bool SendCharacterMovePacket(uint8_t func, uint8_t arg, uint8_t rot, int32_t x, int32_t y, uint32_t time);
bool SendAttackPacket(uint8_t type, uint32_t victimVID);
bool SendChatPacket(const std::string& text, uint8_t type = CHAT_TYPE_TALKING);
bool SendWhisperPacket(const std::string& name, const std::string& text);
bool SendItemUsePacket(uint8_t window, uint16_t cell);
bool SendItemMovePacket(uint8_t srcWindow, uint16_t srcCell, uint8_t dstWindow, uint16_t dstCell, uint32_t count);
bool SendItemPickUpPacket(uint32_t vid);
bool SendItemDropPacket(uint8_t window, uint16_t cell, uint32_t gold);
bool SendItemDropPacketNew(uint8_t window,uint16_t cell,uint32_t gold,uint32_t count);
bool SendOnClickPacket(uint32_t vid);
bool SendFlyTargetingPacket(uint32_t targetVID, int32_t x, int32_t y);
bool SendWarpPacket();
// ── Exchange Protocol ──
bool SendExchangeStartPacket(uint32_t vid);
bool SendExchangeItemAddPacket(uint8_t window, uint16_t cell, uint8_t exchangePos);
bool SendExchangeItemDelPacket(uint8_t exchangePos);
bool SendExchangeElkAddPacket(int64_t elk);
bool SendExchangeAcceptPacket();
bool SendExchangeExitPacket();
// ── SafeBox & Mall Protocol ──
bool SendSafeBoxCheckinPacket(uint8_t window, uint16_t cell, uint8_t safeboxPos);
bool SendSafeBoxCheckoutPacket(uint8_t safeboxPos, uint8_t window, uint16_t cell);
bool SendSafeBoxItemMovePacket(uint8_t srcPos, uint8_t dstPos, uint8_t count);
bool SendSafeBoxMoneyPacket(uint8_t state, uint32_t money);
bool SendMallCheckoutPacket(uint8_t safeboxPos, uint8_t window, uint16_t cell);
// ── Refine & Quest Protocol ──
bool SendRefinePacket(uint8_t targetItemPos, uint8_t type, uint8_t specialStorage = 0, int32_t indexSelect = -1);
bool SendItemUseToItemPacket(uint16_t srcCell, uint16_t dstCell);
bool SendGiveItemPacket(uint32_t targetVID, uint8_t window, uint16_t cell, uint32_t count);
bool SendScriptAnswerPacket(int answer);
bool SendScriptButtonPacket(int button);
// Raw outgoing bytes for network transport / unit test inspection
const std::vector<uint8_t>& GetSendQueue() const { return m_sendBuffer; }
std::vector<uint8_t> PopSendBytes();
void ClearSendQueue() { m_sendBuffer.clear();m_sendPackets.clear(); }
std::vector<std::vector<uint8_t>> PopSendPackets();
// Callback when damage occurs
using DamageCallback = std::function<void(uint32_t vid, int damage, uint8_t flag)>;
void SetDamageCallback(DamageCallback cb) { m_damageCallback = cb; }
// Callback when chat is received
using ChatCallback = std::function<void(uint8_t type, const std::string& text, uint32_t vid)>;
void SetChatCallback(ChatCallback cb) { m_chatCallback = cb; }
// Callback when whisper is received
using WhisperCallback = std::function<void(uint8_t type, const std::string& from, const std::string& text)>;
void SetWhisperCallback(WhisperCallback cb) { m_whisperCallback = cb; }
// Callback when ground item is added/deleted
using GroundItemCallback = std::function<void(uint32_t vid, uint32_t vnum, int32_t x, int32_t y, int32_t z, bool isAdd)>;
void SetGroundItemCallback(GroundItemCallback cb) { m_groundItemCallback = cb; }
// Callback when fly projectile is created
using FlyCallback = std::function<void(uint8_t flyType, uint32_t startVID, uint32_t endVID)>;
void SetFlyCallback(FlyCallback cb) { m_flyCallback = cb; }
private:
bool DispatchGamePhasePacket(uint8_t header);
// Handlers matching CPythonNetworkStreamPhaseGame
bool RecvPhasePacket();
bool RecvMainCharacter();
bool RecvMainCharacter2Empire();
bool RecvMainCharacter3BGM();
bool RecvMainCharacter4BGMVolume();
bool RecvTimePacket();
bool RecvPlayerPoints();
bool RecvAffectAddPacket();
bool RecvAffectRemovePacket();
bool RecvSkillLevel();
bool RecvSkillLevelNew();
void MainCharacterLoaded(int32_t x,int32_t y,int32_t z);
bool RecvCharacterAppendPacket();
bool RecvCharacterAdditionalInfo();
bool RecvCharacterAppendPacketNew();
bool RecvCharacterUpdatePacketNew();
bool RecvCharacterUpdatePacket();
bool RecvCharacterDeletePacket();
bool RecvCharacterMovePacket();
bool RecvSyncPositionPacket();
bool RecvChatPacket();
bool RecvWhisperPacket();
bool RecvDamageInfoPacket();
bool RecvStunPacket();
bool RecvDeadPacket();
bool RecvPointChange();
bool m_refreshSkill=false;
bool m_startGameRequested=false;
std::string m_clientFilename="ava2_client";
std::vector<std::vector<uint8_t>> m_sendPackets;
bool m_refreshInventory=false,m_refreshStatus=false;
bool RecvItemSetPacket();
bool RecvItemSetPacket2();
bool RecvItemUpdatePacket();
bool RecvItemUsePacket();
bool RecvItemGroundAddPacket();
bool RecvItemGroundDelPacket();
bool RecvItemOwnership();
bool RecvQuickSlotAddPacket();
bool RecvQuickSlotDelPacket();
bool RecvQuickSlotMovePacket();
bool RecvCreateFlyPacket();
bool RecvWarpPacket();
bool RecvExchangePacket();
bool RecvShopPacket();
bool RecvSafeBoxSetPacket();
bool RecvSafeBoxDelPacket();
bool RecvSafeBoxWrongPasswordPacket();
bool RecvSafeBoxSizePacket();
bool RecvSafeBoxMoneyChangePacket();
bool RecvMallOpenPacket();
bool RecvMallSetPacket();
bool RecvMallDelPacket();
bool Peek(size_t size, void* outBuf);
bool Read(size_t size, void* outBuf);
void Send(const void* data, size_t size);
private:
EPhase m_phase = PHASE_OFFLINE;
PyObject* m_poHandler = nullptr;
PyObject* m_phaseWindows[7] = {nullptr};
uint32_t m_dwMainActorVID = 0;
uint16_t m_wMainActorRace = 0;
uint8_t m_byMainActorEmpire = 0;
uint8_t m_byMainActorSkillGroup = 0;
std::string m_strMainActorName;
std::string m_strFieldMusicFileName;
float m_fFieldMusicVolume = 0.02f;
std::vector<uint8_t> m_recvBuffer;
std::vector<uint8_t> m_sendBuffer;
// Temporary pending actor data when CharacterAdd arrives before CharacterAdditionalInfo
SNetworkActorData m_pendingActorData;
DamageCallback m_damageCallback;
ChatCallback m_chatCallback;
WhisperCallback m_whisperCallback;
GroundItemCallback m_groundItemCallback;
FlyCallback m_flyCallback;
};
} // namespace ava2
+86
View File
@@ -0,0 +1,86 @@
#include "PythonSafeBox.h"
#include <cstring>
namespace ava2 {
CPythonSafeBox& CPythonSafeBox::Instance() {
static CPythonSafeBox s_instance;
return s_instance;
}
CPythonSafeBox::CPythonSafeBox() {
m_dwMoney = 0;
}
void CPythonSafeBox::OpenSafeBox(int iSize) {
m_dwMoney = 0;
m_itemInstanceVector.clear();
if (iSize > 0) {
m_itemInstanceVector.resize(SAFEBOX_PAGE_SIZE * iSize);
}
}
void CPythonSafeBox::SetItemData(uint32_t dwSlotIndex, const TItemData& rItemData) {
if (dwSlotIndex >= m_itemInstanceVector.size()) return;
m_itemInstanceVector[dwSlotIndex] = rItemData;
}
void CPythonSafeBox::DelItemData(uint32_t dwSlotIndex) {
if (dwSlotIndex >= m_itemInstanceVector.size()) return;
m_itemInstanceVector[dwSlotIndex] = TItemData{};
}
bool CPythonSafeBox::GetSlotItemID(uint32_t dwSlotIndex, uint32_t* pdwItemID) const {
if (!pdwItemID || dwSlotIndex >= m_itemInstanceVector.size()) return false;
*pdwItemID = m_itemInstanceVector[dwSlotIndex].vnum;
return true;
}
bool CPythonSafeBox::GetItemDataPtr(uint32_t dwSlotIndex, const TItemData** ppInstance) const {
if (!ppInstance || dwSlotIndex >= m_itemInstanceVector.size()) return false;
*ppInstance = &m_itemInstanceVector[dwSlotIndex];
return true;
}
bool CPythonSafeBox::GetItemDataPtr(uint32_t dwSlotIndex, TItemData** ppInstance) {
if (!ppInstance || dwSlotIndex >= m_itemInstanceVector.size()) return false;
*ppInstance = &m_itemInstanceVector[dwSlotIndex];
return true;
}
void CPythonSafeBox::OpenMall(int iSize) {
m_mallItemInstanceVector.clear();
if (iSize > 0) {
m_mallItemInstanceVector.resize(SAFEBOX_PAGE_SIZE * iSize);
}
}
void CPythonSafeBox::SetMallItemData(uint32_t dwSlotIndex, const TItemData& rItemData) {
if (dwSlotIndex >= m_mallItemInstanceVector.size()) return;
m_mallItemInstanceVector[dwSlotIndex] = rItemData;
}
void CPythonSafeBox::DelMallItemData(uint32_t dwSlotIndex) {
if (dwSlotIndex >= m_mallItemInstanceVector.size()) return;
m_mallItemInstanceVector[dwSlotIndex] = TItemData{};
}
bool CPythonSafeBox::GetMallItemDataPtr(uint32_t dwSlotIndex, const TItemData** ppInstance) const {
if (!ppInstance || dwSlotIndex >= m_mallItemInstanceVector.size()) return false;
*ppInstance = &m_mallItemInstanceVector[dwSlotIndex];
return true;
}
bool CPythonSafeBox::GetMallItemDataPtr(uint32_t dwSlotIndex, TItemData** ppInstance) {
if (!ppInstance || dwSlotIndex >= m_mallItemInstanceVector.size()) return false;
*ppInstance = &m_mallItemInstanceVector[dwSlotIndex];
return true;
}
bool CPythonSafeBox::GetSlotMallItemID(uint32_t dwSlotIndex, uint32_t* pdwItemID) const {
if (!pdwItemID || dwSlotIndex >= m_mallItemInstanceVector.size()) return false;
*pdwItemID = m_mallItemInstanceVector[dwSlotIndex].vnum;
return true;
}
} // namespace ava2
+53
View File
@@ -0,0 +1,53 @@
#pragma once
#include "Packet.h"
#include <vector>
namespace ava2 {
/**
* CPythonSafeBox:
* 1:1 cross-platform reproduction of Metin2 / AVA2 CPythonSafeBox singleton.
* Manages player personal storeroom (Safebox) and Item Mall stash slots,
* gold deposits, and item slot queries.
*/
class CPythonSafeBox {
public:
static constexpr size_t SAFEBOX_SLOT_X_COUNT = 5;
static constexpr size_t SAFEBOX_SLOT_Y_COUNT = 9;
static constexpr size_t SAFEBOX_PAGE_SIZE = SAFEBOX_SLOT_X_COUNT * SAFEBOX_SLOT_Y_COUNT;
static CPythonSafeBox& Instance();
CPythonSafeBox();
~CPythonSafeBox() = default;
// Safebox (Personal Bank/Warehouse)
void OpenSafeBox(int iSize);
void SetItemData(uint32_t dwSlotIndex, const TItemData& rItemData);
void DelItemData(uint32_t dwSlotIndex);
void SetMoney(uint32_t dwMoney) { m_dwMoney = dwMoney; }
uint32_t GetMoney() const { return m_dwMoney; }
bool GetSlotItemID(uint32_t dwSlotIndex, uint32_t* pdwItemID) const;
int GetCurrentSafeBoxSize() const { return static_cast<int>(m_itemInstanceVector.size()); }
bool GetItemDataPtr(uint32_t dwSlotIndex, const TItemData** ppInstance) const;
bool GetItemDataPtr(uint32_t dwSlotIndex, TItemData** ppInstance);
// Item Mall Warehouse
void OpenMall(int iSize);
void SetMallItemData(uint32_t dwSlotIndex, const TItemData& rItemData);
void DelMallItemData(uint32_t dwSlotIndex);
bool GetMallItemDataPtr(uint32_t dwSlotIndex, const TItemData** ppInstance) const;
bool GetMallItemDataPtr(uint32_t dwSlotIndex, TItemData** ppInstance);
bool GetSlotMallItemID(uint32_t dwSlotIndex, uint32_t* pdwItemID) const;
uint32_t GetMallSize() const { return static_cast<uint32_t>(m_mallItemInstanceVector.size()); }
private:
std::vector<TItemData> m_itemInstanceVector;
std::vector<TItemData> m_mallItemInstanceVector;
uint32_t m_dwMoney = 0;
};
} // namespace ava2
+564
View File
@@ -0,0 +1,564 @@
#include "ActorInstance.h"
#include "MapObjectManager.h"
#include "CRenderTarget.h"
#include <filesystem>
#include <cmath>
#include <algorithm>
#include <iostream>
namespace ava2 {
constexpr float DEG_TO_RAD = 3.14159265358979323846f / 180.0f;
constexpr float RAD_TO_DEG = 180.0f / 3.14159265358979323846f;
ActorInstance::ActorInstance() = default;
std::string ActorInstance::ResolvePath(const std::string& path) const {
std::string clean = path;
if (clean.rfind("d:/", 0) == 0 || clean.rfind("D:/", 0) == 0) {
clean = clean.substr(3);
}
if (std::filesystem::exists(clean)) return clean;
if (std::filesystem::exists("build/dev/" + clean)) return "build/dev/" + clean;
if (std::filesystem::exists("../" + clean)) return "../" + clean;
return clean;
}
bool ActorInstance::SetModel(const std::string& modelPath) {
std::string resolved = ResolvePath(modelPath);
if (!std::filesystem::exists(resolved)) {
std::cerr << "ActorInstance::SetModel file not found: " << modelPath << std::endl;
return false;
}
m_model = Gr2ModelInstance::Load(resolved);
if (!m_model) return false;
m_modelPath = modelPath;
return true;
}
bool ActorInstance::SetWeapon(const std::string& weaponPath, const std::string& boneName) {
if (!m_model) return false;
std::string resolved = ResolvePath(weaponPath);
if (!std::filesystem::exists(resolved)) return false;
auto weaponModel = Gr2ModelInstance::Load(resolved);
if (!weaponModel) {
std::string fallback = ResolvePath("ymir work/item/weapon/set_11_sword.gr2");
if (std::filesystem::exists(fallback)) {
weaponModel = Gr2ModelInstance::Load(fallback);
}
}
if (!weaponModel) return false;
m_model->AttachModel(boneName, std::move(weaponModel));
return true;
}
bool ActorInstance::AttachPart(const std::string& partPath) {
if (!m_model) return false;
std::string resolved = ResolvePath(partPath);
if (!std::filesystem::exists(resolved)) return false;
auto partModel = Gr2ModelInstance::Load(resolved);
if (!partModel) return false;
m_model->AttachPart(std::move(partModel));
return true;
}
void ActorInstance::RegisterMotion(MotionType type, const std::string& motionGr2Path) {
m_motionPaths[type] = motionGr2Path;
}
bool ActorInstance::PlayMotion(MotionType type, bool loop) {
if (!m_model) return false;
auto it = m_motionPaths.find(type);
if (it == m_motionPaths.end()) {
// Fallback: If combo attack not found, try generic attack
if (type == MotionType::ComboAttack1 || type == MotionType::ComboAttack2 || type == MotionType::ComboAttack3) {
it = m_motionPaths.find(MotionType::Attack);
}
}
if (it == m_motionPaths.end()) return false;
std::string resolved = ResolvePath(it->second);
if (!std::filesystem::exists(resolved)) return false;
bool loaded = m_model->LoadExternalAnimation(resolved);
if (!loaded) return false;
m_currentMotion = type;
m_animTime = 0.0f;
m_motionDuration = std::max(0.1f, m_model->GetAnimationDuration());
m_loopMotion = loop;
if (type == MotionType::Attack || type == MotionType::ComboAttack1 ||
type == MotionType::ComboAttack2 || type == MotionType::ComboAttack3 ||
type == MotionType::Skill1 || type == MotionType::Skill2 ||
type == MotionType::Skill3 || type == MotionType::Skill4 ||
type == MotionType::Skill5) {
m_isAttacking = true;
} else {
m_isAttacking = false;
}
return true;
}
bool ActorInstance::IsMotionFinished() const {
if (m_loopMotion) return false;
return m_animTime >= m_motionDuration;
}
void ActorInstance::MoveInDirection(float moveYaw, float dt, const TerrainHeightmap* terrain, const MapObjectManager* mapObjects) {
if (dt <= 0.0f) return;
float rad = moveYaw * DEG_TO_RAD;
m_yaw = moveYaw;
float dx = std::sin(rad) * m_moveSpeed * dt;
float dz = std::cos(rad) * m_moveSpeed * dt;
auto isBlocked = [&](float testX, float testZ) -> bool {
if (terrain && terrain->HasAttrMap() && terrain->IsAttrOn(testX, testZ, TerrainHeightmap::ATTR_FLAG_BLOCK)) {
return true;
}
if (mapObjects && mapObjects->CheckCollision(testX, testZ, 30.0f)) {
return true;
}
return false;
};
float nextX = m_posX + dx;
float nextZ = m_posZ + dz;
if (!isBlocked(nextX, nextZ)) {
m_posX = nextX;
m_posZ = nextZ;
} else {
// Wall sliding: attempt to slide along X axis only
if (!isBlocked(nextX, m_posZ)) {
m_posX = nextX;
} else if (!isBlocked(m_posX, nextZ)) {
// Attempt to slide along Z axis only
m_posZ = nextZ;
} else {
// Check building collision normal for sliding: v' = v - (v . n) * n
float nx = 0.0f, nz = 0.0f;
if (mapObjects && mapObjects->CheckCollisionNormal(nextX, nextZ, 30.0f, nx, nz)) {
float dot = dx * nx + dz * nz;
float slideX = dx - dot * nx;
float slideZ = dz - dot * nz;
if (!isBlocked(m_posX + slideX, m_posZ + slideZ)) {
m_posX += slideX;
m_posZ += slideZ;
}
} else if (m_hasMoveTarget) {
ClearMoveTarget();
StopMoving();
}
}
}
if (terrain) {
m_posY = terrain->GetHeightAtWorld(m_posX, m_posZ);
}
if (!m_isAttacking && m_currentMotion != MotionType::Run) {
PlayMotion(MotionType::Run, true);
}
}
void ActorInstance::StopMoving() {
if (!m_isAttacking && m_currentMotion == MotionType::Run) {
PlayMotion(MotionType::Wait, true);
}
}
void ActorInstance::Update(float dt, const TerrainHeightmap* terrain, const MapObjectManager* mapObjects) {
if (dt <= 0.0f) return;
// 0. Click-to-Move destination pathing (aligned with 40250 CPythonPlayer)
if (m_hasMoveTarget && !m_isAttacking && m_curHP > 0) {
float dx = m_targetX - m_posX;
float dz = m_targetZ - m_posZ;
float dist = std::sqrt(dx * dx + dz * dz);
float step = m_moveSpeed * dt;
if (dist <= 15.0f || dist <= step) {
bool blocked = false;
if (terrain && terrain->HasAttrMap() && terrain->IsAttrOn(m_targetX, m_targetZ, TerrainHeightmap::ATTR_FLAG_BLOCK)) blocked = true;
if (mapObjects && mapObjects->CheckCollision(m_targetX, m_targetZ, 30.0f)) blocked = true;
if (!blocked) {
m_posX = m_targetX;
m_posZ = m_targetZ;
}
if (terrain) m_posY = terrain->GetHeightAtWorld(m_posX, m_posZ);
StopMoving();
m_hasMoveTarget = false;
} else {
float moveYaw = std::atan2(dx, dz) * RAD_TO_DEG;
MoveInDirection(moveYaw, dt, terrain, mapObjects);
}
}
// Apply knockback impulse
if (std::abs(m_knockbackVx) > 0.01f || std::abs(m_knockbackVz) > 0.01f) {
float nextX = m_posX + m_knockbackVx * dt;
float nextZ = m_posZ + m_knockbackVz * dt;
if (!terrain || !terrain->HasAttrMap() || !terrain->IsAttrOn(nextX, nextZ, TerrainHeightmap::ATTR_FLAG_BLOCK)) {
m_posX = nextX;
m_posZ = nextZ;
} else {
m_knockbackVx = 0.0f;
m_knockbackVz = 0.0f;
}
m_knockbackVx *= std::max(0.0f, 1.0f - 8.0f * dt);
m_knockbackVz *= std::max(0.0f, 1.0f - 8.0f * dt);
}
// Clamp Y to terrain height
if (terrain) {
m_posY = terrain->GetHeightAtWorld(m_posX, m_posZ);
}
// Update active buffs
for (auto it = m_buffs.begin(); it != m_buffs.end(); ) {
it->second -= dt;
if (it->second <= 0.0f) {
if (it->first == "berserk") {
m_moveSpeed = 350.0f;
}
it = m_buffs.erase(it);
} else {
++it;
}
}
// Advance animation time
m_animTime += dt;
if (m_loopMotion) {
if (m_motionDuration > 0.001f && m_animTime >= m_motionDuration) {
m_animTime = std::fmod(m_animTime, m_motionDuration);
}
} else {
if (m_animTime >= m_motionDuration) {
m_isAttacking = false;
// On one-shot finish (e.g. attack or hit), return to wait or dead
if (m_curHP <= 0) {
// Keep dead pose or freeze at end of dead motion
m_animTime = m_motionDuration - 0.01f;
} else {
PlayMotion(MotionType::Wait, true);
}
}
}
}
bool ActorInstance::Attack() {
if (m_curHP <= 0) return false;
if (!m_isAttacking) {
m_comboIndex = 1;
if (!PlayMotion(MotionType::ComboAttack1, false)) {
PlayMotion(MotionType::Attack, false);
}
return true;
} else if (m_animTime > m_motionDuration * 0.35f) {
// Advance combo chain
m_comboIndex = (m_comboIndex % 3) + 1;
MotionType next = MotionType::ComboAttack1;
if (m_comboIndex == 2) next = MotionType::ComboAttack2;
else if (m_comboIndex == 3) next = MotionType::ComboAttack3;
if (!PlayMotion(next, false)) {
PlayMotion(MotionType::Attack, false);
}
return true;
}
return false;
}
bool ActorInstance::CastSkill(MotionType skillMotion) {
if (m_curHP <= 0) return false;
ClearMoveTarget();
StopMoving();
m_isAttacking = true;
m_animTime = 0.0f;
return PlayMotion(skillMotion, false);
}
void ActorInstance::SetBuff(const std::string& buffName, float duration) {
m_buffs[buffName] = duration;
if (buffName == "berserk") {
m_moveSpeed = 440.0f;
}
}
bool ActorInstance::HasBuff(const std::string& buffName) const {
auto it = m_buffs.find(buffName);
return it != m_buffs.end() && it->second > 0.0f;
}
float ActorInstance::GetBuffRemaining(const std::string& buffName) const {
auto it = m_buffs.find(buffName);
return (it != m_buffs.end()) ? it->second : 0.0f;
}
float ActorInstance::GetAttackMultiplier() const {
float mult = 1.0f;
if (HasBuff("berserk")) mult += 0.40f;
return mult;
}
int ActorInstance::GetBonusAttackDamage() const {
int bonus = 0;
if (HasBuff("aura")) bonus += 120;
return bonus;
}
void ActorInstance::Die() {
m_curHP = 0;
StopMoving();
PlayMotion(MotionType::Dead, false);
}
void ActorInstance::TakeDamage(int damage, float knockbackDirX, float knockbackDirZ) {
m_curHP = std::max(0, m_curHP - damage);
if (m_curHP <= 0) {
if (!PlayMotion(MotionType::Dead, false)) {
PlayMotion(MotionType::Damage, false);
}
} else {
PlayMotion(MotionType::Damage, false);
}
float len = std::sqrt(knockbackDirX * knockbackDirX + knockbackDirZ * knockbackDirZ);
if (len > 0.001f) {
m_knockbackVx = (knockbackDirX / len) * 260.0f;
m_knockbackVz = (knockbackDirZ / len) * 260.0f;
}
}
void ActorInstance::GetHeadPosition(float& hX, float& hY, float& hZ) const {
hX = m_posX;
hY = m_posY + (m_heightOffset + m_modelYOffset) * m_scale;
hZ = m_posZ;
}
bool ActorInstance::IsTargetInAttackRange(const ActorInstance& target, float maxRange, float maxAngleDeg) const {
float dx = target.GetX() - m_posX;
float dz = target.GetZ() - m_posZ;
float dist = std::sqrt(dx * dx + dz * dz);
if (dist > maxRange) return false;
float dirAngle = std::atan2(dx, dz) * RAD_TO_DEG;
float diff = std::abs(std::fmod(dirAngle - m_yaw + 540.0f, 360.0f) - 180.0f);
return diff <= maxAngleDeg;
}
std::vector<Render3DDraw> ActorInstance::BuildDrawCommands() {
if (!m_model) return {};
float world[16];
MakeTransformMatrix(m_yaw + 180.0f, m_posX, m_posY + m_modelYOffset * m_scale, m_posZ, m_scale, world);
auto draws = m_model->BuildDrawCommands(m_animTime, world);
// Shining system (ENABLE_SHINING_SYSTEM): weapon aura / glow
if (m_weaponShining > 0) {
float hx = 0, hy = 0, hz = 0;
if (GetBonePosition("equip_right_hand", hx, hy, hz) || GetBonePosition("Bip01 R Hand", hx, hy, hz)) {
Render3DDraw sDraw;
sDraw.alpha_blend = true;
sDraw.blend_mode = 1; // Additive
sDraw.z_write = false;
sDraw.lighting = false;
float sz = 20.0f + m_weaponShining * 4.0f;
sDraw.positions = {
hx - sz, hy - sz, hz,
hx + sz, hy - sz, hz,
hx + sz, hy + sz, hz,
hx - sz, hy + sz, hz
};
sDraw.uv0 = {0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f};
sDraw.indices = {0, 1, 2, 0, 2, 3};
sDraw.texture0 = !m_weaponShiningPath.empty() ? m_weaponShiningPath : "ymir work/effect/shiningsystem/shining00.dds";
for (int k = 0; k < 16; ++k) sDraw.world[k] = (k % 5 == 0) ? 1.0f : 0.0f;
draws.push_back(std::move(sDraw));
}
}
// Shining system: armor body glow
if (m_armorShining > 0) {
float ax = m_posX, ay = m_posY + 100.0f * m_scale, az = m_posZ;
Render3DDraw aDraw;
aDraw.alpha_blend = true;
aDraw.blend_mode = 1; // Additive
aDraw.z_write = false;
aDraw.lighting = false;
float sz = 35.0f + m_armorShining * 6.0f;
aDraw.positions = {
ax - sz, ay - sz, az,
ax + sz, ay - sz, az,
ax + sz, ay + sz, az,
ax - sz, ay + sz, az
};
aDraw.uv0 = {0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f};
aDraw.indices = {0, 1, 2, 0, 2, 3};
aDraw.texture0 = !m_armorShiningPath.empty() ? m_armorShiningPath : "ymir work/effect/shiningsystem/shining01.dds";
for (int k = 0; k < 16; ++k) aDraw.world[k] = (k % 5 == 0) ? 1.0f : 0.0f;
draws.push_back(std::move(aDraw));
}
// Shining system: acce wing glow
if (m_acceShining > 0) {
float wx = 0, wy = 0, wz = 0;
if (GetBonePosition("Bip01 Spine2", wx, wy, wz) || GetBonePosition("Bip01 Spine1", wx, wy, wz)) {
Render3DDraw wDraw;
wDraw.alpha_blend = true;
wDraw.blend_mode = 1; // Additive
wDraw.z_write = false;
wDraw.lighting = false;
float sz = 45.0f + m_acceShining * 7.0f;
wDraw.positions = {
wx - sz, wy - sz, wz,
wx + sz, wy - sz, wz,
wx + sz, wy + sz, wz,
wx - sz, wy + sz, wz
};
wDraw.uv0 = {0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f};
wDraw.indices = {0, 1, 2, 0, 2, 3};
wDraw.texture0 = !m_acceShiningPath.empty() ? m_acceShiningPath : "ymir work/effect/shiningsystem/shining_wing.dds";
for (int k = 0; k < 16; ++k) wDraw.world[k] = (k % 5 == 0) ? 1.0f : 0.0f;
draws.push_back(std::move(wDraw));
}
}
return draws;
}
bool ActorInstance::HitTestScreen(float clickX, float clickY, const Gr2SceneRenderer& renderer, float tolerancePx) const {
if (m_curHP <= 0) return false;
float bx = 0.0f, by = 0.0f, hx = 0.0f, hy = 0.0f;
if (!renderer.ProjectToScreen(m_posX, m_posY, m_posZ, bx, by)) return false;
float topY = m_posY + m_heightOffset * m_scale;
if (!renderer.ProjectToScreen(m_posX, topY, m_posZ, hx, hy)) return false;
float segX = hx - bx;
float segY = hy - by;
float segLenSq = segX * segX + segY * segY;
float t = 0.0f;
if (segLenSq > 1e-4f) {
t = std::clamp(((clickX - bx) * segX + (clickY - by) * segY) / segLenSq, 0.0f, 1.0f);
}
float projX = bx + t * segX;
float projY = by + t * segY;
float dist = std::sqrt((clickX - projX) * (clickX - projX) + (clickY - projY) * (clickY - projY));
return dist <= tolerancePx;
}
bool ActorInstance::GetBoneWorldTransform(const std::string& boneName, float* outWorld16) const {
if (!m_model || !outWorld16) return false;
float localBone[16];
if (!m_model->GetBoneWorldTransform(boneName, localBone, m_animTime)) {
return false;
}
float actorWorld[16];
MakeTransformMatrix(m_yaw + 180.0f, m_posX, m_posY + m_modelYOffset * m_scale, m_posZ, m_scale, actorWorld);
for (int r = 0; r < 4; ++r) {
for (int c = 0; c < 4; ++c) {
float sum = 0.0f;
for (int k = 0; k < 4; ++k) {
sum += localBone[r * 4 + k] * actorWorld[k * 4 + c];
}
outWorld16[r * 4 + c] = sum;
}
}
return true;
}
bool ActorInstance::GetBonePosition(const std::string& boneName, float& outX, float& outY, float& outZ) const {
float mat[16];
if (GetBoneWorldTransform(boneName, mat)) {
outX = mat[12];
outY = mat[13];
outZ = mat[14];
return true;
}
return false;
}
bool ActorInstance::SetPolymorph(uint32_t mobVnum) {
std::string mobModel = CRenderTarget::ResolveNpcModel(mobVnum);
if (mobModel.empty() || !std::filesystem::exists(ResolvePath(mobModel))) {
return false;
}
if (!m_isPolymorph) {
m_origModelPath = m_modelPath;
m_origScale = m_scale;
m_origModelYOffset = m_modelYOffset;
m_origMotions = m_motionPaths;
}
if (!SetModel(mobModel)) return false;
std::filesystem::path p(ResolvePath(mobModel));
std::string parentDir = p.parent_path().string() + "/";
m_motionPaths.clear();
auto tryRegister = [&](MotionType mt, const std::string& name) {
std::string cand = parentDir + name;
if (std::filesystem::exists(cand)) {
RegisterMotion(mt, cand);
}
};
tryRegister(MotionType::Wait, "00.gr2");
tryRegister(MotionType::Walk, "02.gr2");
tryRegister(MotionType::Run, "03.gr2");
tryRegister(MotionType::Attack, "20.gr2");
tryRegister(MotionType::ComboAttack1, "20.gr2");
tryRegister(MotionType::ComboAttack2, "20_1.gr2");
tryRegister(MotionType::Damage, "30.gr2");
tryRegister(MotionType::Dead, "31.gr2");
PlayMotion(MotionType::Wait, true);
m_isPolymorph = true;
m_polymorphVnum = mobVnum;
return true;
}
void ActorInstance::ClearPolymorph() {
if (!m_isPolymorph) return;
if (!m_origModelPath.empty()) {
SetModel(m_origModelPath);
}
m_scale = m_origScale;
m_modelYOffset = m_origModelYOffset;
m_motionPaths = m_origMotions;
PlayMotion(MotionType::Wait, true);
m_isPolymorph = false;
m_polymorphVnum = 0;
}
void ActorInstance::SetWeaponShining(int grade, const std::string& effectPath) {
m_weaponShining = grade;
m_weaponShiningPath = effectPath;
}
void ActorInstance::SetArmorShining(int grade, const std::string& effectPath) {
m_armorShining = grade;
m_armorShiningPath = effectPath;
}
void ActorInstance::SetAcceShining(int grade, const std::string& effectPath) {
m_acceShining = grade;
m_acceShiningPath = effectPath;
}
void ActorInstance::ClearShining() {
m_weaponShining = 0;
m_weaponShiningPath.clear();
m_armorShining = 0;
m_armorShiningPath.clear();
m_acceShining = 0;
m_acceShiningPath.clear();
}
} // namespace ava2
+222
View File
@@ -0,0 +1,222 @@
#pragma once
#include "Gr2ModelRenderer.h"
#include "TerrainHeightmap.h"
#include <string>
#include <unordered_map>
#include <memory>
#include <vector>
namespace ava2 {
// Metin2 standard motion types (aligned with 40250 CRaceMotionData::EName)
enum class MotionType {
None = 0,
Wait = 1,
Walk = 2,
Run = 3,
ChangeWeapon = 4,
Damage = 5,
Dead = 11,
Attack = 13,
ComboAttack1 = 14,
ComboAttack2 = 15,
ComboAttack3 = 16,
Skill1 = 101, // Samyeon (三连击)
Skill2 = 102, // Palbang (八方风雨)
Skill3 = 103, // Jeongwi (狂战士)
Skill4 = 104, // Geomgyeong (剑气)
Skill5 = 105, // Tanhwan / Gitu (冲锋)
};
// Character / Monster / NPC actor instance modeled after 40250 CInstanceBase & CActorInstance
class ActorInstance {
public:
ActorInstance();
~ActorInstance() = default;
// Load base character mesh
bool SetModel(const std::string& modelPath);
// Attach weapon mesh to specified skeleton bone
bool SetWeapon(const std::string& weaponPath, const std::string& boneName = "equip_right_hand");
// Attach skinned hair / armor parts
bool AttachPart(const std::string& partPath);
void SetScale(float s) { m_scale = s; }
float GetScale() const { return m_scale; }
void SetModelYOffset(float offset) { m_modelYOffset = offset; }
float GetModelYOffset() const { return m_modelYOffset; }
// Motion management & animation playback
void RegisterMotion(MotionType type, const std::string& motionGr2Path);
bool PlayMotion(MotionType type, bool loop = true);
MotionType GetCurrentMotion() const { return m_currentMotion; }
bool IsMotionFinished() const;
float GetMotionDuration() const { return m_motionDuration; }
float GetAnimTime() const { return m_animTime; }
bool IsAttacking() const { return m_isAttacking; }
// World transform
void SetPosition(float x, float y, float z) { m_posX = x; m_posY = y; m_posZ = z; }
void GetPosition(float& x, float& y, float& z) const { x = m_posX; y = m_posY; z = m_posZ; }
float GetX() const { return m_posX; }
float GetY() const { return m_posY; }
float GetZ() const { return m_posZ; }
void SetYaw(float yaw) { m_yaw = yaw; }
float GetYaw() const { return m_yaw; }
void SetSpeed(float speed) { m_moveSpeed = speed; }
float GetSpeed() const { return m_moveSpeed; }
// VID (Virtual ID aligned with 40250)
void SetVID(uint32_t vid) { m_vid = vid; }
uint32_t GetVID() const { return m_vid; }
// Click-to-Move Target Destination (aligned with 40250 CPythonPlayer)
void SetMoveTarget(float targetX, float targetZ) {
m_targetX = targetX;
m_targetZ = targetZ;
m_hasMoveTarget = true;
}
bool HasMoveTarget() const { return m_hasMoveTarget; }
void ClearMoveTarget() { m_hasMoveTarget = false; }
void GetMoveTarget(float& tx, float& tz) const { tx = m_targetX; tz = m_targetZ; }
// Screen picking test (returns true if 2D click hits projected 3D volume)
bool HitTestScreen(float clickX, float clickY, const Gr2SceneRenderer& renderer, float tolerancePx = 40.0f) const;
// Smooth movement and continuous animation update
void MoveInDirection(float moveYaw, float dt, const TerrainHeightmap* terrain = nullptr, const class MapObjectManager* mapObjects = nullptr);
void StopMoving();
void Update(float dt, const TerrainHeightmap* terrain = nullptr, const class MapObjectManager* mapObjects = nullptr);
// Polymorph System (变身系统)
bool SetPolymorph(uint32_t mobVnum);
void ClearPolymorph();
bool IsPolymorph() const { return m_isPolymorph; }
uint32_t GetPolymorphVnum() const { return m_polymorphVnum; }
// Shining System (ENABLE_SHINING_SYSTEM 高强装备流光系统)
void SetWeaponShining(int grade, const std::string& effectPath = "");
void SetArmorShining(int grade, const std::string& effectPath = "");
void SetAcceShining(int grade, const std::string& effectPath = "");
int GetWeaponShining() const { return m_weaponShining; }
int GetArmorShining() const { return m_armorShining; }
int GetAcceShining() const { return m_acceShining; }
void ClearShining();
// Combat & Health
void SetMaxHP(int hp) { m_maxHP = hp; m_curHP = hp; }
void SetHP(int hp) { m_curHP = hp; }
int GetHP() const { return m_curHP; }
int GetMaxHP() const { return m_maxHP; }
void Die();
void Stun() { m_stunned=true; }
bool IsStun() const { return m_stunned; }
void SetSleep(bool value) { m_sleep=value; }
void SetParalysis(bool value) { m_paralysis=value; }
void SetFaint(bool value) { m_faint=value; }
bool CanAct() const { return !IsDead() && !m_stunned && !m_paralysis && !m_faint && !m_sleep; }
bool IsDead() const { return m_curHP <= 0; }
void SetName(const std::string& name) { m_name = name; }
const std::string& GetName() const { return m_name; }
void SetHeightOffset(float h) { m_heightOffset = h; }
float GetHeightOffset() const { return m_heightOffset; }
// Initiate Attack (cycles combo if already attacking or starts Combo 1)
bool Attack();
// Cast specific skill motion (stops movement, sets attack state, plays one-shot)
bool CastSkill(MotionType skillMotion);
// Buff system (e.g. "berserk", "aura")
void SetBuff(const std::string& buffName, float duration);
bool HasBuff(const std::string& buffName) const;
float GetBuffRemaining(const std::string& buffName) const;
float GetAttackMultiplier() const;
int GetBonusAttackDamage() const;
// Take Damage & Knockback impulse away from attacker
void TakeDamage(int damage, float knockbackDirX = 0.0f, float knockbackDirZ = 0.0f);
// Head position for floating text & nameplates
void GetHeadPosition(float& hX, float& hY, float& hZ) const;
// Check if target is inside forward attack cone
bool IsTargetInAttackRange(const ActorInstance& target, float maxRange = 160.0f, float maxAngleDeg = 75.0f) const;
// Bone attachment queries (e.g. "equip_right_hand", "Bip01 R Hand")
bool GetBonePosition(const std::string& boneName, float& outX, float& outY, float& outZ) const;
bool GetBoneWorldTransform(const std::string& boneName, float* outWorld16) const;
// Generate 3D draw commands
std::vector<Render3DDraw> BuildDrawCommands();
Gr2ModelInstance* GetModel() { return m_model.get(); }
const std::string& GetModelPath() const { return m_modelPath; }
private:
std::string ResolvePath(const std::string& path) const;
std::shared_ptr<Gr2ModelInstance> m_model;
std::string m_modelPath;
std::unordered_map<MotionType, std::string> m_motionPaths;
MotionType m_currentMotion = MotionType::Wait;
float m_animTime = 0.0f;
float m_motionDuration = 1.0f;
bool m_loopMotion = true;
bool m_isAttacking = false;
int m_comboIndex = 0;
std::unordered_map<std::string, float> m_buffs;
// Transform
float m_posX = 0.0f;
float m_posY = 0.0f;
float m_posZ = 0.0f;
float m_yaw = 0.0f;
float m_scale = 1.0f;
float m_modelYOffset = 0.0f;
float m_moveSpeed = 350.0f; // Metin2 typical run speed
// Knockback
float m_knockbackVx = 0.0f;
float m_knockbackVz = 0.0f;
// Attributes & Target State
uint32_t m_vid = 0;
bool m_stunned=false,m_sleep=false,m_paralysis=false,m_faint=false;
int m_curHP = 1000;
int m_maxHP = 1000;
std::string m_name;
float m_heightOffset = 180.0f;
// Click-to-Move Target
bool m_hasMoveTarget = false;
float m_targetX = 0.0f;
float m_targetZ = 0.0f;
// Polymorph state
bool m_isPolymorph = false;
uint32_t m_polymorphVnum = 0;
std::string m_origModelPath;
float m_origScale = 1.0f;
float m_origModelYOffset = 0.0f;
std::unordered_map<MotionType, std::string> m_origMotions;
// Shining state
int m_weaponShining = 0;
std::string m_weaponShiningPath;
int m_armorShining = 0;
std::string m_armorShiningPath;
int m_acceShining = 0;
std::string m_acceShiningPath;
};
} // namespace ava2
+324
View File
@@ -0,0 +1,324 @@
#include "CRenderTarget.h"
#include "eter_resource/ResourceManager.h"
#include <fstream>
#include <sstream>
#include <cmath>
#include <algorithm>
#include <filesystem>
namespace ava2 {
namespace {
static std::unordered_map<uint32_t, std::string> s_npcModelMap;
static std::unordered_map<uint32_t, std::string> s_itemModelMap;
static bool s_tablesLoaded = false;
static std::string NormalizePath(std::string p) {
for (char& c : p) {
if (c == '\\') c = '/';
else c = (char)std::tolower(c);
}
if (p.rfind("d:/", 0) == 0) p = p.substr(3);
else if (p.rfind("d:\\", 0) == 0) p = p.substr(3);
while (!p.empty() && (p.back() == '\r' || p.back() == '\n' || p.back() == ' ' || p.back() == '\t')) {
p.pop_back();
}
return p;
}
static void LoadTablesIfNeeded() {
if (s_tablesLoaded) return;
s_tablesLoaded = true;
// Load npclist.txt
std::vector<std::string> npcPaths = {
"locale/en/npclist.txt",
"../locale/en/npclist.txt",
"build/dev/locale/en/npclist.txt"
};
for (const auto& path : npcPaths) {
std::ifstream f(path);
if (f.is_open()) {
std::string line;
while (std::getline(f, line)) {
if (line.empty() || line[0] == '#') continue;
std::stringstream ss(line);
uint32_t vnum = 0;
std::string name;
if (ss >> vnum >> name) {
s_npcModelMap[vnum] = name;
}
}
break;
}
}
// Load item_list.txt
std::vector<std::string> itemPaths = {
"locale/en/item_list.txt",
"../locale/en/item_list.txt",
"build/dev/locale/en/item_list.txt"
};
for (const auto& path : itemPaths) {
std::ifstream f(path);
if (f.is_open()) {
std::string line;
while (std::getline(f, line)) {
if (line.empty() || line[0] == '#') continue;
std::stringstream ss(line);
uint32_t vnum = 0;
std::string type, icon, model;
if (ss >> vnum >> type >> icon >> model) {
s_itemModelMap[vnum] = NormalizePath(model);
}
}
break;
}
}
}
} // namespace
CRenderTarget::CRenderTarget(int width, int height)
: m_width(width), m_height(height), m_renderer3d(width, height)
{
LoadTablesIfNeeded();
SelectModel(0);
}
CRenderTarget::~CRenderTarget() {
if (m_texture) {
SDL_DestroyTexture(m_texture);
m_texture = nullptr;
}
if (m_surface) {
SDL_DestroySurface(m_surface);
m_surface = nullptr;
}
}
void CRenderTarget::EnsureTextures(SDL_Renderer* renderer) {
if (!m_surface) {
m_surface = SDL_CreateSurface(m_width, m_height, SDL_PIXELFORMAT_ARGB8888);
}
if (!m_texture && renderer) {
m_texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, m_width, m_height);
}
}
std::string CRenderTarget::ResolveNpcModel(uint32_t vnum) {
if (vnum == 0) return "ymir work/pc/warrior/warrior_novice.gr2";
if (vnum == 1) return "ymir work/pc/ninja/ninja_novice.gr2";
if (vnum == 2) return "ymir work/pc/sura/sura_novice.gr2";
if (vnum == 3) return "ymir work/pc/shaman/shaman_novice.gr2";
if (vnum == 4) return "ymir work/pc2/warrior/warrior_novice.gr2";
if (vnum == 5) return "ymir work/pc2/ninja/ninja_novice.gr2";
if (vnum == 6) return "ymir work/pc2/sura/sura_novice.gr2";
if (vnum == 7) return "ymir work/pc2/shaman/shaman_novice.gr2";
if (vnum == 8) return "ymir work/pc3/wolfman/wolfman_novice.gr2";
auto it = s_npcModelMap.find(vnum);
if (it != s_npcModelMap.end()) {
const std::string& name = it->second;
std::vector<std::string> candidates = {
"ymir work/monster/" + name + "/" + name + ".gr2",
"ymir work/monster2/" + name + "/" + name + ".gr2",
"ymir work/npc/" + name + "/" + name + ".gr2",
"ymir work/npc2/" + name + "/" + name + ".gr2"
};
for (const auto& c : candidates) {
if (std::filesystem::exists(c)) return c;
}
}
if (vnum >= 8000 && vnum <= 8100) {
return "ymir work/monster/metinstone/metinstone_loop.gr2";
}
if (std::filesystem::exists("ymir work/monster/stray_dog/stray_dog.gr2")) {
return "ymir work/monster/stray_dog/stray_dog.gr2";
}
return "ymir work/pc/warrior/warrior_novice.gr2";
}
std::string CRenderTarget::ResolveItemModel(uint32_t vnum) {
auto it = s_itemModelMap.find(vnum);
if (it != s_itemModelMap.end() && !it->second.empty()) {
return it->second;
}
// Standard weapon pattern
char buf[128];
std::snprintf(buf, sizeof(buf), "ymir work/item/weapon/%05u.gr2", vnum);
return std::string(buf);
}
void CRenderTarget::SelectModel(uint32_t vnum) {
m_modelVnum = vnum;
std::string path = ResolveNpcModel(vnum);
m_actor.SetModel(path);
if (vnum <= 8) {
m_camDistance = 240.0f;
m_camTargetHeight = 90.0f;
m_actor.RegisterMotion(MotionType::Wait, "ymir work/pc/warrior/general/wait.gr2");
m_actor.PlayMotion(MotionType::Wait, true);
} else if (vnum >= 8000 && vnum <= 8100) {
m_camDistance = 380.0f;
m_camTargetHeight = 120.0f;
m_actor.RegisterMotion(MotionType::Wait, "ymir work/monster/metinstone/metinstone_loop.gr2");
m_actor.PlayMotion(MotionType::Wait, true);
} else {
m_camDistance = 260.0f;
m_camTargetHeight = 60.0f;
m_actor.RegisterMotion(MotionType::Wait, "ymir work/monster/stray_dog/wait.gr2");
m_actor.PlayMotion(MotionType::Wait, true);
}
}
void CRenderTarget::SetArmor(uint32_t vnum) {
m_armorVnum = vnum;
// For warrior armor preview, novice armor is already loaded; can equip body parts
}
void CRenderTarget::SetWeapon(uint32_t vnum) {
m_weaponVnum = vnum;
std::string path = ResolveItemModel(vnum);
m_actor.SetWeapon(path, "equip_right_hand");
}
void CRenderTarget::SetHair(uint32_t vnum) {
m_hairVnum = vnum;
}
void CRenderTarget::SetAcce(uint32_t vnum) {
m_acceVnum = vnum;
// Map acce to wing model
std::vector<std::string> acceCandidates = {
"ymir work/item/wing/acce_01_85_001.gr2",
"ymir work/item/wing/acce_02_85_005.gr2",
"ymir work/item/wing/acce_05_85_021.gr2",
"ymir work/item/wing/acce_07_86_011.gr2",
"ymir work/item/wing/acce_16_86_055.gr2"
};
uint32_t idx = (vnum > 0 ? (vnum % acceCandidates.size()) : 0);
m_actor.AttachPart(acceCandidates[idx]);
}
void CRenderTarget::SetBackground(const std::string& path) {
std::string norm = NormalizePath(path);
auto pRes = CResourceManager::Instance().GetResourcePointer(norm.c_str());
if (pRes && pRes->IsType(CGraphicImage::Type())) {
m_background = std::make_unique<CGraphicImageInstance>();
m_background->SetImagePointer(static_cast<CGraphicImage*>(pRes));
} else {
m_background.reset();
}
}
void CRenderTarget::Zoom(float ratio) {
m_zoom = std::clamp(m_zoom * ratio, 0.3f, 3.0f);
}
void CRenderTarget::RotateEyeAroundTarget(float pitch, float roll) {
m_pitch = std::clamp(m_pitch + pitch, -45.0f, 80.0f);
m_yaw = std::fmod(m_yaw + roll, 360.0f);
}
void CRenderTarget::SetMotionIndex(int motion) {
(void)motion;
}
void CRenderTarget::SetModelV3Eye(float x, float y, float z) {
m_camDistance = std::sqrt(x * x + y * y + z * z);
}
void CRenderTarget::SetModelV3Target(float x, float y, float z) {
m_camTargetHeight = y;
}
void CRenderTarget::Update(float dt) {
m_actor.Update(dt);
m_rotation += dt * 25.0f; // gentle auto-rotation preview
if (m_rotation >= 360.0f) m_rotation -= 360.0f;
}
void CRenderTarget::Render(SDL_Renderer* renderer, const SDL_FRect& destRect) {
if (!m_visible || !renderer) return;
EnsureTextures(renderer);
if (!m_surface || !m_texture) return;
Update(1.0f / 60.0f);
// If background exists, render background first directly to UI
if (m_background) {
m_background->SetPosition((int)destRect.x, (int)destRect.y);
m_background->Render();
}
// Set 3D Camera for RenderTarget
float pitchRad = m_pitch * (3.14159265f / 180.0f);
float yawRad = (m_yaw + m_rotation) * (3.14159265f / 180.0f);
float dist = m_camDistance * m_zoom;
float eyeX = -dist * std::sin(yawRad) * std::cos(pitchRad);
float eyeY = m_camTargetHeight + dist * std::sin(pitchRad);
float eyeZ = -dist * std::cos(yawRad) * std::cos(pitchRad);
m_renderer3d.SetViewport(0, 0, m_width, m_height);
m_renderer3d.SetCameraLookAt(eyeX, eyeY, eyeZ, 0.0f, m_camTargetHeight, 0.0f, 0.0f, 1.0f, 0.0f);
m_renderer3d.SetPerspective(40.0f, (float)m_width / (float)m_height, 10.0f, 2500.0f);
// Clear with dark subtle gradient or transparency
uint32_t clearCol = m_background ? 0x00000000 : 0xFF141A24;
m_renderer3d.Clear(clearCol, 1.0f);
// Render Actor
auto draws = m_actor.BuildDrawCommands();
m_renderer3d.RenderScene(m_surface, draws);
// Stream rendered surface to texture
SDL_UpdateTexture(m_texture, nullptr, m_surface->pixels, m_surface->pitch);
SDL_SetTextureBlendMode(m_texture, SDL_BLENDMODE_BLEND);
SDL_RenderTexture(renderer, m_texture, nullptr, &destRect);
}
// -------------------------------------------------------------
// CRenderTargetManager Implementation
// -------------------------------------------------------------
CRenderTargetManager& CRenderTargetManager::Instance() {
static CRenderTargetManager s_instance;
return s_instance;
}
CRenderTargetManager::CRenderTargetManager() = default;
CRenderTargetManager::~CRenderTargetManager() {
m_targets.clear();
}
std::shared_ptr<CRenderTarget> CRenderTargetManager::GetRenderTarget(int index) {
auto it = m_targets.find(index);
if (it != m_targets.end()) return it->second;
return CreateRenderTarget(index);
}
std::shared_ptr<CRenderTarget> CRenderTargetManager::CreateRenderTarget(int index, int w, int h) {
auto target = std::make_shared<CRenderTarget>(w, h);
m_targets[index] = target;
return target;
}
void CRenderTargetManager::DestroyRenderTarget(int index) {
m_targets.erase(index);
}
int CRenderTargetManager::GetFreeIndex(int minIdx, int maxIdx) {
for (int i = minIdx; i <= maxIdx; ++i) {
if (m_targets.find(i) == m_targets.end()) return i;
}
return minIdx;
}
} // namespace ava2
+91
View File
@@ -0,0 +1,91 @@
#pragma once
#include "ActorInstance.h"
#include "Gr2ModelRenderer.h"
#include "eter_image/GrpImageInstance.h"
#include "shared/common/Singleton.h"
#include <SDL3/SDL.h>
#include <string>
#include <unordered_map>
#include <memory>
namespace ava2 {
class CRenderTarget {
public:
CRenderTarget(int width = 384, int height = 384);
~CRenderTarget();
void SelectModel(uint32_t vnum);
void SetArmor(uint32_t vnum);
void SetWeapon(uint32_t vnum);
void SetHair(uint32_t vnum);
void SetAcce(uint32_t vnum);
void SetBackground(const std::string& path);
void SetRotation(float rot) { m_rotation = rot; }
void SetScale(float scale) { m_scale = scale; }
void SetVisibility(bool visible) { m_visible = visible; }
bool IsVisible() const { return m_visible; }
void Zoom(float ratio);
void RotateEyeAroundTarget(float pitch, float roll);
void SetMotionIndex(int motion);
void SetModelV3Eye(float x, float y, float z);
void SetModelV3Target(float x, float y, float z);
void Update(float dt);
void Render(SDL_Renderer* renderer, const SDL_FRect& destRect);
ActorInstance* GetModel() { return &m_actor; }
static std::string ResolveNpcModel(uint32_t vnum);
static std::string ResolveItemModel(uint32_t vnum);
private:
void EnsureTextures(SDL_Renderer* renderer);
int m_width;
int m_height;
bool m_visible = true;
ActorInstance m_actor;
Gr2SceneRenderer m_renderer3d;
SDL_Surface* m_surface = nullptr;
SDL_Texture* m_texture = nullptr;
std::unique_ptr<CGraphicImageInstance> m_background;
uint32_t m_modelVnum = 0;
uint32_t m_armorVnum = 0;
uint32_t m_weaponVnum = 0;
uint32_t m_hairVnum = 0;
uint32_t m_acceVnum = 0;
float m_rotation = 0.0f;
float m_scale = 1.0f;
float m_zoom = 1.0f;
float m_pitch = 12.0f;
float m_yaw = 0.0f;
float m_camDistance = 240.0f;
float m_camTargetHeight = 90.0f;
float m_modelYOffset = 0.0f;
};
class CRenderTargetManager {
public:
static CRenderTargetManager& Instance();
static CRenderTargetManager* InstancePtr() { return &Instance(); }
CRenderTargetManager();
~CRenderTargetManager();
std::shared_ptr<CRenderTarget> GetRenderTarget(int index);
std::shared_ptr<CRenderTarget> CreateRenderTarget(int index, int w = 384, int h = 384);
void DestroyRenderTarget(int index);
int GetFreeIndex(int minIdx, int maxIdx);
private:
std::unordered_map<int, std::shared_ptr<CRenderTarget>> m_targets;
};
} // namespace ava2
+462
View File
@@ -0,0 +1,462 @@
#include "EnvironmentData.h"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <filesystem>
#include <fstream>
#include <sstream>
namespace ava2 {
namespace {
std::string ToLower(const std::string& str) {
std::string res = str;
std::transform(res.begin(), res.end(), res.begin(), [](unsigned char c) {
return static_cast<char>(std::tolower(c));
});
return res;
}
std::string Trim(const std::string& str) {
size_t first = str.find_first_not_of(" \t\r\n");
if (first == std::string::npos) return "";
size_t last = str.find_last_not_of(" \t\r\n");
return str.substr(first, (last - first + 1));
}
std::string CleanPath(const std::string& raw) {
std::string s = raw;
if (s.size() >= 2 && s.front() == '"' && s.back() == '"') {
s = s.substr(1, s.size() - 2);
}
for (char& c : s) {
if (c == '\\') c = '/';
}
if (s.size() > 2 && s[1] == ':') {
s = s.substr(2);
while (!s.empty() && s[0] == '/') s = s.substr(1);
}
return s;
}
} // namespace
bool EnvironmentData::LoadFromFile(const std::string& filepath) {
std::vector<std::string> candidates = {
filepath,
"ymir work/environment/" + filepath,
"build/dev/ymir work/environment/" + filepath,
"/Users/shen/Work/Code/Metin2/ava2-client/ymir work/environment/" + filepath,
"/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/ETC/ymir work/environment/" + filepath
};
if (filepath.find('/') != std::string::npos || filepath.find('\\') != std::string::npos) {
std::filesystem::path p(filepath);
std::string filename = p.filename().string();
candidates.push_back("ymir work/environment/" + filename);
candidates.push_back("build/dev/ymir work/environment/" + filename);
candidates.push_back("/Users/shen/Work/Code/Metin2/ava2-client/ymir work/environment/" + filename);
candidates.push_back("/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/ETC/ymir work/environment/" + filename);
}
for (const auto& path : candidates) {
if (std::filesystem::exists(path)) {
std::ifstream file(path);
if (file) {
std::stringstream buffer;
buffer << file.rdbuf();
bool ok = LoadFromString(buffer.str());
if (ok) {
name = std::filesystem::path(path).stem().string();
return true;
}
}
}
}
return false;
}
bool EnvironmentData::LoadFromString(const std::string& content) {
std::istringstream stream(content);
std::string line;
std::vector<std::string> scope_stack;
std::vector<float> gradient_floats;
std::vector<float> cloud_color_floats;
while (std::getline(stream, line)) {
std::string trimmed = Trim(line);
if (trimmed.empty() || trimmed[0] == '#' || trimmed.rfind("//", 0) == 0) {
continue;
}
// Handle block transitions
if (trimmed == "{") {
continue;
}
if (trimmed == "}") {
if (!scope_stack.empty()) {
std::string popped = scope_stack.back();
scope_stack.pop_back();
if (popped == "gradient") {
skybox.gradients.clear();
size_t count = gradient_floats.size() / 8;
for (size_t i = 0; i < count; ++i) {
GradientColor gc;
gc.first[0] = gradient_floats[i * 8 + 0];
gc.first[1] = gradient_floats[i * 8 + 1];
gc.first[2] = gradient_floats[i * 8 + 2];
gc.first[3] = gradient_floats[i * 8 + 3];
gc.second[0] = gradient_floats[i * 8 + 4];
gc.second[1] = gradient_floats[i * 8 + 5];
gc.second[2] = gradient_floats[i * 8 + 6];
gc.second[3] = gradient_floats[i * 8 + 7];
skybox.gradients.push_back(gc);
}
gradient_floats.clear();
} else if (popped == "cloudcolor") {
if (cloud_color_floats.size() >= 8) {
skybox.cloud_color.first[0] = cloud_color_floats[0];
skybox.cloud_color.first[1] = cloud_color_floats[1];
skybox.cloud_color.first[2] = cloud_color_floats[2];
skybox.cloud_color.first[3] = cloud_color_floats[3];
skybox.cloud_color.second[0] = cloud_color_floats[4];
skybox.cloud_color.second[1] = cloud_color_floats[5];
skybox.cloud_color.second[2] = cloud_color_floats[6];
skybox.cloud_color.second[3] = cloud_color_floats[7];
}
cloud_color_floats.clear();
}
}
continue;
}
std::istringstream line_stream(trimmed);
std::string token;
line_stream >> token;
std::string lower_token = ToLower(token);
if (lower_token == "group" || lower_token == "list") {
std::string group_name;
line_stream >> group_name;
scope_stack.push_back(ToLower(group_name));
continue;
}
std::string current_scope = scope_stack.empty() ? "" : scope_stack.back();
std::string parent_scope = scope_stack.size() > 1 ? scope_stack[scope_stack.size() - 2] : "";
if (current_scope == "gradient") {
// Read floats on this line
float f = 0.0f;
gradient_floats.push_back(std::stof(token));
while (line_stream >> f) {
gradient_floats.push_back(f);
}
continue;
}
if (current_scope == "cloudcolor") {
float f = 0.0f;
cloud_color_floats.push_back(std::stof(token));
while (line_stream >> f) {
cloud_color_floats.push_back(f);
}
continue;
}
// Directional Light scope
if (current_scope == "directionallight") {
if (lower_token == "direction") {
line_stream >> dir_light.direction[0] >> dir_light.direction[1] >> dir_light.direction[2];
}
} else if (current_scope == "background" && parent_scope == "directionallight") {
if (lower_token == "enable") {
int en = 0; line_stream >> en; dir_light.bg_enable = (en != 0);
} else if (lower_token == "diffuse") {
line_stream >> dir_light.bg_diffuse[0] >> dir_light.bg_diffuse[1] >> dir_light.bg_diffuse[2] >> dir_light.bg_diffuse[3];
} else if (lower_token == "ambient") {
line_stream >> dir_light.bg_ambient[0] >> dir_light.bg_ambient[1] >> dir_light.bg_ambient[2] >> dir_light.bg_ambient[3];
}
} else if (current_scope == "character" && parent_scope == "directionallight") {
if (lower_token == "enable") {
int en = 0; line_stream >> en; dir_light.chr_enable = (en != 0);
} else if (lower_token == "diffuse") {
line_stream >> dir_light.chr_diffuse[0] >> dir_light.chr_diffuse[1] >> dir_light.chr_diffuse[2] >> dir_light.chr_diffuse[3];
} else if (lower_token == "ambient") {
line_stream >> dir_light.chr_ambient[0] >> dir_light.chr_ambient[1] >> dir_light.chr_ambient[2] >> dir_light.chr_ambient[3];
}
}
// Material scope
else if (current_scope == "material") {
if (lower_token == "diffuse") {
line_stream >> material.diffuse[0] >> material.diffuse[1] >> material.diffuse[2] >> material.diffuse[3];
} else if (lower_token == "ambient") {
line_stream >> material.ambient[0] >> material.ambient[1] >> material.ambient[2] >> material.ambient[3];
} else if (lower_token == "emissive") {
line_stream >> material.emissive[0] >> material.emissive[1] >> material.emissive[2] >> material.emissive[3];
}
}
// Fog scope
else if (current_scope == "fog") {
if (lower_token == "enable") {
int en = 0; line_stream >> en; fog.enable = (en != 0);
} else if (lower_token == "isdensity") {
int id = 0; line_stream >> id; fog.is_density = (id != 0);
} else if (lower_token == "neardistance") {
line_stream >> fog.near_dist;
} else if (lower_token == "fardistance") {
line_stream >> fog.far_dist;
} else if (lower_token == "color") {
line_stream >> fog.color[0] >> fog.color[1] >> fog.color[2] >> fog.color[3];
}
}
// SkyBox scope
else if (current_scope == "skybox") {
if (lower_token == "btexturerendermode") {
int trm = 0; line_stream >> trm; skybox.texture_render_mode = (trm != 0);
} else if (lower_token == "scale") {
line_stream >> skybox.scale[0] >> skybox.scale[1] >> skybox.scale[2];
} else if (lower_token == "gradientlevelupper") {
int lvl = 0; line_stream >> lvl; skybox.gradient_level_upper = static_cast<uint8_t>(lvl);
} else if (lower_token == "gradientlevellower") {
int lvl = 0; line_stream >> lvl; skybox.gradient_level_lower = static_cast<uint8_t>(lvl);
} else if (lower_token == "frontfacefilename") {
std::string rest; std::getline(line_stream, rest);
skybox.face_file_names[0] = CleanPath(Trim(rest));
} else if (lower_token == "backfacefilename") {
std::string rest; std::getline(line_stream, rest);
skybox.face_file_names[1] = CleanPath(Trim(rest));
} else if (lower_token == "leftfacefilename") {
std::string rest; std::getline(line_stream, rest);
skybox.face_file_names[2] = CleanPath(Trim(rest));
} else if (lower_token == "rightfacefilename") {
std::string rest; std::getline(line_stream, rest);
skybox.face_file_names[3] = CleanPath(Trim(rest));
} else if (lower_token == "topfacefilename") {
std::string rest; std::getline(line_stream, rest);
skybox.face_file_names[4] = CleanPath(Trim(rest));
} else if (lower_token == "bottomfacefilename") {
std::string rest; std::getline(line_stream, rest);
skybox.face_file_names[5] = CleanPath(Trim(rest));
} else if (lower_token == "cloudscale") {
line_stream >> skybox.cloud_scale[0] >> skybox.cloud_scale[1];
} else if (lower_token == "cloudheight") {
line_stream >> skybox.cloud_height;
} else if (lower_token == "cloudtexturescale") {
line_stream >> skybox.cloud_texture_scale[0] >> skybox.cloud_texture_scale[1];
} else if (lower_token == "cloudspeed") {
line_stream >> skybox.cloud_speed[0] >> skybox.cloud_speed[1];
} else if (lower_token == "cloudtexturefilename") {
std::string rest; std::getline(line_stream, rest);
skybox.cloud_texture_file_name = CleanPath(Trim(rest));
}
}
// LensFlare scope
else if (current_scope == "lensflare") {
if (lower_token == "enable") {
int en = 0; line_stream >> en; lens_flare.enable = (en != 0);
} else if (lower_token == "brightnesscolor") {
line_stream >> lens_flare.brightness_color[0] >> lens_flare.brightness_color[1] >> lens_flare.brightness_color[2] >> lens_flare.brightness_color[3];
} else if (lower_token == "maxbrightness") {
line_stream >> lens_flare.max_brightness;
} else if (lower_token == "mainflareenable") {
int mfe = 0; line_stream >> mfe; lens_flare.main_flare_enable = (mfe != 0);
} else if (lower_token == "mainflaretexturefilename") {
std::string rest; std::getline(line_stream, rest);
lens_flare.main_flare_file_name = CleanPath(Trim(rest));
} else if (lower_token == "mainflaresize") {
line_stream >> lens_flare.main_flare_size;
}
}
}
return true;
}
EnvironmentData EnvironmentData::CreateDayPreset() {
EnvironmentData env;
env.name = "day";
env.dir_light.direction[0] = 0.350156f;
env.dir_light.direction[1] = 0.562609f;
env.dir_light.direction[2] = -0.748907f;
env.dir_light.bg_enable = true;
env.dir_light.bg_diffuse[0] = 1.0f;
env.dir_light.bg_diffuse[1] = 0.972549f;
env.dir_light.bg_diffuse[2] = 0.972549f;
env.dir_light.bg_diffuse[3] = 1.0f;
env.dir_light.bg_ambient[0] = 0.22f;
env.dir_light.bg_ambient[1] = 0.22f;
env.dir_light.bg_ambient[2] = 0.25f;
env.dir_light.bg_ambient[3] = 1.0f;
env.fog.enable = true;
env.fog.near_dist = 4000.0f;
env.fog.far_dist = 18000.0f;
env.fog.color[0] = 0.847059f;
env.fog.color[1] = 0.901961f;
env.fog.color[2] = 1.0f;
env.fog.color[3] = 1.0f;
env.skybox.texture_render_mode = false;
env.skybox.gradient_level_upper = 4;
env.skybox.gradient_level_lower = 1;
env.skybox.cloud_texture_file_name = "ymir work/environment/clouds_zone01.tga";
env.skybox.cloud_speed[0] = 0.004f;
env.skybox.cloud_speed[1] = 0.004f;
env.skybox.gradients = {
{{0.094118f, 0.286275f, 0.658824f, 1.0f}, {0.231373f, 0.403922f, 0.729412f, 1.0f}},
{{0.231373f, 0.403922f, 0.729412f, 1.0f}, {0.376471f, 0.498039f, 0.729412f, 1.0f}},
{{0.376471f, 0.498039f, 0.729412f, 1.0f}, {0.568627f, 0.678431f, 0.882353f, 1.0f}},
{{0.568627f, 0.678431f, 0.882353f, 1.0f}, {0.850980f, 0.901961f, 1.000000f, 1.0f}},
{{0.847059f, 0.901961f, 1.000000f, 1.0f}, {0.529412f, 0.564706f, 0.619608f, 1.0f}}
};
env.lens_flare.enable = true;
env.lens_flare.main_flare_enable = true;
env.lens_flare.main_flare_file_name = "ymir work/environment/sunflare.dds";
env.lens_flare.main_flare_size = 0.35f;
return env;
}
EnvironmentData EnvironmentData::CreateSunsetPreset() {
EnvironmentData env;
env.name = "sunset";
env.dir_light.direction[0] = 0.85f;
env.dir_light.direction[1] = 0.25f;
env.dir_light.direction[2] = -0.45f;
env.dir_light.bg_enable = true;
env.dir_light.bg_diffuse[0] = 1.0f;
env.dir_light.bg_diffuse[1] = 0.65f;
env.dir_light.bg_diffuse[2] = 0.45f;
env.dir_light.bg_diffuse[3] = 1.0f;
env.dir_light.bg_ambient[0] = 0.35f;
env.dir_light.bg_ambient[1] = 0.20f;
env.dir_light.bg_ambient[2] = 0.22f;
env.dir_light.bg_ambient[3] = 1.0f;
env.fog.enable = true;
env.fog.near_dist = 2500.0f;
env.fog.far_dist = 14000.0f;
env.fog.color[0] = 0.88f;
env.fog.color[1] = 0.52f;
env.fog.color[2] = 0.42f;
env.fog.color[3] = 1.0f;
env.skybox.texture_render_mode = false;
env.skybox.gradient_level_upper = 4;
env.skybox.gradient_level_lower = 1;
env.skybox.cloud_texture_file_name = "ymir work/environment/clouds_zone02.tga";
env.skybox.cloud_speed[0] = 0.003f;
env.skybox.cloud_speed[1] = 0.002f;
env.skybox.gradients = {
{{0.15f, 0.12f, 0.35f, 1.0f}, {0.35f, 0.20f, 0.45f, 1.0f}},
{{0.35f, 0.20f, 0.45f, 1.0f}, {0.65f, 0.28f, 0.40f, 1.0f}},
{{0.65f, 0.28f, 0.40f, 1.0f}, {0.92f, 0.48f, 0.25f, 1.0f}},
{{0.92f, 0.48f, 0.25f, 1.0f}, {1.00f, 0.75f, 0.38f, 1.0f}},
{{1.00f, 0.75f, 0.38f, 1.0f}, {0.45f, 0.25f, 0.20f, 1.0f}}
};
env.lens_flare.enable = true;
env.lens_flare.main_flare_enable = true;
env.lens_flare.main_flare_file_name = "ymir work/environment/sunflare.dds";
env.lens_flare.main_flare_size = 0.42f;
return env;
}
EnvironmentData EnvironmentData::CreateNightPreset() {
EnvironmentData env;
env.name = "night";
env.dir_light.direction[0] = -0.4f;
env.dir_light.direction[1] = 0.75f;
env.dir_light.direction[2] = 0.5f;
env.dir_light.bg_enable = true;
env.dir_light.bg_diffuse[0] = 0.35f;
env.dir_light.bg_diffuse[1] = 0.45f;
env.dir_light.bg_diffuse[2] = 0.75f;
env.dir_light.bg_diffuse[3] = 1.0f;
env.dir_light.bg_ambient[0] = 0.12f;
env.dir_light.bg_ambient[1] = 0.14f;
env.dir_light.bg_ambient[2] = 0.24f;
env.dir_light.bg_ambient[3] = 1.0f;
env.fog.enable = true;
env.fog.near_dist = 2000.0f;
env.fog.far_dist = 12000.0f;
env.fog.color[0] = 0.08f;
env.fog.color[1] = 0.10f;
env.fog.color[2] = 0.20f;
env.fog.color[3] = 1.0f;
env.skybox.texture_render_mode = false;
env.skybox.gradient_level_upper = 4;
env.skybox.gradient_level_lower = 1;
env.skybox.cloud_texture_file_name = "ymir work/environment/clouds_zone05.tga";
env.skybox.cloud_speed[0] = 0.002f;
env.skybox.cloud_speed[1] = 0.002f;
env.skybox.gradients = {
{{0.015f, 0.02f, 0.06f, 1.0f}, {0.03f, 0.04f, 0.10f, 1.0f}},
{{0.03f, 0.04f, 0.10f, 1.0f}, {0.05f, 0.07f, 0.16f, 1.0f}},
{{0.05f, 0.07f, 0.16f, 1.0f}, {0.08f, 0.11f, 0.24f, 1.0f}},
{{0.08f, 0.11f, 0.24f, 1.0f}, {0.15f, 0.18f, 0.32f, 1.0f}},
{{0.15f, 0.18f, 0.32f, 1.0f}, {0.05f, 0.06f, 0.12f, 1.0f}}
};
env.lens_flare.enable = false;
return env;
}
EnvironmentData EnvironmentData::CreateSnowPreset() {
EnvironmentData env;
env.name = "snow";
env.dir_light.direction[0] = 0.25f;
env.dir_light.direction[1] = 0.85f;
env.dir_light.direction[2] = -0.45f;
env.dir_light.bg_enable = true;
env.dir_light.bg_diffuse[0] = 0.88f;
env.dir_light.bg_diffuse[1] = 0.92f;
env.dir_light.bg_diffuse[2] = 0.98f;
env.dir_light.bg_diffuse[3] = 1.0f;
env.dir_light.bg_ambient[0] = 0.35f;
env.dir_light.bg_ambient[1] = 0.38f;
env.dir_light.bg_ambient[2] = 0.45f;
env.dir_light.bg_ambient[3] = 1.0f;
env.fog.enable = true;
env.fog.near_dist = 1200.0f;
env.fog.far_dist = 9000.0f;
env.fog.color[0] = 0.78f;
env.fog.color[1] = 0.82f;
env.fog.color[2] = 0.88f;
env.fog.color[3] = 1.0f;
env.skybox.texture_render_mode = false;
env.skybox.gradient_level_upper = 4;
env.skybox.gradient_level_lower = 1;
env.skybox.cloud_texture_file_name = "ymir work/environment/clouds_zone07.tga";
env.skybox.cloud_speed[0] = 0.005f;
env.skybox.cloud_speed[1] = 0.003f;
env.skybox.gradients = {
{{0.35f, 0.42f, 0.52f, 1.0f}, {0.48f, 0.55f, 0.65f, 1.0f}},
{{0.48f, 0.55f, 0.65f, 1.0f}, {0.62f, 0.68f, 0.75f, 1.0f}},
{{0.62f, 0.68f, 0.75f, 1.0f}, {0.75f, 0.80f, 0.86f, 1.0f}},
{{0.75f, 0.80f, 0.86f, 1.0f}, {0.88f, 0.91f, 0.95f, 1.0f}},
{{0.88f, 0.91f, 0.95f, 1.0f}, {0.65f, 0.68f, 0.72f, 1.0f}}
};
return env;
}
} // namespace ava2
+90
View File
@@ -0,0 +1,90 @@
#pragma once
#include <cstdint>
#include <string>
#include <vector>
namespace ava2 {
struct DirectionalLight {
float direction[3] = {0.350156f, 0.562609f, -0.748907f};
bool bg_enable = true;
float bg_diffuse[4] = {1.0f, 0.972549f, 0.972549f, 1.0f};
float bg_ambient[4] = {0.18f, 0.18f, 0.20f, 1.0f};
bool chr_enable = true;
float chr_diffuse[4] = {1.0f, 0.972549f, 0.972549f, 1.0f};
float chr_ambient[4] = {0.32f, 0.32f, 0.35f, 1.0f};
};
struct MaterialData {
float diffuse[4] = {1.0f, 1.0f, 1.0f, 1.0f};
float ambient[4] = {0.882353f, 0.854902f, 0.784314f, 1.0f};
float emissive[4] = {0.321569f, 0.321569f, 0.411765f, 1.0f};
};
struct FogData {
bool enable = true;
bool is_density = false;
float near_dist = 4000.0f;
float far_dist = 18000.0f;
float color[4] = {0.847059f, 0.901961f, 1.0f, 1.0f};
uint32_t GetColorUint() const {
auto r = static_cast<uint32_t>(color[0] * 255.0f) & 0xFF;
auto g = static_cast<uint32_t>(color[1] * 255.0f) & 0xFF;
auto b = static_cast<uint32_t>(color[2] * 255.0f) & 0xFF;
auto a = static_cast<uint32_t>(color[3] * 255.0f) & 0xFF;
return (a << 24) | (r << 16) | (g << 8) | b;
}
};
struct GradientColor {
float first[4] = {0.0f, 0.0f, 0.0f, 0.0f};
float second[4] = {0.0f, 0.0f, 0.0f, 0.0f};
};
struct SkyBoxData {
bool texture_render_mode = false;
float scale[3] = {3500.0f, 3500.0f, 3500.0f};
uint8_t gradient_level_upper = 4;
uint8_t gradient_level_lower = 1;
// Front, Back, Left, Right, Top, Bottom
std::string face_file_names[6];
float cloud_scale[2] = {200000.0f, 200000.0f};
float cloud_height = 30000.0f;
float cloud_texture_scale[2] = {4.0f, 4.0f};
float cloud_speed[2] = {0.004f, 0.004f};
std::string cloud_texture_file_name = "ymir work/environment/clouds_zone01.tga";
GradientColor cloud_color;
std::vector<GradientColor> gradients;
};
struct LensFlareData {
bool enable = false;
float brightness_color[4] = {1.0f, 0.886275f, 0.886275f, 1.0f};
float max_brightness = 0.74f;
bool main_flare_enable = true;
std::string main_flare_file_name = "ymir work/environment/sunflare.dds";
float main_flare_size = 0.35f;
};
struct EnvironmentData {
std::string name;
DirectionalLight dir_light;
MaterialData material;
FogData fog;
SkyBoxData skybox;
LensFlareData lens_flare;
bool LoadFromFile(const std::string& path);
bool LoadFromString(const std::string& content);
// Standard Metin2 presets
static EnvironmentData CreateDayPreset();
static EnvironmentData CreateSunsetPreset();
static EnvironmentData CreateNightPreset();
static EnvironmentData CreateSnowPreset();
};
} // namespace ava2
+102
View File
@@ -0,0 +1,102 @@
#include "FloatingTextManager.h"
#include <algorithm>
#include <cmath>
namespace ava2 {
FloatingTextManager& FloatingTextManager::Instance() {
static FloatingTextManager s_instance;
return s_instance;
}
FloatingTextManager::FloatingTextManager() = default;
void FloatingTextManager::AddDamage(int damage, float worldX, float worldY, float worldZ, bool critical, bool isMonster) {
FloatingTextItem item;
if (critical) {
item.text = "CRITICAL " + std::to_string(damage);
item.color = 0xFFFF4500; // Orange Red for critical
item.scale = 2.2f;
item.maxLifeTime = 1.6f;
item.type = FloatingTextType::CriticalDamage;
} else {
item.text = std::to_string(damage);
item.color = isMonster ? 0xFFFF3333 : 0xFFFFD700; // Red for monster, Gold for player
item.scale = 1.9f;
item.maxLifeTime = 1.2f;
item.type = FloatingTextType::NormalDamage;
}
item.worldX = worldX;
item.worldY = worldY;
item.worldZ = worldZ;
item.currentYOffset = 0.0f;
item.lifeTime = 0.0f;
m_items.push_back(std::move(item));
}
void FloatingTextManager::AddText(const std::string& text, float worldX, float worldY, float worldZ, uint32_t color, float scale, float duration) {
FloatingTextItem item;
item.text = text;
item.worldX = worldX;
item.worldY = worldY;
item.worldZ = worldZ;
item.currentYOffset = 0.0f;
item.lifeTime = 0.0f;
item.maxLifeTime = duration;
item.color = color;
item.scale = scale;
item.type = FloatingTextType::Nameplate;
m_items.push_back(std::move(item));
}
void FloatingTextManager::Update(float dt) {
if (dt <= 0.0f) return;
for (auto& item : m_items) {
item.lifeTime += dt;
item.currentYOffset += 60.0f * dt; // Drift upward in 3D world space
}
// Remove expired texts
m_items.erase(std::remove_if(m_items.begin(), m_items.end(), [](const FloatingTextItem& it) {
return it.lifeTime >= it.maxLifeTime;
}), m_items.end());
}
void FloatingTextManager::Render(SDL_Renderer* renderer, const Gr2SceneRenderer& sceneRenderer) {
if (!renderer || m_items.empty()) return;
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
for (const auto& item : m_items) {
float sx = 0.0f, sy = 0.0f;
if (!sceneRenderer.ProjectToScreen(item.worldX, item.worldY + item.currentYOffset, item.worldZ, sx, sy)) {
continue;
}
float progress = item.lifeTime / item.maxLifeTime;
float alphaFactor = std::clamp(1.0f - progress * progress, 0.0f, 1.0f);
uint8_t a = static_cast<uint8_t>(alphaFactor * 255.0f);
if (a == 0) continue;
uint8_t r = (item.color >> 16) & 0xFF;
uint8_t g = (item.color >> 8) & 0xFF;
uint8_t b = item.color & 0xFF;
float charW = 8.0f * item.scale;
float totalW = static_cast<float>(item.text.size()) * charW;
float tx = sx - totalW * 0.5f;
float ty = sy - 10.0f * item.scale;
// Draw shadow / outline
SDL_SetRenderDrawColor(renderer, 15, 15, 15, a);
SDL_SetRenderScale(renderer, item.scale, item.scale);
SDL_RenderDebugText(renderer, (tx + 1.5f) / item.scale, (ty + 1.5f) / item.scale, item.text.c_str());
// Draw main colored text
SDL_SetRenderDrawColor(renderer, r, g, b, a);
SDL_RenderDebugText(renderer, tx / item.scale, ty / item.scale, item.text.c_str());
SDL_SetRenderScale(renderer, 1.0f, 1.0f);
}
}
} // namespace ava2
+57
View File
@@ -0,0 +1,57 @@
#pragma once
#include "Gr2ModelRenderer.h"
#include <SDL3/SDL.h>
#include <string>
#include <vector>
#include <cstdint>
namespace ava2 {
enum class FloatingTextType {
NormalDamage,
CriticalDamage,
MonsterDamage,
Heal,
Nameplate
};
struct FloatingTextItem {
std::string text;
float worldX = 0.0f;
float worldY = 0.0f;
float worldZ = 0.0f;
float currentYOffset = 0.0f;
float lifeTime = 0.0f;
float maxLifeTime = 1.2f;
uint32_t color = 0xFFFF3333; // ARGB
float scale = 1.8f;
FloatingTextType type = FloatingTextType::NormalDamage;
};
// Floating Combat Text and Floating Nameplate Manager (modeled after 40250 CPythonTextTail)
class FloatingTextManager {
public:
static FloatingTextManager& Instance();
FloatingTextManager();
~FloatingTextManager() = default;
// Add damage popup at world coordinates (e.g. above target's head)
void AddDamage(int damage, float worldX, float worldY, float worldZ, bool critical = false, bool isMonster = true);
// Add general text popup
void AddText(const std::string& text, float worldX, float worldY, float worldZ, uint32_t color, float scale = 1.5f, float duration = 1.5f);
void Update(float dt);
// Render all active floating texts onto the SDL_Renderer using 3D screen projection
void Render(SDL_Renderer* renderer, const Gr2SceneRenderer& sceneRenderer);
size_t GetCount() const { return m_items.size(); }
void Clear() { m_items.clear(); }
private:
std::vector<FloatingTextItem> m_items;
};
} // namespace ava2
File diff suppressed because it is too large Load Diff
+128
View File
@@ -0,0 +1,128 @@
#pragma once
#include "RenderCommands3D.h"
#include <gr2/gr2.h>
#include <SDL3/SDL.h>
#include <string>
#include <vector>
#include <memory>
namespace ava2 {
class Gr2ModelInstance {
public:
static std::unique_ptr<Gr2ModelInstance> Load(const std::string& filepath);
// Load external animation (.gr2) to animate this model
bool LoadExternalAnimation(const std::string& anim_filepath);
float GetAnimationDuration() const;
// Bone queries & attachments
bool GetBoneWorldTransform(const std::string& bone_name, float* out_matrix, float animation_time = -1.0f) const;
void AttachModel(const std::string& bone_name, std::shared_ptr<Gr2ModelInstance> attachment, const float* offset_matrix = nullptr);
void AttachPart(std::shared_ptr<Gr2ModelInstance> part);
void DetachAll();
// Build 3D draw commands for this model and all attached components (weapons, hair, armor parts)
std::vector<Render3DDraw> BuildDrawCommands(float animation_time = -1.0f, const float* world_matrix = nullptr);
// Build draw commands for a skinned part using an external bone palette
std::vector<Render3DDraw> BuildDrawCommandsWithPalette(const std::vector<gr2::Mat4>& skin_matrices,
const float* world_matrix = nullptr,
const gr2::Skeleton* parent_skeleton = nullptr);
bool GetLocalBounds(float& minX, float& minY, float& minZ, float& maxX, float& maxY, float& maxZ) const;
const gr2::File& GetFile() const { return *m_file; }
const gr2::FileInfo& GetInfo() const { return m_file->file_info(); }
private:
struct AttachedModel {
std::string bone_name;
std::shared_ptr<Gr2ModelInstance> model;
float offset[16];
};
std::unique_ptr<gr2::File> m_file;
std::string m_filepath;
std::unique_ptr<gr2::File> m_anim_file;
std::string m_anim_filepath;
std::vector<AttachedModel> m_attached_models;
std::vector<std::shared_ptr<Gr2ModelInstance>> m_attached_parts;
};
// 3D Scene and Model Renderer (modeled after 40250 pipeline architecture)
class Gr2SceneRenderer {
public:
Gr2SceneRenderer(int width = 1024, int height = 768);
~Gr2SceneRenderer();
void SetCameraLookAt(float eyeX, float eyeY, float eyeZ,
float targetX, float targetY, float targetZ,
float upX, float upY, float upZ);
void SetPerspective(float fovYDegrees, float aspect, float zNear, float zFar);
void SetViewport(int x, int y, int width, int height);
void Clear(uint32_t color = 0xFF101520, float depth = 1.0f);
// Rasterize a 3D draw command into the surface using depth buffering and lighting
void RenderDraw(SDL_Surface* targetSurface, const Render3DDraw& draw);
// Rasterize a list of draw commands (CPU software rasterizer)
void RenderScene(SDL_Surface* targetSurface, const std::vector<Render3DDraw>& draws);
// GPU Hardware-accelerated 3D Scene Rendering via SDL_RenderGeometry / Metal / Vulkan
void RenderSceneGPU(SDL_Renderer* renderer, const std::vector<Render3DDraw>& draws);
void DestroyGPUTextures();
SDL_Texture* GetGPUTexture(SDL_Renderer* renderer, const std::string& texturePath);
// Exponential & Linear Depth Fog (modeled after 40250 CMapOutdoor fog)
void SetFog(bool enable, uint32_t color = 0xFFCCDDEE, float density = 0.0003f, float fog_near = 300.0f, float fog_far = 3000.0f, bool exp_mode = true);
bool IsFogEnabled() const { return m_fog_enabled; }
uint32_t GetFogColor() const { return m_fog_color; }
const float* GetViewMatrix() const { return m_view; }
const float* GetProjMatrix() const { return m_proj; }
const int* GetViewport() const { return m_viewport; }
void GetEyePosition(float& x, float& y, float& z) const { x = m_eye[0]; y = m_eye[1]; z = m_eye[2]; }
// Project world coordinates (X, Y, Z) to 2D screen coordinates
bool ProjectToScreen(float worldX, float worldY, float worldZ, float& screenX, float& screenY) const;
// Unproject 2D screen coordinates (screenX, screenY) to a 3D ray in world space
bool ScreenToWorldRay(float screenX, float screenY, float rayOrig[3], float rayDir[3]) const;
// Pick 3D point on terrain heightmap via ray marching and binary search refinement
bool PickTerrain(float screenX, float screenY, const class TerrainHeightmap& terrain,
float& pickX, float& pickY, float& pickZ, float maxRange = 5000.0f) const;
const std::vector<float>& GetDepthBuffer() const { return m_depthBuffer; }
private:
struct TextureData {
int width = 0;
int height = 0;
std::vector<uint8_t> rgba;
};
const TextureData* GetTexture(const std::string& texturePath);
float m_eye[3] = {0.0f, 0.0f, 0.0f};
float m_view[16];
float m_proj[16];
int m_viewport[4];
std::vector<float> m_depthBuffer;
std::unordered_map<std::string, TextureData> m_textureCache;
std::unordered_map<std::string, SDL_Texture*> m_gpuTextureCache;
bool m_fog_enabled = false;
uint32_t m_fog_color = 0xFFCCDDEE;
float m_fog_density = 0.0003f;
float m_fog_near = 300.0f;
float m_fog_far = 3000.0f;
bool m_fog_exp = true;
};
} // namespace ava2
+349
View File
@@ -0,0 +1,349 @@
#include "MapObjectManager.h"
#include "src/eter_render/SpeedTreeForest.h"
#include <algorithm>
#include <cmath>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
namespace ava2 {
static void ComputeObjectOBB(MapObjectInstance& obj);
namespace {
inline void MakeFullTransformMatrix(float yawDeg, float pitchDeg, float rollDeg,
float tx, float ty, float tz, float scale, float* out) {
float ry = yawDeg * 3.14159265358979323846f / 180.0f;
float rx = pitchDeg * 3.14159265358979323846f / 180.0f;
float rz = rollDeg * 3.14159265358979323846f / 180.0f;
float cy = std::cos(ry), sy = std::sin(ry);
float cx = std::cos(rx), sx = std::sin(rx);
float cz = std::cos(rz), sz = std::sin(rz);
// Composite Euler rotation matrix (YXZ / YawPitchRoll)
out[0] = (cy * cz + sy * sx * sz) * scale;
out[1] = (cx * sz) * scale;
out[2] = (-sy * cz + cy * sx * sz) * scale;
out[3] = 0.0f;
out[4] = (-cy * sz + sy * sx * cz) * scale;
out[5] = (cx * cz) * scale;
out[6] = (sy * sz + cy * sx * cz) * scale;
out[7] = 0.0f;
out[8] = (sy * cx) * scale;
out[9] = (-sx) * scale;
out[10] = (cy * cx) * scale;
out[11] = 0.0f;
out[12] = tx;
out[13] = ty;
out[14] = tz;
out[15] = 1.0f;
}
} // namespace
MapObjectManager::MapObjectManager() = default;
std::string MapObjectManager::NormalizePath(const std::string& path) {
std::string p = path;
std::replace(p.begin(), p.end(), '\\', '/');
// Strip drive letter if present (e.g., "d:/", "D:/")
if (p.size() >= 3 && (p[1] == ':' && p[2] == '/')) {
p = p.substr(3);
}
while (!p.empty() && p.front() == '/') {
p.erase(p.begin());
}
if (std::filesystem::exists(p)) return p;
if (std::filesystem::exists("build/dev/" + p)) return "build/dev/" + p;
if (std::filesystem::exists("../" + p)) return "../" + p;
return p;
}
void MapObjectManager::RegisterProperty(uint32_t crc, const std::string& model_path) {
m_property_map[crc] = model_path;
}
size_t MapObjectManager::ScanPropertyDirectory(const std::string& prop_dir) {
if (!std::filesystem::exists(prop_dir)) return 0;
size_t count = 0;
for (const auto& entry : std::filesystem::recursive_directory_iterator(prop_dir, std::filesystem::directory_options::skip_permission_denied)) {
if (!entry.is_regular_file()) continue;
auto ext = entry.path().extension().string();
if (ext != ".prb" && ext != ".prt") continue;
std::ifstream file(entry.path());
if (!file.is_open()) continue;
std::string line;
if (!std::getline(file, line) || line.find("YPRT") == std::string::npos) continue;
std::string crc_line;
if (!std::getline(file, crc_line)) continue;
try {
uint32_t crc = static_cast<uint32_t>(std::stoul(crc_line));
std::string model_file;
while (std::getline(file, line)) {
if (line.find("file") != std::string::npos) {
size_t first = line.find('"');
size_t last = line.rfind('"');
if (first != std::string::npos && last != std::string::npos && last > first) {
model_file = line.substr(first + 1, last - first - 1);
break;
}
}
}
if (!model_file.empty()) {
m_property_map[crc] = model_file;
count++;
}
} catch (...) {
continue;
}
}
return count;
}
std::shared_ptr<Gr2ModelInstance> MapObjectManager::GetOrLoadModel(const std::string& path) {
std::string norm = NormalizePath(path);
auto it = m_model_cache.find(norm);
if (it != m_model_cache.end()) return it->second;
if (!std::filesystem::exists(norm)) {
return nullptr;
}
auto inst = Gr2ModelInstance::Load(norm);
if (inst) {
m_model_cache[norm] = std::move(inst);
return m_model_cache[norm];
}
return nullptr;
}
bool MapObjectManager::LoadAreaData(const std::string& areadata_path, float coord_scale, SpeedTreeForest* forest) {
std::ifstream file(areadata_path);
if (!file.is_open()) {
std::cerr << "MapObjectManager::LoadAreaData failed to open: " << areadata_path << std::endl;
return false;
}
std::string line;
bool in_object = false;
std::vector<std::string> block_lines;
size_t loaded_count = 0;
while (std::getline(file, line)) {
// Strip trailing CR
if (!line.empty() && line.back() == '\r') line.pop_back();
if (line.find("Start Object") != std::string::npos) {
in_object = true;
block_lines.clear();
continue;
}
if (line.find("End Object") != std::string::npos) {
in_object = false;
if (block_lines.size() >= 2) {
// Line 0: X Y Z
// Line 1: CRC
// Line 2 (optional): pitch#roll#yaw or yaw
// Line 3 (optional): height bias
float px = 0.0f, py = 0.0f, pz = 0.0f;
uint32_t crc = 0;
float yaw = 0.0f, pitch = 0.0f, roll = 0.0f;
float bias = 0.0f;
std::istringstream iss(block_lines[0]);
iss >> px >> py >> pz;
try {
crc = static_cast<uint32_t>(std::stoul(block_lines[1]));
} catch (...) {
continue;
}
if (block_lines.size() > 2) {
std::string rot_str = block_lines[2];
size_t s1 = rot_str.find('#');
if (s1 != std::string::npos) {
yaw = std::stof(rot_str.substr(0, s1));
size_t s2 = rot_str.find('#', s1 + 1);
if (s2 != std::string::npos) {
pitch = std::stof(rot_str.substr(s1 + 1, s2 - s1 - 1));
roll = std::stof(rot_str.substr(s2 + 1));
}
} else {
try { yaw = std::stof(rot_str); } catch (...) {}
}
}
if (block_lines.size() > 3) {
try { bias = std::stof(block_lines[3]); } catch (...) {}
}
if (forest && forest->HasMainTree(crc)) {
forest->CreateInstance(px * coord_scale, (pz + bias) * coord_scale, py * coord_scale, crc, yaw, coord_scale);
loaded_count++;
continue;
}
auto prop_it = m_property_map.find(crc);
if (prop_it != m_property_map.end()) {
const std::string& mfile = prop_it->second;
if (forest && (mfile.find(".spt") != std::string::npos || mfile.find(".SPT") != std::string::npos)) {
forest->CreateInstance(px * coord_scale, (pz + bias) * coord_scale, py * coord_scale, crc, yaw, coord_scale, mfile.c_str());
loaded_count++;
continue;
}
auto model = GetOrLoadModel(mfile);
if (model) {
MapObjectInstance obj;
obj.model_path = mfile;
obj.property_crc = crc;
obj.x = px * coord_scale;
obj.y = (pz + bias) * coord_scale;
obj.z = py * coord_scale;
obj.yaw = yaw;
obj.pitch = pitch;
obj.roll = roll;
obj.scale = coord_scale;
obj.model = model;
ComputeObjectOBB(obj);
m_objects.push_back(std::move(obj));
loaded_count++;
}
}
}
continue;
}
if (in_object) {
// Trim leading spaces
size_t start = line.find_first_not_of(" \t");
if (start != std::string::npos) {
block_lines.push_back(line.substr(start));
}
}
}
return loaded_count > 0 || !m_objects.empty();
}
static void ComputeObjectOBB(MapObjectInstance& obj) {
if (!obj.model) {
obj.has_collision = false;
return;
}
float minX = 0, minY = 0, minZ = 0, maxX = 0, maxY = 0, maxZ = 0;
if (obj.model->GetLocalBounds(minX, minY, minZ, maxX, maxY, maxZ)) {
float scale = obj.scale;
float hx = (maxX - minX) * 0.5f * scale;
float hy = (maxY - minY) * 0.5f * scale;
float hz = (maxZ - minZ) * 0.5f * scale;
if (hx < 10.0f && hz < 10.0f) {
obj.has_collision = false;
return;
}
obj.obb.halfExtents[0] = hx;
obj.obb.halfExtents[1] = hy;
obj.obb.halfExtents[2] = hz;
float cxLocal = (minX + maxX) * 0.5f * scale;
float cyLocal = (minY + maxY) * 0.5f * scale;
float czLocal = (minZ + maxZ) * 0.5f * scale;
float yawRad = obj.yaw * (3.14159265f / 180.0f);
obj.obb.yawRad = yawRad;
float cosY = std::cos(yawRad);
float sinY = std::sin(yawRad);
obj.obb.centerX = obj.x + (cxLocal * cosY - czLocal * sinY);
obj.obb.centerY = obj.y + cyLocal;
obj.obb.centerZ = obj.z + (cxLocal * sinY + czLocal * cosY);
obj.has_collision = true;
} else {
obj.has_collision = false;
}
}
bool MapObjectManager::AddObject(const std::string& model_path, float x, float y, float z,
float yaw, float pitch, float roll, float scale) {
auto model = GetOrLoadModel(model_path);
if (!model) return false;
MapObjectInstance obj;
obj.model_path = model_path;
obj.x = x;
obj.y = y;
obj.z = z;
obj.yaw = yaw;
obj.pitch = pitch;
obj.roll = roll;
obj.scale = scale;
obj.model = model;
ComputeObjectOBB(obj);
m_objects.push_back(std::move(obj));
return true;
}
bool MapObjectManager::CheckCollision(float worldX, float worldZ, float actorRadius) const {
for (const auto& obj : m_objects) {
if (!obj.has_collision) continue;
float maxR = std::max(obj.obb.halfExtents[0], obj.obb.halfExtents[2]) * 1.5f + actorRadius;
float dx = worldX - obj.obb.centerX;
float dz = worldZ - obj.obb.centerZ;
if (dx * dx + dz * dz > maxR * maxR) continue;
if (obj.obb.IntersectsCircle2D(worldX, worldZ, actorRadius)) {
return true;
}
}
return false;
}
bool MapObjectManager::CheckCollisionNormal(float worldX, float worldZ, float actorRadius, float& outNx, float& outNz) const {
for (const auto& obj : m_objects) {
if (!obj.has_collision) continue;
float maxR = std::max(obj.obb.halfExtents[0], obj.obb.halfExtents[2]) * 1.5f + actorRadius;
float dx = worldX - obj.obb.centerX;
float dz = worldZ - obj.obb.centerZ;
if (dx * dx + dz * dz > maxR * maxR) continue;
float pen = 0.0f;
if (obj.obb.GetPenetrationAndNormal(worldX, worldZ, actorRadius, outNx, outNz, pen)) {
return true;
}
}
return false;
}
std::vector<Render3DDraw> MapObjectManager::BuildDrawCommands() const {
std::vector<Render3DDraw> all_draws;
for (const auto& obj : m_objects) {
if (!obj.model) continue;
float world[16];
MakeFullTransformMatrix(obj.yaw, obj.pitch, obj.roll, obj.x, obj.y, obj.z, obj.scale, world);
auto draws = obj.model->BuildDrawCommands(-1.0f, world);
for (auto& d : draws) {
all_draws.push_back(std::move(d));
}
}
return all_draws;
}
void MapObjectManager::ClearObjects() {
m_objects.clear();
}
} // namespace ava2
+152
View File
@@ -0,0 +1,152 @@
#pragma once
#include "RenderCommands3D.h"
#include "Gr2ModelRenderer.h"
#include <cstdint>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include <cmath>
#include <algorithm>
namespace ava2 {
struct OrientedBoundingBox {
float centerX = 0.0f;
float centerY = 0.0f;
float centerZ = 0.0f;
float halfExtents[3] = {0.0f, 0.0f, 0.0f}; // half-width along local axes [X, Y, Z]
float yawRad = 0.0f; // rotation around Y axis
bool IntersectsCircle2D(float circleX, float circleZ, float radius) const {
float dx = circleX - centerX;
float dz = circleZ - centerZ;
float cosA = std::cos(-yawRad);
float sinA = std::sin(-yawRad);
float localX = dx * cosA - dz * sinA;
float localZ = dx * sinA + dz * cosA;
float hx = halfExtents[0];
float hz = halfExtents[2];
float clampedX = std::clamp(localX, -hx, hx);
float clampedZ = std::clamp(localZ, -hz, hz);
float diffX = localX - clampedX;
float diffZ = localZ - clampedZ;
return (diffX * diffX + diffZ * diffZ) < (radius * radius);
}
bool GetPenetrationAndNormal(float circleX, float circleZ, float radius, float& outNx, float& outNz, float& outPenetration) const {
float dx = circleX - centerX;
float dz = circleZ - centerZ;
float cosA = std::cos(-yawRad);
float sinA = std::sin(-yawRad);
float localX = dx * cosA - dz * sinA;
float localZ = dx * sinA + dz * cosA;
float hx = halfExtents[0];
float hz = halfExtents[2];
float clampedX = std::clamp(localX, -hx, hx);
float clampedZ = std::clamp(localZ, -hz, hz);
float diffX = localX - clampedX;
float diffZ = localZ - clampedZ;
float distSq = diffX * diffX + diffZ * diffZ;
if (distSq >= radius * radius) return false;
float dist = std::sqrt(distSq);
float localNx = 0.0f, localNz = 0.0f;
if (dist > 0.0001f) {
localNx = diffX / dist;
localNz = diffZ / dist;
outPenetration = radius - dist;
} else {
float overlapX = hx - std::abs(localX);
float overlapZ = hz - std::abs(localZ);
if (overlapX < overlapZ) {
localNx = (localX >= 0.0f) ? 1.0f : -1.0f;
localNz = 0.0f;
outPenetration = radius + overlapX;
} else {
localNx = 0.0f;
localNz = (localZ >= 0.0f) ? 1.0f : -1.0f;
outPenetration = radius + overlapZ;
}
}
float cosBack = std::cos(yawRad);
float sinBack = std::sin(yawRad);
outNx = localNx * cosBack - localNz * sinBack;
outNz = localNx * sinBack + localNz * cosBack;
return true;
}
};
struct MapObjectInstance {
std::string model_path;
uint32_t property_crc = 0;
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
float yaw = 0.0f;
float pitch = 0.0f;
float roll = 0.0f;
float scale = 1.0f;
std::shared_ptr<Gr2ModelInstance> model;
OrientedBoundingBox obb;
bool has_collision = true;
};
class SpeedTreeForest;
/**
* MapObjectManager:
* Manages static outdoor map objects (buildings, trees, fences, props)
* parsed from Metin2 AreaData.txt and Property (.prb/.prt) files.
*/
class MapObjectManager {
public:
MapObjectManager();
~MapObjectManager() = default;
// Register a property definition mapping (CRC32 -> model file path)
void RegisterProperty(uint32_t crc, const std::string& model_path);
// Scan a property directory for .prb (Building) and .prt (Tree) files
size_t ScanPropertyDirectory(const std::string& prop_dir);
// Load AreaData.txt and instantiate objects (GR2 buildings and SpeedTree instances)
bool LoadAreaData(const std::string& areadata_path, float coord_scale = 1.0f, SpeedTreeForest* forest = nullptr);
// Manually add an object instance
bool AddObject(const std::string& model_path, float x, float y, float z,
float yaw = 0.0f, float pitch = 0.0f, float roll = 0.0f, float scale = 1.0f);
// 3D Oriented Bounding Box (OBB) Building Collision Detection
bool CheckCollision(float worldX, float worldZ, float actorRadius = 30.0f) const;
bool CheckCollisionNormal(float worldX, float worldZ, float actorRadius, float& outNx, float& outNz) const;
// Build 3D draw commands for all instantiated objects
std::vector<Render3DDraw> BuildDrawCommands() const;
// Clear all instantiated objects (retaining loaded model cache)
void ClearObjects();
// Query stats
size_t GetObjectCount() const { return m_objects.size(); }
size_t GetPropertyCount() const { return m_property_map.size(); }
size_t GetCachedModelCount() const { return m_model_cache.size(); }
const std::vector<MapObjectInstance>& GetObjects() const { return m_objects; }
private:
std::shared_ptr<Gr2ModelInstance> GetOrLoadModel(const std::string& path);
static std::string NormalizePath(const std::string& path);
std::unordered_map<uint32_t, std::string> m_property_map;
std::unordered_map<std::string, std::shared_ptr<Gr2ModelInstance>> m_model_cache;
std::vector<MapObjectInstance> m_objects;
};
} // namespace ava2
+212
View File
@@ -0,0 +1,212 @@
#include "MinimapManager.h"
#include "eter_resource/dxt.h"
#include <algorithm>
#include <cmath>
#include <iostream>
namespace ava2 {
constexpr float PI = 3.14159265358979323846f;
constexpr float DEG_TO_RAD = PI / 180.0f;
MinimapManager::MinimapManager() = default;
bool MinimapManager::LoadMinimap(const std::string& ddsPath) {
auto img = mtimage::load_dds_path(ddsPath.c_str());
if (!img.ok()) {
GenerateProceduralMinimap(256, 256);
return false;
}
m_texWidth = img.w;
m_texHeight = img.h;
m_texPixels.resize(m_texWidth * m_texHeight);
for (size_t i = 0; i < m_texPixels.size(); ++i) {
uint8_t r = img.rgba[i * 4 + 0];
uint8_t g = img.rgba[i * 4 + 1];
uint8_t b = img.rgba[i * 4 + 2];
uint8_t a = img.rgba[i * 4 + 3];
m_texPixels[i] = (static_cast<uint32_t>(a) << 24) |
(static_cast<uint32_t>(r) << 16) |
(static_cast<uint32_t>(g) << 8) |
static_cast<uint32_t>(b);
}
m_hasTexture = true;
return true;
}
void MinimapManager::GenerateProceduralMinimap(int width, int height) {
m_texWidth = std::max(64, width);
m_texHeight = std::max(64, height);
m_texPixels.resize(m_texWidth * m_texHeight);
for (int y = 0; y < m_texHeight; ++y) {
for (int x = 0; x < m_texWidth; ++x) {
float fx = static_cast<float>(x) / m_texWidth;
float fy = static_cast<float>(y) / m_texHeight;
// Natural Metin2 terrain terrain coloring (plains, hills, river)
float river = std::sin(fx * 3.14f * 2.0f + 1.0f) * 0.2f + 0.5f;
bool is_water = std::abs(fy - river) < 0.08f;
uint8_t r = is_water ? 40 : static_cast<uint8_t>(50 + 40 * std::sin(fx * 10.0f));
uint8_t g = is_water ? 110 : static_cast<uint8_t>(90 + 35 * std::cos(fy * 10.0f));
uint8_t b = is_water ? 160 : static_cast<uint8_t>(40 + 20 * std::sin((fx + fy) * 8.0f));
m_texPixels[y * m_texWidth + x] = (0xFFu << 24) | (r << 16) | (g << 8) | b;
}
}
m_hasTexture = true;
}
void MinimapManager::ClearBlips() {
m_blips.clear();
}
void MinimapManager::AddBlip(float worldX, float worldZ, MinimapBlipType type, float yaw) {
m_blips.push_back({worldX, worldZ, yaw, type});
}
void MinimapManager::RenderRadar(SDL_Surface* targetSurface, int radarX, int radarY, int radarSize,
float playerWorldX, float playerWorldZ, float playerYaw) {
if (!targetSurface || !m_hasTexture || radarSize <= 10) return;
int surfW = targetSurface->w;
int surfH = targetSurface->h;
uint32_t* dst = static_cast<uint32_t*>(targetSurface->pixels);
int pitch = targetSurface->pitch / 4;
float radius = static_cast<float>(radarSize) * 0.5f;
float centerX = static_cast<float>(radarX) + radius;
float centerY = static_cast<float>(radarY) + radius;
float worldSpanX = m_maxX - m_minX;
float worldSpanZ = m_maxZ - m_minZ;
if (worldSpanX < 1.0f) worldSpanX = 5120.0f;
if (worldSpanZ < 1.0f) worldSpanZ = 5120.0f;
// Zoom scale: how many world units per radar pixel
float worldUnitsPerPixel = 12.0f;
// 1. Draw Radar Background & Map Texture
int minPy = std::max(0, radarY);
int maxPy = std::min(surfH - 1, radarY + radarSize);
int minPx = std::max(0, radarX);
int maxPx = std::min(surfW - 1, radarX + radarSize);
for (int py = minPy; py <= maxPy; ++py) {
float dy = static_cast<float>(py) - centerY;
for (int px = minPx; px <= maxPx; ++px) {
float dx = static_cast<float>(px) - centerX;
float dist = std::sqrt(dx * dx + dy * dy);
if (dist > radius) continue;
// Gold/Bronze metallic border ring
if (dist >= radius - 3.5f) {
dst[py * pitch + px] = 0xFFC29B4A; // Metin2 golden radar frame
continue;
} else if (dist >= radius - 4.5f) {
dst[py * pitch + px] = 0xFF2B2213; // Dark bevel ring
continue;
}
// Sample map texture centered at player position
float wx = playerWorldX + dx * worldUnitsPerPixel;
float wz = playerWorldZ + dy * worldUnitsPerPixel;
float u = (wx - m_minX) / worldSpanX;
float v = (wz - m_minZ) / worldSpanZ;
uint32_t texCol = 0xFF18222E;
if (u >= 0.0f && u <= 1.0f && v >= 0.0f && v <= 1.0f) {
int tx = std::clamp(static_cast<int>(u * (m_texWidth - 1)), 0, m_texWidth - 1);
int ty = std::clamp(static_cast<int>(v * (m_texHeight - 1)), 0, m_texHeight - 1);
texCol = m_texPixels[ty * m_texWidth + tx];
}
dst[py * pitch + px] = texCol;
}
}
// 2. Draw Entity Blips (Monsters, NPCs, Party members)
for (const auto& blip : m_blips) {
float relX = (blip.worldX - playerWorldX) / worldUnitsPerPixel;
float relZ = (blip.worldZ - playerWorldZ) / worldUnitsPerPixel;
float blipDist = std::sqrt(relX * relX + relZ * relZ);
if (blipDist > radius - 6.0f) continue;
int bx = static_cast<int>(std::round(centerX + relX));
int by = static_cast<int>(std::round(centerY + relZ));
uint32_t blipCol = 0xFFFF2222; // Red for Monster
int bRadius = 3;
if (blip.type == MinimapBlipType::NPC) {
blipCol = 0xFFFFD700; // Gold for NPC
bRadius = 4;
} else if (blip.type == MinimapBlipType::Party) {
blipCol = 0xFF33CCFF; // Cyan for Party
bRadius = 3;
}
for (int oy = -bRadius; oy <= bRadius; ++oy) {
int py = by + oy;
if (py < 0 || py >= surfH) continue;
for (int ox = -bRadius; ox <= bRadius; ++ox) {
int px = bx + ox;
if (px < 0 || px >= surfW) continue;
if (ox * ox + oy * oy <= bRadius * bRadius) {
dst[py * pitch + px] = blipCol;
}
}
}
}
// 3. Draw Player Blip (Centered Arrow / Pointer oriented with playerYaw)
float rotDeg = 540.0f - playerYaw;
while (rotDeg >= 360.0f) rotDeg -= 360.0f;
while (rotDeg < 0.0f) rotDeg += 360.0f;
float yawRad = rotDeg * DEG_TO_RAD;
// Oriented triangle arrow pointing in player forward direction
float tipX = std::sin(yawRad) * 8.0f;
float tipY = -std::cos(yawRad) * 8.0f;
float leftX = std::sin(yawRad + 2.5f) * 6.0f;
float leftY = -std::cos(yawRad + 2.5f) * 6.0f;
float rightX = std::sin(yawRad - 2.5f) * 6.0f;
float rightY = -std::cos(yawRad - 2.5f) * 6.0f;
float x1 = centerX + tipX, y1 = centerY + tipY;
float x2 = centerX + leftX, y2 = centerY + leftY;
float x3 = centerX + rightX, y3 = centerY + rightY;
auto sign = [](float p1x, float p1y, float p2x, float p2y, float p3x, float p3y) {
return (p1x - p3x) * (p2y - p3y) - (p2x - p3x) * (p1y - p3y);
};
int minAy = std::max(0, static_cast<int>(centerY - 9));
int maxAy = std::min(surfH - 1, static_cast<int>(centerY + 9));
int minAx = std::max(0, static_cast<int>(centerX - 9));
int maxAx = std::min(surfW - 1, static_cast<int>(centerX + 9));
uint32_t arrowCol = 0xFF00FF7F; // Metin2 Spring green player arrow
for (int py = minAy; py <= maxAy; ++py) {
for (int px = minAx; px <= maxAx; ++px) {
float ptX = static_cast<float>(px) + 0.5f;
float ptY = static_cast<float>(py) + 0.5f;
float d1 = sign(ptX, ptY, x1, y1, x2, y2);
float d2 = sign(ptX, ptY, x2, y2, x3, y3);
float d3 = sign(ptX, ptY, x3, y3, x1, y1);
bool has_neg = (d1 < 0) || (d2 < 0) || (d3 < 0);
bool has_pos = (d1 > 0) || (d2 > 0) || (d3 > 0);
if (!(has_neg && has_pos)) {
dst[py * pitch + px] = arrowCol;
}
}
}
}
} // namespace ava2
+67
View File
@@ -0,0 +1,67 @@
#pragma once
#include <SDL3/SDL.h>
#include <string>
#include <vector>
#include <cstdint>
namespace ava2 {
enum class MinimapBlipType {
Player,
Monster,
NPC,
Party,
Waypoint
};
struct MinimapBlip {
float worldX = 0.0f;
float worldZ = 0.0f;
float yaw = 0.0f;
MinimapBlipType type = MinimapBlipType::Monster;
};
class MinimapManager {
public:
MinimapManager();
~MinimapManager() = default;
// Load Metin2 minimap.dds texture (256x256 DXT1)
bool LoadMinimap(const std::string& ddsPath);
// Procedural fallback radar texture if minimap.dds not found
void GenerateProceduralMinimap(int width = 256, int height = 256);
void SetWorldBounds(float minX, float maxX, float minZ, float maxZ) {
m_minX = minX; m_maxX = maxX;
m_minZ = minZ; m_maxZ = maxZ;
}
void ClearBlips();
void AddBlip(float worldX, float worldZ, MinimapBlipType type, float yaw = 0.0f);
// Render radar HUD into SDL_Surface
void RenderRadar(SDL_Surface* targetSurface, int radarX, int radarY, int radarSize,
float playerWorldX, float playerWorldZ, float playerYaw);
bool HasTexture() const { return m_hasTexture; }
int GetTextureWidth() const { return m_texWidth; }
int GetTextureHeight() const { return m_texHeight; }
size_t GetBlipCount() const { return m_blips.size(); }
private:
bool m_hasTexture = false;
int m_texWidth = 0;
int m_texHeight = 0;
std::vector<uint32_t> m_texPixels; // ARGB8888 or RGBA8888 converted
float m_minX = -2560.0f;
float m_maxX = 2560.0f;
float m_minZ = -2560.0f;
float m_maxZ = 2560.0f;
std::vector<MinimapBlip> m_blips;
};
} // namespace ava2
+109
View File
@@ -0,0 +1,109 @@
#include "OrbitCamera.h"
#include "TerrainHeightmap.h"
namespace ava2 {
constexpr float DEG_TO_RAD = 3.14159265358979323846f / 180.0f;
OrbitCamera::OrbitCamera() = default;
void OrbitCamera::BeginDrag(int mouseX, int mouseY) {
m_isDragging = true;
m_lastMouseX = mouseX;
m_lastMouseY = mouseY;
}
void OrbitCamera::Drag(int mouseX, int mouseY, float sensitivity) {
if (!m_isDragging) return;
int dx = mouseX - m_lastMouseX;
int dy = mouseY - m_lastMouseY;
SetYaw(m_yaw + static_cast<float>(dx) * sensitivity);
SetPitch(m_pitch - static_cast<float>(dy) * sensitivity);
m_lastMouseX = mouseX;
m_lastMouseY = mouseY;
}
void OrbitCamera::EndDrag() {
m_isDragging = false;
}
void OrbitCamera::Zoom(float wheelDelta, float zoomStep) {
SetDistance(m_distance - wheelDelta * zoomStep);
}
void OrbitCamera::GetLookTarget(float& targetX, float& targetY, float& targetZ) const {
targetX = m_targetX;
targetY = m_targetY + m_targetHeight;
targetZ = m_targetZ;
}
void OrbitCamera::GetEye(float& eyeX, float& eyeY, float& eyeZ) const {
float pitchRad = m_pitch * DEG_TO_RAD;
float yawRad = m_yaw * DEG_TO_RAD;
float horiz = m_distance * std::cos(pitchRad);
float vert = m_distance * std::sin(pitchRad);
eyeX = m_targetX - horiz * std::sin(yawRad);
eyeY = m_targetY + m_targetHeight + vert;
eyeZ = m_targetZ - horiz * std::cos(yawRad);
}
void OrbitCamera::UpdateWithTerrain(const TerrainHeightmap* terrain) {
if (!terrain) return;
float pitchRad = m_pitch * DEG_TO_RAD;
float yawRad = m_yaw * DEG_TO_RAD;
float horiz = m_distance * std::cos(pitchRad);
float vert = m_distance * std::sin(pitchRad);
float eyeX = m_targetX - horiz * std::sin(yawRad);
float eyeY = m_targetY + m_targetHeight + vert;
float eyeZ = m_targetZ - horiz * std::cos(yawRad);
float groundY = terrain->GetHeightAtWorld(eyeX, eyeZ);
float minGroundY = groundY + 45.0f;
if (eyeY < minGroundY) {
float requiredVert = minGroundY - (m_targetY + m_targetHeight);
if (requiredVert > 0.0f && m_distance > m_minDistance) {
float newPitch = std::asin(std::clamp(requiredVert / m_distance, -1.0f, 1.0f)) / DEG_TO_RAD;
if (newPitch > m_pitch && newPitch <= m_maxPitch) {
m_pitch = newPitch;
} else {
m_distance = std::clamp(m_distance * 0.85f, m_minDistance, m_maxDistance);
}
}
}
float tX = m_targetX;
float tY = m_targetY + m_targetHeight;
float tZ = m_targetZ;
for (int step = 1; step <= 5; ++step) {
float frac = static_cast<float>(step) / 5.0f;
float sx = tX + (eyeX - tX) * frac;
float sy = tY + (eyeY - tY) * frac;
float sz = tZ + (eyeZ - tZ) * frac;
float hillY = terrain->GetHeightAtWorld(sx, sz) + 30.0f;
if (sy < hillY && frac > 0.15f) {
m_distance = std::clamp(m_distance * frac * 0.95f, m_minDistance, m_maxDistance);
break;
}
}
}
void OrbitCamera::ApplyToRenderer(Gr2SceneRenderer& renderer) const {
float eyeX = 0.0f, eyeY = 0.0f, eyeZ = 0.0f;
GetEye(eyeX, eyeY, eyeZ);
float tX = 0.0f, tY = 0.0f, tZ = 0.0f;
GetLookTarget(tX, tY, tZ);
renderer.SetCameraLookAt(eyeX, eyeY, eyeZ, tX, tY, tZ, 0.0f, 1.0f, 0.0f);
}
} // namespace ava2
+79
View File
@@ -0,0 +1,79 @@
#pragma once
#include "Gr2ModelRenderer.h"
#include <algorithm>
#include <cmath>
namespace ava2 {
// Third-Person Orbit Camera modeled after 40250 CCamera / CPythonApplicationCamera
class OrbitCamera {
public:
OrbitCamera();
~OrbitCamera() = default;
void SetTarget(float x, float y, float z) {
m_targetX = x;
m_targetY = y;
m_targetZ = z;
}
void SetTargetHeight(float h) { m_targetHeight = h; }
float GetTargetHeight() const { return m_targetHeight; }
void SetDistance(float dist) {
m_distance = std::clamp(dist, m_minDistance, m_maxDistance);
}
float GetDistance() const { return m_distance; }
void SetPitch(float pitch) {
m_pitch = std::clamp(pitch, m_minPitch, m_maxPitch);
}
float GetPitch() const { return m_pitch; }
void SetYaw(float yaw) {
m_yaw = std::fmod(yaw, 360.0f);
if (m_yaw < 0.0f) m_yaw += 360.0f;
}
float GetYaw() const { return m_yaw; }
// Mouse Dragging (Right Click)
void BeginDrag(int mouseX, int mouseY);
void Drag(int mouseX, int mouseY, float sensitivity = 0.25f);
void EndDrag();
bool IsDragging() const { return m_isDragging; }
// Mouse Wheel Zoom
void Zoom(float wheelDelta, float zoomStep = 40.0f);
// Collision avoidance with terrain heightmap
void UpdateWithTerrain(const class TerrainHeightmap* terrain);
// Coordinate Queries
void GetEye(float& eyeX, float& eyeY, float& eyeZ) const;
void GetLookTarget(float& targetX, float& targetY, float& targetZ) const;
// Apply view transform directly to scene renderer
void ApplyToRenderer(Gr2SceneRenderer& renderer) const;
private:
float m_targetX = 0.0f;
float m_targetY = 0.0f;
float m_targetZ = 0.0f;
float m_targetHeight = 90.0f;
float m_distance = 450.0f;
float m_pitch = 24.0f;
float m_yaw = 0.0f;
float m_minDistance = 120.0f;
float m_maxDistance = 1800.0f;
float m_minPitch = 5.0f;
float m_maxPitch = 85.0f;
bool m_isDragging = false;
int m_lastMouseX = 0;
int m_lastMouseY = 0;
};
} // namespace ava2
+70
View File
@@ -0,0 +1,70 @@
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include <cmath>
namespace ava2 {
inline void MakeTransformMatrix(float yawDegrees, float tx, float ty, float tz, float scale, float* out) {
float rad = yawDegrees * 3.14159265358979323846f / 180.0f;
float c = std::cos(rad) * scale;
float s = std::sin(rad) * scale;
out[0] = c; out[1] = 0.0f; out[2] = -s; out[3] = 0.0f;
out[4] = 0.0f; out[5] = scale;out[6] = 0.0f; out[7] = 0.0f;
out[8] = s; out[9] = 0.0f; out[10] = c; out[11] = 0.0f;
out[12] = tx; out[13] = ty; out[14] = tz; out[15] = 1.0f;
}
// Intermediate 3D draw command structure, modeled after 40250 cross-platform architecture.
// Decouples game logic/animation (GR2) from the underlying GPU/software renderer.
struct Render3DDraw {
std::uint64_t geometry_key = 0;
std::uint64_t geometry_revision = 0;
// D3D row-vector matrices (translation in elements 12..14)
float world[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
float view[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
float proj[16] = {1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1};
float viewport[4] = {0, 0, 1024, 768}; // x, y, width, height
float viewport_z[2] = {0.0f, 1.0f}; // MinZ, MaxZ
// Textures: file path (e.g. "season1/pc/warrior/warrior_4-1.dds") or memory texture
std::string texture0;
std::string texture1;
// Vertex data
std::vector<float> positions; // 3 floats (x, y, z) per vertex
std::vector<float> normals; // 3 floats (nx, ny, nz) per vertex
std::vector<float> uv0; // 2 floats (u, v) per vertex
std::vector<float> uv1; // 2 floats (u, v) per vertex
std::vector<std::uint32_t> diffuse; // 0xAARRGGBB per vertex
std::vector<std::uint32_t> indices; // Triangle list indices (3 per triangle)
// Skeletal skinning streams
std::vector<std::uint8_t> bone_indices; // 4 uint8 per vertex
std::vector<float> bone_weights; // 4 floats per vertex
std::vector<float> bone_matrices; // 16 floats per bone (palette)
// Render states
bool z_enable = true;
bool z_write = true;
std::uint32_t cull_mode = 2; // 1: None, 2: CW, 3: CCW
bool alpha_blend = false;
std::uint32_t blend_mode = 0; // 0: Alpha (D3DBLEND_INVSRCALPHA), 1: Additive (D3DBLEND_ONE)
bool alpha_test = false;
std::uint32_t alpha_ref = 0;
bool fog = true;
// Lighting & Material
bool lighting = true;
float material_diffuse[4] = {1.0f, 1.0f, 1.0f, 1.0f};
float material_ambient[4] = {0.4f, 0.4f, 0.4f, 1.0f};
float material_emissive[4] = {0.0f, 0.0f, 0.0f, 0.0f};
float light_direction[3] = {0.577f, 0.577f, -0.577f}; // Normalized key light
float light_diffuse[4] = {1.0f, 1.0f, 1.0f, 1.0f};
float light_ambient[4] = {0.3f, 0.3f, 0.3f, 1.0f};
};
} // namespace ava2
+396
View File
@@ -0,0 +1,396 @@
#include "SkyBox.h"
#include <algorithm>
#include <cmath>
namespace ava2 {
namespace {
constexpr float PI = 3.14159265358979323846f;
constexpr float DEG2RAD = PI / 180.0f;
uint32_t ColorToUint(const float col[4]) {
auto r = static_cast<uint32_t>(std::clamp(col[0], 0.0f, 1.0f) * 255.0f) & 0xFF;
auto g = static_cast<uint32_t>(std::clamp(col[1], 0.0f, 1.0f) * 255.0f) & 0xFF;
auto b = static_cast<uint32_t>(std::clamp(col[2], 0.0f, 1.0f) * 255.0f) & 0xFF;
auto a = static_cast<uint32_t>(std::clamp(col[3], 0.0f, 1.0f) * 255.0f) & 0xFF;
return (a << 24) | (r << 16) | (g << 8) | b;
}
void InterpolateGradientColor(const std::vector<GradientColor>& gradients, float t, float out_col[4]) {
if (gradients.empty()) {
out_col[0] = 0.5f; out_col[1] = 0.7f; out_col[2] = 0.95f; out_col[3] = 1.0f;
return;
}
float scaled = std::clamp(t, 0.0f, 1.0f) * static_cast<float>(gradients.size());
size_t idx = static_cast<size_t>(scaled);
if (idx >= gradients.size()) idx = gradients.size() - 1;
float local_t = scaled - static_cast<float>(idx);
const auto& gc = gradients[idx];
for (int c = 0; c < 4; ++c) {
out_col[c] = gc.first[c] * (1.0f - local_t) + gc.second[c] * local_t;
}
}
} // namespace
SkyBox::SkyBox() {
m_env = EnvironmentData::CreateDayPreset();
}
SkyBox::~SkyBox() = default;
void SkyBox::SetEnvironment(const EnvironmentData& env) {
m_env = env;
}
void SkyBox::Update(float dt) {
m_total_time += dt;
float speed_u = m_env.skybox.cloud_speed[0];
float speed_v = m_env.skybox.cloud_speed[1];
m_cloud_u += speed_u * dt;
if (m_cloud_u >= 1.0f) m_cloud_u -= std::floor(m_cloud_u);
m_cloud_v += speed_v * dt;
if (m_cloud_v >= 1.0f) m_cloud_v -= std::floor(m_cloud_v);
}
std::vector<Render3DDraw> SkyBox::BuildDrawCommands(const float* viewMatrix,
const float* projMatrix,
float camEyeX,
float camEyeY,
float camEyeZ) {
std::vector<Render3DDraw> draws;
if (m_env.skybox.texture_render_mode) {
auto cubeDraws = BuildTexturedCube(camEyeX, camEyeY, camEyeZ);
for (auto& cd : cubeDraws) {
draws.push_back(std::move(cd));
}
} else {
draws.push_back(BuildGradientSkyDome(camEyeX, camEyeY, camEyeZ));
}
// Dynamic Cloud Layer
if (!m_env.skybox.cloud_texture_file_name.empty()) {
draws.push_back(BuildCloudPlane(camEyeX, camEyeY, camEyeZ));
}
// Radiant Sun Flare Billboard
if (m_env.lens_flare.main_flare_enable && !m_env.lens_flare.main_flare_file_name.empty()) {
draws.push_back(BuildSunFlareBillboard(viewMatrix, camEyeX, camEyeY, camEyeZ));
}
return draws;
}
Render3DDraw SkyBox::BuildGradientSkyDome(float camEyeX, float camEyeY, float camEyeZ) {
Render3DDraw draw;
draw.lighting = false;
draw.fog = false;
draw.z_enable = false; // Pure background layer
draw.z_write = false;
draw.cull_mode = 1; // Double-sided / interior facing
constexpr int SECTORS = 24;
constexpr int NUM_UPPER = 8;
constexpr int NUM_LOWER = 4;
constexpr int NUM_RINGS = NUM_UPPER + NUM_LOWER + 1;
struct RingLevel {
float y_offset;
float radius;
uint32_t color;
};
std::vector<RingLevel> rings;
rings.reserve(NUM_RINGS);
// Build upper rings (zenith 80 deg down to horizon 2 deg)
for (int k = 0; k <= NUM_UPPER; ++k) {
float t = static_cast<float>(k) / static_cast<float>(NUM_UPPER); // 0 at top, 1 at horizon
float angle_deg = 80.0f - t * 78.0f; // 80 -> 2 deg
float phi = angle_deg * DEG2RAD;
float y_off = m_radius * std::sin(phi);
float rad = m_radius * std::cos(phi);
float col[4];
float grad_t = t * 0.80f; // Maps to upper portion of gradients
InterpolateGradientColor(m_env.skybox.gradients, grad_t, col);
rings.push_back({y_off, rad, ColorToUint(col)});
}
// Build lower rings (horizon -2 deg down to -36 deg)
for (int k = 1; k <= NUM_LOWER; ++k) {
float t = static_cast<float>(k) / static_cast<float>(NUM_LOWER);
float angle_deg = -2.0f - t * 34.0f; // -2 -> -36 deg
float phi = angle_deg * DEG2RAD;
float y_off = m_radius * std::sin(phi);
float rad = m_radius * std::cos(phi);
float col[4];
float grad_t = 0.80f + t * 0.20f;
InterpolateGradientColor(m_env.skybox.gradients, grad_t, col);
rings.push_back({y_off, rad, ColorToUint(col)});
}
int total_rings = static_cast<int>(rings.size());
// Top zenith vertex
float top_col[4];
InterpolateGradientColor(m_env.skybox.gradients, 0.0f, top_col);
uint32_t top_vertex_idx = 0;
draw.positions.push_back(camEyeX);
draw.positions.push_back(camEyeY + m_radius * 0.98f);
draw.positions.push_back(camEyeZ);
draw.diffuse.push_back(ColorToUint(top_col));
draw.normals.push_back(0.0f); draw.normals.push_back(-1.0f); draw.normals.push_back(0.0f);
draw.uv0.push_back(0.5f); draw.uv0.push_back(0.0f);
// Ring vertices
std::vector<std::vector<uint32_t>> ring_indices(total_rings, std::vector<uint32_t>(SECTORS + 1));
for (int r = 0; r < total_rings; ++r) {
for (int s = 0; s <= SECTORS; ++s) {
float theta = (2.0f * PI * static_cast<float>(s)) / static_cast<float>(SECTORS);
float vx = camEyeX + rings[r].radius * std::cos(theta);
float vy = camEyeY + rings[r].y_offset;
float vz = camEyeZ + rings[r].radius * std::sin(theta);
uint32_t idx = static_cast<uint32_t>(draw.positions.size() / 3);
ring_indices[r][s] = idx;
draw.positions.push_back(vx);
draw.positions.push_back(vy);
draw.positions.push_back(vz);
draw.diffuse.push_back(rings[r].color);
float nx = -std::cos(theta);
float ny = -rings[r].y_offset / m_radius;
float nz = -std::sin(theta);
draw.normals.push_back(nx); draw.normals.push_back(ny); draw.normals.push_back(nz);
draw.uv0.push_back(static_cast<float>(s) / static_cast<float>(SECTORS));
draw.uv0.push_back(static_cast<float>(r) / static_cast<float>(total_rings));
}
}
// Bottom nadir vertex
float bot_col[4];
InterpolateGradientColor(m_env.skybox.gradients, 1.0f, bot_col);
uint32_t bottom_vertex_idx = static_cast<uint32_t>(draw.positions.size() / 3);
draw.positions.push_back(camEyeX);
draw.positions.push_back(camEyeY - m_radius * 0.65f);
draw.positions.push_back(camEyeZ);
draw.diffuse.push_back(ColorToUint(bot_col));
draw.normals.push_back(0.0f); draw.normals.push_back(1.0f); draw.normals.push_back(0.0f);
draw.uv0.push_back(0.5f); draw.uv0.push_back(1.0f);
// Top fan triangles
for (int s = 0; s < SECTORS; ++s) {
draw.indices.push_back(top_vertex_idx);
draw.indices.push_back(ring_indices[0][s + 1]);
draw.indices.push_back(ring_indices[0][s]);
}
// Quads between successive rings
for (int r = 0; r < total_rings - 1; ++r) {
for (int s = 0; s < SECTORS; ++s) {
uint32_t v00 = ring_indices[r][s];
uint32_t v01 = ring_indices[r][s + 1];
uint32_t v10 = ring_indices[r + 1][s];
uint32_t v11 = ring_indices[r + 1][s + 1];
draw.indices.push_back(v00);
draw.indices.push_back(v01);
draw.indices.push_back(v10);
draw.indices.push_back(v01);
draw.indices.push_back(v11);
draw.indices.push_back(v10);
}
}
// Bottom fan triangles
for (int s = 0; s < SECTORS; ++s) {
draw.indices.push_back(ring_indices[total_rings - 1][s]);
draw.indices.push_back(ring_indices[total_rings - 1][s + 1]);
draw.indices.push_back(bottom_vertex_idx);
}
return draw;
}
std::vector<Render3DDraw> SkyBox::BuildTexturedCube(float camEyeX, float camEyeY, float camEyeZ) {
std::vector<Render3DDraw> results;
float R = m_radius * 0.85f;
struct FaceDef {
int texture_index;
float corners[4][3];
};
// Front (+Z), Back (-Z), Left (-X), Right (+X), Top (+Y)
FaceDef faces[] = {
{0, {{-R, -R, R}, {R, -R, R}, {R, R, R}, {-R, R, R}}},
{1, {{R, -R, -R}, {-R, -R, -R}, {-R, R, -R}, {R, R, -R}}},
{2, {{-R, -R, -R}, {-R, -R, R}, {-R, R, R}, {-R, R, -R}}},
{3, {{R, -R, R}, {R, -R, -R}, {R, R, -R}, {R, R, R}}},
{4, {{-R, R, R}, {R, R, R}, {R, R, -R}, {-R, R, -R}}}
};
for (const auto& f : faces) {
if (f.texture_index >= 6 || m_env.skybox.face_file_names[f.texture_index].empty()) {
continue;
}
Render3DDraw draw;
draw.texture0 = m_env.skybox.face_file_names[f.texture_index];
draw.lighting = false;
draw.fog = false;
draw.z_enable = false;
draw.z_write = false;
draw.cull_mode = 1;
draw.positions = {
camEyeX + f.corners[0][0], camEyeY + f.corners[0][1], camEyeZ + f.corners[0][2],
camEyeX + f.corners[1][0], camEyeY + f.corners[1][1], camEyeZ + f.corners[1][2],
camEyeX + f.corners[2][0], camEyeY + f.corners[2][1], camEyeZ + f.corners[2][2],
camEyeX + f.corners[3][0], camEyeY + f.corners[3][1], camEyeZ + f.corners[3][2],
};
draw.uv0 = {0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f};
draw.diffuse = {0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF};
draw.indices = {0, 1, 2, 0, 2, 3};
results.push_back(std::move(draw));
}
return results;
}
Render3DDraw SkyBox::BuildCloudPlane(float camEyeX, float camEyeY, float camEyeZ) {
Render3DDraw draw;
draw.texture0 = m_env.skybox.cloud_texture_file_name;
draw.lighting = false;
draw.fog = false;
draw.z_enable = false;
draw.z_write = false;
draw.cull_mode = 1;
draw.alpha_blend = true;
draw.blend_mode = 0; // Alpha blend
constexpr int GRID = 8;
float half_size = m_radius * 0.85f;
float cloud_y = camEyeY + 750.0f;
float scale_u = m_env.skybox.cloud_texture_scale[0] > 0.0f ? m_env.skybox.cloud_texture_scale[0] : 4.0f;
float scale_v = m_env.skybox.cloud_texture_scale[1] > 0.0f ? m_env.skybox.cloud_texture_scale[1] : 4.0f;
for (int j = 0; j <= GRID; ++j) {
float fz = static_cast<float>(j) / static_cast<float>(GRID);
float z = camEyeZ + (fz - 0.5f) * 2.0f * half_size;
for (int i = 0; i <= GRID; ++i) {
float fx = static_cast<float>(i) / static_cast<float>(GRID);
float x = camEyeX + (fx - 0.5f) * 2.0f * half_size;
float dx = (fx - 0.5f) * 2.0f;
float dz = (fz - 0.5f) * 2.0f;
float dist_sq = dx * dx + dz * dz;
float alpha = std::clamp(1.0f - dist_sq * 0.70f, 0.0f, 1.0f) * 0.78f;
uint32_t a_byte = static_cast<uint32_t>(alpha * 255.0f);
uint32_t col = (a_byte << 24) | 0x00FFFFFF;
draw.positions.push_back(x);
draw.positions.push_back(cloud_y);
draw.positions.push_back(z);
draw.normals.push_back(0.0f);
draw.normals.push_back(-1.0f);
draw.normals.push_back(0.0f);
draw.uv0.push_back(fx * scale_u + m_cloud_u);
draw.uv0.push_back(fz * scale_v + m_cloud_v);
draw.diffuse.push_back(col);
}
}
int stride = GRID + 1;
for (int j = 0; j < GRID; ++j) {
for (int i = 0; i < GRID; ++i) {
uint32_t i0 = j * stride + i;
uint32_t i1 = j * stride + (i + 1);
uint32_t i2 = (j + 1) * stride + i;
uint32_t i3 = (j + 1) * stride + (i + 1);
draw.indices.push_back(i0);
draw.indices.push_back(i1);
draw.indices.push_back(i2);
draw.indices.push_back(i1);
draw.indices.push_back(i3);
draw.indices.push_back(i2);
}
}
return draw;
}
Render3DDraw SkyBox::BuildSunFlareBillboard(const float* viewMatrix, float camEyeX, float camEyeY, float camEyeZ) {
Render3DDraw draw;
draw.texture0 = m_env.lens_flare.main_flare_file_name;
draw.lighting = false;
draw.fog = false;
draw.z_enable = false;
draw.z_write = false;
draw.cull_mode = 1;
draw.alpha_blend = true;
draw.blend_mode = 1; // Additive blend (D3DBLEND_ONE) for brilliant glow
// Calculate sun vector from directional light
float lx = m_env.dir_light.direction[0];
float ly = m_env.dir_light.direction[1];
float lz = m_env.dir_light.direction[2];
float len = std::sqrt(lx * lx + ly * ly + lz * lz);
if (len > 1e-5f) { lx /= len; ly /= len; lz /= len; }
// Rays come from the sun: sun direction vector points up into sky
float sun_dir[3] = {-lx, std::abs(ly) > 0.1f ? std::abs(ly) : 0.6f, -lz};
float slen = std::sqrt(sun_dir[0] * sun_dir[0] + sun_dir[1] * sun_dir[1] + sun_dir[2] * sun_dir[2]);
sun_dir[0] /= slen; sun_dir[1] /= slen; sun_dir[2] /= slen;
float sun_dist = m_radius * 0.88f;
float sun_x = camEyeX + sun_dir[0] * sun_dist;
float sun_y = camEyeY + sun_dir[1] * sun_dist;
float sun_z = camEyeZ + sun_dir[2] * sun_dist;
// Camera view right and up vectors
float rx = viewMatrix[0], ry = viewMatrix[4], rz = viewMatrix[8];
float ux = viewMatrix[1], uy = viewMatrix[5], uz = viewMatrix[9];
float flare_size = 900.0f * (m_env.lens_flare.main_flare_size > 0.0f ? m_env.lens_flare.main_flare_size : 0.35f);
float h_size = flare_size * 0.5f;
// 4 corners of screen-aligned billboard
float c0[3] = {sun_x - rx * h_size - ux * h_size, sun_y - ry * h_size - uy * h_size, sun_z - rz * h_size - uz * h_size};
float c1[3] = {sun_x + rx * h_size - ux * h_size, sun_y + ry * h_size - uy * h_size, sun_z + rz * h_size - uz * h_size};
float c2[3] = {sun_x + rx * h_size + ux * h_size, sun_y + ry * h_size + uy * h_size, sun_z + rz * h_size + uz * h_size};
float c3[3] = {sun_x - rx * h_size + ux * h_size, sun_y - ry * h_size + uy * h_size, sun_z - rz * h_size + uz * h_size};
draw.positions = {
c0[0], c0[1], c0[2],
c1[0], c1[1], c1[2],
c2[0], c2[1], c2[2],
c3[0], c3[1], c3[2]
};
draw.uv0 = {0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f};
draw.diffuse = {0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF};
draw.indices = {0, 1, 2, 0, 2, 3};
return draw;
}
} // namespace ava2
+48
View File
@@ -0,0 +1,48 @@
#pragma once
#include "EnvironmentData.h"
#include "RenderCommands3D.h"
#include <vector>
namespace ava2 {
class SkyBox {
public:
SkyBox();
~SkyBox();
// Set active environment data
void SetEnvironment(const EnvironmentData& env);
const EnvironmentData& GetEnvironment() const { return m_env; }
EnvironmentData& GetEnvironmentRef() { return m_env; }
// Update cloud scrolling UVs and dynamic state
void Update(float dt);
// Build all sky render draw commands:
// 1. SkyDome / SkyBox background quads with gradient or cube textures
// 2. Cloud plane with scrolling UVs and alpha blending
// 3. Sun flare / lens flare billboard
std::vector<Render3DDraw> BuildDrawCommands(const float* viewMatrix,
const float* projMatrix,
float camEyeX,
float camEyeY,
float camEyeZ);
void SetSkyBoxRadius(float radius) { m_radius = radius; }
float GetSkyBoxRadius() const { return m_radius; }
private:
Render3DDraw BuildGradientSkyDome(float camEyeX, float camEyeY, float camEyeZ);
std::vector<Render3DDraw> BuildTexturedCube(float camEyeX, float camEyeY, float camEyeZ);
Render3DDraw BuildCloudPlane(float camEyeX, float camEyeY, float camEyeZ);
Render3DDraw BuildSunFlareBillboard(const float* viewMatrix, float camEyeX, float camEyeY, float camEyeZ);
EnvironmentData m_env;
float m_radius = 4500.0f;
float m_cloud_u = 0.0f;
float m_cloud_v = 0.0f;
float m_total_time = 0.0f;
};
} // namespace ava2
+240
View File
@@ -0,0 +1,240 @@
#include "src/eter_render/SpeedTreeForest.h"
#include <cmath>
#include <filesystem>
#include <iostream>
namespace ava2 {
namespace {
void MultiplyMat4(const float* a, const float* b, float* out) {
for (int r = 0; r < 4; ++r) {
for (int c = 0; c < 4; ++c) {
out[r * 4 + c] =
a[r * 4 + 0] * b[0 * 4 + c] +
a[r * 4 + 1] * b[1 * 4 + c] +
a[r * 4 + 2] * b[2 * 4 + c] +
a[r * 4 + 3] * b[3 * 4 + c];
}
}
}
void ExtractFrustumPlanes(const float* vp, float planes[6][4]) {
// Left: row3 + row0
planes[0][0] = vp[3] + vp[0];
planes[0][1] = vp[7] + vp[4];
planes[0][2] = vp[11] + vp[8];
planes[0][3] = vp[15] + vp[12];
// Right: row3 - row0
planes[1][0] = vp[3] - vp[0];
planes[1][1] = vp[7] - vp[4];
planes[1][2] = vp[11] - vp[8];
planes[1][3] = vp[15] - vp[12];
// Bottom: row3 + row1
planes[2][0] = vp[3] + vp[1];
planes[2][1] = vp[7] + vp[5];
planes[2][2] = vp[11] + vp[9];
planes[2][3] = vp[15] + vp[13];
// Top: row3 - row1
planes[3][0] = vp[3] - vp[1];
planes[3][1] = vp[7] - vp[5];
planes[3][2] = vp[11] - vp[9];
planes[3][3] = vp[15] - vp[13];
// Near: row2
planes[4][0] = vp[2];
planes[4][1] = vp[6];
planes[4][2] = vp[10];
planes[4][3] = vp[14];
// Far: row3 - row2
planes[5][0] = vp[3] - vp[2];
planes[5][1] = vp[7] - vp[6];
planes[5][2] = vp[11] - vp[10];
planes[5][3] = vp[15] - vp[14];
for (int i = 0; i < 6; ++i) {
float len = std::sqrt(planes[i][0] * planes[i][0] +
planes[i][1] * planes[i][1] +
planes[i][2] * planes[i][2]);
if (len > 1e-6f) {
planes[i][0] /= len;
planes[i][1] /= len;
planes[i][2] /= len;
planes[i][3] /= len;
}
}
}
bool IsSphereInFrustum(const float planes[6][4], float cx, float cy, float cz, float radius) {
for (int i = 0; i < 6; ++i) {
float d = planes[i][0] * cx + planes[i][1] * cy + planes[i][2] * cz + planes[i][3];
if (d < -radius) return false;
}
return true;
}
} // namespace
SpeedTreeForest::SpeedTreeForest() {}
SpeedTreeForest::~SpeedTreeForest() {
Clear();
}
void SpeedTreeForest::Clear() {
m_instances.clear();
}
void SpeedTreeForest::ClearMainTree() {
m_instances.clear();
m_tree_templates.clear();
m_properties.clear();
}
bool SpeedTreeForest::RegisterProperty(uint32_t crc, const std::string& prtPath) {
SpeedTreeProperty prop;
if (SpeedTreeProperty::LoadFromFile(prtPath, prop)) {
if (crc != 0) prop.crc = crc;
return RegisterPropertyData(prop);
}
return false;
}
bool SpeedTreeForest::RegisterPropertyData(const SpeedTreeProperty& prop) {
if (prop.crc == 0) return false;
m_properties[prop.crc] = prop;
return true;
}
void SpeedTreeForest::ScanPropertyDirectory(const std::string& dirPath) {
namespace fs = std::filesystem;
if (!fs::exists(dirPath)) return;
try {
for (const auto& entry : fs::recursive_directory_iterator(dirPath, fs::directory_options::skip_permission_denied)) {
if (entry.is_regular_file() && entry.path().extension() == ".prt") {
SpeedTreeProperty prop;
if (SpeedTreeProperty::LoadFromFile(entry.path().string(), prop)) {
m_properties[prop.crc] = prop;
}
}
}
} catch (const std::exception& e) {
std::cerr << "SpeedTreeForest: ScanPropertyDirectory warning: " << e.what() << std::endl;
}
}
SpeedTreeForest::TreeInstance* SpeedTreeForest::CreateInstance(float x, float y, float z,
uint32_t dwTreeCRC,
float yaw, float scale,
const char* name) {
std::shared_ptr<SpeedTreeModel> model = GetMainTree(dwTreeCRC);
if (!model) {
// Fallback procedural model
std::string tname = name ? name : ("Tree_" + std::to_string(dwTreeCRC));
model = SpeedTreeModel::CreateProcedural(tname, 1000.0f);
m_tree_templates[dwTreeCRC] = model;
}
auto inst = std::make_unique<TreeInstance>();
inst->x = x;
inst->y = y;
inst->z = z;
inst->crc = dwTreeCRC;
inst->yaw = yaw;
inst->scale = (scale > 0.01f) ? scale : 1.0f;
inst->name = name ? name : model->GetName();
inst->model = model;
TreeInstance* ptr = inst.get();
m_instances.push_back(std::move(inst));
return ptr;
}
void SpeedTreeForest::DeleteInstance(TreeInstance* pTree) {
if (!pTree) return;
auto it = std::find_if(m_instances.begin(), m_instances.end(),
[pTree](const std::unique_ptr<TreeInstance>& item) {
return item.get() == pTree;
});
if (it != m_instances.end()) {
m_instances.erase(it);
}
}
std::shared_ptr<SpeedTreeModel> SpeedTreeForest::GetMainTree(uint32_t crc) {
auto it = m_tree_templates.find(crc);
if (it != m_tree_templates.end()) {
return it->second;
}
auto prop_it = m_properties.find(crc);
if (prop_it != m_properties.end()) {
const auto& prop = prop_it->second;
auto model = SpeedTreeModel::Create(prop.tree_file, prop.tree_size);
if (model) {
m_tree_templates[crc] = model;
return model;
}
}
return nullptr;
}
bool SpeedTreeForest::HasMainTree(uint32_t crc) const {
return m_tree_templates.find(crc) != m_tree_templates.end() ||
m_properties.find(crc) != m_properties.end();
}
void SpeedTreeForest::UpdateSystem(float dt) {
m_wind_time += dt;
if (m_wind_time > 10000.0f) m_wind_time -= 10000.0f;
}
std::vector<Render3DDraw> SpeedTreeForest::BuildDrawCommands(const float* viewMatrix,
const float* projMatrix,
float camEyeX, float camEyeY, float camEyeZ,
float maxDist) const {
std::vector<Render3DDraw> draws;
if (m_instances.empty()) return draws;
float vp[16];
MultiplyMat4(viewMatrix, projMatrix, vp);
float planes[6][4];
ExtractFrustumPlanes(vp, planes);
float maxDistSq = maxDist * maxDist;
for (const auto& inst : m_instances) {
if (!inst || !inst->model) continue;
float dx = inst->x - camEyeX;
float dy = inst->y - camEyeY;
float dz = inst->z - camEyeZ;
float distSq = dx * dx + dz * dz;
if (distSq > maxDistSq) continue;
// Frustum culling bounding sphere
float h = inst->model->GetHeight() * inst->scale;
float r = std::max(inst->model->GetRadius() * inst->scale, h * 0.5f);
float cy = inst->y + h * 0.5f;
if (!IsSphereInFrustum(planes, inst->x, cy, inst->z, r)) {
continue;
}
auto inst_draws = inst->model->BuildDrawCommands(inst->x, inst->y, inst->z,
inst->yaw, inst->scale,
m_wind_time, m_wind_strength);
for (auto& id : inst_draws) {
draws.push_back(std::move(id));
}
}
return draws;
}
} // namespace ava2
+63
View File
@@ -0,0 +1,63 @@
#pragma once
#include "src/eter_render/SpeedTreeRT.h"
#include <map>
#include <memory>
#include <string>
#include <vector>
namespace ava2 {
class SpeedTreeForest {
public:
struct TreeInstance {
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
uint32_t crc = 0;
float yaw = 0.0f;
float scale = 1.0f;
std::string name;
std::shared_ptr<SpeedTreeModel> model;
};
SpeedTreeForest();
~SpeedTreeForest();
void Clear();
void ClearMainTree();
bool RegisterProperty(uint32_t crc, const std::string& prtPath);
bool RegisterPropertyData(const SpeedTreeProperty& prop);
void ScanPropertyDirectory(const std::string& dirPath);
TreeInstance* CreateInstance(float x, float y, float z, uint32_t dwTreeCRC,
float yaw = 0.0f, float scale = 1.0f, const char* name = nullptr);
void DeleteInstance(TreeInstance* pTree);
void UpdateSystem(float dt);
std::vector<Render3DDraw> BuildDrawCommands(const float* viewMatrix, const float* projMatrix,
float camEyeX, float camEyeY, float camEyeZ,
float maxDist = 6500.0f) const;
size_t GetInstanceCount() const { return m_instances.size(); }
size_t GetMainTreeCount() const { return m_tree_templates.size(); }
const std::vector<std::unique_ptr<TreeInstance>>& GetInstances() const { return m_instances; }
std::shared_ptr<SpeedTreeModel> GetMainTree(uint32_t crc);
bool HasMainTree(uint32_t crc) const;
void SetWindStrength(float s) { m_wind_strength = s; }
float GetWindStrength() const { return m_wind_strength; }
private:
float m_wind_time = 0.0f;
float m_wind_strength = 16.0f;
std::map<uint32_t, SpeedTreeProperty> m_properties;
std::map<uint32_t, std::shared_ptr<SpeedTreeModel>> m_tree_templates;
std::vector<std::unique_ptr<TreeInstance>> m_instances;
};
} // namespace ava2
+668
View File
@@ -0,0 +1,668 @@
#include "src/eter_render/SpeedTreeRT.h"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstring>
#include <fstream>
#include <iostream>
#include <sstream>
namespace ava2 {
namespace {
constexpr float kPI = 3.14159265358979323846f;
constexpr float kTAU = 2.0f * kPI;
std::string ToLower(std::string s) {
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) {
return static_cast<char>(std::tolower(c));
});
return s;
}
std::string BaseName(std::string p) {
for (char& c : p) if (c == '\\') c = '/';
size_t s = p.find_last_of('/');
return (s == std::string::npos) ? p : p.substr(s + 1);
}
std::string StripQuotes(const std::string& s) {
size_t start = s.find_first_not_of(" \t\r\n\"");
if (start == std::string::npos) return "";
size_t end = s.find_last_not_of(" \t\r\n\"");
return s.substr(start, end - start + 1);
}
bool EndsWithCI(const std::string& s, const char* suf) {
size_t n = std::strlen(suf);
if (s.size() < n) return false;
for (size_t i = 0; i < n; ++i) {
if (std::tolower((unsigned char)s[s.size() - n + i]) != std::tolower((unsigned char)suf[i]))
return false;
}
return true;
}
std::string AsDds(std::string s) {
if (s.empty()) return s;
size_t dot = s.find_last_of('.');
if (dot != std::string::npos) s.resize(dot);
return s + ".dds";
}
bool IsConifer(const std::string& name) {
std::string s = ToLower(name);
return s.find("pine") != std::string::npos || s.find("cypress") != std::string::npos ||
s.find("fir") != std::string::npos || s.find("spruce") != std::string::npos ||
s.find("cedar") != std::string::npos || s.find("conifer") != std::string::npos ||
s.find("tanne") != std::string::npos;
}
bool IsGrassOrShrubSpecies(const std::string& name) {
std::string s = ToLower(name);
return s.find("grass") != std::string::npos || s.find("flower") != std::string::npos ||
s.find("plant") != std::string::npos || s.find("bush") != std::string::npos ||
s.find("shrub") != std::string::npos || s.find("tufis") != std::string::npos ||
s.find("duester") != std::string::npos;
}
std::string ResolvePath(const std::string& path) {
if (path.empty()) return "";
std::string clean = path;
for (char& c : clean) if (c == '\\') c = '/';
if (clean.size() > 2 && clean[1] == ':') {
clean = clean.substr(2);
while (!clean.empty() && clean[0] == '/') clean = clean.substr(1);
}
std::vector<std::string> roots = {
"",
"build/dev/",
"../",
"ymir work/",
"build/dev/ymir work/",
"/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/",
"/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/property/",
"/Users/shen/Work/Code/Metin2/ava2-client/"
};
for (const auto& r : roots) {
std::string cand = r + clean;
std::ifstream f(cand, std::ios::binary);
if (f.good()) return cand;
}
return clean;
}
} // namespace
bool SpeedTreeProperty::LoadFromFile(const std::string& filename, SpeedTreeProperty& out) {
std::string resolved = ResolvePath(filename);
std::ifstream file(resolved);
if (!file.is_open()) return false;
std::string line;
bool has_yprt = false;
while (std::getline(file, line)) {
std::istringstream iss(line);
std::string token;
if (!(iss >> token)) continue;
if (token == "YPRT") {
has_yprt = true;
if (file >> out.crc) {
// crc parsed
}
} else if (token == "propertyname") {
std::string rem;
std::getline(iss, rem);
out.property_name = StripQuotes(rem);
} else if (token == "propertytype") {
// expected "Tree"
} else if (token == "treefile") {
std::string rem;
std::getline(iss, rem);
out.tree_file = StripQuotes(rem);
} else if (token == "treesize") {
std::string rem;
std::getline(iss, rem);
try { out.tree_size = std::stof(StripQuotes(rem)); } catch (...) {}
} else if (token == "treevariance") {
std::string rem;
std::getline(iss, rem);
try { out.tree_variance = std::stof(StripQuotes(rem)); } catch (...) {}
}
}
return has_yprt && out.crc != 0;
}
bool SpeedTreeSptInfo::SniffMemory(const uint8_t* p, size_t n, SpeedTreeSptInfo& out) {
out = SpeedTreeSptInfo{};
if (!p || n < 20) return false;
// Check magic
std::string bytes(reinterpret_cast<const char*>(p), n);
size_t magic_pos = bytes.find("__IdvSpt_02_");
if (magic_pos != std::string::npos) {
out.ok = true;
}
auto i32_at = [&](size_t o) -> int32_t {
if (o + 4 > n) return 0;
int32_t val = 0;
std::memcpy(&val, p + o, 4);
return val;
};
// Parse tokens if structured
for (size_t o = 0; o + 12 <= n; ++o) {
int32_t token = i32_at(o);
if (token == 2000) {
// branch texture name
int32_t len = i32_at(o + 4);
if (len > 0 && len < 256 && o + 8 + len <= n) {
std::string s(reinterpret_cast<const char*>(p + o + 8), len);
out.bark_texture = BaseName(s);
}
} else if (token == 2001) {
float sz = 0.0f;
std::memcpy(&sz, p + o + 4, 4);
if (sz > 1.0f && sz < 50000.0f) out.size = sz;
} else if (token == 2002) {
float var = 0.0f;
std::memcpy(&var, p + o + 4, 4);
out.variance = var;
} else if (token == 10000 && i32_at(o + 4) == 10002) {
// Texture coordinates section: 10002 <count> leaf maps
size_t c = o + 4;
for (int32_t section : {10002, 10003, 10004}) {
if (c + 8 > n || i32_at(c) != section) break;
int32_t count = i32_at(c + 4);
c += 8;
if (count <= 0 || count > 64 || c + count * 32 > n) break;
auto& target = (section == 10002) ? out.leaf_uvs : (section == 10003 ? out.frond_uvs : out.billboard_uvs);
for (int32_t i = 0; i < count; ++i, c += 32) {
float f[8];
std::memcpy(f, p + c, sizeof(f));
target.push_back({f[2], 1.0f - f[1], f[0], 1.0f - f[5]});
}
}
}
}
// String scan fallback for bark & composite maps
std::string cur;
std::vector<std::string> str_refs;
for (size_t i = 0; i < n; ++i) {
unsigned char c = p[i];
if (c >= 0x20 && c < 0x7F) {
cur += static_cast<char>(c);
} else {
if (cur.size() >= 4 && (EndsWithCI(cur, ".tga") || EndsWithCI(cur, ".dds"))) {
str_refs.push_back(BaseName(cur));
}
cur.clear();
}
}
for (const auto& r : str_refs) {
std::string low = ToLower(r);
if (out.bark_texture.empty() && low.find("bark") != std::string::npos) {
out.bark_texture = AsDds(r);
} else if (out.leaf_texture.empty() && (low.find("leaf") != std::string::npos || low.find("leaves") != std::string::npos || low.find("grass") != std::string::npos)) {
out.leaf_texture = AsDds(r);
}
}
// Check composite maps
auto find_token = [&](const char* needle) -> std::string {
size_t pos = bytes.find(needle);
if (pos == std::string::npos) return "";
size_t end = pos + std::strlen(needle);
while (end < bytes.size() && (std::isalnum((unsigned char)bytes[end]) || bytes[end] == '_' || bytes[end] == '-')) {
++end;
}
return bytes.substr(pos, end - pos);
};
std::string comp = find_token("CompositeMap");
if (!comp.empty()) out.leaf_texture = AsDds(comp);
std::string shadow = find_token("CompositeShadowMap");
if (!shadow.empty()) out.shadow_texture = AsDds(shadow);
if (out.leaf_texture.empty() && !str_refs.empty()) {
out.leaf_texture = AsDds(str_refs.front());
}
return out.ok || !out.bark_texture.empty() || !out.leaf_texture.empty();
}
bool SpeedTreeSptInfo::SniffSpt(const std::string& filepath, SpeedTreeSptInfo& out) {
std::string resolved = ResolvePath(filepath);
std::ifstream file(resolved, std::ios::binary);
if (!file.is_open()) return false;
std::vector<uint8_t> buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
return SniffMemory(buffer.data(), buffer.size(), out);
}
SpeedTreeModel::SpeedTreeModel() {}
std::shared_ptr<SpeedTreeModel> SpeedTreeModel::Create(const std::string& sptPath, float treeSize) {
auto model = std::make_shared<SpeedTreeModel>();
model->m_spt_path = sptPath;
model->m_name = BaseName(sptPath);
model->m_height = treeSize > 1.0f ? treeSize : 1000.0f;
model->m_radius = model->m_height * 0.35f;
model->m_is_grass_or_shrub = IsGrassOrShrubSpecies(model->m_name);
SpeedTreeSptInfo info;
SpeedTreeSptInfo::SniffSpt(sptPath, info);
if (info.size > 1.0f && treeSize <= 0.0f) {
model->m_height = info.size;
model->m_radius = model->m_height * 0.35f;
}
model->BuildGeometry(info);
return model;
}
std::shared_ptr<SpeedTreeModel> SpeedTreeModel::CreateProcedural(const std::string& name, float treeSize,
const std::string& barkTex,
const std::string& leafTex) {
auto model = std::make_shared<SpeedTreeModel>();
model->m_name = name;
model->m_height = treeSize > 1.0f ? treeSize : 1000.0f;
model->m_radius = model->m_height * 0.35f;
model->m_is_grass_or_shrub = IsGrassOrShrubSpecies(name);
SpeedTreeSptInfo info;
info.ok = true;
info.bark_texture = barkTex;
info.leaf_texture = leafTex;
info.size = treeSize;
model->BuildGeometry(info);
return model;
}
static bool TextureFileExists(const std::string& p) {
if (p.empty()) return false;
std::string s = p;
for (char& c : s) if (c == '\\') c = '/';
if (std::filesystem::exists(s)) return true;
if (std::filesystem::exists("build/dev/" + s)) return true;
std::string lower = s;
for (char& c : lower) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
if (std::filesystem::exists(lower)) return true;
if (std::filesystem::exists("build/dev/" + lower)) return true;
return false;
}
static std::string ResolveExistingTexture(const std::string& candidate,
const std::string& dir,
const std::string& modelName,
bool isGrass,
bool isBark) {
std::string lowerName = modelName;
for (char& c : lowerName) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
// Specific species exact mappings for Metin2 authentic assets
if (lowerName.find("scotchpine") != std::string::npos || lowerName.find("pine") != std::string::npos) {
if (isBark && TextureFileExists("ymir work/palnts_2/all/ot/treescotchpinebark.dds"))
return "ymir work/palnts_2/all/ot/treescotchpinebark.dds";
if (!isBark && TextureFileExists("ymir work/palnts_2/all/ot/treescotchpineleaves.dds"))
return "ymir work/palnts_2/all/ot/treescotchpineleaves.dds";
}
if (lowerName.find("willowoak") != std::string::npos || lowerName.find("oak") != std::string::npos) {
if (isBark && TextureFileExists("ymir work/palnts_2/all/ot/treewillowoakbarkmoss.dds"))
return "ymir work/palnts_2/all/ot/treewillowoakbarkmoss.dds";
if (!isBark && TextureFileExists("ymir work/palnts_2/all/ot/treewillowoakleavessu.dds"))
return "ymir work/palnts_2/all/ot/treewillowoakleavessu.dds";
}
if (lowerName.find("beech") != std::string::npos) {
if (isBark && TextureFileExists("ymir work/zone/b/tree/1/beechbark.dds"))
return "ymir work/zone/b/tree/1/beechbark.dds";
if (!isBark && TextureFileExists("ymir work/zone/b/tree/1/compositemap.dds"))
return "ymir work/zone/b/tree/1/compositemap.dds";
}
if (!candidate.empty()) {
std::string p1 = candidate;
std::string p2 = dir + candidate;
if (TextureFileExists(p1)) return p1;
if (TextureFileExists(p2)) return p2;
}
if (isGrass) {
if (!isBark) {
std::vector<std::string> grass_cands = {
dir + "plant_grass.dds",
dir + "compositemapn2.dds",
dir + "plant_grass_bush1.dds",
"ymir work/plants/plant_grass.dds",
"ymir work/plants/compositemapn2.dds",
"ymir work/plants/plant_grass_bush1.dds",
"ymir work/palnts_2/all/os/shrubgenericelderberryleavessu.dds",
"ymir work/zone/b/tree/1/compositemap.dds"
};
for (const auto& g : grass_cands) if (TextureFileExists(g)) return g;
} else {
std::vector<std::string> bark_cands = {
dir + "aloeverabark.dds",
"ymir work/plants/aloeverabark.dds",
"ymir work/zone/b/tree/1/beechbark.dds"
};
for (const auto& b : bark_cands) if (TextureFileExists(b)) return b;
}
} else {
if (isBark) {
std::vector<std::string> bark_cands = {
dir + "beechbark.dds",
dir + "treewillowoakbarkmoss.dds",
dir + "treescotchpinebark.dds",
"ymir work/zone/b/tree/1/beechbark.dds",
"ymir work/palnts_2/all/ot/treewillowoakbarkmoss.dds",
"ymir work/palnts_2/all/ot/treescotchpinebark.dds",
"ymir work/zone/b/tree/c/englishoakbark.dds"
};
for (const auto& b : bark_cands) if (TextureFileExists(b)) return b;
} else {
std::vector<std::string> leaf_cands = {
dir + "compositemap.dds",
dir + "treewillowoakleavessu.dds",
dir + "treescotchpineleaves.dds",
"ymir work/zone/b/tree/1/compositemap.dds",
"ymir work/zone/b/tree/c/compositemap.dds",
"ymir work/palnts_2/all/ot/treewillowoakleavessu.dds",
"ymir work/palnts_2/all/ot/treescotchpineleaves.dds"
};
for (const auto& l : leaf_cands) if (TextureFileExists(l)) return l;
}
}
return isBark ? "ymir work/zone/b/tree/1/beechbark.dds" : "ymir work/zone/b/tree/1/compositemap.dds";
}
void SpeedTreeModel::BuildGeometry(const SpeedTreeSptInfo& info) {
// Resolve textures with directory prefixes if known
std::string dir = "";
size_t last_slash = m_spt_path.find_last_of("/\\");
if (last_slash != std::string::npos) {
dir = m_spt_path.substr(0, last_slash + 1);
}
m_bark_texture = ResolveExistingTexture(info.bark_texture, dir, m_name, m_is_grass_or_shrub, true);
m_leaf_texture = ResolveExistingTexture(info.leaf_texture, dir, m_name, m_is_grass_or_shrub, false);
if (m_is_grass_or_shrub) {
BuildGrassShrubGeometry(m_height, info);
} else {
BuildTreeGeometry(m_height, info);
}
}
void SpeedTreeModel::BuildGrassShrubGeometry(float H, const SpeedTreeSptInfo& info) {
// 3 intersecting vertical quads (Star pattern at 0, 60, 120 degrees)
m_leaf_template.positions.clear();
m_leaf_template.normals.clear();
m_leaf_template.uv0.clear();
m_leaf_template.diffuse.clear();
m_leaf_template.indices.clear();
m_leaf_template.texture0 = m_leaf_texture;
m_leaf_template.alpha_test = true;
m_leaf_template.alpha_ref = 70;
m_leaf_template.cull_mode = 1; // Double-sided
m_leaf_template.lighting = true;
m_leaf_template.z_enable = true;
m_leaf_template.z_write = true;
float W = H * 0.85f;
float hW = W * 0.5f;
float angles[] = {0.0f, kPI / 3.0f, 2.0f * kPI / 3.0f};
for (int p = 0; p < 3; ++p) {
float a = angles[p];
float dx = std::cos(a) * hW;
float dz = std::sin(a) * hW;
float nx = -std::sin(a);
float nz = std::cos(a);
uint32_t base_idx = static_cast<uint32_t>(m_leaf_template.positions.size() / 3);
// 4 corners of vertical plane
// Bottom-left, Bottom-right, Top-right, Top-left
float corners[4][3] = {
{-dx, 0.0f, -dz},
{ dx, 0.0f, dz},
{ dx, H, dz},
{-dx, H, -dz}
};
for (int c = 0; c < 4; ++c) {
m_leaf_template.positions.push_back(corners[c][0]);
m_leaf_template.positions.push_back(corners[c][1]);
m_leaf_template.positions.push_back(corners[c][2]);
m_leaf_template.normals.push_back(nx);
m_leaf_template.normals.push_back(0.3f);
m_leaf_template.normals.push_back(nz);
m_leaf_template.diffuse.push_back(0xFFFFFFFF);
}
m_leaf_template.uv0.push_back(0.0f); m_leaf_template.uv0.push_back(1.0f);
m_leaf_template.uv0.push_back(1.0f); m_leaf_template.uv0.push_back(1.0f);
m_leaf_template.uv0.push_back(1.0f); m_leaf_template.uv0.push_back(0.0f);
m_leaf_template.uv0.push_back(0.0f); m_leaf_template.uv0.push_back(0.0f);
m_leaf_template.indices.push_back(base_idx + 0);
m_leaf_template.indices.push_back(base_idx + 1);
m_leaf_template.indices.push_back(base_idx + 2);
m_leaf_template.indices.push_back(base_idx + 0);
m_leaf_template.indices.push_back(base_idx + 2);
m_leaf_template.indices.push_back(base_idx + 3);
}
}
void SpeedTreeModel::BuildTreeGeometry(float H, const SpeedTreeSptInfo& info) {
bool conifer = IsConifer(m_name);
// 1. Build Trunk Cylindrical Tube
m_trunk_template.positions.clear();
m_trunk_template.normals.clear();
m_trunk_template.uv0.clear();
m_trunk_template.diffuse.clear();
m_trunk_template.indices.clear();
m_trunk_template.texture0 = m_bark_texture;
m_trunk_template.alpha_test = false;
m_trunk_template.cull_mode = 2; // Backface cull
m_trunk_template.lighting = true;
m_trunk_template.z_enable = true;
m_trunk_template.z_write = true;
constexpr int SEGS = 8;
constexpr int LEVELS = 4;
float trunk_top = H * (conifer ? 0.90f : 0.72f);
float r_base = H * 0.038f;
float r_top = H * 0.012f;
for (int l = 0; l <= LEVELS; ++l) {
float f = static_cast<float>(l) / LEVELS;
float y = f * trunk_top;
float r = r_base * (1.0f - f) + r_top * f;
float v = f * 3.0f; // Tile bark vertically
for (int s = 0; s <= SEGS; ++s) {
float a = static_cast<float>(s) / SEGS * kTAU;
float cos_a = std::cos(a);
float sin_a = std::sin(a);
m_trunk_template.positions.push_back(cos_a * r);
m_trunk_template.positions.push_back(y);
m_trunk_template.positions.push_back(sin_a * r);
m_trunk_template.normals.push_back(cos_a);
m_trunk_template.normals.push_back(0.0f);
m_trunk_template.normals.push_back(sin_a);
m_trunk_template.uv0.push_back(static_cast<float>(s) / SEGS);
m_trunk_template.uv0.push_back(v);
m_trunk_template.diffuse.push_back(0xFFFFFFFF);
}
}
int stride = SEGS + 1;
for (int l = 0; l < LEVELS; ++l) {
for (int s = 0; s < SEGS; ++s) {
uint32_t i0 = l * stride + s;
uint32_t i1 = l * stride + (s + 1);
uint32_t i2 = (l + 1) * stride + s;
uint32_t i3 = (l + 1) * stride + (s + 1);
m_trunk_template.indices.push_back(i0);
m_trunk_template.indices.push_back(i2);
m_trunk_template.indices.push_back(i1);
m_trunk_template.indices.push_back(i1);
m_trunk_template.indices.push_back(i2);
m_trunk_template.indices.push_back(i3);
}
}
// 2. Build Foliage Canopy Clusters (Multiple Cross Quads)
m_leaf_template.positions.clear();
m_leaf_template.normals.clear();
m_leaf_template.uv0.clear();
m_leaf_template.diffuse.clear();
m_leaf_template.indices.clear();
m_leaf_template.texture0 = m_leaf_texture;
m_leaf_template.alpha_test = true;
m_leaf_template.alpha_ref = 84;
m_leaf_template.cull_mode = 1; // Double sided
m_leaf_template.lighting = true;
m_leaf_template.z_enable = true;
m_leaf_template.z_write = true;
UVRect default_uv{0.0f, 0.0f, 1.0f, 1.0f};
const auto& uv_pool = info.leaf_uvs.empty() ? (info.frond_uvs.empty() ? std::vector<UVRect>{default_uv} : info.frond_uvs) : info.leaf_uvs;
int cluster_count = conifer ? 14 : 12;
for (int k = 0; k < cluster_count; ++k) {
float f = static_cast<float>(k) / cluster_count;
float y = H * (conifer ? (0.28f + f * 0.65f) : (0.42f + f * 0.48f));
float spread = H * (conifer ? (0.24f * (1.0f - f * 0.70f)) : (0.28f * std::sin(f * kPI)));
float angle = f * kTAU * 1.618f;
float cx = (k == cluster_count - 1) ? 0.0f : (std::cos(angle) * spread);
float cz = (k == cluster_count - 1) ? 0.0f : (std::sin(angle) * spread);
float quad_w = H * (conifer ? 0.28f : 0.38f);
float quad_h = H * (conifer ? 0.24f : 0.32f);
float hw = quad_w * 0.5f;
float hh = quad_h * 0.5f;
UVRect uv = uv_pool[k % uv_pool.size()];
// 2 perpendicular planes per cluster (0 and 90 deg)
for (int p = 0; p < 2; ++p) {
float pa = angle + p * (kPI * 0.5f);
float dx = std::cos(pa) * hw;
float dz = std::sin(pa) * hw;
uint32_t bidx = static_cast<uint32_t>(m_leaf_template.positions.size() / 3);
float pts[4][3] = {
{cx - dx, y - hh, cz - dz},
{cx + dx, y - hh, cz + dz},
{cx + dx, y + hh, cz + dz},
{cx - dx, y + hh, cz - dz}
};
for (int i = 0; i < 4; ++i) {
m_leaf_template.positions.push_back(pts[i][0]);
m_leaf_template.positions.push_back(pts[i][1]);
m_leaf_template.positions.push_back(pts[i][2]);
m_leaf_template.normals.push_back(std::cos(pa + kPI * 0.5f));
m_leaf_template.normals.push_back(0.4f);
m_leaf_template.normals.push_back(std::sin(pa + kPI * 0.5f));
m_leaf_template.diffuse.push_back(0xFFFFFFFF);
}
m_leaf_template.uv0.push_back(uv.u0); m_leaf_template.uv0.push_back(uv.v1);
m_leaf_template.uv0.push_back(uv.u1); m_leaf_template.uv0.push_back(uv.v1);
m_leaf_template.uv0.push_back(uv.u1); m_leaf_template.uv0.push_back(uv.v0);
m_leaf_template.uv0.push_back(uv.u0); m_leaf_template.uv0.push_back(uv.v0);
m_leaf_template.indices.push_back(bidx + 0);
m_leaf_template.indices.push_back(bidx + 1);
m_leaf_template.indices.push_back(bidx + 2);
m_leaf_template.indices.push_back(bidx + 0);
m_leaf_template.indices.push_back(bidx + 2);
m_leaf_template.indices.push_back(bidx + 3);
}
}
}
std::vector<Render3DDraw> SpeedTreeModel::BuildDrawCommands(float worldX, float worldY, float worldZ,
float yawDeg, float scale,
float windTime, float windStrength) const {
std::vector<Render3DDraw> results;
float rad = yawDeg * (kPI / 180.0f);
float cos_y = std::cos(rad);
float sin_y = std::sin(rad);
auto transform_mesh = [&](const Render3DDraw& tmpl, bool is_canopy) -> Render3DDraw {
Render3DDraw out = tmpl;
size_t nverts = tmpl.positions.size() / 3;
out.positions.resize(tmpl.positions.size());
out.normals.resize(tmpl.normals.size());
float inv_H = 1.0f / (m_height * scale);
for (size_t i = 0; i < nverts; ++i) {
float lx = tmpl.positions[i * 3 + 0] * scale;
float ly = tmpl.positions[i * 3 + 1] * scale;
float lz = tmpl.positions[i * 3 + 2] * scale;
// Rotate around Y
float rx = lx * cos_y + lz * sin_y;
float ry = ly;
float rz = -lx * sin_y + lz * cos_y;
// Wind Sway displacement proportional to height squared
float h_factor = std::clamp(ry * inv_H, 0.0f, 1.2f);
float flex = is_canopy ? (h_factor * h_factor) : (h_factor * h_factor * 0.4f);
float sway_x = std::sin(windTime * 2.2f + worldX * 0.008f + worldZ * 0.008f) * windStrength * flex;
float sway_z = std::cos(windTime * 1.8f + worldX * 0.012f) * windStrength * flex * 0.6f;
out.positions[i * 3 + 0] = worldX + rx + sway_x;
out.positions[i * 3 + 1] = worldY + ry;
out.positions[i * 3 + 2] = worldZ + rz + sway_z;
// Rotate normal
float nx = tmpl.normals[i * 3 + 0];
float ny = tmpl.normals[i * 3 + 1];
float nz = tmpl.normals[i * 3 + 2];
out.normals[i * 3 + 0] = nx * cos_y + nz * sin_y;
out.normals[i * 3 + 1] = ny;
out.normals[i * 3 + 2] = -nx * sin_y + nz * cos_y;
}
return out;
};
if (!m_trunk_template.positions.empty()) {
results.push_back(transform_mesh(m_trunk_template, false));
}
if (!m_leaf_template.positions.empty()) {
results.push_back(transform_mesh(m_leaf_template, true));
}
return results;
}
} // namespace ava2
+80
View File
@@ -0,0 +1,80 @@
#pragma once
#include "src/eter_render/Gr2ModelRenderer.h"
#include <cstdint>
#include <string>
#include <vector>
#include <memory>
namespace ava2 {
struct UVRect {
float u0 = 0.0f, v0 = 0.0f, u1 = 1.0f, v1 = 1.0f;
};
struct SpeedTreeProperty {
uint32_t crc = 0;
std::string property_name;
std::string tree_file;
float tree_size = 1000.0f;
float tree_variance = 0.0f;
static bool LoadFromFile(const std::string& filename, SpeedTreeProperty& out);
};
struct SpeedTreeSptInfo {
bool ok = false;
float size = 1000.0f;
float variance = 0.0f;
std::string bark_texture;
std::string leaf_texture;
std::string shadow_texture;
std::vector<UVRect> leaf_uvs;
std::vector<UVRect> frond_uvs;
std::vector<UVRect> billboard_uvs;
static bool SniffSpt(const std::string& filepath, SpeedTreeSptInfo& out);
static bool SniffMemory(const uint8_t* data, size_t size, SpeedTreeSptInfo& out);
};
class SpeedTreeModel {
public:
SpeedTreeModel();
~SpeedTreeModel() = default;
static std::shared_ptr<SpeedTreeModel> Create(const std::string& sptPath, float treeSize = 1000.0f);
static std::shared_ptr<SpeedTreeModel> CreateProcedural(const std::string& name, float treeSize = 1000.0f,
const std::string& barkTex = "",
const std::string& leafTex = "");
std::vector<Render3DDraw> BuildDrawCommands(float worldX, float worldY, float worldZ,
float yawDeg, float scale,
float windTime, float windStrength = 15.0f) const;
float GetHeight() const { return m_height; }
float GetRadius() const { return m_radius; }
bool IsGrassOrShrub() const { return m_is_grass_or_shrub; }
const std::string& GetName() const { return m_name; }
const std::string& GetBarkTexture() const { return m_bark_texture; }
const std::string& GetLeafTexture() const { return m_leaf_texture; }
private:
void BuildGeometry(const SpeedTreeSptInfo& info);
void BuildTreeGeometry(float H, const SpeedTreeSptInfo& info);
void BuildGrassShrubGeometry(float H, const SpeedTreeSptInfo& info);
std::string m_name;
std::string m_spt_path;
float m_height = 1000.0f;
float m_radius = 350.0f;
bool m_is_grass_or_shrub = false;
std::string m_bark_texture;
std::string m_leaf_texture;
// Base mesh templates in model local space (Z-forward / Y-up)
Render3DDraw m_trunk_template;
Render3DDraw m_leaf_template;
};
} // namespace ava2
+250
View File
@@ -0,0 +1,250 @@
#include "TargetManager.h"
#include "TerrainHeightmap.h"
#include <cmath>
#include <algorithm>
namespace ava2 {
constexpr float PI = 3.14159265358979323846f;
TargetManager::TargetManager() = default;
void TargetManager::SelectTarget(ActorInstance* actor) {
m_target = actor;
}
void TargetManager::ClearTarget() {
m_target = nullptr;
}
void TargetManager::AddGroundPickEffect(float x, float y, float z) {
m_groundPick.x = x;
m_groundPick.y = y;
m_groundPick.z = z;
m_groundPick.timer = 0.0f;
m_groundPick.maxDuration = 0.75f;
m_groundPick.active = true;
}
void TargetManager::Update(float dt) {
if (dt <= 0.0f) return;
// Rotate selection decal ring
m_rotation += 1.8f * dt;
if (m_rotation > 2.0f * PI) m_rotation -= 2.0f * PI;
// Auto-clear target if target dies
if (m_target && m_target->IsDead()) {
m_target = nullptr;
}
// Update ground click ripple effect
if (m_groundPick.active) {
m_groundPick.timer += dt;
if (m_groundPick.timer >= m_groundPick.maxDuration) {
m_groundPick.active = false;
}
}
}
void TargetManager::Render(SDL_Renderer* renderer, const Gr2SceneRenderer& sceneRenderer, const TerrainHeightmap* terrain) {
if (!renderer) return;
// 1. Render Ground Click Ripple Decal if active
if (m_groundPick.active) {
RenderGroundPickRipple(renderer, sceneRenderer);
}
// 2. Render Target Decal Ring and Info Board if target is active
if (m_target && !m_target->IsDead()) {
RenderTargetDecal(renderer, sceneRenderer, *m_target, terrain);
RenderTargetBoard(renderer, *m_target);
}
}
void TargetManager::RenderTargetDecal(SDL_Renderer* renderer, const Gr2SceneRenderer& sceneRenderer, const ActorInstance& target, const TerrainHeightmap* terrain) {
float tx = target.GetX();
float tz = target.GetZ();
float default_ty = target.GetY() + 2.0f; // Baseline fallback height
float radius = 55.0f * std::max(0.6f, target.GetScale());
// 1. Outer rotating reticle ring in bright crimson red (32 segments)
const int numSegments = 32;
float prevSX = 0.0f, prevSY = 0.0f;
bool hasPrev = false;
float firstSX = 0.0f, firstSY = 0.0f;
SDL_SetRenderDrawColor(renderer, 245, 45, 45, 235); // Bright Red
for (int i = 0; i < numSegments; ++i) {
float angle = m_rotation + (static_cast<float>(i) / static_cast<float>(numSegments)) * (2.0f * PI);
float px = tx + std::cos(angle) * radius;
float pz = tz + std::sin(angle) * radius;
float py = terrain ? (terrain->GetHeightAtWorld(px, pz) + 2.0f) : default_ty;
float sx = 0.0f, sy = 0.0f;
if (sceneRenderer.ProjectToScreen(px, py, pz, sx, sy)) {
if (hasPrev) {
SDL_RenderLine(renderer, prevSX, prevSY, sx, sy);
} else {
firstSX = sx;
firstSY = sy;
}
prevSX = sx;
prevSY = sy;
hasPrev = true;
} else {
hasPrev = false;
}
}
if (hasPrev && (firstSX != 0.0f || firstSY != 0.0f)) {
SDL_RenderLine(renderer, prevSX, prevSY, firstSX, firstSY);
}
// 2. Inner concentric ring in warm gold rotating opposite direction
const int innerSegments = 24;
float innerRadius = radius * 0.72f;
hasPrev = false;
firstSX = firstSY = 0.0f;
SDL_SetRenderDrawColor(renderer, 255, 195, 45, 220); // Warm Gold
for (int i = 0; i < innerSegments; ++i) {
float angle = -m_rotation * 1.3f + (static_cast<float>(i) / static_cast<float>(innerSegments)) * (2.0f * PI);
float px = tx + std::cos(angle) * innerRadius;
float pz = tz + std::sin(angle) * innerRadius;
float py = terrain ? (terrain->GetHeightAtWorld(px, pz) + 2.0f) : default_ty;
float sx = 0.0f, sy = 0.0f;
if (sceneRenderer.ProjectToScreen(px, py, pz, sx, sy)) {
if (hasPrev) {
SDL_RenderLine(renderer, prevSX, prevSY, sx, sy);
} else {
firstSX = sx;
firstSY = sy;
}
prevSX = sx;
prevSY = sy;
hasPrev = true;
} else {
hasPrev = false;
}
}
if (hasPrev && (firstSX != 0.0f || firstSY != 0.0f)) {
SDL_RenderLine(renderer, prevSX, prevSY, firstSX, firstSY);
}
// 3. Four directional pointer bracket notches at cardinal points (Metin2 lock brackets)
SDL_SetRenderDrawColor(renderer, 255, 230, 80, 240);
for (int k = 0; k < 4; ++k) {
float angle = m_rotation + static_cast<float>(k) * (PI * 0.5f);
float p1x = tx + std::cos(angle) * (radius * 1.18f);
float p1z = tz + std::sin(angle) * (radius * 1.18f);
float p1y = terrain ? (terrain->GetHeightAtWorld(p1x, p1z) + 2.5f) : default_ty;
float p2x = tx + std::cos(angle) * (radius * 0.88f);
float p2z = tz + std::sin(angle) * (radius * 0.88f);
float p2y = terrain ? (terrain->GetHeightAtWorld(p2x, p2z) + 2.5f) : default_ty;
float s1x = 0.0f, s1y = 0.0f, s2x = 0.0f, s2y = 0.0f;
if (sceneRenderer.ProjectToScreen(p1x, p1y, p1z, s1x, s1y) &&
sceneRenderer.ProjectToScreen(p2x, p2y, p2z, s2x, s2y)) {
SDL_RenderLine(renderer, s1x, s1y, s2x, s2y);
}
}
}
void TargetManager::RenderGroundPickRipple(SDL_Renderer* renderer, const Gr2SceneRenderer& sceneRenderer) {
float progress = m_groundPick.timer / m_groundPick.maxDuration;
float currentRadius = 10.0f + 40.0f * progress;
uint8_t alpha = static_cast<uint8_t>(std::clamp((1.0f - progress * progress) * 255.0f, 0.0f, 255.0f));
const int numSegments = 20;
float prevSX = 0.0f, prevSY = 0.0f;
bool hasPrev = false;
float firstSX = 0.0f, firstSY = 0.0f;
SDL_SetRenderDrawColor(renderer, 40, 240, 140, alpha); // Cyan / Green pulse
for (int i = 0; i < numSegments; ++i) {
float angle = (static_cast<float>(i) / static_cast<float>(numSegments)) * (2.0f * PI);
float px = m_groundPick.x + std::cos(angle) * currentRadius;
float pz = m_groundPick.z + std::sin(angle) * currentRadius;
float sx = 0.0f, sy = 0.0f;
if (sceneRenderer.ProjectToScreen(px, m_groundPick.y + 1.5f, pz, sx, sy)) {
if (hasPrev) {
SDL_RenderLine(renderer, prevSX, prevSY, sx, sy);
} else {
firstSX = sx;
firstSY = sy;
}
prevSX = sx;
prevSY = sy;
hasPrev = true;
} else {
hasPrev = false;
}
}
if (hasPrev && (firstSX != 0.0f || firstSY != 0.0f)) {
SDL_RenderLine(renderer, prevSX, prevSY, firstSX, firstSY);
}
}
void TargetManager::RenderTargetBoard(SDL_Renderer* renderer, const ActorInstance& target) {
// 40250-aligned TargetBoard at top-center of screen
float boardW = 280.0f;
float boardH = 46.0f;
float boardX = (1280.0f - boardW) * 0.5f;
float boardY = 22.0f;
// Dark slate background
SDL_FRect bgRect = { boardX, boardY, boardW, boardH };
SDL_SetRenderDrawColor(renderer, 20, 26, 36, 230);
SDL_RenderFillRect(renderer, &bgRect);
// Golden border
SDL_SetRenderDrawColor(renderer, 194, 155, 74, 255);
SDL_RenderRect(renderer, &bgRect);
// Target Name
std::string title = target.GetName();
SDL_SetRenderDrawColor(renderer, 240, 220, 140, 255);
SDL_SetRenderScale(renderer, 1.4f, 1.4f);
SDL_RenderDebugText(renderer, (boardX + 12.0f) / 1.4f, (boardY + 6.0f) / 1.4f, title.c_str());
SDL_SetRenderScale(renderer, 1.0f, 1.0f);
// HP Gauge Bar
float barX = boardX + 12.0f;
float barY = boardY + 26.0f;
float barW = boardW - 24.0f;
float barH = 12.0f;
// Bar background
SDL_FRect barBg = { barX, barY, barW, barH };
SDL_SetRenderDrawColor(renderer, 50, 15, 15, 255);
SDL_RenderFillRect(renderer, &barBg);
// Bar fill proportional to HP
float hpRatio = 0.0f;
if (target.GetMaxHP() > 0) {
hpRatio = std::clamp(static_cast<float>(target.GetHP()) / static_cast<float>(target.GetMaxHP()), 0.0f, 1.0f);
}
if (hpRatio > 0.0f) {
SDL_FRect barFill = { barX + 1.0f, barY + 1.0f, (barW - 2.0f) * hpRatio, barH - 2.0f };
SDL_SetRenderDrawColor(renderer, 210, 45, 45, 255);
SDL_RenderFillRect(renderer, &barFill);
}
// Bar outline
SDL_SetRenderDrawColor(renderer, 120, 120, 120, 255);
SDL_RenderRect(renderer, &barBg);
// HP Text
int pct = static_cast<int>(hpRatio * 100.0f);
std::string hpStr = std::to_string(target.GetHP()) + " / " + std::to_string(target.GetMaxHP()) + " (" + std::to_string(pct) + "%)";
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 230);
SDL_SetRenderScale(renderer, 1.0f, 1.0f);
SDL_RenderDebugText(renderer, barX + (barW - hpStr.size() * 8.0f) * 0.5f, barY + 1.5f, hpStr.c_str());
}
} // namespace ava2
+56
View File
@@ -0,0 +1,56 @@
#pragma once
#include "ActorInstance.h"
#include "Gr2ModelRenderer.h"
#include <SDL3/SDL.h>
#include <cstdint>
#include <string>
#include <vector>
namespace ava2 {
struct GroundPickEffect {
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
float timer = 0.0f;
float maxDuration = 0.8f;
bool active = false;
};
class TerrainHeightmap;
// Target Selection & Click-to-Move Visual Feedback Manager (modeled after 40250 CPythonPlayer TargetBoard & EFFECT_PICK)
class TargetManager {
public:
TargetManager();
~TargetManager() = default;
// Target Selection
void SelectTarget(ActorInstance* actor);
void ClearTarget();
ActorInstance* GetTarget() const { return m_target; }
uint32_t GetTargetVID() const { return m_target ? m_target->GetVID() : 0; }
bool HasTarget() const { return m_target != nullptr && !m_target->IsDead(); }
// Ground Pick Ripple (EFFECT_PICK)
void AddGroundPickEffect(float x, float y, float z);
bool HasGroundPickEffect() const { return m_groundPick.active; }
// Update animation timers & decal rotations
void Update(float dt);
// Render 3D selection ring, Ground pick ripple, and Target Info Board onto SDL_Renderer
void Render(SDL_Renderer* renderer, const Gr2SceneRenderer& sceneRenderer, const TerrainHeightmap* terrain = nullptr);
private:
void RenderTargetDecal(SDL_Renderer* renderer, const Gr2SceneRenderer& sceneRenderer, const ActorInstance& target, const TerrainHeightmap* terrain = nullptr);
void RenderGroundPickRipple(SDL_Renderer* renderer, const Gr2SceneRenderer& sceneRenderer);
void RenderTargetBoard(SDL_Renderer* renderer, const ActorInstance& target);
ActorInstance* m_target = nullptr;
GroundPickEffect m_groundPick;
float m_rotation = 0.0f;
};
} // namespace ava2
+770
View File
@@ -0,0 +1,770 @@
#include "TerrainHeightmap.h"
#include <algorithm>
#include <cmath>
#include <fstream>
#include <iostream>
namespace ava2 {
namespace {
inline void Normalize3(float v[3]) {
float len = std::sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
if (len > 1e-6f) {
float inv = 1.0f / len;
v[0] *= inv;
v[1] *= inv;
v[2] *= inv;
} else {
v[0] = 0.0f; v[1] = 1.0f; v[2] = 0.0f;
}
}
inline void ExtractFrustumPlanes(const float view[16], const float proj[16], float planes[6][4]) {
float vp[16];
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
vp[i * 4 + j] = view[i * 4 + 0] * proj[0 * 4 + j] +
view[i * 4 + 1] * proj[1 * 4 + j] +
view[i * 4 + 2] * proj[2 * 4 + j] +
view[i * 4 + 3] * proj[3 * 4 + j];
}
}
// Left
planes[0][0] = vp[3] + vp[0]; planes[0][1] = vp[7] + vp[4]; planes[0][2] = vp[11] + vp[8]; planes[0][3] = vp[15] + vp[12];
// Right
planes[1][0] = vp[3] - vp[0]; planes[1][1] = vp[7] - vp[4]; planes[1][2] = vp[11] - vp[8]; planes[1][3] = vp[15] - vp[12];
// Bottom
planes[2][0] = vp[3] + vp[1]; planes[2][1] = vp[7] + vp[5]; planes[2][2] = vp[11] + vp[9]; planes[2][3] = vp[15] + vp[13];
// Top
planes[3][0] = vp[3] - vp[1]; planes[3][1] = vp[7] - vp[5]; planes[3][2] = vp[11] - vp[9]; planes[3][3] = vp[15] - vp[13];
// Near (Direct3D 0 <= z <= w convention)
planes[4][0] = vp[2]; planes[4][1] = vp[6]; planes[4][2] = vp[10]; planes[4][3] = vp[14];
// Far
planes[5][0] = vp[3] - vp[2]; planes[5][1] = vp[7] - vp[6]; planes[5][2] = vp[11] - vp[10]; planes[5][3] = vp[15] - vp[14];
// Normalize planes
for (int p = 0; p < 6; ++p) {
float len = std::sqrt(planes[p][0] * planes[p][0] + planes[p][1] * planes[p][1] + planes[p][2] * planes[p][2]);
if (len > 1e-6f) {
float inv = 1.0f / len;
planes[p][0] *= inv;
planes[p][1] *= inv;
planes[p][2] *= inv;
planes[p][3] *= inv;
}
}
}
inline bool IsBoxInFrustum(const float aabb_min[3], const float aabb_max[3], const float planes[6][4]) {
for (int i = 0; i < 6; ++i) {
float px = (planes[i][0] > 0.0f) ? aabb_max[0] : aabb_min[0];
float py = (planes[i][1] > 0.0f) ? aabb_max[1] : aabb_min[1];
float pz = (planes[i][2] > 0.0f) ? aabb_max[2] : aabb_min[2];
if (planes[i][0] * px + planes[i][1] * py + planes[i][2] * pz + planes[i][3] < 0.0f) {
return false;
}
}
return true;
}
} // namespace
TerrainHeightmap::TerrainHeightmap() = default;
bool TerrainHeightmap::LoadRaw(const std::string& raw_path, float height_scale, float cell_scale) {
std::ifstream file(raw_path, std::ios::binary);
if (!file.is_open()) {
std::cerr << "TerrainHeightmap::LoadRaw failed to open: " << raw_path << std::endl;
return false;
}
file.seekg(0, std::ios::end);
size_t file_size = static_cast<size_t>(file.tellg());
file.seekg(0, std::ios::beg);
if (file_size < sizeof(uint16_t) * RAW_XSIZE * RAW_YSIZE) {
std::cerr << "TerrainHeightmap::LoadRaw file size mismatch: " << file_size << std::endl;
return false;
}
std::vector<uint16_t> buffer(RAW_XSIZE * RAW_YSIZE);
file.read(reinterpret_cast<char*>(buffer.data()), buffer.size() * sizeof(uint16_t));
if (!file) {
return false;
}
return LoadFromBuffer(buffer.data(), buffer.size(), height_scale, cell_scale);
}
bool TerrainHeightmap::LoadFromBuffer(const uint16_t* raw_data, size_t count, float height_scale, float cell_scale) {
if (!raw_data || count < static_cast<size_t>(RAW_XSIZE * RAW_YSIZE)) {
return false;
}
m_width = RAW_XSIZE;
m_height = RAW_YSIZE;
m_cell_scale = cell_scale;
m_height_scale = height_scale;
m_heights.resize(m_width * m_height);
m_min_height = 1e9f;
m_max_height = -1e9f;
for (size_t i = 0; i < m_heights.size(); ++i) {
float h = static_cast<float>(raw_data[i]) * m_height_scale;
m_heights[i] = h;
if (h < m_min_height) m_min_height = h;
if (h > m_max_height) m_max_height = h;
}
UpdateBounds();
CalculateNormals();
BuildPatchesAndQuadtree();
return true;
}
bool TerrainHeightmap::LoadTileRaw(const std::string& tile_path) {
std::ifstream file(tile_path, std::ios::binary);
if (!file.is_open()) {
std::cerr << "TerrainHeightmap::LoadTileRaw failed to open: " << tile_path << std::endl;
return false;
}
file.seekg(0, std::ios::end);
size_t file_size = static_cast<size_t>(file.tellg());
file.seekg(0, std::ios::beg);
if (file_size < static_cast<size_t>(TILEMAP_RAW_XSIZE * TILEMAP_RAW_YSIZE)) {
std::cerr << "TerrainHeightmap::LoadTileRaw size mismatch: " << file_size << std::endl;
return false;
}
std::vector<uint8_t> buffer(TILEMAP_RAW_XSIZE * TILEMAP_RAW_YSIZE);
file.read(reinterpret_cast<char*>(buffer.data()), buffer.size());
if (!file) {
return false;
}
return LoadTileFromBuffer(buffer.data(), buffer.size());
}
bool TerrainHeightmap::LoadTileFromBuffer(const uint8_t* tile_data, size_t count) {
if (!tile_data || count < static_cast<size_t>(TILEMAP_RAW_XSIZE * TILEMAP_RAW_YSIZE)) {
return false;
}
m_tile_width = TILEMAP_RAW_XSIZE;
m_tile_height = TILEMAP_RAW_YSIZE;
m_tiles.assign(tile_data, tile_data + count);
// Rebuild patches to update dominant tiles
if (!m_heights.empty()) {
BuildPatchesAndQuadtree();
}
return true;
}
bool TerrainHeightmap::LoadAttr(const std::string& attr_path) {
std::ifstream file(attr_path, std::ios::binary);
if (!file.is_open()) {
std::cerr << "TerrainHeightmap::LoadAttr failed to open: " << attr_path << std::endl;
return false;
}
file.seekg(0, std::ios::end);
size_t file_size = static_cast<size_t>(file.tellg());
file.seekg(0, std::ios::beg);
std::vector<uint8_t> buffer(file_size);
file.read(reinterpret_cast<char*>(buffer.data()), file_size);
if (!file) return false;
return LoadAttrFromBuffer(buffer.data(), buffer.size());
}
bool TerrainHeightmap::LoadAttrFromBuffer(const uint8_t* attr_data, size_t count) {
if (!attr_data || count < static_cast<size_t>(ATTRMAP_XSIZE * ATTRMAP_YSIZE)) {
return false;
}
m_attr_width = ATTRMAP_XSIZE;
m_attr_height = ATTRMAP_YSIZE;
#pragma pack(push, 1)
struct SAttrMapHeader {
uint16_t m_wMagic;
uint16_t m_wWidth;
uint16_t m_wHeight;
};
#pragma pack(pop)
const size_t expected_data_size = ATTRMAP_XSIZE * ATTRMAP_YSIZE;
if (count >= sizeof(SAttrMapHeader) + expected_data_size) {
const auto* hdr = reinterpret_cast<const SAttrMapHeader*>(attr_data);
if (hdr->m_wMagic == 2634 && hdr->m_wWidth == ATTRMAP_XSIZE && hdr->m_wHeight == ATTRMAP_YSIZE) {
const uint8_t* src = attr_data + sizeof(SAttrMapHeader);
m_attr.assign(src, src + expected_data_size);
return true;
}
}
m_attr.assign(attr_data, attr_data + expected_data_size);
return true;
}
bool TerrainHeightmap::LoadTextureSet(const std::string& textureset_path) {
std::ifstream file(textureset_path);
if (!file.is_open()) {
std::cerr << "TerrainHeightmap::LoadTextureSet failed to open: " << textureset_path << std::endl;
return false;
}
std::string line;
int current_id = 0;
bool in_texture = false;
while (std::getline(file, line)) {
while (!line.empty() && (line.back() == '\r' || line.back() == ' ' || line.back() == '\t')) {
line.pop_back();
}
size_t start = line.find_first_not_of(" \t");
if (start == std::string::npos) continue;
std::string trim = line.substr(start);
if (trim.rfind("Start Texture", 0) == 0) {
std::string id_str = trim.substr(13);
current_id = std::atoi(id_str.c_str());
in_texture = true;
} else if (trim.rfind("End Texture", 0) == 0) {
in_texture = false;
current_id = 0;
} else if (in_texture && current_id > 0) {
if (trim.front() == '"' || trim.find(".dds") != std::string::npos || trim.find(".tga") != std::string::npos) {
std::string path = trim;
if (path.front() == '"' && path.back() == '"') {
path = path.substr(1, path.size() - 2);
}
if (path.size() >= 3 && (path[0] == 'd' || path[0] == 'D') && path[1] == ':') {
path = path.substr(3);
}
for (char& c : path) {
if (c == '\\') c = '/';
}
while (!path.empty() && path.front() == '/') {
path = path.substr(1);
}
m_textureSet[static_cast<uint8_t>(current_id)] = path;
in_texture = false;
}
}
}
return !m_textureSet.empty();
}
void TerrainHeightmap::GenerateProcedural(int width, int height, float cell_scale, float hill_amplitude) {
m_width = std::max(width, 16);
m_height = std::max(height, 16);
m_cell_scale = cell_scale;
m_height_scale = 1.0f;
m_heights.resize(m_width * m_height);
m_min_height = 1e9f;
m_max_height = -1e9f;
for (int j = 0; j < m_height; ++j) {
for (int i = 0; i < m_width; ++i) {
float fx = static_cast<float>(i);
float fz = static_cast<float>(j);
float h1 = std::sin(fx * 0.12f) * std::cos(fz * 0.12f) * (hill_amplitude * 0.6f);
float h2 = std::sin(fx * 0.05f + 1.2f) * std::cos(fz * 0.06f + 0.8f) * (hill_amplitude * 0.4f);
float h3 = std::sin(fx * 0.25f) * (hill_amplitude * 0.1f);
float h = h1 + h2 + h3;
int idx = j * m_width + i;
m_heights[idx] = h;
if (h < m_min_height) m_min_height = h;
if (h > m_max_height) m_max_height = h;
}
}
UpdateBounds();
CalculateNormals();
BuildPatchesAndQuadtree();
}
void TerrainHeightmap::UpdateBounds() {
float total_w = static_cast<float>(m_width - 1) * m_cell_scale;
float total_h = static_cast<float>(m_height - 1) * m_cell_scale;
m_world_min_x = -total_w * 0.5f;
m_world_max_x = total_w * 0.5f;
m_world_min_z = -total_h * 0.5f;
m_world_max_z = total_h * 0.5f;
}
void TerrainHeightmap::CalculateNormals() {
m_normals.resize(m_width * m_height * 3);
for (int j = 0; j < m_height; ++j) {
for (int i = 0; i < m_width; ++i) {
int x_prev = std::max(0, i - 1);
int x_next = std::min(m_width - 1, i + 1);
int z_prev = std::max(0, j - 1);
int z_next = std::min(m_height - 1, j + 1);
float h_left = m_heights[j * m_width + x_prev];
float h_right = m_heights[j * m_width + x_next];
float h_down = m_heights[z_prev * m_width + i];
float h_up = m_heights[z_next * m_width + i];
float dx = (h_right - h_left);
float dz = (h_up - h_down);
float scale_x = static_cast<float>(x_next - x_prev) * m_cell_scale;
float scale_z = static_cast<float>(z_next - z_prev) * m_cell_scale;
float norm[3] = { -dx / scale_x, 1.0f, -dz / scale_z };
Normalize3(norm);
int n_idx = (j * m_width + i) * 3;
m_normals[n_idx + 0] = norm[0];
m_normals[n_idx + 1] = norm[1];
m_normals[n_idx + 2] = norm[2];
}
}
}
float TerrainHeightmap::GetHeightAtGrid(int x, int y) const {
if (m_heights.empty()) return 0.0f;
x = std::clamp(x, 0, m_width - 1);
y = std::clamp(y, 0, m_height - 1);
return m_heights[y * m_width + x];
}
float TerrainHeightmap::GetHeightAtWorld(float world_x, float world_z) const {
if (m_heights.empty() || m_width < 2 || m_height < 2) return 0.0f;
float grid_x = (world_x - m_world_min_x) / m_cell_scale;
float grid_z = (world_z - m_world_min_z) / m_cell_scale;
grid_x = std::clamp(grid_x, 0.0f, static_cast<float>(m_width - 1));
grid_z = std::clamp(grid_z, 0.0f, static_cast<float>(m_height - 1));
int x0 = static_cast<int>(std::floor(grid_x));
int z0 = static_cast<int>(std::floor(grid_z));
int x1 = std::min(x0 + 1, m_width - 1);
int z1 = std::min(z0 + 1, m_height - 1);
float tx = grid_x - static_cast<float>(x0);
float tz = grid_z - static_cast<float>(z0);
float h00 = m_heights[z0 * m_width + x0];
float h10 = m_heights[z0 * m_width + x1];
float h01 = m_heights[z1 * m_width + x0];
float h11 = m_heights[z1 * m_width + x1];
float h0 = h00 * (1.0f - tx) + h10 * tx;
float h1 = h01 * (1.0f - tx) + h11 * tx;
return h0 * (1.0f - tz) + h1 * tz;
}
void TerrainHeightmap::GetNormalAtWorld(float world_x, float world_z, float out_normal[3]) const {
if (m_normals.empty() || m_width < 2 || m_height < 2) {
out_normal[0] = 0.0f; out_normal[1] = 1.0f; out_normal[2] = 0.0f;
return;
}
float grid_x = (world_x - m_world_min_x) / m_cell_scale;
float grid_z = (world_z - m_world_min_z) / m_cell_scale;
grid_x = std::clamp(grid_x, 0.0f, static_cast<float>(m_width - 1));
grid_z = std::clamp(grid_z, 0.0f, static_cast<float>(m_height - 1));
int x0 = static_cast<int>(std::round(grid_x));
int z0 = static_cast<int>(std::round(grid_z));
x0 = std::clamp(x0, 0, m_width - 1);
z0 = std::clamp(z0, 0, m_height - 1);
int idx = (z0 * m_width + x0) * 3;
out_normal[0] = m_normals[idx + 0];
out_normal[1] = m_normals[idx + 1];
out_normal[2] = m_normals[idx + 2];
}
uint8_t TerrainHeightmap::GetTileAtGrid(int x, int y) const {
if (m_tiles.empty() || m_tile_width <= 0 || m_tile_height <= 0) return 0;
x = std::clamp(x, 0, m_tile_width - 1);
y = std::clamp(y, 0, m_tile_height - 1);
return m_tiles[y * m_tile_width + x];
}
uint8_t TerrainHeightmap::GetTileAtWorld(float world_x, float world_z) const {
if (m_tiles.empty() || m_tile_width <= 0 || m_tile_height <= 0) return 0;
float grid_x = (world_x - m_world_min_x) / (static_cast<float>(m_width - 1) * m_cell_scale) * static_cast<float>(m_tile_width - 1);
float grid_z = (world_z - m_world_min_z) / (static_cast<float>(m_height - 1) * m_cell_scale) * static_cast<float>(m_tile_height - 1);
int tx = std::clamp(static_cast<int>(std::round(grid_x)), 0, m_tile_width - 1);
int tz = std::clamp(static_cast<int>(std::round(grid_z)), 0, m_tile_height - 1);
return m_tiles[tz * m_tile_width + tx];
}
std::string TerrainHeightmap::GetTexturePathForTile(uint8_t tile_id) const {
auto it = m_textureSet.find(tile_id);
if (it != m_textureSet.end()) {
return it->second;
}
return "ymir work/terrainmaps/map1/grass/grass 01.dds";
}
uint8_t TerrainHeightmap::GetAttrAtGrid(int x, int y) const {
if (m_attr.empty() || m_attr_width <= 0 || m_attr_height <= 0) return 0;
x = std::clamp(x, 0, m_attr_width - 1);
y = std::clamp(y, 0, m_attr_height - 1);
return m_attr[y * m_attr_width + x];
}
uint8_t TerrainHeightmap::GetAttrAtWorld(float world_x, float world_z) const {
if (m_attr.empty() || m_attr_width <= 0 || m_attr_height <= 0 || m_width < 2 || m_height < 2) return 0;
float grid_x = (world_x - m_world_min_x) / (static_cast<float>(m_width - 1) * m_cell_scale) * static_cast<float>(m_attr_width - 1);
float grid_z = (world_z - m_world_min_z) / (static_cast<float>(m_height - 1) * m_cell_scale) * static_cast<float>(m_attr_height - 1);
int ax = std::clamp(static_cast<int>(std::round(grid_x)), 0, m_attr_width - 1);
int az = std::clamp(static_cast<int>(std::round(grid_z)), 0, m_attr_height - 1);
return m_attr[az * m_attr_width + ax];
}
bool TerrainHeightmap::IsAttrOn(float world_x, float world_z, uint8_t flag) const {
return (GetAttrAtWorld(world_x, world_z) & flag) != 0;
}
void TerrainHeightmap::BuildPatchesAndQuadtree() {
if (m_width < 16 || m_height < 16) return;
m_patches.resize(PATCH_COUNT * PATCH_COUNT);
int patch_cells_x = (m_width - 1) / PATCH_COUNT;
int patch_cells_z = (m_height - 1) / PATCH_COUNT;
for (int py = 0; py < PATCH_COUNT; ++py) {
for (int px = 0; px < PATCH_COUNT; ++px) {
int p_idx = py * PATCH_COUNT + px;
auto& patch = m_patches[p_idx];
patch.patch_x = px;
patch.patch_y = py;
int x0 = px * patch_cells_x;
int x1 = (px + 1) * patch_cells_x;
int z0 = py * patch_cells_z;
int z1 = (py + 1) * patch_cells_z;
patch.aabb_min[0] = m_world_min_x + static_cast<float>(x0) * m_cell_scale;
patch.aabb_max[0] = m_world_min_x + static_cast<float>(x1) * m_cell_scale;
patch.aabb_min[2] = m_world_min_z + static_cast<float>(z0) * m_cell_scale;
patch.aabb_max[2] = m_world_min_z + static_cast<float>(z1) * m_cell_scale;
float min_y = 1e9f, max_y = -1e9f;
std::unordered_map<uint8_t, int> tile_freq;
for (int j = z0; j <= z1 && j < m_height; ++j) {
for (int i = x0; i <= x1 && i < m_width; ++i) {
float h = m_heights[j * m_width + i];
if (h < min_y) min_y = h;
if (h > max_y) max_y = h;
if (!m_tiles.empty() && m_tile_width > 0 && m_tile_height > 0) {
int tx = (i * (m_tile_width - 1)) / (m_width - 1);
int tz = (j * (m_tile_height - 1)) / (m_height - 1);
uint8_t t = m_tiles[tz * m_tile_width + tx];
tile_freq[t]++;
}
}
}
patch.aabb_min[1] = min_y;
patch.aabb_max[1] = max_y;
uint8_t dom_tile = 4; // default grass 01
int max_c = 0;
for (const auto& [t, c] : tile_freq) {
if (c > max_c) {
max_c = c;
dom_tile = t;
}
}
patch.dominant_tile = dom_tile;
}
}
m_quadtreeRoot = BuildQuadtreeNode(m_world_min_x, m_world_max_x, m_world_min_z, m_world_max_z, 0);
}
std::unique_ptr<TerrainQuadNode> TerrainHeightmap::BuildQuadtreeNode(float min_x, float max_x, float min_z, float max_z, int depth) {
auto node = std::make_unique<TerrainQuadNode>();
node->depth = depth;
node->aabb_min[0] = min_x;
node->aabb_max[0] = max_x;
node->aabb_min[2] = min_z;
node->aabb_max[2] = max_z;
node->aabb_min[1] = m_min_height;
node->aabb_max[1] = m_max_height;
if (depth >= 3) {
float cx = (min_x + max_x) * 0.5f;
float cz = (min_z + max_z) * 0.5f;
float u = (cx - m_world_min_x) / (m_world_max_x - m_world_min_x);
float v = (cz - m_world_min_z) / (m_world_max_z - m_world_min_z);
int px = std::clamp(static_cast<int>(u * static_cast<float>(PATCH_COUNT)), 0, PATCH_COUNT - 1);
int py = std::clamp(static_cast<int>(v * static_cast<float>(PATCH_COUNT)), 0, PATCH_COUNT - 1);
int idx = py * PATCH_COUNT + px;
node->patch_idx = idx;
if (idx < static_cast<int>(m_patches.size())) {
node->aabb_min[1] = m_patches[idx].aabb_min[1];
node->aabb_max[1] = m_patches[idx].aabb_max[1];
}
return node;
}
float mid_x = (min_x + max_x) * 0.5f;
float mid_z = (min_z + max_z) * 0.5f;
node->children[0] = BuildQuadtreeNode(min_x, mid_x, min_z, mid_z, depth + 1);
node->children[1] = BuildQuadtreeNode(mid_x, max_x, min_z, mid_z, depth + 1);
node->children[2] = BuildQuadtreeNode(min_x, mid_x, mid_z, max_z, depth + 1);
node->children[3] = BuildQuadtreeNode(mid_x, max_x, mid_z, max_z, depth + 1);
float cmin_y = 1e9f, cmax_y = -1e9f;
for (int k = 0; k < 4; ++k) {
if (node->children[k]) {
cmin_y = std::min(cmin_y, node->children[k]->aabb_min[1]);
cmax_y = std::max(cmax_y, node->children[k]->aabb_max[1]);
}
}
node->aabb_min[1] = cmin_y;
node->aabb_max[1] = cmax_y;
return node;
}
void TerrainHeightmap::QueryQuadtree(const TerrainQuadNode* node, const float planes[6][4], const float eye[3], float max_distance, std::vector<int>& out_visible_patches) const {
if (!node) return;
if (!IsBoxInFrustum(node->aabb_min, node->aabb_max, planes)) {
return; // Culled by frustum!
}
if (node->patch_idx >= 0) {
float cx = (node->aabb_min[0] + node->aabb_max[0]) * 0.5f;
float cy = (node->aabb_min[1] + node->aabb_max[1]) * 0.5f;
float cz = (node->aabb_min[2] + node->aabb_max[2]) * 0.5f;
float dx = cx - eye[0];
float dy = cy - eye[1];
float dz = cz - eye[2];
float dist_sq = dx * dx + dy * dy + dz * dz;
if (dist_sq <= max_distance * max_distance) {
out_visible_patches.push_back(node->patch_idx);
}
return;
}
for (int k = 0; k < 4; ++k) {
if (node->children[k]) {
QueryQuadtree(node->children[k].get(), planes, eye, max_distance, out_visible_patches);
}
}
}
std::vector<Render3DDraw> TerrainHeightmap::BuildCulledDraws(const float view[16], const float proj[16], float max_distance) const {
std::vector<Render3DDraw> draws;
if (m_heights.empty() || m_patches.empty() || !m_quadtreeRoot) return draws;
float planes[6][4];
ExtractFrustumPlanes(view, proj, planes);
float eye[3] = {
-(view[0] * view[12] + view[1] * view[13] + view[2] * view[14]),
-(view[4] * view[12] + view[5] * view[13] + view[6] * view[14]),
-(view[8] * view[12] + view[9] * view[13] + view[10] * view[14])
};
std::vector<int> visible_patches;
visible_patches.reserve(64);
QueryQuadtree(m_quadtreeRoot.get(), planes, eye, max_distance, visible_patches);
for (int p_idx : visible_patches) {
if (p_idx < 0 || p_idx >= static_cast<int>(m_patches.size())) continue;
const auto& patch = m_patches[p_idx];
float cx = (patch.aabb_min[0] + patch.aabb_max[0]) * 0.5f;
float cz = (patch.aabb_min[2] + patch.aabb_max[2]) * 0.5f;
float dx = cx - eye[0];
float dz = cz - eye[2];
float dist = std::sqrt(dx * dx + dz * dz);
int step = (dist > 2200.0f) ? 2 : 1;
auto d = BuildPatchDraw(patch.patch_x, patch.patch_y, step);
if (!d.positions.empty()) {
draws.push_back(std::move(d));
}
}
return draws;
}
Render3DDraw TerrainHeightmap::BuildPatchDraw(int patch_x, int patch_y, int step) const {
Render3DDraw draw;
if (m_heights.empty() || m_width < 2 || m_height < 2) return draw;
int p_idx = patch_y * PATCH_COUNT + patch_x;
uint8_t dom_tile = 4;
if (p_idx >= 0 && p_idx < static_cast<int>(m_patches.size())) {
dom_tile = m_patches[p_idx].dominant_tile;
}
draw.texture0 = GetTexturePathForTile(dom_tile);
draw.cull_mode = 1; // D3DCULL_NONE: double-sided for terrain meshes
step = std::max(1, step);
int patch_cells_x = (m_width - 1) / PATCH_COUNT;
int patch_cells_z = (m_height - 1) / PATCH_COUNT;
int start_x = patch_x * patch_cells_x;
int end_x = std::min((patch_x + 1) * patch_cells_x, m_width - 1);
int start_z = patch_y * patch_cells_z;
int end_z = std::min((patch_y + 1) * patch_cells_z, m_height - 1);
int grid_w = (end_x - start_x) / step + 1;
int grid_h = (end_z - start_z) / step + 1;
size_t total_verts = static_cast<size_t>(grid_w * grid_h);
draw.positions.reserve(total_verts * 3);
draw.normals.reserve(total_verts * 3);
draw.uv0.reserve(total_verts * 2);
draw.diffuse.reserve(total_verts);
draw.indices.reserve((grid_w - 1) * (grid_h - 1) * 6);
for (int j = start_z; j <= end_z; j += step) {
for (int i = start_x; i <= end_x; i += step) {
float vx = m_world_min_x + static_cast<float>(i) * m_cell_scale;
float vy = m_heights[j * m_width + i];
float vz = m_world_min_z + static_cast<float>(j) * m_cell_scale;
draw.positions.push_back(vx);
draw.positions.push_back(vy);
draw.positions.push_back(vz);
int n_idx = (j * m_width + i) * 3;
float nx = m_normals[n_idx + 0];
float ny = m_normals[n_idx + 1];
float nz = m_normals[n_idx + 2];
draw.normals.push_back(nx);
draw.normals.push_back(ny);
draw.normals.push_back(nz);
float u = (vx - m_world_min_x) / 500.0f;
float v = (vz - m_world_min_z) / 500.0f;
draw.uv0.push_back(u);
draw.uv0.push_back(v);
float lx = 0.577f, ly = 0.577f, lz = 0.577f;
float dot = std::max(0.25f, nx * lx + ny * ly + nz * lz);
uint8_t c = static_cast<uint8_t>(std::clamp(dot * 255.0f, 0.0f, 255.0f));
uint32_t color = (0xFF << 24) | (c << 16) | (c << 8) | c;
draw.diffuse.push_back(color);
}
}
for (int j = 0; j < grid_h - 1; ++j) {
for (int i = 0; i < grid_w - 1; ++i) {
uint32_t top_left = j * grid_w + i;
uint32_t top_right = top_left + 1;
uint32_t bot_left = (j + 1) * grid_w + i;
uint32_t bot_right = bot_left + 1;
draw.indices.push_back(top_left);
draw.indices.push_back(bot_left);
draw.indices.push_back(top_right);
draw.indices.push_back(top_right);
draw.indices.push_back(bot_left);
draw.indices.push_back(bot_right);
}
}
return draw;
}
Render3DDraw TerrainHeightmap::BuildDrawCommand(const float world[16], int step) const {
Render3DDraw draw;
if (m_heights.empty() || m_width < 2 || m_height < 2) return draw;
if (world) {
std::copy(world, world + 16, draw.world);
}
draw.texture0 = GetTexturePathForTile(4); // Default grass 01
draw.cull_mode = 1; // D3DCULL_NONE: double-sided for terrain meshes
step = std::max(1, step);
int grid_w = (m_width - 1) / step + 1;
int grid_h = (m_height - 1) / step + 1;
size_t total_verts = static_cast<size_t>(grid_w * grid_h);
draw.positions.reserve(total_verts * 3);
draw.normals.reserve(total_verts * 3);
draw.uv0.reserve(total_verts * 2);
draw.diffuse.reserve(total_verts);
draw.indices.reserve((grid_w - 1) * (grid_h - 1) * 6);
for (int j = 0; j < m_height; j += step) {
for (int i = 0; i < m_width; i += step) {
float vx = m_world_min_x + static_cast<float>(i) * m_cell_scale;
float vy = m_heights[j * m_width + i];
float vz = m_world_min_z + static_cast<float>(j) * m_cell_scale;
draw.positions.push_back(vx);
draw.positions.push_back(vy);
draw.positions.push_back(vz);
int n_idx = (j * m_width + i) * 3;
float nx = m_normals[n_idx + 0];
float ny = m_normals[n_idx + 1];
float nz = m_normals[n_idx + 2];
draw.normals.push_back(nx);
draw.normals.push_back(ny);
draw.normals.push_back(nz);
float u = (vx - m_world_min_x) / 500.0f;
float v = (vz - m_world_min_z) / 500.0f;
draw.uv0.push_back(u);
draw.uv0.push_back(v);
float lx = 0.577f, ly = 0.577f, lz = 0.577f;
float dot = std::max(0.25f, nx * lx + ny * ly + nz * lz);
uint8_t c = static_cast<uint8_t>(std::clamp(dot * 255.0f, 0.0f, 255.0f));
uint32_t color = (0xFF << 24) | (c << 16) | (c << 8) | c;
draw.diffuse.push_back(color);
}
}
for (int j = 0; j < grid_h - 1; ++j) {
for (int i = 0; i < grid_w - 1; ++i) {
uint32_t top_left = j * grid_w + i;
uint32_t top_right = top_left + 1;
uint32_t bot_left = (j + 1) * grid_w + i;
uint32_t bot_right = bot_left + 1;
draw.indices.push_back(top_left);
draw.indices.push_back(bot_left);
draw.indices.push_back(top_right);
draw.indices.push_back(top_right);
draw.indices.push_back(bot_left);
draw.indices.push_back(bot_right);
}
}
return draw;
}
} // namespace ava2
+169
View File
@@ -0,0 +1,169 @@
#pragma once
#include "RenderCommands3D.h"
#include <cstdint>
#include <string>
#include <vector>
#include <unordered_map>
#include <memory>
namespace ava2 {
// Metin2 collision and map attribute flags (aligned with 40250 CTerrainImpl)
enum TerrainAttr : uint8_t {
ATTR_NONE = 0,
ATTR_BLOCK = (1 << 0), // Movement collision blocking (cannot walk)
ATTR_WATER = (1 << 1), // Water surface / swimming
ATTR_BANPK = (1 << 2), // Safe zone / peace zone (PvP disabled)
};
struct TerrainPatch {
int patch_x = 0; // 0..7
int patch_y = 0; // 0..7
float aabb_min[3] = {0};
float aabb_max[3] = {0};
uint8_t dominant_tile = 0;
};
struct TerrainQuadNode {
float aabb_min[3] = {0};
float aabb_max[3] = {0};
int depth = 0;
int patch_idx = -1; // -1 if internal, >=0 if leaf (0..63)
std::unique_ptr<TerrainQuadNode> children[4];
};
/**
* TerrainHeightmap:
* Parses Metin2 terrain heightmap data (such as height.raw: 131x131 uint16_t),
* tile texture map (tile.raw: 258x258 uint8_t),
* collision attribute map (attr.atr: magic 2634 + 256x256 uint8_t),
* and textureset configuration (metin2_map1.txt).
* Implements 8x8 patch subdivision and QuadTree frustum culling.
*/
class TerrainHeightmap {
public:
static constexpr int RAW_XSIZE = 131;
static constexpr int RAW_YSIZE = 131;
static constexpr int MAP_XSIZE = 128;
static constexpr int MAP_YSIZE = 128;
static constexpr int TILEMAP_RAW_XSIZE = 258;
static constexpr int TILEMAP_RAW_YSIZE = 258;
static constexpr int ATTRMAP_XSIZE = 256;
static constexpr int ATTRMAP_YSIZE = 256;
static constexpr int PATCH_SIZE = 16;
static constexpr int PATCH_COUNT = MAP_XSIZE / PATCH_SIZE; // 8x8 = 64
static constexpr float DEFAULT_CELL_SCALE = 200.0f;
static constexpr float DEFAULT_HEIGHT_SCALE = 0.5f;
// Metin2 attribute constants
static constexpr uint8_t ATTR_FLAG_BLOCK = ATTR_BLOCK;
static constexpr uint8_t ATTR_FLAG_WATER = ATTR_WATER;
static constexpr uint8_t ATTR_FLAG_BANPK = ATTR_BANPK;
TerrainHeightmap();
~TerrainHeightmap() = default;
// Load from Metin2 height.raw file (131x131 uint16_t, 34322 bytes)
bool LoadRaw(const std::string& raw_path, float height_scale = DEFAULT_HEIGHT_SCALE, float cell_scale = DEFAULT_CELL_SCALE);
bool LoadFromBuffer(const uint16_t* raw_data, size_t count, float height_scale = DEFAULT_HEIGHT_SCALE, float cell_scale = DEFAULT_CELL_SCALE);
// Load from Metin2 tile.raw file (258x258 uint8_t, 66564 bytes)
bool LoadTileRaw(const std::string& tile_path);
bool LoadTileFromBuffer(const uint8_t* tile_data, size_t count);
// Load from Metin2 attr.atr file (65542 bytes = 6 bytes header + 256*256 bytes) or raw 65536 bytes
bool LoadAttr(const std::string& attr_path);
bool LoadAttrFromBuffer(const uint8_t* attr_data, size_t count);
// Load TextureSet file (e.g. textureset/metin2_map1.txt)
bool LoadTextureSet(const std::string& textureset_path);
// Procedural terrain generation for testing
void GenerateProcedural(int width = 64, int height = 64, float cell_scale = 100.0f, float hill_amplitude = 80.0f);
// Query height at grid or world coordinates (continuous bilinear interpolation)
float GetHeightAtGrid(int x, int y) const;
float GetHeightAtWorld(float world_x, float world_z) const;
// Query normal at world space coordinates (normalized, Y-up)
void GetNormalAtWorld(float world_x, float world_z, float out_normal[3]) const;
// Query tile type at grid or world coordinates
uint8_t GetTileAtGrid(int x, int y) const;
uint8_t GetTileAtWorld(float world_x, float world_z) const;
std::string GetTexturePathForTile(uint8_t tile_id) const;
// Query attribute flag (ATTR_BLOCK, ATTR_WATER, ATTR_BANPK)
bool HasAttrMap() const { return !m_attr.empty(); }
uint8_t GetAttrAtGrid(int x, int y) const;
uint8_t GetAttrAtWorld(float world_x, float world_z) const;
bool IsAttrOn(float world_x, float world_z, uint8_t flag) const;
// Build single full-mesh 3D draw command
Render3DDraw BuildDrawCommand(const float world[16] = nullptr, int step = 1) const;
// Build multi-texture, patch-subdivided 3D draw commands with QuadTree frustum culling
std::vector<Render3DDraw> BuildCulledDraws(const float view[16], const float proj[16], float max_distance = 4000.0f) const;
// Build patch draw command for a single patch
Render3DDraw BuildPatchDraw(int patch_x, int patch_y, int step = 1) const;
// QuadTree & Patch hierarchy
size_t GetPatchCount() const { return m_patches.size(); }
const TerrainPatch& GetPatch(size_t index) const { return m_patches[index]; }
// Terrain bounds & properties
int GetWidth() const { return m_width; }
int GetHeight() const { return m_height; }
int GetTileWidth() const { return m_tile_width; }
int GetTileHeight() const { return m_tile_height; }
int GetAttrWidth() const { return m_attr_width; }
int GetAttrHeight() const { return m_attr_height; }
bool HasTileMap() const { return !m_tiles.empty(); }
float GetCellScale() const { return m_cell_scale; }
float GetHeightScale() const { return m_height_scale; }
float GetWorldMinX() const { return m_world_min_x; }
float GetWorldMaxX() const { return m_world_max_x; }
float GetWorldMinZ() const { return m_world_min_z; }
float GetWorldMaxZ() const { return m_world_max_z; }
float GetMinHeight() const { return m_min_height; }
float GetMaxHeight() const { return m_max_height; }
const std::unordered_map<uint8_t, std::string>& GetTextureSet() const { return m_textureSet; }
private:
void CalculateNormals();
void UpdateBounds();
void BuildPatchesAndQuadtree();
std::unique_ptr<TerrainQuadNode> BuildQuadtreeNode(float min_x, float max_x, float min_z, float max_z, int depth);
void QueryQuadtree(const TerrainQuadNode* node, const float planes[6][4], const float eye[3], float max_distance, std::vector<int>& out_visible_patches) const;
int m_width = 0;
int m_height = 0;
float m_cell_scale = DEFAULT_CELL_SCALE;
float m_height_scale = DEFAULT_HEIGHT_SCALE;
float m_world_min_x = 0.0f;
float m_world_max_x = 0.0f;
float m_world_min_z = 0.0f;
float m_world_max_z = 0.0f;
float m_min_height = 0.0f;
float m_max_height = 0.0f;
std::vector<float> m_heights; // m_width * m_height floats
std::vector<float> m_normals; // (m_width * m_height) * 3 floats
int m_tile_width = 0;
int m_tile_height = 0;
std::vector<uint8_t> m_tiles; // m_tile_width * m_tile_height tile indices
int m_attr_width = 0;
int m_attr_height = 0;
std::vector<uint8_t> m_attr; // m_attr_width * m_attr_height attribute flags
std::unordered_map<uint8_t, std::string> m_textureSet; // tile_id -> texture dds path
std::vector<TerrainPatch> m_patches; // 8x8 = 64 patches
std::unique_ptr<TerrainQuadNode> m_quadtreeRoot;
};
} // namespace ava2
+653
View File
@@ -0,0 +1,653 @@
#include "TextTailManager.h"
#include "src/eter_image/MarkManager.h"
#include <algorithm>
#include <cmath>
namespace ava2 {
TextTailManager& TextTailManager::Instance() {
static TextTailManager s_instance;
return s_instance;
}
TextTailManager::TextTailManager() = default;
void TextTailManager::Clear() {
m_characterMap.clear();
m_itemMap.clear();
m_characterList.clear();
m_itemList.clear();
m_selectedItemVID = 0;
}
void TextTailManager::RegisterCharacterTextTail(uint32_t guildID, uint32_t vid, uint32_t color, float fAddHeight) {
auto tail = std::make_shared<TextTailItem>();
tail->dwVirtualID = vid;
tail->guildID = guildID;
tail->color = color;
tail->fHeight = fAddHeight;
tail->isItem = false;
tail->bNameFlag = true;
// Check if character already has an entry
auto it = m_characterMap.find(vid);
if (it != m_characterMap.end()) {
tail->name = it->second->name;
tail->title = it->second->title;
tail->level = it->second->level;
tail->guildName = it->second->guildName;
tail->worldX = it->second->worldX;
tail->worldY = it->second->worldY;
tail->worldZ = it->second->worldZ;
tail->hasWorldPos = it->second->hasWorldPos;
}
m_characterMap[vid] = tail;
}
void TextTailManager::SetCharacterPosition(uint32_t vid, float worldX, float worldY, float worldZ) {
auto it = m_characterMap.find(vid);
if (it != m_characterMap.end()) {
it->second->worldX = worldX;
it->second->worldY = worldY;
it->second->worldZ = worldZ;
it->second->hasWorldPos = true;
}
}
void TextTailManager::SetCharacterName(uint32_t vid, const std::string& name) {
auto it = m_characterMap.find(vid);
if (it != m_characterMap.end()) {
it->second->name = name;
} else {
auto tail = std::make_shared<TextTailItem>();
tail->dwVirtualID = vid;
tail->name = name;
m_characterMap[vid] = tail;
}
}
void TextTailManager::SetCharacterTextTailColor(uint32_t vid, uint32_t color) {
auto it = m_characterMap.find(vid);
if (it != m_characterMap.end()) {
it->second->color = color;
}
}
void TextTailManager::AttachTitle(uint32_t vid, const std::string& title, uint32_t color) {
if (!m_pkTitleEnable) return;
auto it = m_characterMap.find(vid);
if (it != m_characterMap.end()) {
it->second->title = title;
it->second->titleColor = color;
}
}
void TextTailManager::DetachTitle(uint32_t vid) {
auto it = m_characterMap.find(vid);
if (it != m_characterMap.end()) {
it->second->title.clear();
}
}
void TextTailManager::AttachLevel(uint32_t vid, const std::string& levelText, uint32_t color) {
if (!m_pkTitleEnable) return;
auto it = m_characterMap.find(vid);
if (it != m_characterMap.end()) {
it->second->level = levelText;
it->second->levelColor = color;
}
}
void TextTailManager::DetachLevel(uint32_t vid) {
auto it = m_characterMap.find(vid);
if (it != m_characterMap.end()) {
it->second->level.clear();
}
}
void TextTailManager::SetGuildName(uint32_t vid, const std::string& guildName, uint32_t guildID) {
auto it = m_characterMap.find(vid);
if (it != m_characterMap.end()) {
it->second->guildName = guildName;
if (guildID != 0) {
it->second->guildID = guildID;
}
}
}
void TextTailManager::DeleteCharacterTextTail(uint32_t vid) {
m_characterMap.erase(vid);
m_characterList.erase(std::remove_if(m_characterList.begin(), m_characterList.end(),
[vid](const std::shared_ptr<TextTailItem>& t) { return t && t->dwVirtualID == vid; }),
m_characterList.end());
}
void TextTailManager::ShowCharacterTextTail(uint32_t vid) {
auto it = m_characterMap.find(vid);
if (it == m_characterMap.end()) return;
auto tail = it->second;
if (std::find(m_characterList.begin(), m_characterList.end(), tail) == m_characterList.end()) {
tail->isShowing = true;
m_characterList.push_back(tail);
}
}
void TextTailManager::RegisterItemTextTail(uint32_t vid, const std::string& text, float worldX, float worldY, float worldZ, int ownerTime, const std::string& ownerName, bool isMine, uint32_t color) {
auto tail = std::make_shared<TextTailItem>();
tail->dwVirtualID = vid;
tail->name = text;
tail->worldX = worldX;
tail->worldY = worldY;
tail->worldZ = worldZ;
tail->hasWorldPos = true;
tail->ownerTime = ownerTime;
tail->ownerName = ownerName;
tail->isMineItem = isMine;
tail->color = color;
tail->isItem = true;
tail->fHeight = 12.0f; // item height above ground
// Calculate initial 2D bounds for mouse picking and overlap resolution
float textW = static_cast<float>(text.size()) * 8.0f;
bool hasOwner = !ownerName.empty() || ownerTime > 0;
tail->xStart = -textW * 0.5f - 6.0f;
tail->xEnd = textW * 0.5f + 6.0f;
tail->yStart = hasOwner ? -28.0f : -14.0f;
tail->yEnd = 6.0f;
m_itemMap[vid] = tail;
}
void TextTailManager::SetItemPosition(uint32_t vid, float worldX, float worldY, float worldZ) {
auto it = m_itemMap.find(vid);
if (it != m_itemMap.end()) {
it->second->worldX = worldX;
it->second->worldY = worldY;
it->second->worldZ = worldZ;
it->second->hasWorldPos = true;
}
}
void TextTailManager::SetItemTextTailOwner(uint32_t vid, const std::string& ownerName, bool isMine) {
auto it = m_itemMap.find(vid);
if (it != m_itemMap.end()) {
it->second->ownerName = ownerName;
it->second->isMineItem = isMine;
if (!ownerName.empty()) {
it->second->yStart = -28.0f;
}
}
}
void TextTailManager::DeleteItemTextTail(uint32_t vid) {
m_itemMap.erase(vid);
m_itemList.erase(std::remove_if(m_itemList.begin(), m_itemList.end(),
[vid](const std::shared_ptr<TextTailItem>& t) { return t && t->dwVirtualID == vid; }),
m_itemList.end());
if (m_selectedItemVID == vid) {
m_selectedItemVID = 0;
}
}
void TextTailManager::ShowItemTextTail(uint32_t vid) {
auto it = m_itemMap.find(vid);
if (it == m_itemMap.end()) return;
auto tail = it->second;
if (std::find(m_itemList.begin(), m_itemList.end(), tail) == m_itemList.end()) {
tail->isShowing = true;
m_itemList.push_back(tail);
}
}
void TextTailManager::RegisterChatTail(uint32_t vid, const std::string& chatText) {
auto it = m_characterMap.find(vid);
if (it != m_characterMap.end()) {
it->second->chatText = chatText;
it->second->chatTimer = 0.0f;
it->second->hasChat = true;
ShowCharacterTextTail(vid);
}
}
void TextTailManager::RegisterInfoTail(uint32_t vid, const std::string& infoText) {
auto it = m_characterMap.find(vid);
if (it == m_characterMap.end()) {
RegisterCharacterTextTail(0, vid, 0xFFFFAA33, 40.0f);
SetCharacterName(vid, infoText);
ShowCharacterTextTail(vid);
} else {
RegisterChatTail(vid, infoText);
}
}
bool TextTailManager::IsChatTextTail(uint32_t vid) const {
auto it = m_characterMap.find(vid);
if (it != m_characterMap.end()) {
return it->second->hasChat && it->second->chatTimer < it->second->chatMaxDuration;
}
return false;
}
void TextTailManager::ShowAllTextTail() {
for (auto& [vid, tail] : m_characterMap) {
if (std::find(m_characterList.begin(), m_characterList.end(), tail) == m_characterList.end()) {
tail->isShowing = true;
m_characterList.push_back(tail);
}
}
for (auto& [vid, tail] : m_itemMap) {
if (std::find(m_itemList.begin(), m_itemList.end(), tail) == m_itemList.end()) {
tail->isShowing = true;
m_itemList.push_back(tail);
}
}
}
void TextTailManager::HideAllTextTail() {
for (auto& tail : m_characterList) {
if (tail) tail->isShowing = false;
}
m_characterList.clear();
for (auto& tail : m_itemList) {
if (tail) {
tail->isShowing = false;
tail->isSelected = false;
}
}
m_itemList.clear();
}
int TextTailManager::Pick(int ixMouse, int iyMouse) {
float mx = static_cast<float>(ixMouse);
float my = static_cast<float>(iyMouse);
for (const auto& tail : m_itemList) {
if (!tail) continue;
float bx1 = tail->x + tail->xStart;
float bx2 = tail->x + tail->xEnd;
float by1 = tail->y + tail->yStart;
float by2 = tail->y + tail->yEnd;
if (mx >= bx1 && mx <= bx2 && my >= by1 && my <= by2) {
SelectItemName(tail->dwVirtualID);
return static_cast<int>(tail->dwVirtualID);
}
}
return -1;
}
void TextTailManager::SelectItemName(uint32_t vid) {
m_selectedItemVID = vid;
for (auto& tail : m_itemList) {
if (tail && tail->dwVirtualID == vid) {
tail->isSelected = true;
}
}
}
bool TextTailManager::GetTextTailPosition(uint32_t vid, float& x, float& y, float& z) const {
auto it = m_characterMap.find(vid);
if (it != m_characterMap.end()) {
x = it->second->x;
y = it->second->y;
z = it->second->z;
return true;
}
auto itItem = m_itemMap.find(vid);
if (itItem != m_itemMap.end()) {
x = itItem->second->x;
y = itItem->second->y;
z = itItem->second->z;
return true;
}
return false;
}
const std::shared_ptr<TextTailItem> TextTailManager::GetCharacterTail(uint32_t vid) const {
auto it = m_characterMap.find(vid);
return it != m_characterMap.end() ? it->second : nullptr;
}
const std::shared_ptr<TextTailItem> TextTailManager::GetItemTail(uint32_t vid) const {
auto it = m_itemMap.find(vid);
return it != m_itemMap.end() ? it->second : nullptr;
}
void TextTailManager::Update(float dt) {
if (dt <= 0.0f) return;
for (auto& [vid, tail] : m_characterMap) {
if (tail && tail->hasChat) {
tail->chatTimer += dt;
if (tail->chatTimer >= tail->chatMaxDuration) {
tail->hasChat = false;
tail->chatText.clear();
}
}
}
for (auto& [vid, tail] : m_itemMap) {
if (tail && tail->ownerTime > 0) {
// Can tick countdown timer
}
}
}
void TextTailManager::UpdateAllTextTail(float playerX, float playerY, float playerZ, const Gr2SceneRenderer* sceneRenderer) {
const auto* r = sceneRenderer ? sceneRenderer : m_currentSceneRenderer;
for (auto& [vid, tail] : m_characterMap) {
if (!tail) continue;
if (tail->hasWorldPos) {
float dx = tail->worldX - playerX;
float dy = tail->worldY - playerY;
float dz = tail->worldZ - playerZ;
tail->fDistanceFromPlayer = std::sqrt(dx * dx + dy * dy + dz * dz);
if (r) {
float sx = 0.0f, sy = 0.0f;
if (r->ProjectToScreen(tail->worldX, tail->worldY + tail->fHeight, tail->worldZ, sx, sy)) {
tail->x = std::floor(sx);
tail->y = std::floor(sy);
tail->z = 0.0f;
}
}
}
}
for (auto& [vid, tail] : m_itemMap) {
if (!tail) continue;
if (tail->hasWorldPos) {
float dx = tail->worldX - playerX;
float dy = tail->worldY - playerY;
float dz = tail->worldZ - playerZ;
tail->fDistanceFromPlayer = std::sqrt(dx * dx + dy * dy + dz * dz);
if (r) {
float sx = 0.0f, sy = 0.0f;
if (r->ProjectToScreen(tail->worldX, tail->worldY + tail->fHeight, tail->worldZ, sx, sy)) {
tail->x = std::floor(sx);
tail->y = std::floor(sy);
tail->z = 0.0f;
}
}
}
}
}
void TextTailManager::UpdateShowingTextTail(const Gr2SceneRenderer* sceneRenderer) {
const auto* r = sceneRenderer ? sceneRenderer : m_currentSceneRenderer;
if (!r) return;
for (auto& tail : m_characterList) {
if (!tail || !tail->hasWorldPos) continue;
float sx = 0.0f, sy = 0.0f;
if (r->ProjectToScreen(tail->worldX, tail->worldY + tail->fHeight, tail->worldZ, sx, sy)) {
tail->x = std::floor(sx);
tail->y = std::floor(sy);
}
}
for (auto& tail : m_itemList) {
if (!tail || !tail->hasWorldPos) continue;
float sx = 0.0f, sy = 0.0f;
if (r->ProjectToScreen(tail->worldX, tail->worldY + tail->fHeight, tail->worldZ, sx, sy)) {
tail->x = std::floor(sx);
tail->y = std::floor(sy);
}
}
}
bool TextTailManager::isIn(const TextTailItem& src, const TextTailItem& tgt) const {
float x1Source = src.x + src.xStart;
float y1Source = src.y + src.yStart;
float x2Source = src.x + src.xEnd;
float y2Source = src.y + src.yEnd;
float x1Target = tgt.x + tgt.xStart;
float y1Target = tgt.y + tgt.yStart;
float x2Target = tgt.x + tgt.xEnd;
float y2Target = tgt.y + tgt.yEnd;
return (x1Source <= x2Target && x2Source >= x1Target &&
y1Source <= y2Target && y2Source >= y1Target);
}
void TextTailManager::ArrangeTextTail() {
// 1. Arrange Item TextTails to avoid mutual overlap
for (size_t i = 0; i < m_itemList.size(); ++i) {
auto& pInsert = m_itemList[i];
if (!pInsert) continue;
int limitCount = 0;
for (size_t j = 0; j < m_itemList.size();) {
if (i == j) {
++j;
continue;
}
auto& pCompare = m_itemList[j];
if (!pCompare) {
++j;
continue;
}
if (limitCount >= 20) break;
if (isIn(*pInsert, *pCompare)) {
pInsert->y = pCompare->y + pCompare->yEnd - pInsert->yStart + 4.0f;
j = 0;
limitCount++;
continue;
}
++j;
}
}
// 2. Arrange Character TextTails (compute Level, Title, Guild bounding boxes)
for (auto& tail : m_characterList) {
if (!tail) continue;
float nameWidth = static_cast<float>(tail->name.size()) * 8.0f;
float titleWidth = tail->title.empty() ? 0.0f : (static_cast<float>(tail->title.size()) * 8.0f);
float levelWidth = tail->level.empty() ? 0.0f : (static_cast<float>(tail->level.size()) * 8.0f);
float totalW = nameWidth;
if (!tail->title.empty()) totalW += titleWidth + 6.0f;
if (!tail->level.empty()) totalW += levelWidth + 6.0f;
tail->xStart = -totalW * 0.5f - 4.0f;
tail->xEnd = totalW * 0.5f + 4.0f;
tail->yStart = -16.0f;
tail->yEnd = 4.0f;
}
}
void TextTailManager::RenderTextTailBox(SDL_Renderer* renderer, const TextTailItem& tail) {
float bx1 = tail.x + tail.xStart;
float by1 = tail.y + tail.yStart;
float w = tail.xEnd - tail.xStart;
float h = tail.yEnd - tail.yStart;
SDL_FRect rect{bx1, by1, w, h};
// Dark translucent background bar
SDL_SetRenderDrawColor(renderer, 10, 10, 10, 190);
SDL_RenderFillRect(renderer, &rect);
// Border: Green if selected, golden/subtle grey otherwise
if (tail.isSelected || tail.dwVirtualID == m_selectedItemVID) {
SDL_SetRenderDrawColor(renderer, 50, 240, 80, 255); // Emerald Green highlight
} else {
SDL_SetRenderDrawColor(renderer, 45, 45, 45, 230);
}
SDL_RenderRect(renderer, &rect);
}
void TextTailManager::RenderText(SDL_Renderer* renderer, float x, float y, const std::string& text, uint32_t color, float scale, bool shadow) {
if (text.empty()) return;
uint8_t a = (color >> 24) & 0xFF;
if (a == 0) a = 0xFF;
uint8_t r = (color >> 16) & 0xFF;
uint8_t g = (color >> 8) & 0xFF;
uint8_t b = color & 0xFF;
SDL_SetRenderScale(renderer, scale, scale);
if (shadow) {
// Outline shadow
SDL_SetRenderDrawColor(renderer, 10, 10, 10, a);
SDL_RenderDebugText(renderer, (x + 1.0f) / scale, (y + 1.0f) / scale, text.c_str());
SDL_RenderDebugText(renderer, (x - 1.0f) / scale, (y) / scale, text.c_str());
SDL_RenderDebugText(renderer, (x) / scale, (y - 1.0f) / scale, text.c_str());
}
// Main text
SDL_SetRenderDrawColor(renderer, r, g, b, a);
SDL_RenderDebugText(renderer, x / scale, y / scale, text.c_str());
SDL_SetRenderScale(renderer, 1.0f, 1.0f);
}
void TextTailManager::RenderChatBubble(SDL_Renderer* renderer, const TextTailItem& tail) {
if (!tail.hasChat || tail.chatText.empty()) return;
float textW = static_cast<float>(tail.chatText.size()) * 8.0f;
float bubbleW = textW + 16.0f;
float bubbleH = 22.0f;
float bx = tail.x - bubbleW * 0.5f;
float by = tail.y - 36.0f;
// Speech bubble background (white/cream)
SDL_FRect bgRect{bx, by, bubbleW, bubbleH};
SDL_SetRenderDrawColor(renderer, 245, 245, 235, 240);
SDL_RenderFillRect(renderer, &bgRect);
// Dark border
SDL_SetRenderDrawColor(renderer, 40, 40, 40, 255);
SDL_RenderRect(renderer, &bgRect);
// Downward notch / pointer
SDL_RenderLine(renderer, tail.x - 4.0f, by + bubbleH, tail.x, by + bubbleH + 6.0f);
SDL_RenderLine(renderer, tail.x, by + bubbleH + 6.0f, tail.x + 4.0f, by + bubbleH);
// Dark text inside speech bubble
RenderText(renderer, bx + 8.0f, by + 4.0f, tail.chatText, 0xFF1A1A1A, 1.0f, false);
}
void TextTailManager::Render(SDL_Renderer* renderer, const Gr2SceneRenderer* sceneRenderer) {
if (!renderer) {
renderer = m_currentRenderer;
}
if (!renderer) return;
if (sceneRenderer) {
UpdateShowingTextTail(sceneRenderer);
ArrangeTextTail();
}
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
// 1. Render Item TextTails
for (const auto& tail : m_itemList) {
if (!tail) continue;
RenderTextTailBox(renderer, *tail);
float textW = static_cast<float>(tail->name.size()) * 8.0f;
float tx = tail->x - textW * 0.5f;
float ty = tail->y - 10.0f;
// Render item name
uint32_t nameColor = tail->isSelected ? 0xFF50F050 : tail->color;
RenderText(renderer, tx, ty, tail->name, nameColor, 1.0f, true);
// If item has owner protection timer
if (!tail->ownerName.empty() || tail->ownerTime > 0) {
std::string ownerTag = tail->ownerName;
if (tail->ownerTime > 0) {
int m = tail->ownerTime / 60;
int s = tail->ownerTime % 60;
char buf[32];
std::snprintf(buf, sizeof(buf), "(%dm %ds) ", m, s);
ownerTag = std::string(buf) + ownerTag;
}
float owW = static_cast<float>(ownerTag.size()) * 8.0f * 0.9f;
uint32_t owColor = tail->isMineItem ? 0xFFFFD700 : 0xFFFF6060;
RenderText(renderer, tail->x - owW * 0.5f, ty - 14.0f, ownerTag, owColor, 0.9f, true);
}
}
// 2. Render Character TextTails
for (const auto& tail : m_characterList) {
if (!tail) continue;
float nameW = static_cast<float>(tail->name.size()) * 8.0f;
float titleW = tail->title.empty() ? 0.0f : (static_cast<float>(tail->title.size()) * 8.0f);
float levelW = tail->level.empty() ? 0.0f : (static_cast<float>(tail->level.size()) * 8.0f);
float totalW = nameW;
if (!tail->title.empty()) totalW += titleW + 6.0f;
if (!tail->level.empty()) totalW += levelW + 6.0f;
float curX = tail->x - totalW * 0.5f;
float curY = tail->y - 10.0f;
// Level tag e.g. "[Lv. 99]" in lime green
if (!tail->level.empty()) {
RenderText(renderer, curX, curY, tail->level, tail->levelColor, 1.0f, true);
curX += levelW + 6.0f;
}
// Title e.g. "Noble" in gold
if (!tail->title.empty()) {
RenderText(renderer, curX, curY, tail->title, tail->titleColor, 1.0f, true);
curX += titleW + 6.0f;
}
// Character Name in tail->color (white / red / yellow / etc.)
RenderText(renderer, curX, curY, tail->name, tail->color, 1.0f, true);
// Guild Name e.g. "[GuildName]" in light cyan above character name, with Guild Mark
if (!tail->guildName.empty()) {
std::string gStr = "[" + tail->guildName + "]";
float gW = static_cast<float>(gStr.size()) * 8.0f * 0.9f;
float totalW = gW;
bool hasMark = false;
float u0 = 0.0f, v0 = 0.0f, u1 = 0.0f, v1 = 0.0f;
uint32_t imgIdx = 0;
if (tail->guildID != 0 && GuildMarkManager::Instance().GetMarkUV(tail->guildID, u0, v0, u1, v1, imgIdx)) {
hasMark = true;
totalW += 16.0f + 4.0f; // 16px mark + 4px spacing
}
float startX = tail->x - totalW * 0.5f;
float guildY = curY - 14.0f;
if (hasMark) {
SDL_Texture* markTex = GuildMarkManager::Instance().GetSDLTexture(imgIdx, renderer);
if (markTex) {
SDL_FRect srcRect{ u0 * 512.0f, v0 * 512.0f, (u1 - u0) * 512.0f, (v1 - v0) * 512.0f };
SDL_FRect dstRect{ startX, guildY - 2.0f, 16.0f, 12.0f };
SDL_SetTextureBlendMode(markTex, SDL_BLENDMODE_BLEND);
SDL_RenderTexture(renderer, markTex, &srcRect, &dstRect);
}
startX += 16.0f + 4.0f;
}
RenderText(renderer, startX, guildY, gStr, 0xFF80D0FF, 0.9f, true);
}
// Chat speech bubble
if (tail->hasChat) {
RenderChatBubble(renderer, *tail);
}
}
}
} // namespace ava2
+157
View File
@@ -0,0 +1,157 @@
#pragma once
#include "Gr2ModelRenderer.h"
#include <SDL3/SDL.h>
#include <cstdint>
#include <string>
#include <vector>
#include <unordered_map>
#include <memory>
namespace ava2 {
struct TextTailItem {
uint32_t dwVirtualID = 0;
std::string name;
std::string title;
std::string level;
std::string guildName;
uint32_t guildID = 0;
uint32_t color = 0xFFFFFFFF; // ARGB (white by default)
uint32_t titleColor = 0xFFFFD700; // Gold default
uint32_t levelColor = 0xFF98FF33; // Lime green default
// Screen projected position
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
// Height offset in 3D world (above character origin)
float fHeight = 10.0f;
float fDistanceFromPlayer = 0.0f;
// 2D Bounding box relative to (x, y) for picking and overlap checks
float xStart = 0.0f;
float yStart = 0.0f;
float xEnd = 0.0f;
float yEnd = 0.0f;
// Item specifics
bool isItem = false;
int ownerTime = 0; // seconds left
std::string ownerName;
bool isMineItem = false;
bool isSelected = false;
// Visibility flags
bool bNameFlag = true;
bool isShowing = false;
// Chat / Speech Bubble
std::string chatText;
float chatTimer = 0.0f;
float chatMaxDuration = 4.0f;
bool hasChat = false;
// World position (fallback or explicit coordinates)
float worldX = 0.0f;
float worldY = 0.0f;
float worldZ = 0.0f;
bool hasWorldPos = false;
};
/**
* TextTailManager:
* Full cross-platform implementation of Metin2 / AVA2 CPythonTextTail.
* Manages overhead character nameplates, guild titles, level tags,
* dropped ground item text boxes (with mouse picking and overlap resolution),
* and comic-style chat speech bubbles.
*/
class TextTailManager {
public:
static TextTailManager& Instance();
TextTailManager();
~TextTailManager() = default;
void Clear();
// Character TextTails
void RegisterCharacterTextTail(uint32_t guildID, uint32_t vid, uint32_t color = 0xFFFFFFFF, float fAddHeight = 10.0f);
void SetCharacterPosition(uint32_t vid, float worldX, float worldY, float worldZ);
void SetCharacterName(uint32_t vid, const std::string& name);
void SetCharacterTextTailColor(uint32_t vid, uint32_t color);
void AttachTitle(uint32_t vid, const std::string& title, uint32_t color = 0xFFFFD700);
void DetachTitle(uint32_t vid);
void AttachLevel(uint32_t vid, const std::string& levelText, uint32_t color = 0xFF98FF33);
void DetachLevel(uint32_t vid);
void SetGuildName(uint32_t vid, const std::string& guildName, uint32_t guildID = 0);
void DeleteCharacterTextTail(uint32_t vid);
void ShowCharacterTextTail(uint32_t vid);
// Item TextTails
void RegisterItemTextTail(uint32_t vid, const std::string& text, float worldX = 0.0f, float worldY = 0.0f, float worldZ = 0.0f, int ownerTime = 0, const std::string& ownerName = "", bool isMine = false, uint32_t color = 0xFFFFFFFF);
void SetItemPosition(uint32_t vid, float worldX, float worldY, float worldZ);
void SetItemTextTailOwner(uint32_t vid, const std::string& ownerName, bool isMine = false);
void DeleteItemTextTail(uint32_t vid);
void ShowItemTextTail(uint32_t vid);
// Chat / Info Speech Bubbles
void RegisterChatTail(uint32_t vid, const std::string& chatText);
void RegisterInfoTail(uint32_t vid, const std::string& infoText);
bool IsChatTextTail(uint32_t vid) const;
// Visibility & Control
void ShowAllTextTail();
void HideAllTextTail();
void EnablePKTitle(bool bFlag) { m_pkTitleEnable = bFlag; }
// Screen Position & Mouse Picking
int Pick(int ixMouse, int iyMouse);
void SelectItemName(uint32_t vid);
bool GetTextTailPosition(uint32_t vid, float& x, float& y, float& z) const;
// Simulation & Layout
void Update(float dt);
void UpdateAllTextTail(float playerX = 0.0f, float playerY = 0.0f, float playerZ = 0.0f, const Gr2SceneRenderer* sceneRenderer = nullptr);
void UpdateShowingTextTail(const Gr2SceneRenderer* sceneRenderer = nullptr);
void ArrangeTextTail();
// Rendering
void Render(SDL_Renderer* renderer, const Gr2SceneRenderer* sceneRenderer = nullptr);
// Queries & Getters
size_t GetCharacterCount() const { return m_characterMap.size(); }
size_t GetItemCount() const { return m_itemMap.size(); }
size_t GetShowingCharacterCount() const { return m_characterList.size(); }
size_t GetShowingItemCount() const { return m_itemList.size(); }
bool HasCharacter(uint32_t vid) const { return m_characterMap.find(vid) != m_characterMap.end(); }
bool HasItem(uint32_t vid) const { return m_itemMap.find(vid) != m_itemMap.end(); }
const std::shared_ptr<TextTailItem> GetCharacterTail(uint32_t vid) const;
const std::shared_ptr<TextTailItem> GetItemTail(uint32_t vid) const;
// Active renderer reference for Python bindings
void SetCurrentSceneRenderer(const Gr2SceneRenderer* renderer) { m_currentSceneRenderer = renderer; }
void SetCurrentRenderer(SDL_Renderer* renderer) { m_currentRenderer = renderer; }
private:
bool isIn(const TextTailItem& src, const TextTailItem& tgt) const;
void RenderTextTailBox(SDL_Renderer* renderer, const TextTailItem& tail);
void RenderText(SDL_Renderer* renderer, float x, float y, const std::string& text, uint32_t color, float scale = 1.0f, bool shadow = true);
void RenderChatBubble(SDL_Renderer* renderer, const TextTailItem& tail);
std::unordered_map<uint32_t, std::shared_ptr<TextTailItem>> m_characterMap;
std::unordered_map<uint32_t, std::shared_ptr<TextTailItem>> m_itemMap;
std::vector<std::shared_ptr<TextTailItem>> m_characterList; // list of currently showing character tails
std::vector<std::shared_ptr<TextTailItem>> m_itemList; // list of currently showing item tails
bool m_pkTitleEnable = true;
uint32_t m_selectedItemVID = 0;
const Gr2SceneRenderer* m_currentSceneRenderer = nullptr;
SDL_Renderer* m_currentRenderer = nullptr;
};
} // namespace ava2
+227
View File
@@ -0,0 +1,227 @@
#include "WaterManager.h"
#include <fstream>
#include <iostream>
#include <cmath>
#include <algorithm>
namespace ava2 {
#pragma pack(push, 1)
struct SWaterMapHeader {
uint16_t magic; // 5426
uint16_t width; // 128
uint16_t height; // 128
uint8_t layer_count;
};
#pragma pack(pop)
WaterManager::WaterManager() = default;
WaterManager::~WaterManager() = default;
bool WaterManager::LoadWater(const std::string& filepath, float cell_scale, float height_scale, float height_bias,
float world_min_x, float world_min_z) {
std::ifstream file(filepath, std::ios::binary);
if (!file) {
return false;
}
file.seekg(0, std::ios::end);
std::streamsize file_size = file.tellg();
file.seekg(0, std::ios::beg);
if (file_size < static_cast<std::streamsize>(sizeof(SWaterMapHeader))) {
return false;
}
SWaterMapHeader header{};
file.read(reinterpret_cast<char*>(&header), sizeof(header));
if (!file) return false;
constexpr uint16_t WATER_MAGIC = 5426;
if (header.magic != WATER_MAGIC || header.width == 0 || header.height == 0) {
return false;
}
m_width = header.width;
m_height = header.height;
size_t grid_size = static_cast<size_t>(m_width) * m_height;
m_water_grid.resize(grid_size);
file.read(reinterpret_cast<char*>(m_water_grid.data()), grid_size);
if (!file) return false;
size_t rest_bytes = static_cast<size_t>(file_size - sizeof(SWaterMapHeader) - grid_size);
m_water_heights.clear();
if (header.layer_count > 0) {
if (rest_bytes == header.layer_count * sizeof(int32_t)) {
m_water_heights.resize(header.layer_count);
file.read(reinterpret_cast<char*>(m_water_heights.data()), rest_bytes);
} else if (rest_bytes == header.layer_count * sizeof(uint16_t)) {
std::vector<uint16_t> h16(header.layer_count);
file.read(reinterpret_cast<char*>(h16.data()), rest_bytes);
for (auto h : h16) {
m_water_heights.push_back(static_cast<int32_t>(h));
}
}
}
m_cell_scale = cell_scale;
m_height_scale = height_scale;
m_height_bias = height_bias;
m_world_min_x = world_min_x;
m_world_min_z = world_min_z;
size_t valid_cells = 0;
for (uint8_t b : m_water_grid) {
if (b != 0xFF && b < m_water_heights.size()) {
valid_cells++;
}
}
m_face_count = valid_cells * 2;
m_has_water = (valid_cells > 0);
m_procedural = false;
return m_has_water;
}
void WaterManager::GenerateProceduralWater(float water_level, float min_x, float max_x, float min_z, float max_z, float cell_size) {
m_procedural = true;
m_proc_plane.water_level = water_level;
m_proc_plane.min_x = min_x;
m_proc_plane.max_x = max_x;
m_proc_plane.min_z = min_z;
m_proc_plane.max_z = max_z;
m_proc_plane.cell_size = std::max(10.0f, cell_size);
int count_x = static_cast<int>(std::ceil((max_x - min_x) / m_proc_plane.cell_size));
int count_z = static_cast<int>(std::ceil((max_z - min_z) / m_proc_plane.cell_size));
m_face_count = static_cast<size_t>(count_x * count_z * 2);
m_has_water = true;
}
float WaterManager::GetWaterLevel(size_t layer) const {
if (m_procedural) return m_proc_plane.water_level;
if (layer < m_water_heights.size()) {
return static_cast<float>(m_water_heights[layer]) * m_height_scale - m_height_bias;
}
return 0.0f;
}
Render3DDraw WaterManager::BuildDrawCommand(float anim_time) const {
Render3DDraw draw;
if (!m_has_water) return draw;
draw.material_diffuse[0] = ((m_water_color >> 16) & 0xFF) / 255.0f;
draw.material_diffuse[1] = ((m_water_color >> 8) & 0xFF) / 255.0f;
draw.material_diffuse[2] = (m_water_color & 0xFF) / 255.0f;
draw.material_diffuse[3] = ((m_water_color >> 24) & 0xFF) / 255.0f;
draw.light_direction[0] = 0.4f;
draw.light_direction[1] = 0.8f;
draw.light_direction[2] = 0.45f;
float wave_offset = std::sin(anim_time * 2.0f) * 1.5f;
draw.alpha_blend = true;
if (m_procedural) {
int nx = static_cast<int>(std::ceil((m_proc_plane.max_x - m_proc_plane.min_x) / m_proc_plane.cell_size));
int nz = static_cast<int>(std::ceil((m_proc_plane.max_z - m_proc_plane.min_z) / m_proc_plane.cell_size));
int verts_x = nx + 1;
int verts_z = nz + 1;
draw.positions.reserve(verts_x * verts_z * 3);
draw.normals.reserve(verts_x * verts_z * 3);
draw.uv0.reserve(verts_x * verts_z * 2);
draw.diffuse.reserve(verts_x * verts_z);
draw.indices.reserve(nx * nz * 6);
for (int j = 0; j <= nz; ++j) {
float z = m_proc_plane.min_z + static_cast<float>(j) * m_proc_plane.cell_size;
for (int i = 0; i <= nx; ++i) {
float x = m_proc_plane.min_x + static_cast<float>(i) * m_proc_plane.cell_size;
float y = m_proc_plane.water_level + wave_offset;
draw.positions.push_back(x);
draw.positions.push_back(y);
draw.positions.push_back(z);
draw.normals.push_back(0.0f);
draw.normals.push_back(1.0f);
draw.normals.push_back(0.0f);
draw.uv0.push_back(x * 0.005f + anim_time * 0.02f);
draw.uv0.push_back(z * 0.005f + anim_time * 0.02f);
draw.diffuse.push_back(m_water_color);
}
}
for (int j = 0; j < nz; ++j) {
for (int i = 0; i < nx; ++i) {
uint32_t i0 = j * verts_x + i;
uint32_t i1 = j * verts_x + (i + 1);
uint32_t i2 = (j + 1) * verts_x + i;
uint32_t i3 = (j + 1) * verts_x + (i + 1);
draw.indices.push_back(i0);
draw.indices.push_back(i2);
draw.indices.push_back(i1);
draw.indices.push_back(i1);
draw.indices.push_back(i2);
draw.indices.push_back(i3);
}
}
return draw;
}
// Step sampling for 128x128 water map to optimize draw call vertex counts
const int step = 2;
for (int j = 0; j < m_height; j += step) {
for (int i = 0; i < m_width; i += step) {
uint8_t layer = m_water_grid[j * m_width + i];
if (layer == 0xFF || layer >= m_water_heights.size()) continue;
float base_y = static_cast<float>(m_water_heights[layer]) * m_height_scale - m_height_bias + wave_offset;
float x0 = m_world_min_x + static_cast<float>(i) * m_cell_scale;
float x1 = x0 + m_cell_scale * static_cast<float>(step);
float z0 = m_world_min_z + static_cast<float>(j) * m_cell_scale;
float z1 = z0 + m_cell_scale * static_cast<float>(step);
uint32_t start_idx = static_cast<uint32_t>(draw.positions.size() / 3);
// 4 vertices
draw.positions.push_back(x0); draw.positions.push_back(base_y); draw.positions.push_back(z0);
draw.positions.push_back(x1); draw.positions.push_back(base_y); draw.positions.push_back(z0);
draw.positions.push_back(x0); draw.positions.push_back(base_y); draw.positions.push_back(z1);
draw.positions.push_back(x1); draw.positions.push_back(base_y); draw.positions.push_back(z1);
for (int k = 0; k < 4; ++k) {
draw.normals.push_back(0.0f);
draw.normals.push_back(1.0f);
draw.normals.push_back(0.0f);
draw.diffuse.push_back(m_water_color);
}
draw.uv0.push_back(x0 * 0.005f); draw.uv0.push_back(z0 * 0.005f);
draw.uv0.push_back(x1 * 0.005f); draw.uv0.push_back(z0 * 0.005f);
draw.uv0.push_back(x0 * 0.005f); draw.uv0.push_back(z1 * 0.005f);
draw.uv0.push_back(x1 * 0.005f); draw.uv0.push_back(z1 * 0.005f);
// 2 triangles (CW for top-down view)
draw.indices.push_back(start_idx + 0);
draw.indices.push_back(start_idx + 2);
draw.indices.push_back(start_idx + 1);
draw.indices.push_back(start_idx + 1);
draw.indices.push_back(start_idx + 2);
draw.indices.push_back(start_idx + 3);
}
}
return draw;
}
} // namespace ava2
+56
View File
@@ -0,0 +1,56 @@
#pragma once
#include "RenderCommands3D.h"
#include <string>
#include <vector>
#include <cstdint>
namespace ava2 {
class WaterManager {
public:
WaterManager();
~WaterManager();
// Load Metin2 binary water.wtr file
bool LoadWater(const std::string& filepath, float cell_scale = 40.0f, float height_scale = 0.5f, float height_bias = 0.0f,
float world_min_x = -2560.0f, float world_min_z = -2560.0f);
// Generate procedural water plane (for valleys, rivers, or lakes)
void GenerateProceduralWater(float water_level, float min_x, float max_x, float min_z, float max_z, float cell_size = 60.0f);
// Build unified 3D draw commands for water rasterization
Render3DDraw BuildDrawCommand(float anim_time = 0.0f) const;
bool HasWater() const { return m_has_water; }
size_t GetWaterFaceCount() const { return m_face_count; }
float GetWaterLevel(size_t layer = 0) const;
void SetWaterColor(uint32_t color) { m_water_color = color; }
uint32_t GetWaterColor() const { return m_water_color; }
private:
bool m_has_water = false;
uint16_t m_width = 0;
uint16_t m_height = 0;
std::vector<uint8_t> m_water_grid;
std::vector<int32_t> m_water_heights;
float m_cell_scale = 40.0f;
float m_height_scale = 0.5f;
float m_height_bias = 0.0f;
float m_world_min_x = 0.0f;
float m_world_min_z = 0.0f;
size_t m_face_count = 0;
uint32_t m_water_color = 0xAA2C7CA3; // 40250-like translucent aqua cyan water
struct ProceduralWaterPlane {
float water_level = 0.0f;
float min_x = 0.0f, max_x = 0.0f;
float min_z = 0.0f, max_z = 0.0f;
float cell_size = 60.0f;
};
bool m_procedural = false;
ProceduralWaterPlane m_proc_plane;
};
} // namespace ava2
+71
View File
@@ -0,0 +1,71 @@
#pragma once
#include "shared/common/Win32Types.h"
#include "shared/common/ReferenceObject.h"
#include "shared/common/Ref.h"
#include "shared/common/CRC32.h"
#include <string>
class CResource : public CReferenceObject
{
public:
typedef DWORD TType;
enum EState
{
STATE_EMPTY,
STATE_ERROR,
STATE_EXIST,
STATE_LOAD,
STATE_FREE
};
static TType StringToType(const char* c_szType)
{
return GetCRC32(c_szType, strlen(c_szType));
}
static TType Type()
{
static TType s_type = StringToType("CResource");
return s_type;
}
CResource(const char* c_szFileName)
: m_stFileName(c_szFileName ? c_szFileName : ""), m_dwLoadCostMilliSecond(0)
{
}
virtual ~CResource() {}
void Clear() { OnClear(); }
bool IsEmpty() const { return OnIsEmpty(); }
bool IsType(TType type) { return OnIsType(type); }
const char* GetFileName() const { return m_stFileName.c_str(); }
const std::string& GetFileNameString() const { return m_stFileName; }
virtual bool OnLoad(int iSize, const void* c_pvBuf) = 0;
protected:
void SetFileName(const char* c_szFileName)
{
m_stFileName = c_szFileName ? c_szFileName : "";
}
virtual void OnClear() = 0;
virtual bool OnIsEmpty() const = 0;
virtual bool OnIsType(TType type)
{
return Type() == type;
}
void OnSelfDestruct() override
{
// Cached in CResourceManager; life cycle managed by CResourceManager::Destroy()
}
protected:
std::string m_stFileName;
DWORD m_dwLoadCostMilliSecond;
};
+234
View File
@@ -0,0 +1,234 @@
#pragma once
#include "src/eter_image/GrpImage.h"
#include "src/eter_image/GrpSubImage.h"
#include "src/eter_resource/Resource.h"
#include "src/eter_resource/SubImage.h"
#include "shared/common/Singleton.h"
#include <unordered_map>
#include <memory>
#include <string>
#include <algorithm>
#include <vector>
class CResourceManager : public CSingleton<CResourceManager>
{
public:
CResourceManager() = default;
virtual ~CResourceManager()
{
Destroy();
}
void Destroy()
{
std::vector<CResource*> resources;
resources.reserve(m_resourceMap.size());
for (auto& pair : m_resourceMap)
{
if (pair.second)
resources.push_back(pair.second);
}
m_resourceMap.clear();
for (auto* res : resources)
res->Clear();
for (auto* res : resources)
delete res;
}
CResource* GetResourcePointer(const char* c_szFileName)
{
if (!c_szFileName || !*c_szFileName)
return nullptr;
std::string path = NormalizePath(c_szFileName);
auto it = m_resourceMap.find(path);
if (it != m_resourceMap.end())
return it->second;
// Determine type based on extension
std::string ext;
size_t dot_pos = path.rfind('.');
if (dot_pos != std::string::npos)
{
ext = path.substr(dot_pos);
std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
}
CResource* pRes = nullptr;
if (ext == ".sub")
{
pRes = LoadSubImage(path.c_str());
}
else
{
pRes = LoadImage(path.c_str());
}
if (pRes)
m_resourceMap[path] = pRes;
return pRes;
}
static std::string NormalizePath(const char* c_szPath)
{
std::string path = c_szPath ? c_szPath : "";
for (char& ch : path)
{
if (ch == '\\') ch = '/';
else if (static_cast<unsigned char>(ch) < 128)
ch = static_cast<char>(::tolower(static_cast<unsigned char>(ch)));
}
return path;
}
static std::vector<std::string> GetCandidatePaths(const std::string& path)
{
std::vector<std::string> candidates;
candidates.push_back(path);
if (path.rfind("d:/", 0) == 0)
{
std::string no_drive = path.substr(3); // e.g. "ymir work/ui/pattern/..."
candidates.push_back(no_drive);
if (no_drive.rfind("ymir work/", 0) == 0)
{
candidates.push_back(no_drive.substr(10)); // e.g. "ui/pattern/..."
}
}
else if (path.rfind("ymir work/", 0) == 0)
{
candidates.push_back(path.substr(10));
}
else
{
candidates.push_back("ymir work/" + path);
}
// Handle legacy CP949/Latin-1 raw bytes in filenames by generating UTF-8 candidates
size_t initial_size = candidates.size();
for (size_t i = 0; i < initial_size; ++i)
{
const std::string& cand = candidates[i];
bool has_high_byte = false;
for (unsigned char c : cand)
{
if (c >= 0x80)
{
has_high_byte = true;
break;
}
}
if (has_high_byte)
{
std::string utf8_path;
for (unsigned char c : cand)
{
if (c < 0x80)
{
utf8_path.push_back(static_cast<char>(c));
}
else
{
utf8_path.push_back(static_cast<char>(0xC0 | (c >> 6)));
utf8_path.push_back(static_cast<char>(0x80 | (c & 0x3F)));
}
}
candidates.push_back(utf8_path);
}
}
return candidates;
}
private:
CGraphicImage* LoadImage(const char* path)
{
auto candidates = GetCandidatePaths(path);
for (const auto& c : candidates)
{
auto* img = new CGraphicImage(path);
if (img->LoadFile(c.c_str()))
{
return img;
}
delete img;
}
return nullptr;
}
CGraphicSubImage* LoadSubImage(const char* path)
{
ava2::SubImageInfo subInfo;
bool parsed = false;
auto candidates = GetCandidatePaths(path);
for (const auto& c : candidates)
{
if (ava2::SubImageParser::ParseFile(c, subInfo))
{
parsed = true;
break;
}
}
if (!parsed)
return nullptr;
// Try getting referenced base image
CResource* baseRes = GetResourcePointer(subInfo.image_file.c_str());
if (!baseRes || !baseRes->IsType(CGraphicImage::Type()))
{
// Resolve relative to .sub directory
std::string subDir = path;
size_t slash = subDir.rfind('/');
if (slash != std::string::npos)
{
std::string relPath = subDir.substr(0, slash + 1);
size_t imgSlash = subInfo.image_file.rfind('/');
std::string baseName = (imgSlash != std::string::npos) ? subInfo.image_file.substr(imgSlash + 1) : subInfo.image_file;
relPath += baseName;
baseRes = GetResourcePointer(relPath.c_str());
}
}
// If still not found, check parent directory of .sub
if (!baseRes || !baseRes->IsType(CGraphicImage::Type()))
{
std::string subDir = path;
size_t slash = subDir.rfind('/');
if (slash != std::string::npos)
{
size_t prevSlash = subDir.rfind('/', slash - 1);
if (prevSlash != std::string::npos)
{
std::string parentPath = subDir.substr(0, prevSlash + 1) + subInfo.image_file;
baseRes = GetResourcePointer(parentPath.c_str());
}
}
}
// Also check "ymir work/ui/" + baseName and "d:/ymir work/ui/" + baseName
if (!baseRes || !baseRes->IsType(CGraphicImage::Type()))
{
size_t imgSlash = subInfo.image_file.rfind('/');
std::string baseName = (imgSlash != std::string::npos) ? subInfo.image_file.substr(imgSlash + 1) : subInfo.image_file;
std::string uiPath = "ymir work/ui/" + baseName;
baseRes = GetResourcePointer(uiPath.c_str());
}
if (!baseRes || !baseRes->IsType(CGraphicImage::Type()))
return nullptr;
CGraphicImage* baseImg = static_cast<CGraphicImage*>(baseRes);
auto* subImg = new CGraphicSubImage(path);
subImg->SetImagePointer(baseImg);
subImg->SetRectPosition(subInfo.left, subInfo.top, subInfo.right, subInfo.bottom);
return subImg;
}
std::unordered_map<std::string, CResource*> m_resourceMap;
};
+109
View File
@@ -0,0 +1,109 @@
#pragma once
#include "shared/common/Win32Types.h"
#include <string>
#include <vector>
#include <map>
#include <fstream>
#include <sstream>
#include <algorithm>
namespace ava2
{
struct SubImageInfo
{
std::string title;
std::string version;
std::string image_file;
int left = 0;
int top = 0;
int right = 0;
int bottom = 0;
int width() const { return right - left; }
int height() const { return bottom - top; }
bool is_valid() const { return !image_file.empty() && width() > 0 && height() > 0; }
};
class SubImageParser
{
public:
static bool Parse(const std::string& sub_content, const std::string& sub_file_path, SubImageInfo& out_info)
{
std::istringstream stream(sub_content);
std::string line;
std::map<std::string, std::string> token_map;
while (std::getline(stream, line))
{
// Strip carriage returns and leading/trailing whitespace
while (!line.empty() && (line.back() == '\r' || line.back() == ' ' || line.back() == '\t'))
line.pop_back();
size_t start = line.find_first_not_of(" \t");
if (start == std::string::npos) continue;
std::string trimmed = line.substr(start);
if (trimmed.empty() || trimmed[0] == '#') continue;
std::istringstream line_stream(trimmed);
std::string key, val;
line_stream >> key;
if (!(line_stream >> val)) continue;
// Strip quotes from value if present
if (val.size() >= 2 && val.front() == '"' && val.back() == '"')
val = val.substr(1, val.size() - 2);
std::transform(key.begin(), key.end(), key.begin(), [](unsigned char c) {
return (c < 128) ? static_cast<char>(::tolower(c)) : static_cast<char>(c);
});
std::string val_lower = val;
std::transform(val_lower.begin(), val_lower.end(), val_lower.begin(), [](unsigned char c) {
return (c < 128) ? static_cast<char>(::tolower(c)) : static_cast<char>(c);
});
if (key == "title") val = val_lower;
token_map[key] = val;
}
if (token_map["title"] != "subimage" && token_map["title"] != "subImage")
return false;
out_info.title = token_map["title"];
out_info.version = token_map["version"];
std::string image_name = token_map["image"];
if (token_map["version"] == "2.0")
{
// Relative to .sub directory
size_t pos = sub_file_path.find_last_of("/\\");
if (pos != std::string::npos)
out_info.image_file = sub_file_path.substr(0, pos + 1) + image_name;
else
out_info.image_file = image_name;
}
else
{
// Default search path prefix
out_info.image_file = "d:/ymir work/ui/" + image_name;
}
try {
if (token_map.count("left")) out_info.left = std::stoi(token_map["left"]);
if (token_map.count("top")) out_info.top = std::stoi(token_map["top"]);
if (token_map.count("right")) out_info.right = std::stoi(token_map["right"]);
if (token_map.count("bottom")) out_info.bottom = std::stoi(token_map["bottom"]);
} catch (...) {
return false;
}
return out_info.is_valid();
}
static bool ParseFile(const std::string& sub_file_path, SubImageInfo& out_info)
{
std::ifstream file(sub_file_path, std::ios::binary);
if (!file.is_open()) return false;
std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
return Parse(content, sub_file_path, out_info);
}
};
}
+289
View File
@@ -0,0 +1,289 @@
// engine/dxt —— DDS(DXT1/3/5) + 未压缩 BGRA8 → RGBA8 软解。M1 T3。
#include "dxt.h"
#include <cstdio>
#include <algorithm>
#include <cstring>
namespace mtimage {
namespace {
inline uint32_t rd_le32(const uint8_t* p) {
return uint32_t(p[0]) | (uint32_t(p[1]) << 8) | (uint32_t(p[2]) << 16) | (uint32_t(p[3]) << 24);
}
// 5:6:5 → r,g,b (0..255)
inline void unpack565(uint16_t c, int& r, int& g, int& b) {
r = ((c >> 11) & 0x1f); r = (r << 3) | (r >> 2);
g = ((c >> 5) & 0x3f); g = (g << 2) | (g >> 4);
b = (c & 0x1f); b = (b << 3) | (b >> 2);
}
// 解一个 DXT1 颜色块(8B)→ 16 像素 RGB(不写 alpha;dxt1_alpha=true 时按 1-bit alpha 写)
void decode_color_block(const uint8_t* blk, uint8_t out[16][4], bool dxt1_alpha) {
uint16_t c0 = uint16_t(blk[0] | (blk[1] << 8));
uint16_t c1 = uint16_t(blk[2] | (blk[3] << 8));
int r[4], g[4], b[4], a[4] = {255, 255, 255, 255};
unpack565(c0, r[0], g[0], b[0]);
unpack565(c1, r[1], g[1], b[1]);
if (c0 > c1 || !dxt1_alpha) {
r[2] = (2 * r[0] + r[1]) / 3; g[2] = (2 * g[0] + g[1]) / 3; b[2] = (2 * b[0] + b[1]) / 3;
r[3] = (r[0] + 2 * r[1]) / 3; g[3] = (g[0] + 2 * g[1]) / 3; b[3] = (b[0] + 2 * b[1]) / 3;
} else {
r[2] = (r[0] + r[1]) / 2; g[2] = (g[0] + g[1]) / 2; b[2] = (b[0] + b[1]) / 2;
r[3] = g[3] = b[3] = 0; a[3] = 0; // 透明
}
uint32_t bits = rd_le32(blk + 4);
for (int i = 0; i < 16; ++i) {
int idx = (bits >> (i * 2)) & 3;
out[i][0] = uint8_t(r[idx]); out[i][1] = uint8_t(g[idx]);
out[i][2] = uint8_t(b[idx]); out[i][3] = uint8_t(a[idx]);
}
}
// DXT3:alpha 块(8B)= 16 个 4-bit alpha,直接展开
void decode_dxt3_alpha(const uint8_t* blk, uint8_t out[16][4]) {
for (int i = 0; i < 8; ++i) {
int a0 = blk[i] & 0x0f, a1 = (blk[i] >> 4) & 0x0f;
out[i * 2 + 0][3] = uint8_t(a0 * 17); // 0..15 → 0..255
out[i * 2 + 1][3] = uint8_t(a1 * 17);
}
}
// DXT5:alpha 块(8B)= 2 端点 + 16×3-bit 索引
void decode_dxt5_alpha(const uint8_t* blk, uint8_t out[16][4]) {
int a0 = blk[0], a1 = blk[1];
int a[8];
a[0] = a0; a[1] = a1;
if (a0 > a1) {
for (int i = 1; i < 7; ++i) a[i + 1] = ((7 - i) * a0 + i * a1) / 7;
} else {
for (int i = 1; i < 5; ++i) a[i + 1] = ((5 - i) * a0 + i * a1) / 5;
a[6] = 0; a[7] = 255;
}
uint64_t bits = 0;
for (int i = 0; i < 6; ++i) bits |= uint64_t(blk[2 + i]) << (8 * i);
for (int i = 0; i < 16; ++i) {
int idx = int((bits >> (i * 3)) & 7);
out[i][3] = uint8_t(a[idx]);
}
}
enum Fmt { F_NONE, F_DXT1, F_DXT3, F_DXT5, F_RGB };
bool valid_mask(uint32_t mask, uint32_t bits) {
if (!mask || (bits < 32 && (mask >> bits))) return false;
while (!(mask & 1)) mask >>= 1;
return (mask & (mask + 1)) == 0; // contiguous channel bits
}
uint8_t channel(uint32_t pixel, uint32_t mask) {
if (!mask) return 255;
while (!(mask & 1)) { mask >>= 1; pixel >>= 1; }
return uint8_t((uint64_t(pixel & mask) * 255 + mask / 2) / mask);
}
void decode_dxt_level(Fmt fmt, const uint8_t* src, uint32_t w, uint32_t h, uint8_t* rgba) {
const int block_bytes = (fmt == F_DXT1) ? 8 : 16;
const size_t bx = (w + 3) / 4, by = (h + 3) / 4;
for (size_t byi = 0; byi < by; ++byi) {
for (size_t bxi = 0; bxi < bx; ++bxi) {
const uint8_t* blk = src + (byi * bx + bxi) * block_bytes;
uint8_t px[16][4];
if (fmt == F_DXT1) {
decode_color_block(blk, px, /*dxt1_alpha=*/true);
} else {
decode_color_block(blk + 8, px, /*dxt1_alpha=*/false);
if (fmt == F_DXT3) decode_dxt3_alpha(blk, px);
else decode_dxt5_alpha(blk, px);
}
for (int py = 0; py < 4; ++py) {
size_t y = byi * 4 + py;
if (y >= h) break;
for (int pxx = 0; pxx < 4; ++pxx) {
size_t x = bxi * 4 + pxx;
if (x >= w) break;
uint8_t* o = &rgba[(y * w + x) * 4];
const uint8_t* s = px[py * 4 + pxx];
o[0] = s[0]; o[1] = s[1]; o[2] = s[2]; o[3] = s[3];
}
}
}
}
}
Image decode_tga(const uint8_t* data, size_t size) {
Image out;
if (size < 18) return out;
const uint8_t id_len = data[0];
const uint8_t cmap_type = data[1];
const uint8_t img_type = data[2];
const uint32_t w = uint32_t(data[12]) | (uint32_t(data[13]) << 8);
const uint32_t h = uint32_t(data[14]) | (uint32_t(data[15]) << 8);
const uint8_t bpp = data[16];
const uint8_t desc = data[17];
if (cmap_type != 0 || !w || !h || w > 4096 || h > 4096) return out;
if (img_type != 2 && img_type != 3 && img_type != 10) return out;
const size_t bytes_per_pixel = bpp / 8;
if (bytes_per_pixel != 1 && bytes_per_pixel != 3 && bytes_per_pixel != 4) return out;
size_t offset = 18 + size_t(id_len);
if (offset > size) return out;
const size_t pixel_count = size_t(w) * size_t(h);
std::vector<uint8_t> temp(pixel_count * 4);
auto write_pixel = [&](size_t idx, const uint8_t* src) {
uint8_t* dst = &temp[idx * 4];
if (bytes_per_pixel == 1) {
dst[0] = dst[1] = dst[2] = src[0];
dst[3] = 255;
} else if (bytes_per_pixel == 3) {
dst[0] = src[2];
dst[1] = src[1];
dst[2] = src[0];
dst[3] = 255;
} else {
dst[0] = src[2];
dst[1] = src[1];
dst[2] = src[0];
dst[3] = src[3];
}
};
if (img_type == 2 || img_type == 3) {
if (offset + pixel_count * bytes_per_pixel > size) return out;
for (size_t i = 0; i < pixel_count; ++i)
write_pixel(i, data + offset + i * bytes_per_pixel);
} else if (img_type == 10) {
size_t i = 0;
while (i < pixel_count && offset < size) {
const uint8_t header = data[offset++];
const size_t run = (header & 0x7fu) + 1u;
if (header & 0x80u) {
if (offset + bytes_per_pixel > size) return out;
for (size_t r = 0; r < run && i < pixel_count; ++r, ++i)
write_pixel(i, data + offset);
offset += bytes_per_pixel;
} else {
if (offset + run * bytes_per_pixel > size) return out;
for (size_t r = 0; r < run && i < pixel_count; ++r, ++i) {
write_pixel(i, data + offset);
offset += bytes_per_pixel;
}
}
}
if (i < pixel_count) return out;
}
out.w = static_cast<uint16_t>(w);
out.h = static_cast<uint16_t>(h);
out.rgba.resize(pixel_count * 4);
bool flip_vertically = !(desc & 0x20);
for (size_t y = 0; y < h; ++y) {
size_t src_y = flip_vertically ? (h - 1 - y) : y;
std::memcpy(&out.rgba[y * w * 4], &temp[src_y * w * 4], w * 4);
}
out.format = (bytes_per_pixel == 4) ? "TGA32" : "TGA24";
return out;
}
Image decode(const uint8_t* d, size_t len) {
Image img;
if (len < 18) return img;
if (len < 128 || std::memcmp(d, "DDS ", 4) != 0) {
return decode_tga(d, len);
}
uint32_t hsize = rd_le32(d + 4);
if (hsize != 124) return img;
uint32_t h = rd_le32(d + 12);
uint32_t w = rd_le32(d + 16);
uint32_t pf_flags = rd_le32(d + 80);
const uint8_t* fourcc = d + 84;
uint32_t rgb_bitcount = rd_le32(d + 88);
Fmt fmt = F_NONE;
if (pf_flags & 0x4) { // DDPF_FOURCC
if (!std::memcmp(fourcc, "DXT1", 4)) fmt = F_DXT1;
else if (!std::memcmp(fourcc, "DXT3", 4)) fmt = F_DXT3;
else if (!std::memcmp(fourcc, "DXT5", 4)) fmt = F_DXT5;
} else if ((pf_flags & 0x40) && (rgb_bitcount == 16 || rgb_bitcount == 24 || rgb_bitcount == 32)) {
fmt = F_RGB;
}
if (fmt == F_NONE || w == 0 || h == 0 || w > 8192 || h > 8192) return img;
const uint8_t* src = d + 128;
size_t avail = len - 128;
img.w = uint16_t(w);
img.h = uint16_t(h);
img.rgba.assign(size_t(w) * h * 4, 0);
if (fmt == F_RGB) {
const uint32_t r = rd_le32(d + 92), g = rd_le32(d + 96), b = rd_le32(d + 100);
const uint32_t a = (pf_flags & 1) ? rd_le32(d + 104) : 0;
if (!valid_mask(r, rgb_bitcount) || !valid_mask(g, rgb_bitcount) || !valid_mask(b, rgb_bitcount) ||
(a && !valid_mask(a, rgb_bitcount)) || ((pf_flags & 1) && !a) ||
(r & g) || (r & b) || (g & b) || (a & (r | g | b))) return {};
const size_t bytes = rgb_bitcount / 8, row_bytes = size_t(w) * bytes;
const size_t pitch = (rd_le32(d + 8) & 8) ? rd_le32(d + 20) : row_bytes;
if (pitch < row_bytes || avail < row_bytes || pitch > avail || (h - 1) > (avail - row_bytes) / pitch) return {};
for (size_t y = 0; y < h; ++y) {
for (size_t x = 0; x < w; ++x) {
uint32_t pixel = 0;
for (size_t k = 0; k < bytes; ++k) pixel |= uint32_t(src[y * pitch + x * bytes + k]) << (8 * k);
auto* out = &img.rgba[(y * w + x) * 4];
out[0] = channel(pixel, r); out[1] = channel(pixel, g);
out[2] = channel(pixel, b); out[3] = channel(pixel, a);
}
}
img.format = rgb_bitcount == 32 && r == 0xff0000 && b == 0xff ? "BGRA8" : "RGB_MASKED";
return img;
}
const int block_bytes = (fmt == F_DXT1) ? 8 : 16;
const size_t bx = (w + 3) / 4, by = (h + 3) / 4;
if (avail < bx * by * block_bytes) { img = Image{}; return img; }
decode_dxt_level(fmt, src, uint32_t(w), uint32_t(h), img.rgba.data());
// 40250 CDXTCImage::LoadHeaderFromMemory + CGraphicImageTexture::CreateDDSTexture:
// mipmapCount = max(1, min(dwMipMapCount, MAX_MIPLEVELS)); level i starts at
// sum(dwLinearSize >> 2k) and Copy() memcpy's dwLinearSize >> 2i bytes of it. Only
// with DDSD_MIPMAPCOUNT and without DDSD_PITCH are levels > 0 filled — otherwise 40250
// creates them uninitialized; here that case is one level.
const uint32_t dds_flags = rd_le32(d + 8);
const uint32_t linear_size = rd_le32(d + 20);
uint32_t mip_count = std::min<uint32_t>(rd_le32(d + 28), 12u);
if (mip_count == 0) mip_count = 1;
if (!(dds_flags & 0x20000u) || (dds_flags & 0x8u) || linear_size == 0) mip_count = 1;
size_t offset = linear_size;
for (uint32_t i = 1; i < mip_count; ++i) {
const uint32_t lw = std::max<uint32_t>(1, w >> i), lh = std::max<uint32_t>(1, h >> i);
const size_t level_bytes = ((lw + 3) / 4) * ((lh + 3) / 4) * size_t(block_bytes);
const size_t copy_bytes = std::min<size_t>(size_t(linear_size) >> (2 * i), level_bytes);
std::vector<uint8_t> blocks(level_bytes, 0);
if (offset < avail) std::memcpy(blocks.data(), src + offset, std::min(copy_bytes, avail - offset));
offset += size_t(linear_size) >> (2 * i);
std::vector<uint8_t> level(size_t(lw) * lh * 4, 0);
decode_dxt_level(fmt, blocks.data(), lw, lh, level.data());
img.mips.push_back(std::move(level));
}
img.file_mip_levels = uint8_t(mip_count);
img.format = (fmt == F_DXT1) ? "DXT1" : (fmt == F_DXT3) ? "DXT3" : "DXT5";
return img;
}
} // namespace
Image load_dds(const uint8_t* bytes, size_t len) { return decode(bytes, len); }
Image load_dds_path(const char* path) {
FILE* f = std::fopen(path, "rb");
if (!f) return {};
std::fseek(f, 0, SEEK_END);
long n = std::ftell(f);
std::fseek(f, 0, SEEK_SET);
std::vector<uint8_t> buf(n > 0 ? size_t(n) : 0);
size_t rd = buf.empty() ? 0 : std::fread(buf.data(), 1, buf.size(), f);
std::fclose(f);
if (rd != buf.size()) return {};
return decode(buf.data(), buf.size());
}
} // namespace mtimage
+27
View File
@@ -0,0 +1,27 @@
// dxt.{h,cpp} — ported verbatim from xrender-poc/engine/dxt.{h,cpp}
// (namespace engine -> mtimage). DDS DXT1/3/5 + masked 16/24/32-bit RGB -> RGBA8, level 0.
// engine/dxt —— DDS(DXT1/3/5) → RGBA8 软解。见 docs/steps/M1-static-render.md T3
// 自己写 ~150 行绕开 reuse/EterImageLib 的 windows.h 依赖(M1 风险表允许)。
// 对拍时两侧都喂软解 RGBA,不被 GPU S3TC 的 bit 级差异污染。
#pragma once
#include <cstdint>
#include <vector>
namespace mtimage {
struct Image {
uint16_t w = 0, h = 0;
std::vector<uint8_t> rgba; // w*h*4,level 0
// DXT DDS only: level count 40250 CreateDDSTexture gives the texture (0 = not a DXT
// DDS, caller follows the D3DX_DEFAULT full-chain path) and levels 1.. decoded to RGBA8.
uint8_t file_mip_levels = 0;
std::vector<std::vector<uint8_t>> mips;
const char* format = ""; // "DXT1" / "DXT3" / "DXT5" / "BGRA8" / ""
bool ok() const { return w && h && rgba.size() == size_t(w) * h * 4; }
};
// 读整个 .dds 文件字节,解 level 0 到 RGBA8(DXT 另解文件内 mip 到 mips)。失败返回 !ok()。
Image load_dds(const uint8_t* bytes, size_t len);
Image load_dds_path(const char* path);
} // namespace mtimage
+203
View File
@@ -0,0 +1,203 @@
#include "texture_decode.h"
#ifdef MT_NATIVE_HAS_LIVE_CLIENT
#include "hd_ui_archive.h"
#include <SDL3/SDL.h>
#include "platform/PackBackend.h"
#endif
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <stdexcept>
#include <unordered_map>
#include <utility>
namespace mt_host {
mtimage::Image decode_tga(const std::uint8_t* data, std::size_t size) {
mtimage::Image out;
if (size < 18) return out;
const std::uint8_t id_len = data[0];
const std::uint8_t cmap_type = data[1];
const std::uint8_t img_type = data[2];
const std::uint32_t w = std::uint32_t(data[12]) | (std::uint32_t(data[13]) << 8);
const std::uint32_t h = std::uint32_t(data[14]) | (std::uint32_t(data[15]) << 8);
const std::uint8_t bpp = data[16];
const std::uint8_t desc = data[17];
if (cmap_type != 0 || !w || !h || w > 4096 || h > 4096) return out;
if (img_type != 2 && img_type != 3 && img_type != 10) return out;
const std::size_t bytes_per_pixel = bpp / 8;
if (bytes_per_pixel != 1 && bytes_per_pixel != 3 && bytes_per_pixel != 4) return out;
std::size_t offset = 18 + std::size_t(id_len);
if (offset > size) return out;
const std::size_t pixel_count = std::size_t(w) * std::size_t(h);
std::vector<std::uint8_t> temp(pixel_count * 4);
auto write_pixel = [&](std::size_t idx, const std::uint8_t* src) {
std::uint8_t* dst = &temp[idx * 4];
if (bytes_per_pixel == 1) {
dst[0] = dst[1] = dst[2] = src[0];
dst[3] = 255;
} else if (bytes_per_pixel == 3) {
dst[0] = src[2];
dst[1] = src[1];
dst[2] = src[0];
dst[3] = 255;
} else {
dst[0] = src[2];
dst[1] = src[1];
dst[2] = src[0];
dst[3] = src[3];
}
};
if (img_type == 2 || img_type == 3) {
if (offset + pixel_count * bytes_per_pixel > size) return out;
for (std::size_t i = 0; i < pixel_count; ++i)
write_pixel(i, data + offset + i * bytes_per_pixel);
} else if (img_type == 10) {
std::size_t i = 0;
while (i < pixel_count && offset < size) {
const std::uint8_t header = data[offset++];
const std::size_t run = (header & 0x7fu) + 1u;
if (header & 0x80u) {
if (offset + bytes_per_pixel > size) return out;
for (std::size_t r = 0; r < run && i < pixel_count; ++r, ++i)
write_pixel(i, data + offset);
offset += bytes_per_pixel;
} else {
if (offset + run * bytes_per_pixel > size) return out;
for (std::size_t r = 0; r < run && i < pixel_count; ++r, ++i) {
write_pixel(i, data + offset);
offset += bytes_per_pixel;
}
}
}
if (i != pixel_count) return out;
}
out.w = static_cast<std::uint16_t>(w);
out.h = static_cast<std::uint16_t>(h);
const bool top_origin = (desc & 0x20u) != 0;
if (top_origin) {
out.rgba = std::move(temp);
} else {
out.rgba.resize(pixel_count * 4);
const std::size_t row_bytes = std::size_t(w) * 4;
for (std::uint32_t y = 0; y < h; ++y)
std::memcpy(&out.rgba[std::size_t(y) * row_bytes], &temp[std::size_t(h - 1 - y) * row_bytes], row_bytes);
}
return out;
}
mtimage::Image decode_texture_bytes(const std::uint8_t* data, std::size_t size) {
if (!data || size < 12) return {};
if (data[0] == 'M' && data[1] == 'T' && data[2] == 'R' && data[3] == 'A') {
std::uint32_t w = 0, h = 0;
std::memcpy(&w, data + 4, 4);
std::memcpy(&h, data + 8, 4);
const std::size_t bytes = std::size_t(w) * std::size_t(h) * 4;
if (w > 0 && h > 0 && w <= 4096 && h <= 4096 && size == 12 + bytes) {
mtimage::Image out;
out.w = static_cast<std::uint16_t>(w);
out.h = static_cast<std::uint16_t>(h);
out.rgba.assign(data + 12, data + 12 + bytes);
return out;
}
return {};
}
if (data[0] == 'D' && data[1] == 'D' && data[2] == 'S' && data[3] == ' ')
return mtimage::load_dds(data, size);
auto tga = decode_tga(data, size);
if (tga.ok()) return tga;
if (size > static_cast<std::size_t>(INT_MAX)) return {};
int w = 0, h = 0, channels = 0;
stbi_uc* pixels = stbi_load_from_memory(data, static_cast<int>(size), &w, &h, &channels, 4);
if (pixels && w > 0 && h > 0 && w <= 4096 && h <= 4096) {
mtimage::Image out;
out.w = static_cast<std::uint16_t>(w);
out.h = static_cast<std::uint16_t>(h);
out.rgba.assign(pixels, pixels + std::size_t(w) * std::size_t(h) * 4);
stbi_image_free(pixels);
return out;
}
stbi_image_free(pixels);
return {};
}
#ifdef MT_NATIVE_HAS_LIVE_CLIENT
namespace {
// The spellings a 40250 texture name may be registered under in the packs (CEterPackManager::Get
// accepts "d:/ymir work/..." and "ymir work/..." alike, in any case).
std::vector<std::string> pack_name_candidates(const std::string& vpath) {
std::string norm = vpath;
for (char& ch : norm)
if (ch == '\\') ch = '/';
std::string stripped = norm;
if (stripped.size() >= 2 && stripped[1] == ':')
stripped = stripped.substr(2);
while (!stripped.empty() && stripped.front() == '/')
stripped.erase(stripped.begin());
auto lower = [](std::string s) {
for (char& ch : s)
if (ch >= 'A' && ch <= 'Z')
ch = static_cast<char>(ch - 'A' + 'a');
return s;
};
return {norm, stripped, "d:/" + stripped, lower(norm), lower(stripped), lower("d:/" + stripped)};
}
// PORT: application resources take priority over the launch directory. Finder
// changes cwd and the original Client packs can live outside the app bundle.
std::unique_ptr<HdUiArchive> open_hd_ui_pak() {
if (const char* env = std::getenv("MT_HD_UI"); env && std::strcmp(env, "0") == 0) return {};
std::vector<std::string> paths;
if (const char* path = std::getenv("MT_HD_UI_PAK"); path && *path) paths.emplace_back(path);
else {
if (const char* base = SDL_GetBasePath()) paths.emplace_back(std::string(base) + "hd_ui.pak");
paths.emplace_back("hd_ui.pak");
}
for (const auto& path : paths) {
auto pak = std::make_unique<HdUiArchive>();
if (pak->open(path)) {
std::fprintf(stderr, "[hd_ui] loaded %zu textures from %s\n", pak->size(), path.c_str());
return pak;
}
}
std::fprintf(stderr, "[hd_ui] no valid archive found; using original UI textures\n");
return {};
}
} // namespace
bool read_live_pack_texture(const std::string& vpath, std::vector<std::uint8_t>& bytes) {
if (vpath.empty() || !mtpack40250::ready())
return false;
for (const std::string& candidate : pack_name_candidates(vpath)) {
if (mtpack40250::read(candidate, bytes) && !bytes.empty())
return true;
}
return false;
}
bool read_hd_ui_texture(const std::string& vpath, std::vector<std::uint8_t>& bytes) {
// The minimap atlas contains SCREEN-blended waypoint frames. Their black RGB
// background is significant even at alpha=0 (INVDESTCOLOR + ONE ignores alpha).
// HD alpha-edge colour bleeding destroys it; retain the original packed atlas.
for (const auto& candidate : pack_name_candidates(vpath))
if (candidate == "d:/ymir work/ui/minimap.dds") return false;
static auto pak = open_hd_ui_pak();
if (!pak || vpath.empty()) return false;
for (const auto& candidate : pack_name_candidates(vpath))
if (pak->read(candidate, bytes)) return true;
return false;
}
#endif
} // namespace mt_host
+21
View File
@@ -0,0 +1,21 @@
#pragma once
#include "dxt.h"
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
namespace mt_host {
mtimage::Image decode_tga(const std::uint8_t* data, std::size_t size);
mtimage::Image decode_texture_bytes(const std::uint8_t* data, std::size_t size);
#ifdef MT_NATIVE_HAS_LIVE_CLIENT
bool read_live_pack_texture(const std::string& vpath, std::vector<std::uint8_t>& bytes);
// 2x UI replacement: MT_HD_UI_PAK, then application resources, then the client directory.
// MT_HD_UI=0 disables it. Invalid archives or uncovered images use the original pack texture.
bool read_hd_ui_texture(const std::string& vpath, std::vector<std::uint8_t>& bytes);
#endif
} // namespace mt_host
+578
View File
@@ -0,0 +1,578 @@
#include "SoundManager.h"
#define DR_MP3_IMPLEMENTATION
#include "third_party/extern_include/dr_mp3.h"
#include <iostream>
#include <filesystem>
#include <fstream>
#include <sstream>
#include <cmath>
#include <algorithm>
namespace ava2 {
namespace {
inline std::string ToLower(std::string s) {
for (char& c : s) {
if (c >= 'A' && c <= 'Z') c = static_cast<char>(c + 32);
else if (c == '\\') c = '/';
}
return s;
}
inline void CrossProduct(float ax, float ay, float az, float bx, float by, float bz, float& rx, float& ry, float& rz) {
rx = ay * bz - az * by;
ry = az * bx - ax * bz;
rz = ax * by - ay * bx;
}
} // namespace
SoundManager& SoundManager::Instance() {
static SoundManager s_instance;
return s_instance;
}
SoundManager::SoundManager() {
m_instances.resize(MAX_SOUND_INSTANCES);
for (size_t i = 0; i < MAX_SOUND_INSTANCES; ++i) {
m_instances[i].id = static_cast<int>(i + 1);
}
}
SoundManager::~SoundManager() {
Destroy();
}
bool SoundManager::Initialize() {
if (m_initialized) return true;
if (!SDL_InitSubSystem(SDL_INIT_AUDIO)) {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "SDL_InitSubSystem(SDL_INIT_AUDIO) warning: %s", SDL_GetError());
}
m_deviceSpec.format = SDL_AUDIO_F32;
m_deviceSpec.channels = 2;
m_deviceSpec.freq = 44100;
m_deviceId = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &m_deviceSpec);
if (m_deviceId != 0) {
SDL_ResumeAudioDevice(m_deviceId);
SDL_Log("SoundManager: Audio device opened successfully (ID %u, 44.1kHz Stereo F32)", m_deviceId);
} else {
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "SoundManager: Running without physical audio device: %s", SDL_GetError());
}
// Initialize SFX streams
for (size_t i = 0; i < MAX_SOUND_INSTANCES; ++i) {
m_instances[i].inUse = false;
m_instances[i].stream = SDL_CreateAudioStream(&m_deviceSpec, &m_deviceSpec);
if (m_instances[i].stream && m_deviceId != 0) {
SDL_BindAudioStream(m_deviceId, m_instances[i].stream);
}
}
// Initialize Music streaming channels
for (size_t c = 0; c < 2; ++c) {
m_musicChannels[c].state = MusicState::Off;
m_musicChannels[c].stream = SDL_CreateAudioStream(&m_deviceSpec, &m_deviceSpec);
if (m_musicChannels[c].stream && m_deviceId != 0) {
SDL_BindAudioStream(m_deviceId, m_musicChannels[c].stream);
}
}
m_initialized = true;
return true;
}
void SoundManager::Destroy() {
if (!m_initialized) return;
m_initialized = false;
bool sdl_alive = (SDL_WasInit(SDL_INIT_AUDIO) != 0);
for (size_t i = 0; i < MAX_SOUND_INSTANCES; ++i) {
if (m_instances[i].stream) {
if (m_deviceId != 0 && sdl_alive) SDL_UnbindAudioStream(m_instances[i].stream);
if (sdl_alive) SDL_DestroyAudioStream(m_instances[i].stream);
m_instances[i].stream = nullptr;
}
m_instances[i].inUse = false;
}
for (size_t c = 0; c < 2; ++c) {
if (m_musicChannels[c].stream) {
if (m_deviceId != 0 && sdl_alive) SDL_UnbindAudioStream(m_musicChannels[c].stream);
if (sdl_alive) SDL_DestroyAudioStream(m_musicChannels[c].stream);
m_musicChannels[c].stream = nullptr;
}
m_musicChannels[c].state = MusicState::Off;
}
if (m_deviceId != 0 && sdl_alive) {
SDL_CloseAudioDevice(m_deviceId);
m_deviceId = 0;
}
m_soundCache.clear();
}
std::string SoundManager::ResolveAudioPath(const std::string& filename) const {
if (filename.empty()) return "";
std::string clean = filename;
for (char& c : clean) {
if (c == '\\') c = '/';
}
// Strip drive letters like "d:/" or "D:/"
if (clean.size() >= 3 && clean[1] == ':' && clean[2] == '/') {
clean = clean.substr(3);
}
std::vector<std::string> candidates = {
clean,
ToLower(clean),
"sound/" + clean,
"bgm/" + clean,
"BGM/" + clean,
"/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/Sound/" + clean,
"/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/BGM/" + clean,
"/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/ETC/" + clean,
"/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/Sound/sound/" + clean,
"/Users/shen/Work/Code/Metin2/AVA2/TEST/1. Client DEV/pack_maker/BGM/bgm/" + clean,
"build/dev/" + clean
};
for (const auto& path : candidates) {
if (std::filesystem::exists(path)) {
return path;
}
}
return clean;
}
const SoundManager::CachedAudio* SoundManager::GetOrLoadAudio(const std::string& filename) {
std::string key = ToLower(filename);
auto it = m_soundCache.find(key);
if (it != m_soundCache.end()) {
return &it->second;
}
std::string resolved = ResolveAudioPath(filename);
if (!std::filesystem::exists(resolved)) {
return nullptr;
}
CachedAudio audio;
bool ok = false;
std::string ext = "";
auto dotPos = resolved.rfind('.');
if (dotPos != std::string::npos) {
ext = ToLower(resolved.substr(dotPos));
}
if (ext == ".wav") {
ok = LoadWavFile(resolved, audio);
} else if (ext == ".mp3") {
ok = LoadMp3File(resolved, audio);
}
if (ok) {
auto [inserted_it, _] = m_soundCache.emplace(key, std::move(audio));
return &inserted_it->second;
}
return nullptr;
}
bool SoundManager::LoadWavFile(const std::string& resolvedPath, CachedAudio& outAudio) {
SDL_AudioSpec file_spec{};
Uint8* wav_buffer = nullptr;
Uint32 wav_length = 0;
if (!SDL_LoadWAV(resolvedPath.c_str(), &file_spec, &wav_buffer, &wav_length)) {
return false;
}
outAudio.spec = file_spec;
outAudio.data.assign(wav_buffer, wav_buffer + wav_length);
SDL_free(wav_buffer);
return true;
}
bool SoundManager::LoadMp3File(const std::string& resolvedPath, CachedAudio& outAudio) {
drmp3_config config{};
drmp3_uint64 total_pcm_frames = 0;
float* pcm = drmp3_open_file_and_read_pcm_frames_f32(resolvedPath.c_str(), &config, &total_pcm_frames, nullptr);
if (!pcm) {
return false;
}
outAudio.spec.format = SDL_AUDIO_F32;
outAudio.spec.channels = static_cast<Uint8>(config.channels);
outAudio.spec.freq = static_cast<int>(config.sampleRate);
size_t byte_count = total_pcm_frames * config.channels * sizeof(float);
outAudio.data.resize(byte_count);
std::memcpy(outAudio.data.data(), pcm, byte_count);
drmp3_free(pcm, nullptr);
return true;
}
float SoundManager::ConvertRatioVolumeToApplyVolume(float ratio) const {
if (ratio < 0.1f) return std::max(0.0f, ratio);
return std::pow(10.0f, -1.0f + ratio);
}
float SoundManager::ConvertGradeVolumeToApplyVolume(int grade) const {
return ConvertRatioVolumeToApplyVolume(static_cast<float>(grade) / 5.0f);
}
void SoundManager::SetSoundVolume(float volume) {
m_soundVolume = std::clamp(volume, 0.0f, 1.0f);
m_backupSoundVolume = m_soundVolume;
}
void SoundManager::SetSoundVolumeRatio(float ratio) {
SetSoundVolume(ConvertRatioVolumeToApplyVolume(ratio));
}
void SoundManager::SetSoundVolumeGrade(int grade) {
SetSoundVolume(ConvertGradeVolumeToApplyVolume(grade));
}
void SoundManager::SetMusicVolume(float volume) {
m_musicVolume = std::clamp(volume, 0.0f, 1.0f);
m_backupMusicVolume = m_musicVolume;
for (auto& ch : m_musicChannels) {
if (ch.state == MusicState::Play) {
ch.volume = m_musicVolume;
if (ch.stream) SDL_SetAudioStreamGain(ch.stream, ch.volume);
}
}
}
void SoundManager::SetMusicVolumeRatio(float ratio) {
SetMusicVolume(ConvertRatioVolumeToApplyVolume(ratio));
}
void SoundManager::SetMusicVolumeGrade(int grade) {
SetMusicVolume(ConvertGradeVolumeToApplyVolume(grade));
}
void SoundManager::SaveVolume() {
m_backupSoundVolume = m_soundVolume;
m_backupMusicVolume = m_musicVolume;
}
void SoundManager::RestoreVolume() {
SetSoundVolume(m_backupSoundVolume);
SetMusicVolume(m_backupMusicVolume);
}
void SoundManager::SetPosition(float fx, float fy, float fz) {
m_listenerX = fx;
m_listenerY = fy;
m_listenerZ = fz;
}
void SoundManager::SetDirection(float fxDir, float fyDir, float fzDir, float fxUp, float fyUp, float fzUp) {
float len = std::sqrt(fxDir*fxDir + fyDir*fyDir + fzDir*fzDir);
if (len > 1e-4f) {
m_listenerDirX = fxDir / len;
m_listenerDirY = fyDir / len;
m_listenerDirZ = fzDir / len;
}
float ulen = std::sqrt(fxUp*fxUp + fyUp*fyUp + fzUp*fzUp);
if (ulen > 1e-4f) {
m_listenerUpX = fxUp / ulen;
m_listenerUpY = fyUp / ulen;
m_listenerUpZ = fzUp / ulen;
}
}
void SoundManager::PlaySound2D(const std::string& filename) {
if (m_soundVolume <= 0.0f) return;
const auto* audio = GetOrLoadAudio(filename);
if (!audio || audio->data.empty()) return;
SoundInstance* target = nullptr;
for (auto& inst : m_instances) {
if (!inst.inUse || (inst.stream && SDL_GetAudioStreamAvailable(inst.stream) == 0)) {
target = &inst;
break;
}
}
if (!target) target = &m_instances[0];
target->filename = filename;
target->is3D = false;
target->volume = m_soundVolume;
target->inUse = true;
if (target->stream) {
SDL_ClearAudioStream(target->stream);
SDL_SetAudioStreamFormat(target->stream, &audio->spec, &m_deviceSpec);
SDL_SetAudioStreamGain(target->stream, m_soundVolume);
SDL_PutAudioStreamData(target->stream, audio->data.data(), static_cast<int>(audio->data.size()));
SDL_FlushAudioStream(target->stream);
}
}
void SoundManager::PlaySound3D(float fx, float fy, float fz, const std::string& filename, int playCount) {
if (m_soundVolume <= 0.0f) return;
const auto* audio = GetOrLoadAudio(filename);
if (!audio || audio->data.empty()) return;
float dx = fx - m_listenerX;
float dy = fy - m_listenerY;
float dz = fz - m_listenerZ;
float dist = std::sqrt(dx*dx + dy*dy + dz*dz);
// Distance attenuation matching Metin2 formula: 1.0 / (1.0 + (dist / scale))
float attn = 1.0f / (1.0f + std::max(0.0f, dist - 80.0f) / m_soundScale);
float gain = std::clamp(attn * m_soundVolume, 0.0f, 1.0f);
if (gain < 0.005f) return; // Inaudible
SoundInstance* target = nullptr;
for (auto& inst : m_instances) {
if (!inst.inUse || (inst.stream && SDL_GetAudioStreamAvailable(inst.stream) == 0)) {
target = &inst;
break;
}
}
if (!target) target = &m_instances[0];
target->filename = filename;
target->is3D = true;
target->worldX = fx; target->worldY = fy; target->worldZ = fz;
target->scale = m_soundScale;
target->volume = gain;
target->playCount = playCount;
target->inUse = true;
if (target->stream) {
SDL_ClearAudioStream(target->stream);
SDL_SetAudioStreamFormat(target->stream, &audio->spec, &m_deviceSpec);
SDL_SetAudioStreamGain(target->stream, gain);
SDL_PutAudioStreamData(target->stream, audio->data.data(), static_cast<int>(audio->data.size()));
SDL_FlushAudioStream(target->stream);
}
}
int SoundManager::PlayAmbienceSound3D(float fx, float fy, float fz, const std::string& filename, int playCount) {
float oldScale = m_soundScale;
m_soundScale = m_ambienceScale;
PlaySound3D(fx, fy, fz, filename, playCount);
m_soundScale = oldScale;
return m_nextInstanceId++;
}
void SoundManager::StopSound3D(int index) {
for (auto& inst : m_instances) {
if (inst.id == index && inst.inUse) {
if (inst.stream) SDL_ClearAudioStream(inst.stream);
inst.inUse = false;
}
}
}
void SoundManager::StopAllSound3D() {
for (auto& inst : m_instances) {
if (inst.is3D && inst.inUse) {
if (inst.stream) SDL_ClearAudioStream(inst.stream);
inst.inUse = false;
}
}
}
void SoundManager::PlayMusic(const std::string& filename) {
FadeInMusic(filename, 10.0f); // Instant / direct start
}
void SoundManager::FadeInMusic(const std::string& filename, float speed) {
if (filename.empty()) return;
// If already playing this music on active channel, ensure it fades in to full volume
for (size_t c = 0; c < 2; ++c) {
if (m_musicChannels[c].filename == filename && m_musicChannels[c].state != MusicState::Off) {
m_musicChannels[c].state = MusicState::FadeIn;
m_musicChannels[c].volumeSpeed = speed;
m_currentMusicFile = filename;
return;
}
}
// Fade out other music channels
FadeOutAllMusic();
// Select available music channel
MusicChannel* ch = &m_musicChannels[0];
if (ch->state != MusicState::Off) ch = &m_musicChannels[1];
const auto* audio = GetOrLoadAudio(filename);
if (!audio || audio->data.empty()) return;
ch->filename = filename;
ch->cachedPcm = *audio;
ch->playOffsetBytes = 0;
ch->volume = (speed > 5.0f) ? m_musicVolume : 0.0f;
ch->targetVolume = m_musicVolume;
ch->volumeSpeed = speed;
ch->state = (speed > 5.0f) ? MusicState::Play : MusicState::FadeIn;
m_currentMusicFile = filename;
if (ch->stream) {
SDL_ClearAudioStream(ch->stream);
SDL_SetAudioStreamFormat(ch->stream, &ch->cachedPcm.spec, &m_deviceSpec);
SDL_SetAudioStreamGain(ch->stream, ch->volume);
// Pre-buffer first chunk
size_t chunk = std::min(ch->cachedPcm.data.size(), static_cast<size_t>(65536));
SDL_PutAudioStreamData(ch->stream, ch->cachedPcm.data.data(), static_cast<int>(chunk));
ch->playOffsetBytes = chunk;
}
}
void SoundManager::FadeOutMusic(const std::string& filename, float speed) {
for (size_t c = 0; c < 2; ++c) {
if (m_musicChannels[c].filename == filename && m_musicChannels[c].state != MusicState::Off) {
m_musicChannels[c].state = MusicState::FadeOut;
m_musicChannels[c].volumeSpeed = speed;
}
}
}
void SoundManager::FadeLimitOutMusic(const std::string& filename, float limitVolume, float speed) {
for (size_t c = 0; c < 2; ++c) {
if (m_musicChannels[c].filename == filename && m_musicChannels[c].state != MusicState::Off) {
m_musicChannels[c].state = MusicState::FadeLimitOut;
m_musicChannels[c].limitVolume = ConvertRatioVolumeToApplyVolume(limitVolume);
m_musicChannels[c].volumeSpeed = speed;
}
}
}
void SoundManager::FadeOutAllMusic() {
for (size_t c = 0; c < 2; ++c) {
if (m_musicChannels[c].state != MusicState::Off) {
m_musicChannels[c].state = MusicState::FadeOut;
m_musicChannels[c].volumeSpeed = 0.02f;
}
}
}
void SoundManager::Update(float dt) {
if (!m_initialized) return;
// 1. Update SFX instances
for (auto& inst : m_instances) {
if (inst.inUse && inst.stream) {
if (SDL_GetAudioStreamAvailable(inst.stream) == 0) {
inst.inUse = false;
}
}
}
// 2. Update BGM streaming and fading
for (size_t c = 0; c < 2; ++c) {
auto& ch = m_musicChannels[c];
if (ch.state == MusicState::Off || !ch.stream) continue;
switch (ch.state) {
case MusicState::FadeIn:
ch.volume = std::min(m_musicVolume, ch.volume + ch.volumeSpeed * dt * 5.0f);
if (ch.volume >= m_musicVolume) {
ch.volume = m_musicVolume;
ch.state = MusicState::Play;
}
SDL_SetAudioStreamGain(ch.stream, ch.volume);
break;
case MusicState::FadeOut:
ch.volume = std::max(0.0f, ch.volume - ch.volumeSpeed * dt * 5.0f);
if (ch.volume <= 0.0f) {
ch.volume = 0.0f;
ch.state = MusicState::Off;
SDL_ClearAudioStream(ch.stream);
}
SDL_SetAudioStreamGain(ch.stream, ch.volume);
break;
case MusicState::FadeLimitOut:
ch.volume = std::max(ch.limitVolume, ch.volume - ch.volumeSpeed * dt * 5.0f);
if (ch.volume <= ch.limitVolume) {
ch.volume = ch.limitVolume;
ch.state = MusicState::Play;
}
SDL_SetAudioStreamGain(ch.stream, ch.volume);
break;
case MusicState::Play:
SDL_SetAudioStreamGain(ch.stream, m_musicVolume);
break;
default:
break;
}
// Loop buffering: refill stream when available buffer is low (< 32KB)
if (ch.state != MusicState::Off && !ch.cachedPcm.data.empty()) {
int avail = SDL_GetAudioStreamAvailable(ch.stream);
if (avail < 32768) {
size_t remaining = ch.cachedPcm.data.size() - ch.playOffsetBytes;
size_t toWrite = std::min(remaining, static_cast<size_t>(32768));
if (toWrite > 0) {
SDL_PutAudioStreamData(ch.stream, ch.cachedPcm.data.data() + ch.playOffsetBytes, static_cast<int>(toWrite));
ch.playOffsetBytes += toWrite;
}
if (ch.playOffsetBytes >= ch.cachedPcm.data.size()) {
// Loop back to beginning
ch.playOffsetBytes = 0;
}
}
}
}
}
size_t SoundManager::GetActiveSoundCount() const {
size_t count = 0;
for (const auto& inst : m_instances) {
if (inst.inUse) ++count;
}
return count;
}
bool SoundManager::LoadCharacterSoundScript(const std::string& mssPath, std::vector<CharacterSoundEvent>& outEvents) const {
std::string resolved = ResolveAudioPath(mssPath);
std::ifstream file(resolved);
if (!file.is_open()) return false;
outEvents.clear();
std::string line;
while (std::getline(file, line)) {
if (line.empty() || line[0] == '#') continue;
std::istringstream iss(line);
std::string token;
iss >> token;
if (token.rfind("SoundData", 0) == 0 && token != "SoundDataCount") {
float timeVal = 0.0f;
std::string soundFile;
if (iss >> timeVal) {
std::getline(iss, soundFile);
auto firstQuote = soundFile.find('"');
auto lastQuote = soundFile.rfind('"');
if (firstQuote != std::string::npos && lastQuote != std::string::npos && lastQuote > firstQuote) {
soundFile = soundFile.substr(firstQuote + 1, lastQuote - firstQuote - 1);
} else {
auto nonSpace = soundFile.find_first_not_of(" \t");
if (nonSpace != std::string::npos) soundFile = soundFile.substr(nonSpace);
}
outEvents.push_back({timeVal, soundFile});
}
}
}
return !outEvents.empty();
}
} // namespace ava2
+159
View File
@@ -0,0 +1,159 @@
#pragma once
#include <SDL3/SDL.h>
#include <string>
#include <vector>
#include <unordered_map>
#include <memory>
#include <cstdint>
namespace ava2 {
struct CharacterSoundEvent {
float time = 0.0f;
std::string soundFile;
};
// 1:1 Implementation of Metin2 / MilesLib CSoundManager using SDL3 modern Audio Streams
class SoundManager {
public:
static SoundManager& Instance();
SoundManager();
~SoundManager();
bool Initialize();
void Destroy();
bool IsInitialized() const { return m_initialized; }
bool HasAudioDevice() const { return m_deviceId != 0; }
// Frame update for music fades, 3D stream lifetimes, and looping
void Update(float dt = 0.016f);
// 3D Listener Orientation (Camera / Player)
void SetPosition(float fx, float fy, float fz);
void SetDirection(float fxDir, float fyDir, float fzDir, float fxUp = 0.0f, float fyUp = 1.0f, float fzUp = 0.0f);
void GetPosition(float& fx, float& fy, float& fz) const { fx = m_listenerX; fy = m_listenerY; fz = m_listenerZ; }
// Volume & Scale configuration
void SetSoundVolume(float volume);
void SetSoundVolumeRatio(float ratio);
void SetSoundVolumeGrade(int grade);
float GetSoundVolume() const { return m_soundVolume; }
void SetMusicVolume(float volume);
void SetMusicVolumeRatio(float ratio);
void SetMusicVolumeGrade(int grade);
float GetMusicVolume() const { return m_musicVolume; }
void SetSoundScale(float scale) { m_soundScale = (scale > 0.0f) ? scale : 200.0f; }
float GetSoundScale() const { return m_soundScale; }
void SetAmbienceSoundScale(float scale) { m_ambienceScale = (scale > 0.0f) ? scale : 1000.0f; }
float GetAmbienceSoundScale() const { return m_ambienceScale; }
void SaveVolume();
void RestoreVolume();
// 2D & 3D Sound Effects
void PlaySound2D(const std::string& filename);
void PlaySound3D(float fx, float fy, float fz, const std::string& filename, int playCount = 1);
int PlayAmbienceSound3D(float fx, float fy, float fz, const std::string& filename, int playCount = 1);
void StopSound3D(int index);
void StopAllSound3D();
// Background Music (BGM) Streaming & Fading
void PlayMusic(const std::string& filename);
void FadeInMusic(const std::string& filename, float speed = 0.016f);
void FadeOutMusic(const std::string& filename, float speed = 0.016f);
void FadeLimitOutMusic(const std::string& filename, float limitVolume, float speed = 0.016f);
void FadeOutAllMusic();
std::string GetCurrentMusic() const { return m_currentMusicFile; }
// Character Sound Script (.mss) Parser
bool LoadCharacterSoundScript(const std::string& mssPath, std::vector<CharacterSoundEvent>& outEvents) const;
// Cache & diagnostics
std::string ResolveAudioPath(const std::string& filename) const;
size_t GetCachedSoundCount() const { return m_soundCache.size(); }
size_t GetActiveSoundCount() const;
private:
struct CachedAudio {
SDL_AudioSpec spec;
std::vector<uint8_t> data;
};
enum class MusicState {
Off,
Play,
FadeIn,
FadeOut,
FadeLimitOut
};
struct MusicChannel {
std::string filename;
SDL_AudioStream* stream = nullptr;
MusicState state = MusicState::Off;
float volume = 0.0f;
float targetVolume = 1.0f;
float limitVolume = 0.0f;
float volumeSpeed = 0.016f;
CachedAudio cachedPcm;
size_t playOffsetBytes = 0;
};
struct SoundInstance {
int id = 0;
SDL_AudioStream* stream = nullptr;
std::string filename;
bool is3D = false;
float worldX = 0.0f, worldY = 0.0f, worldZ = 0.0f;
float scale = 200.0f;
float volume = 1.0f;
int playCount = 1;
bool inUse = false;
};
const CachedAudio* GetOrLoadAudio(const std::string& filename);
bool LoadWavFile(const std::string& resolvedPath, CachedAudio& outAudio);
bool LoadMp3File(const std::string& resolvedPath, CachedAudio& outAudio);
float ConvertRatioVolumeToApplyVolume(float ratio) const;
float ConvertGradeVolumeToApplyVolume(int grade) const;
bool m_initialized = false;
SDL_AudioDeviceID m_deviceId = 0;
SDL_AudioSpec m_deviceSpec{};
// Listener
float m_listenerX = 0.0f, m_listenerY = 0.0f, m_listenerZ = 0.0f;
float m_listenerDirX = 0.0f, m_listenerDirY = 0.0f, m_listenerDirZ = 1.0f;
float m_listenerUpX = 0.0f, m_listenerUpY = 1.0f, m_listenerUpZ = 0.0f;
// Volume
float m_soundVolume = 1.0f;
float m_musicVolume = 1.0f;
float m_backupSoundVolume = 1.0f;
float m_backupMusicVolume = 1.0f;
float m_soundScale = 200.0f;
float m_ambienceScale = 1000.0f;
// Cache
std::unordered_map<std::string, CachedAudio> m_soundCache;
// Sound instance pool (32 channels for 2D/3D SFX)
static constexpr size_t MAX_SOUND_INSTANCES = 32;
std::vector<SoundInstance> m_instances;
int m_nextInstanceId = 1;
// Music streaming (up to 2 channels for seamless cross-fading)
MusicChannel m_musicChannels[2];
std::string m_currentMusicFile;
};
// Typedef alias for 1:1 legacy Metin2 code compatibility
using CSoundManager = SoundManager;
} // namespace ava2
File diff suppressed because it is too large Load Diff
+694
View File
@@ -0,0 +1,694 @@
#pragma once
#include "shared/common/Win32Types.h"
#include "shared/common/EterBaseUtils.h"
#include "shared/common/PythonUtils.h"
#include <string>
#include <vector>
#include <list>
#include <map>
#include <algorithm>
#include "src/eter_image/GrpImageInstance.h"
#include "src/eter_image/GrpExpandedImageInstance.h"
#include "src/eter_image/GrpMarkInstance.h"
#include "src/eter_resource/ResourceManager.h"
namespace UI
{
class CGraphicTextInstance {
public:
enum {
HORIZONTAL_ALIGN_LEFT = 0x01,
HORIZONTAL_ALIGN_CENTER = 0x02,
HORIZONTAL_ALIGN_RIGHT = 0x03,
VERTICAL_ALIGN_TOP = 0x10,
VERTICAL_ALIGN_CENTER = 0x20,
VERTICAL_ALIGN_BOTTOM = 0x30
};
CGraphicTextInstance() = default;
~CGraphicTextInstance() = default;
void SetText(const char* text) { if (text) m_text = text; }
const char* GetText() const { return m_text.c_str(); }
void SetValue(const char* text) { SetText(text); }
void SetHorizonalAlign(int align) { m_hAlign = align; }
void SetVerticalAlign(int align) { m_vAlign = align; }
void SetMax(int max) { m_max = max; }
void SetFontName(const char* name) { if (name) m_font = name; }
void SetFontColor(DWORD color) { m_color = color; }
void SetLimitWidth(float w) { m_limitWidth = w; }
void SetSecret(BOOL b) { m_secret = b; }
void SetOutline(BOOL b) { m_outline = b; }
void SetFeather(BOOL b) { m_feather = b; }
void SetMultiLine(BOOL b) { m_multiLine = b; }
void SetLineHeight(int h) { m_lineHeight = h; }
int GetLineHeight() const { return m_lineHeight; }
int GetTextLineCount() const { return 1; }
void DisableEnterToken() {}
void ShowCursor() { m_showCursor = true; }
void HideCursor() { m_showCursor = false; }
int GetCursorPosition() const { return (int)m_text.length(); }
void GetTextSize(int* w, int* h) {
if (w) *w = (int)m_text.length() * 6;
if (h) *h = 12;
}
void SetPosition(float fx, float fy) { m_v2Position.x = fx; m_v2Position.y = fy; }
D3DXVECTOR2 GetPosition() const { return m_v2Position; }
void Update() {}
void Render();
static const char* Hyperlink_GetText(const std::string&, int, int*) { return ""; }
private:
D3DXVECTOR2 m_v2Position = D3DXVECTOR2(0.0f, 0.0f);
std::string m_text;
std::string m_font;
DWORD m_color = 0xffffffff;
int m_hAlign = HORIZONTAL_ALIGN_LEFT;
int m_vAlign = VERTICAL_ALIGN_TOP;
int m_max = 0;
int m_lineHeight = 12;
float m_limitWidth = 0.0f;
BOOL m_secret = FALSE;
BOOL m_outline = FALSE;
BOOL m_feather = FALSE;
BOOL m_multiLine = FALSE;
bool m_showCursor = false;
};
class CWindow
{
public:
typedef std::list<CWindow *> TWindowContainer;
static DWORD Type();
BOOL IsType(DWORD dwType);
enum EHorizontalAlign
{
HORIZONTAL_ALIGN_LEFT = 0,
HORIZONTAL_ALIGN_CENTER = 1,
HORIZONTAL_ALIGN_RIGHT = 2,
};
enum EVerticalAlign
{
VERTICAL_ALIGN_TOP = 0,
VERTICAL_ALIGN_CENTER = 1,
VERTICAL_ALIGN_BOTTOM = 2,
};
enum EFlags
{
FLAG_MOVABLE = (1 << 0),
FLAG_LIMIT = (1 << 1),
FLAG_SNAP = (1 << 2),
FLAG_DRAGABLE = (1 << 3),
FLAG_ATTACH = (1 << 4),
FLAG_RESTRICT_X = (1 << 5),
FLAG_RESTRICT_Y = (1 << 6),
FLAG_NOT_CAPTURE = (1 << 7),
FLAG_FLOAT = (1 << 8),
FLAG_NOT_PICK = (1 << 9),
FLAG_IGNORE_SIZE = (1 << 10),
FLAG_RTL = (1 << 11),
};
public:
CWindow(PyObject * ppyObject);
virtual ~CWindow();
void AddChild(CWindow * pWin);
void Clear();
void DestroyHandle();
void Update();
void Render();
void SetName(const char * c_szName);
const char * GetName() { return m_strName.c_str(); }
void SetSize(long width, long height);
long GetWidth() { return m_lWidth; }
long GetHeight() { return m_lHeight; }
void SetHorizontalAlign(DWORD dwAlign);
void SetVerticalAlign(DWORD dwAlign);
void SetPosition(long x, long y);
void GetPosition(long * plx, long * ply);
long GetPositionX( void ) const { return m_x; }
long GetPositionY( void ) const { return m_y; }
RECT & GetRect() { return m_rect; }
void GetLocalPosition(long & rlx, long & rly);
void GetMouseLocalPosition(long & rlx, long & rly);
long UpdateRect();
RECT & GetLimitBias() { return m_limitBiasRect; }
void SetLimitBias(long l, long r, long t, long b) { m_limitBiasRect.left = l; m_limitBiasRect.right = r; m_limitBiasRect.top = t; m_limitBiasRect.bottom = b; }
void Show();
void Hide();
bool IsShow() { return m_bShow; }
bool IsRendering();
bool HasParent() { return m_pParent ? true : false; }
bool HasChild() { return !m_pChildList.empty(); }
int GetChildCount() { return (int)m_pChildList.size(); }
CWindow * GetRoot();
CWindow * GetParent();
bool IsChild(CWindow * pWin);
void DeleteChild(CWindow * pWin);
void SetTop(CWindow * pWin);
bool IsIn(long x, long y);
bool IsIn();
CWindow * PickWindow(long x, long y);
CWindow * PickTopWindow(long x, long y);
void __RemoveReserveChildren();
void AddFlag(DWORD flag) { SET_BIT(m_dwFlag, flag); }
void RemoveFlag(DWORD flag) { REMOVE_BIT(m_dwFlag, flag); }
bool IsFlag(DWORD flag) { return (m_dwFlag & flag) ? true : false; }
virtual void OnRender();
virtual void OnUpdate();
virtual void OnChangePosition(){}
virtual void OnSetFocus();
virtual void OnKillFocus();
virtual void OnMouseDrag(long lx, long ly);
virtual void OnMouseOverIn();
virtual void OnMouseOverOut();
virtual void OnMouseOver();
virtual void OnDrop();
virtual void OnTop();
virtual void OnIMEUpdate();
virtual void OnMoveWindow(long x, long y);
BOOL RunIMETabEvent();
BOOL RunIMEReturnEvent();
BOOL RunIMEKeyDownEvent(int ikey);
CWindow * RunKeyDownEvent(int ikey);
BOOL RunKeyUpEvent(int ikey);
BOOL RunPressEscapeKeyEvent();
BOOL RunPressExitKeyEvent();
virtual BOOL OnIMETabEvent();
virtual BOOL OnIMEReturnEvent();
virtual BOOL OnIMEKeyDownEvent(int ikey);
virtual BOOL OnIMEChangeCodePage();
virtual BOOL OnIMEOpenCandidateListEvent();
virtual BOOL OnIMECloseCandidateListEvent();
virtual BOOL OnIMEOpenReadingWndEvent();
virtual BOOL OnIMECloseReadingWndEvent();
virtual BOOL OnMouseLeftButtonDown();
virtual BOOL OnMouseLeftButtonUp();
virtual BOOL OnMouseLeftButtonDoubleClick();
virtual BOOL OnMouseRightButtonDown();
virtual BOOL OnMouseRightButtonUp();
virtual BOOL OnMouseRightButtonDoubleClick();
virtual BOOL OnMouseMiddleButtonDown();
virtual BOOL OnMouseMiddleButtonUp();
virtual BOOL OnMouseWheelScroll(short wDelta) { return FALSE; }
virtual void SetScrollable() { m_bIsScrollable = true; }
virtual BOOL OnMouseWheel(int nLen) { return FALSE; }
virtual BOOL RunMouseWheelEvent(long nLen) { return FALSE; }
virtual BOOL OnKeyDown(int ikey);
virtual BOOL OnKeyUp(int ikey);
virtual BOOL OnPressEscapeKey();
virtual BOOL OnPressExitKey();
virtual void SetColor(DWORD dwColor){}
virtual BOOL OnIsType(DWORD dwType);
virtual BOOL IsWindow() { return TRUE; }
protected:
std::string m_strName;
EHorizontalAlign m_HorizontalAlign;
EVerticalAlign m_VerticalAlign;
long m_x, m_y;
long m_lWidth, m_lHeight;
RECT m_rect;
RECT m_limitBiasRect;
bool m_bMovable;
bool m_bShow;
DWORD m_dwFlag;
PyObject * m_poHandler;
CWindow * m_pParent;
TWindowContainer m_pChildList;
BOOL m_isUpdatingChildren;
TWindowContainer m_pReserveChildList;
bool m_bIsScrollable = false;
};
class CLayer : public CWindow
{
public:
CLayer(PyObject * ppyObject) : CWindow(ppyObject) {}
virtual ~CLayer() {}
BOOL IsWindow() override { return FALSE; }
};
class CBox : public CWindow
{
public:
CBox(PyObject * ppyObject) : CWindow(ppyObject), m_dwColor(0) {}
virtual ~CBox() {}
void SetColor(DWORD dwColor) override { m_dwColor = dwColor; }
protected:
void OnRender() override;
DWORD m_dwColor;
};
class CBar : public CWindow
{
public:
CBar(PyObject * ppyObject) : CWindow(ppyObject), m_dwColor(0) {}
virtual ~CBar() {}
void SetColor(DWORD dwColor) override { m_dwColor = dwColor; }
protected:
void OnRender() override;
DWORD m_dwColor;
};
class CLine : public CWindow
{
public:
CLine(PyObject * ppyObject) : CWindow(ppyObject), m_dwColor(0) {}
virtual ~CLine() {}
void SetColor(DWORD dwColor) override { m_dwColor = dwColor; }
protected:
void OnRender() override;
DWORD m_dwColor;
};
class CBar3D : public CWindow
{
public:
static DWORD Type();
CBar3D(PyObject * ppyObject) : CWindow(ppyObject), m_dwLeftColor(0), m_dwRightColor(0), m_dwCenterColor(0) {}
virtual ~CBar3D() {}
void SetColor(DWORD l, DWORD r, DWORD c) { m_dwLeftColor = l; m_dwRightColor = r; m_dwCenterColor = c; }
protected:
void OnRender() override;
BOOL OnIsType(DWORD dwType) override;
DWORD m_dwLeftColor, m_dwRightColor, m_dwCenterColor;
};
class CTextLine : public CWindow
{
public:
static DWORD Type();
CTextLine(PyObject * ppyObject);
virtual ~CTextLine();
void SetMax(int iMax) { m_TextInstance.SetMax(iMax); }
void SetHorizontalAlign(int iType) { m_TextInstance.SetHorizonalAlign(iType); }
void SetVerticalAlign(int iType) { m_TextInstance.SetVerticalAlign(iType); }
void SetSecret(BOOL bFlag) { m_TextInstance.SetSecret(bFlag); }
void SetOutline(BOOL bFlag) { m_TextInstance.SetOutline(bFlag); }
void SetFeather(BOOL bFlag) { m_TextInstance.SetFeather(bFlag); }
void SetMultiLine(BOOL bFlag) { m_TextInstance.SetMultiLine(bFlag); }
void SetFontName(const char * c_szFontName) { m_TextInstance.SetFontName(c_szFontName); }
void SetFontColor(DWORD dwColor) { m_TextInstance.SetFontColor(dwColor); }
void SetLimitWidth(float fWidth) { m_TextInstance.SetLimitWidth(fWidth); }
void ShowCursor() { m_TextInstance.ShowCursor(); }
void HideCursor() { m_TextInstance.HideCursor(); }
int GetCursorPosition() { return m_TextInstance.GetCursorPosition(); }
void SetText(const char * c_szText);
const char * GetText() { return m_TextInstance.GetText(); }
void GetTextSize(int* pnWidth, int* pnHeight) { m_TextInstance.GetTextSize(pnWidth, pnHeight); }
int GetTextLineCount() { return m_TextInstance.GetTextLineCount(); }
void DisableEnterToken() { m_TextInstance.DisableEnterToken(); }
void SetLineHeight(int iHeight) { m_TextInstance.SetLineHeight(iHeight); }
int GetLineHeight() { return m_TextInstance.GetLineHeight(); }
protected:
void OnRender() override;
void OnChangePosition() override;
BOOL OnIsType(DWORD dwType) override;
CGraphicTextInstance m_TextInstance;
};
class CNumberLine : public CWindow
{
public:
static DWORD Type();
CNumberLine(PyObject * ppyObject) : CWindow(ppyObject), m_iHorizontalAlign(0), m_dwWidthSummary(0) {}
CNumberLine(CWindow * pParent) : CWindow(nullptr), m_iHorizontalAlign(0), m_dwWidthSummary(0) { m_pParent = pParent; }
virtual ~CNumberLine() {}
void SetPath(const char * c_szPath) { if (c_szPath) m_strPath = c_szPath; }
void SetHorizontalAlign(int iType) { m_iHorizontalAlign = iType; }
void SetNumber(const char * c_szNumber) { if (c_szNumber) m_strNumber = c_szNumber; }
protected:
BOOL OnIsType(DWORD dwType) override;
std::string m_strPath, m_strNumber;
int m_iHorizontalAlign;
DWORD m_dwWidthSummary;
};
class CImageBox : public CWindow
{
public:
static DWORD Type();
CImageBox(PyObject * ppyObject);
virtual ~CImageBox();
void LeftRightReverse();
BOOL LoadImage(CGraphicImageInstance* imageInstance);
BOOL LoadImage(const char * c_szFileName);
void SetDiffuseColor(float fr, float fg, float fb, float fa);
void Clear();
int GetWidth();
int GetHeight();
void SetScale(float sx, float sy);
void SetCoolTime(float fCoolTime) { m_fCoolTime = fCoolTime; }
void SetCoolTimeStart(float fCoolTimeStart) { m_fCoolTimeStart = fCoolTimeStart; }
protected:
virtual void OnCreateInstance();
virtual void OnDestroyInstance();
void OnUpdate() override;
void OnRender() override;
void OnChangePosition() override;
BOOL OnIsType(DWORD dwType) override;
protected:
CGraphicImageInstance * m_pImageInstance;
float m_fCoolTime;
float m_fCoolTimeStart;
};
class CMarkBox : public CWindow
{
public:
static DWORD Type();
CMarkBox(PyObject * ppyObject);
virtual ~CMarkBox();
void LoadImage(const char * c_szFilename);
void SetDiffuseColor(float fr, float fg, float fb, float fa);
void SetIndex(UINT uIndex);
void SetScale(FLOAT fScale);
protected:
virtual void OnCreateInstance();
virtual void OnDestroyInstance();
void OnUpdate() override;
void OnRender() override;
void OnChangePosition() override;
BOOL OnIsType(DWORD dwType) override;
protected:
CGraphicMarkInstance * m_pMarkInstance;
};
class CExpandedImageBox : public CImageBox
{
public:
static DWORD Type();
CExpandedImageBox(PyObject * ppyObject);
virtual ~CExpandedImageBox();
void SetScale(float fx, float fy);
void SetOrigin(float fx, float fy);
void SetRotation(float fRotation);
void SetRenderingRect(float fLeft, float fTop, float fRight, float fBottom);
void SetRenderingMode(int iMode);
void SetImageClipRect(float fLeft, float fTop, float fRight, float fBottom, bool bIsVertical = false) {}
protected:
void OnCreateInstance() override;
void OnDestroyInstance() override;
void OnUpdate() override;
void OnRender() override;
BOOL OnIsType(DWORD dwType) override;
};
class CAniImageBox : public CWindow
{
public:
static DWORD Type();
CAniImageBox(PyObject * ppyObject);
virtual ~CAniImageBox();
void SetDelay(int iDelay);
void AppendImage(const char * c_szFileName, float r = 1.0, float g = 1.0, float b = 1.0, float a = 1.0);
void SetRenderingRect(float fLeft, float fTop, float fRight, float fBottom);
void SetRenderingMode(int iMode);
void AppendImageScale(const char * c_szFileName, float scale_x, float scale_y);
void ResetFrame();
void SetRotation(float fRotation);
void SetMoveStatus(bool bFlag);
void SetMoveSpeed(float speed);
void SetMovePos(float directionX, float directionY);
float GetRotation();
protected:
void OnUpdate() override;
void OnRender() override;
void OnChangePosition() override;
virtual void OnEndFrame();
BOOL OnIsType(DWORD dwType) override;
protected:
BYTE m_bycurDelay;
BYTE m_byDelay;
BYTE m_bycurIndex;
std::vector<CGraphicExpandedImageInstance*> m_ImageVector;
};
class CButton : public CWindow
{
public:
static DWORD Type();
CButton(PyObject * ppyObject);
virtual ~CButton();
void LeftRightReverse();
BOOL SetUpVisual(const char * c_szFileName);
BOOL SetOverVisual(const char * c_szFileName);
BOOL SetDownVisual(const char * c_szFileName);
BOOL SetDisableVisual(const char * c_szFileName);
void SetRenderingRect(float fLeft, float fTop, float fRight, float fBottom) {}
const char * GetUpVisualFileName();
const char * GetOverVisualFileName();
const char * GetDownVisualFileName();
void FlashEx() { m_isFlashEx = TRUE; }
void Flash(bool bFlash = true) { m_isFlash = bFlash; }
void Enable() { m_bEnable = TRUE; }
void Disable() { m_bEnable = FALSE; }
void SetUp();
void Up();
void Over();
void Down();
BOOL IsDisable() { return !m_bEnable; }
BOOL IsPressed() { return m_isPressed; }
protected:
void OnUpdate() override;
void OnRender() override;
void OnChangePosition() override;
BOOL OnMouseLeftButtonDown() override;
BOOL OnMouseLeftButtonUp() override;
void OnMouseOverIn() override;
void OnMouseOverOut() override;
BOOL IsEnable() { return m_bEnable; }
void SetCurrentVisual(CGraphicImageInstance* pVisual);
BOOL OnIsType(DWORD dwType) override;
protected:
BOOL m_bEnable;
BOOL m_isPressed;
BOOL m_isFlashEx;
BOOL m_isFlash;
CGraphicImageInstance* m_pcurVisual;
CGraphicImageInstance m_upVisual;
CGraphicImageInstance m_overVisual;
CGraphicImageInstance m_downVisual;
CGraphicImageInstance m_disableVisual;
};
class CRadioButton : public CButton
{
public:
static DWORD Type();
CRadioButton(PyObject* ppyObject) : CButton(ppyObject) {}
virtual ~CRadioButton() {}
protected:
BOOL OnIsType(DWORD dwType) override;
};
class CToggleButton : public CButton
{
public:
static DWORD Type();
CToggleButton(PyObject* ppyObject) : CButton(ppyObject) {}
virtual ~CToggleButton() {}
protected:
BOOL OnIsType(DWORD dwType) override;
};
class CDragButton : public CButton
{
public:
static DWORD Type();
CDragButton(PyObject * ppyObject) : CButton(ppyObject) { memset(&m_restrictArea, 0, sizeof(m_restrictArea)); }
virtual ~CDragButton() {}
void SetRestrictMovementArea(int ix, int iy, int iwidth, int iheight) {
m_restrictArea.left = ix; m_restrictArea.top = iy;
m_restrictArea.right = ix + iwidth; m_restrictArea.bottom = iy + iheight;
}
protected:
BOOL OnIsType(DWORD dwType) override;
RECT m_restrictArea;
};
class CUiRenderTarget : public CWindow
{
public:
static DWORD Type();
CUiRenderTarget(PyObject* ppyObject) : CWindow(ppyObject), m_dwIndex(0) {}
virtual ~CUiRenderTarget() {}
bool SetRenderTarget(int index) { m_dwIndex = (DWORD)index; return true; }
void SetRenderingRect(float fLeft, float fTop, float fRight, float fBottom) {}
protected:
void OnRender() override;
BOOL OnIsType(DWORD dwType) override;
DWORD m_dwIndex;
};
class CSlotWindow : public CWindow
{
public:
struct SSlot
{
DWORD dwIndex = 0;
int ixPosition = 0;
int iyPosition = 0;
int ixCellSize = 32;
int iyCellSize = 32;
BYTE byWidth = 1;
BYTE byHeight = 1;
bool bRenderBaseSlotImage = true;
bool isItem = false;
DWORD dwItemIndex = 0;
CGraphicImageInstance* pInstance = nullptr;
CGraphicImageInstance* pCoverInstance = nullptr;
DWORD dwItemCount = 0;
DWORD dwGrade = 0;
bool bActive = false;
bool bLocked = false;
float fCoolTime = 0.0f;
float fStartCoolTime = 0.0f;
};
static DWORD Type();
CSlotWindow(PyObject * ppyObject);
virtual ~CSlotWindow();
void Destroy();
void SetSlotID(DWORD dwIndex, DWORD dwID) {}
void SetSlotType(DWORD dwType) { m_dwSlotType = dwType; }
void SetSlotStyle(DWORD dwStyle) { m_dwSlotStyle = dwStyle; }
void AppendSlot(DWORD dwIndex, int ix, int iy, int iw, int ih);
void SetCoverButton(DWORD dwIndex, const char* c_szUpImageName, const char* c_szOverImageName, const char* c_szDownImageName, const char* c_szDisableImageName, BOOL bLeftButtonEnable, BOOL bRightButtonEnable);
void SetSlotBaseImage(const char* szFileName, float fr = 1.0f, float fg = 1.0f, float fb = 1.0f, float fa = 1.0f);
void AppendSlotButton(const char*, const char*, const char*) {}
void AppendRequirementSignImage(const char*) {}
void SetSlotBaseImageScale(const char*, float, float, float, float, float, float) {}
void SetSlotScale(DWORD dwIndex, DWORD dwItemIndex, BYTE byWidth, BYTE byHeight, CGraphicImage* pImage, float sx, float sy, const D3DXCOLOR& diffuseColor);
void EnableCoverButton(DWORD) {}
void DisableCoverButton(DWORD) {}
void SetAlwaysRenderCoverButton(DWORD, bool = false) {}
void ShowSlotBaseImage(DWORD dwIndex);
void HideSlotBaseImage(DWORD dwIndex);
BOOL IsDisableCoverButton(DWORD) { return FALSE; }
BOOL HasSlot(DWORD dwIndex);
void ClearAllSlot();
void ClearSlot(DWORD dwIndex);
void SetSlot(DWORD dwIndex, DWORD dwItemIndex, BYTE byWidth, BYTE byHeight, CGraphicImage* pImage, const D3DXCOLOR& diffuseColor);
void SetCardSlot(DWORD dwIndex, DWORD, BYTE, BYTE, const char*, DWORD) { if (!HasSlot(dwIndex)) AppendSlot(dwIndex, 0, 0, 32, 32); }
void SetSlotCount(DWORD dwIndex, DWORD dwCount);
void SetSlotCountNew(DWORD dwIndex, DWORD dwGrade, DWORD dwCount);
void SetSlotCoolTime(DWORD dwIndex, float fCoolTime, float fElapsedTime = 0.0f);
bool IsSlotCoolTime(DWORD dwIndex);
float GetSlotCoolTime(DWORD dwIndex);
float GetSlotRemainingCoolTime(DWORD dwIndex);
void StoreSlotCoolTime(DWORD, DWORD, float, float = 0.0f) {}
void RestoreSlotCoolTime(DWORD) {}
void ActivateSlot(DWORD dwIndex);
void DeactivateSlot(DWORD dwIndex);
void RefreshSlot() {}
DWORD GetSlotCount() { return (DWORD)m_slotMap.size(); }
void LockSlot(DWORD dwIndex);
void UnlockSlot(DWORD dwIndex);
BOOL IsLockSlot(DWORD dwIndex);
void SetCantUseSlot(DWORD) {}
void SetUseSlot(DWORD) {}
BOOL IsCantUseSlot(DWORD) { return FALSE; }
void EnableSlot(DWORD) {}
void DisableSlot(DWORD) {}
BOOL IsEnableSlot(DWORD) { return TRUE; }
void SetCanMouseEventSlot(DWORD) {}
void SetCantMouseEventSlot(DWORD) {}
void SetUsableSlotOnTopWnd(DWORD) {}
void SetUnusableSlotOnTopWnd(DWORD) {}
void ClearSelected() { m_selected.clear(); }
void SelectSlot(DWORD dwIndex) { m_selected.push_back(dwIndex); }
BOOL isSelectedSlot(DWORD dwIndex) {
return std::find(m_selected.begin(), m_selected.end(), dwIndex) != m_selected.end();
}
DWORD GetSelectedSlotCount() { return (DWORD)m_selected.size(); }
DWORD GetSelectedSlotNumber(DWORD dwIndex) {
return (dwIndex < m_selected.size()) ? m_selected[dwIndex] : 0;
}
void ShowSlotButton(DWORD) {}
void HideAllSlotButton() {}
void ShowRequirementSign(DWORD) {}
void HideRequirementSign(DWORD) {}
void SetUseMode(BOOL) {}
void SetUsableItem(BOOL) {}
void ActivateEffect(DWORD, float, float, float, float) {}
void DeactivateEffect(DWORD) {}
protected:
void OnRender() override;
BOOL OnIsType(DWORD dwType) override;
DWORD m_dwSlotType;
DWORD m_dwSlotStyle;
std::vector<DWORD> m_slots;
std::vector<DWORD> m_selected;
std::map<DWORD, SSlot> m_slotMap;
CGraphicImageInstance* m_pBaseImageInstance;
};
class CGridSlotWindow : public CSlotWindow
{
public:
static DWORD Type();
CGridSlotWindow(PyObject * ppyObject) : CSlotWindow(ppyObject) {}
virtual ~CGridSlotWindow() {}
void ArrangeGridSlot(DWORD dwStartIndex, DWORD dwxCount, DWORD dwyCount, int ixSlotSize, int iySlotSize, int ixTemporarySize, int iyTemporarySize);
protected:
BOOL OnIsType(DWORD dwType) override;
};
}
+446
View File
@@ -0,0 +1,446 @@
#include "PythonWindowManager.h"
#include <cassert>
namespace UI
{
static PyObject* gs_poEmptyTuple = nullptr;
PyObject * BuildEmptyTuple()
{
if (!gs_poEmptyTuple)
gs_poEmptyTuple = PyTuple_New(0);
Py_INCREF(gs_poEmptyTuple);
return gs_poEmptyTuple;
}
CWindowManager::CWindowManager()
: m_lWidth(1024),
m_lHeight(768),
m_iVres(768),
m_iHres(1024),
m_lMouseX(0), m_lMouseY(0),
m_lDragX(0), m_lDragY(0),
m_lPickedX(0), m_lPickedY(0),
m_bOnceIgnoreMouseLeftButtonUpEventFlag(FALSE),
m_iIgnoreEndTime(0),
m_poMouseHandler(nullptr),
m_bAttachingFlag(FALSE),
m_dwAttachingType(0),
m_dwAttachingIndex(0),
m_dwAttachingSlotNumber(0),
m_byAttachingIconWidth(0),
m_byAttachingIconHeight(0),
m_pActiveWindow(nullptr),
m_pLockWindow(nullptr),
m_pPointWindow(nullptr),
m_pLeftCaptureWindow(nullptr),
m_pRightCaptureWindow(nullptr),
m_pMiddleCaptureWindow(nullptr)
{
m_pRootWindow = new CWindow(nullptr);
m_pRootWindow->SetName("root");
m_pRootWindow->Show();
const char * layerTbl[] = {"GAME","UI_BOTTOM","UI","TOP_MOST","CURTAIN"};
for(size_t layer = 0; layer < sizeof(layerTbl)/sizeof(layerTbl[0]); layer++)
{
CWindow * pLayer = new CLayer(nullptr);
pLayer->SetName(layerTbl[layer]);
pLayer->Show();
m_LayerWindowMap[layerTbl[layer]] = pLayer;
m_pRootWindow->AddChild(pLayer);
m_LayerWindowList.push_back(pLayer);
}
m_ActiveWindowList.clear();
m_LockWindowList.clear();
}
CWindowManager::~CWindowManager()
{
__ClearReserveDeleteWindowList();
if (Py_IsInitialized())
{
Py_XDECREF(gs_poEmptyTuple);
}
gs_poEmptyTuple = nullptr;
for (auto& pair : m_LayerWindowMap)
delete pair.second;
m_LayerWindowMap.clear();
m_LayerWindowList.clear();
m_KeyCaptureWindowMap.clear();
delete m_pRootWindow;
m_pRootWindow = nullptr;
}
void CWindowManager::Destroy()
{
__ClearReserveDeleteWindowList();
}
float CWindowManager::GetAspect()
{
return (m_lHeight > 0) ? ((float)m_lWidth / (float)m_lHeight) : 1.333333f;
}
void CWindowManager::SetScreenSize(long lWidth, long lHeight)
{
m_lWidth = lWidth;
m_lHeight = lHeight;
if (m_pRootWindow)
m_pRootWindow->SetSize(lWidth, lHeight);
}
void CWindowManager::SetResolution(int hres, int vres)
{
m_iHres = hres;
m_iVres = vres;
}
void CWindowManager::SetMouseHandler(PyObject * poMouseHandler)
{
m_poMouseHandler = poMouseHandler;
}
void CWindowManager::SetMousePosition(long x, long y)
{
if (m_iHres == 0 || m_iVres == 0) return;
m_lMouseX = m_lWidth * x / m_iHres;
m_lMouseY = m_lHeight * y / m_iVres;
}
void CWindowManager::GetMousePosition(long & rx, long & ry)
{
rx = m_lMouseX;
ry = m_lMouseY;
}
BOOL CWindowManager::IsDragging()
{
return (m_pLeftCaptureWindow != nullptr);
}
void CWindowManager::SetParent(CWindow * pWindow, CWindow * pParentWindow)
{
if (!pWindow || !pParentWindow) return;
if (pWindow->GetParent())
{
CWindow * pOldParentWindow = pWindow->GetParent();
if (pParentWindow == pOldParentWindow)
return;
pOldParentWindow->DeleteChild(pWindow);
}
pParentWindow->AddChild(pWindow);
pWindow->UpdateRect();
}
void CWindowManager::SetPickAlways(CWindow * pWindow)
{
if (!pWindow) return;
m_PickAlwaysWindowList.push_back(pWindow);
}
CWindow * CWindowManager::__NewWindow(PyObject * po, DWORD dwWndType)
{
switch(dwWndType)
{
case WT_SLOT: return new CSlotWindow(po);
case WT_GRIDSLOT: return new CGridSlotWindow(po);
case WT_TEXTLINE: return new CTextLine(po);
case WT_MARKBOX: return new CMarkBox(po);
case WT_IMAGEBOX: return new CImageBox(po);
case WT_EXP_IMAGEBOX: return new CExpandedImageBox(po);
case WT_ANI_IMAGEBOX: return new CAniImageBox(po);
case WT_BUTTON: return new CButton(po);
case WT_RATIOBUTTON: return new CRadioButton(po);
case WT_TOGGLEBUTTON: return new CToggleButton(po);
case WT_DRAGBUTTON: return new CDragButton(po);
case WT_BOX: return new CBox(po);
case WT_BAR: return new CBar(po);
case WT_LINE: return new CLine(po);
case WT_BAR3D: return new CBar3D(po);
case WT_NUMLINE: return new CNumberLine(po);
default: break;
}
return new CWindow(po);
}
CWindow * CWindowManager::RegisterTypeWindow(PyObject * po, DWORD dwWndType, const char * c_szLayer)
{
if (m_LayerWindowMap.find(c_szLayer) == m_LayerWindowMap.end()) return nullptr;
CWindow * pWin = __NewWindow(po, dwWndType);
m_LayerWindowMap[c_szLayer]->AddChild(pWin);
return pWin;
}
CWindow * CWindowManager::RegisterWindow(PyObject * po, const char * c_szLayer) { return RegisterTypeWindow(po, WT_NORMAL, c_szLayer); }
CWindow * CWindowManager::RegisterSlotWindow(PyObject * po, const char * c_szLayer) { return RegisterTypeWindow(po, WT_SLOT, c_szLayer); }
CWindow * CWindowManager::RegisterGridSlotWindow(PyObject * po, const char * c_szLayer) { return RegisterTypeWindow(po, WT_GRIDSLOT, c_szLayer); }
CWindow * CWindowManager::RegisterTextLine(PyObject * po, const char * c_szLayer) { return RegisterTypeWindow(po, WT_TEXTLINE, c_szLayer); }
CWindow * CWindowManager::RegisterMarkBox(PyObject * po, const char * c_szLayer) { return RegisterTypeWindow(po, WT_MARKBOX, c_szLayer); }
CWindow * CWindowManager::RegisterImageBox(PyObject * po, const char * c_szLayer) { return RegisterTypeWindow(po, WT_IMAGEBOX, c_szLayer); }
CWindow * CWindowManager::RegisterExpandedImageBox(PyObject * po, const char * c_szLayer) { return RegisterTypeWindow(po, WT_EXP_IMAGEBOX, c_szLayer); }
CWindow * CWindowManager::RegisterAniImageBox(PyObject * po, const char * c_szLayer) { return RegisterTypeWindow(po, WT_ANI_IMAGEBOX, c_szLayer); }
CWindow * CWindowManager::RegisterButton(PyObject * po, const char * c_szLayer) { return RegisterTypeWindow(po, WT_BUTTON, c_szLayer); }
CWindow * CWindowManager::RegisterRadioButton(PyObject * po, const char * c_szLayer) { return RegisterTypeWindow(po, WT_RATIOBUTTON, c_szLayer); }
CWindow * CWindowManager::RegisterToggleButton(PyObject * po, const char * c_szLayer) { return RegisterTypeWindow(po, WT_TOGGLEBUTTON, c_szLayer); }
CWindow * CWindowManager::RegisterDragButton(PyObject * po, const char * c_szLayer) { return RegisterTypeWindow(po, WT_DRAGBUTTON, c_szLayer); }
CWindow * CWindowManager::RegisterBox(PyObject * po, const char * c_szLayer) { return RegisterTypeWindow(po, WT_BOX, c_szLayer); }
CWindow * CWindowManager::RegisterBar(PyObject * po, const char * c_szLayer) { return RegisterTypeWindow(po, WT_BAR, c_szLayer); }
CWindow * CWindowManager::RegisterLine(PyObject * po, const char * c_szLayer) { return RegisterTypeWindow(po, WT_LINE, c_szLayer); }
CWindow * CWindowManager::RegisterBar3D(PyObject * po, const char * c_szLayer) { return RegisterTypeWindow(po, WT_BAR3D, c_szLayer); }
CWindow * CWindowManager::RegisterNumberLine(PyObject * po, const char * c_szLayer) { return RegisterTypeWindow(po, WT_NUMLINE, c_szLayer); }
CWindow * CWindowManager::RegisterRenderTarget(PyObject * po, const char * c_szLayer)
{
if (m_LayerWindowMap.find(c_szLayer) == m_LayerWindowMap.end()) return nullptr;
CWindow * pWin = new CUiRenderTarget(po);
m_LayerWindowMap[c_szLayer]->AddChild(pWin);
return pWin;
}
void CWindowManager::DestroyWindow(CWindow * pWin)
{
if (!pWin) return;
for (auto* existing : m_ReserveDeleteWindowList)
{
if (existing == pWin)
return;
}
NotifyDestroyWindow(pWin);
if (pWin->GetParent())
{
CWindow * pParentWin = pWin->GetParent();
pParentWin->DeleteChild(pWin);
}
pWin->Clear();
m_ReserveDeleteWindowList.push_back(pWin);
}
void CWindowManager::NotifyDestroyWindow(CWindow * pWindow)
{
if (pWindow == m_pActiveWindow) m_pActiveWindow = nullptr;
if (pWindow == m_pPointWindow) m_pPointWindow = nullptr;
if (pWindow == m_pLeftCaptureWindow) m_pLeftCaptureWindow = nullptr;
if (pWindow == m_pRightCaptureWindow) m_pRightCaptureWindow = nullptr;
if (pWindow == m_pMiddleCaptureWindow) m_pMiddleCaptureWindow = nullptr;
if (pWindow == m_pLockWindow) m_pLockWindow = nullptr;
m_ActiveWindowList.remove(pWindow);
m_LockWindowList.remove(pWindow);
m_PickAlwaysWindowList.remove(pWindow);
}
void CWindowManager::__ClearReserveDeleteWindowList()
{
for (auto* win : m_ReserveDeleteWindowList)
delete win;
m_ReserveDeleteWindowList.clear();
}
BOOL CWindowManager::IsAttaching() { return m_bAttachingFlag; }
DWORD CWindowManager::GetAttachingType() { return m_dwAttachingType; }
DWORD CWindowManager::GetAttachingIndex() { return m_dwAttachingIndex; }
DWORD CWindowManager::GetAttachingSlotNumber() { return m_dwAttachingSlotNumber; }
void CWindowManager::GetAttachingIconSize(BYTE * pbyWidth, BYTE * pbyHeight) {
if (pbyWidth) *pbyWidth = m_byAttachingIconWidth;
if (pbyHeight) *pbyHeight = m_byAttachingIconHeight;
}
void CWindowManager::AttachIcon(DWORD dwType, DWORD dwIndex, DWORD dwSlotNumber, BYTE byWidth, BYTE byHeight) {
m_bAttachingFlag = TRUE;
m_dwAttachingType = dwType;
m_dwAttachingIndex = dwIndex;
m_dwAttachingSlotNumber = dwSlotNumber;
m_byAttachingIconWidth = byWidth;
m_byAttachingIconHeight = byHeight;
}
void CWindowManager::DeattachIcon() { m_bAttachingFlag = FALSE; }
void CWindowManager::SetAttachingFlag(BOOL bFlag) { m_bAttachingFlag = bFlag; }
void CWindowManager::OnceIgnoreMouseLeftButtonUpEvent() { m_bOnceIgnoreMouseLeftButtonUpEventFlag = TRUE; }
void CWindowManager::LockWindow(CWindow * pWin) { m_pLockWindow = pWin; }
void CWindowManager::UnlockWindow() { m_pLockWindow = nullptr; }
void CWindowManager::ActivateWindow(CWindow * pWin)
{
m_ActiveWindowList.remove(pWin);
if (pWin == m_pActiveWindow) return;
if (m_pActiveWindow)
{
m_ActiveWindowList.push_back(m_pActiveWindow);
m_pActiveWindow->OnKillFocus();
}
m_pActiveWindow = pWin;
if (m_pActiveWindow) m_pActiveWindow->OnSetFocus();
}
void CWindowManager::DeactivateWindow()
{
if (m_pActiveWindow)
{
m_pActiveWindow->OnKillFocus();
if (m_ActiveWindowList.empty())
m_pActiveWindow = nullptr;
else
{
m_pActiveWindow = m_ActiveWindowList.back();
m_ActiveWindowList.pop_back();
m_pActiveWindow->OnSetFocus();
}
}
}
CWindow * CWindowManager::GetActivateWindow() { return m_pActiveWindow; }
void CWindowManager::SetTop(CWindow * pWin)
{
if (!pWin || !pWin->IsFlag(CWindow::FLAG_FLOAT)) return;
CWindow* parent = pWin->GetParent();
if (parent) parent->SetTop(pWin);
}
void CWindowManager::SetTopUIWindow() {}
void CWindowManager::ResetCapture() { m_pLeftCaptureWindow = nullptr; }
void CWindowManager::Update()
{
__ClearReserveDeleteWindowList();
if (m_pRootWindow) m_pRootWindow->Update();
}
void CWindowManager::Render()
{
if (m_pRootWindow) m_pRootWindow->Render();
}
CWindow * CWindowManager::__PickWindow(long x, long y)
{
if (m_pLockWindow) return m_pLockWindow->PickWindow(x, y);
for (auto* win : m_PickAlwaysWindowList)
{
if (win->IsRendering() && win->IsIn(x, y)) return win;
}
for (auto it = m_LayerWindowList.rbegin(); it != m_LayerWindowList.rend(); ++it)
{
CWindow* pPicked = (*it)->PickWindow(x, y);
if (pPicked && pPicked != *it) return pPicked;
}
return nullptr;
}
void CWindowManager::RunMouseMove(long x, long y)
{
SetMousePosition(x, y);
CWindow * pPointWindow = __PickWindow(m_lMouseX, m_lMouseY);
if (m_pLeftCaptureWindow)
{
if (m_pLeftCaptureWindow->IsFlag(CWindow::FLAG_MOVABLE))
{
long new_x = m_lMouseX - m_lDragX;
long new_y = m_lMouseY - m_lDragY;
if (m_pLeftCaptureWindow->IsFlag(CWindow::FLAG_LIMIT))
{
if (new_x < 0) new_x = 0;
if (new_y < 0) new_y = 0;
if (new_x > m_lWidth - m_pLeftCaptureWindow->GetWidth()) new_x = m_lWidth - m_pLeftCaptureWindow->GetWidth();
if (new_y > m_lHeight - m_pLeftCaptureWindow->GetHeight()) new_y = m_lHeight - m_pLeftCaptureWindow->GetHeight();
}
m_pLeftCaptureWindow->SetPosition(new_x, new_y);
}
m_pLeftCaptureWindow->OnMouseDrag(m_lMouseX, m_lMouseY);
}
if (pPointWindow != m_pPointWindow)
{
if (m_pPointWindow) m_pPointWindow->OnMouseOverOut();
m_pPointWindow = pPointWindow;
if (m_pPointWindow) m_pPointWindow->OnMouseOverIn();
}
else if (m_pPointWindow)
{
m_pPointWindow->OnMouseOver();
}
}
void CWindowManager::RunMouseLeftButtonDown(long x, long y)
{
SetMousePosition(x, y);
CWindow * pWin = GetPointWindow();
if (!pWin) return;
if (pWin->IsFlag(CWindow::FLAG_ATTACH)) pWin = pWin->GetRoot();
if (!pWin->IsFlag(CWindow::FLAG_NOT_CAPTURE)) m_pLeftCaptureWindow = pWin;
m_lDragX = m_lMouseX - pWin->GetPositionX();
m_lDragY = m_lMouseY - pWin->GetPositionY();
pWin->OnMouseLeftButtonDown();
}
void CWindowManager::RunMouseLeftButtonUp(long x, long y)
{
SetMousePosition(x, y);
if (m_pLeftCaptureWindow)
{
m_pLeftCaptureWindow->OnMouseLeftButtonUp();
m_pLeftCaptureWindow = nullptr;
}
}
void CWindowManager::RunMouseLeftButtonDoubleClick(long x, long y)
{
SetMousePosition(x, y);
if (m_pPointWindow) m_pPointWindow->OnMouseLeftButtonDoubleClick();
}
void CWindowManager::RunMouseRightButtonDown(long x, long y)
{
SetMousePosition(x, y);
if (m_pPointWindow) m_pPointWindow->OnMouseRightButtonDown();
}
void CWindowManager::RunMouseRightButtonUp(long x, long y)
{
SetMousePosition(x, y);
if (m_pPointWindow) m_pPointWindow->OnMouseRightButtonUp();
}
void CWindowManager::RunMouseRightButtonDoubleClick(long x, long y)
{
SetMousePosition(x, y);
if (m_pPointWindow) m_pPointWindow->OnMouseRightButtonDoubleClick();
}
void CWindowManager::RunMouseMiddleButtonDown(long x, long y)
{
SetMousePosition(x, y);
if (m_pPointWindow) m_pPointWindow->OnMouseMiddleButtonDown();
}
void CWindowManager::RunMouseMiddleButtonUp(long x, long y)
{
SetMousePosition(x, y);
if (m_pPointWindow) m_pPointWindow->OnMouseMiddleButtonUp();
}
void CWindowManager::RunKeyDown(int vkey)
{
if (m_pRootWindow) m_pRootWindow->RunKeyDownEvent(vkey);
}
void CWindowManager::RunKeyUp(int vkey)
{
if (m_pRootWindow) m_pRootWindow->RunKeyUpEvent(vkey);
}
void CWindowManager::RunPressEscapeKey()
{
if (m_pRootWindow) m_pRootWindow->RunPressEscapeKeyEvent();
}
void CWindowManager::RunPressExitKey()
{
if (m_pRootWindow) m_pRootWindow->RunPressExitKeyEvent();
}
}
+168
View File
@@ -0,0 +1,168 @@
#pragma once
#include "PythonWindow.h"
#include "shared/common/Singleton.h"
#include <map>
#include <list>
#include <string>
namespace UI
{
class CWindowManager : public CSingleton<CWindowManager>
{
public:
typedef std::map<std::string, CWindow *> TLayerContainer;
typedef std::list<CWindow *> TWindowContainer;
typedef std::map<int, CWindow *> TKeyCaptureWindowMap;
public:
CWindowManager();
virtual ~CWindowManager();
void Destroy();
float GetAspect();
void SetScreenSize(long lWidth, long lHeight);
void SetResolution(int hres, int vres);
void GetResolution(long & rx, long & ry) { rx = m_iHres; ry = m_iVres; }
void SetMouseHandler(PyObject * poMouseHandler);
long GetScreenWidth() { return m_lWidth; }
long GetScreenHeight() { return m_lHeight; }
void GetMousePosition(long & rx, long & ry);
BOOL IsDragging();
CWindow * GetLockWindow() { return m_pLockWindow; }
CWindow * GetPointWindow() { return m_pPointWindow; }
bool IsFocus() { return (m_pActiveWindow || m_pLockWindow); }
bool IsFocusWindow(CWindow * pWindow) { return pWindow == m_pActiveWindow; }
void SetParent(CWindow * pWindow, CWindow * pParentWindow);
void SetPickAlways(CWindow * pWindow);
enum
{
WT_NORMAL,
WT_SLOT,
WT_GRIDSLOT,
WT_TEXTLINE,
WT_MARKBOX,
WT_IMAGEBOX,
WT_EXP_IMAGEBOX,
WT_ANI_IMAGEBOX,
WT_BUTTON,
WT_RATIOBUTTON,
WT_TOGGLEBUTTON,
WT_DRAGBUTTON,
WT_BOX,
WT_BAR,
WT_LINE,
WT_BAR3D,
WT_NUMLINE,
};
CWindow * RegisterWindow(PyObject * po, const char * c_szLayer);
CWindow * RegisterTypeWindow(PyObject * po, DWORD dwWndType, const char * c_szLayer);
CWindow * RegisterSlotWindow(PyObject * po, const char * c_szLayer);
CWindow * RegisterGridSlotWindow(PyObject * po, const char * c_szLayer);
CWindow * RegisterTextLine(PyObject * po, const char * c_szLayer);
CWindow * RegisterMarkBox(PyObject * po, const char * c_szLayer);
CWindow * RegisterImageBox(PyObject * po, const char * c_szLayer);
CWindow * RegisterExpandedImageBox(PyObject * po, const char * c_szLayer);
CWindow * RegisterAniImageBox(PyObject * po, const char * c_szLayer);
CWindow * RegisterButton(PyObject * po, const char * c_szLayer);
CWindow * RegisterRadioButton(PyObject * po, const char * c_szLayer);
CWindow * RegisterToggleButton(PyObject * po, const char * c_szLayer);
CWindow * RegisterDragButton(PyObject * po, const char * c_szLayer);
CWindow * RegisterBox(PyObject * po, const char * c_szLayer);
CWindow * RegisterRenderTarget(PyObject * po, const char * c_szLayer);
CWindow * RegisterBar(PyObject * po, const char * c_szLayer);
CWindow * RegisterLine(PyObject * po, const char * c_szLayer);
CWindow * RegisterBar3D(PyObject * po, const char * c_szLayer);
CWindow * RegisterNumberLine(PyObject * po, const char * c_szLayer);
void DestroyWindow(CWindow * pWin);
void NotifyDestroyWindow(CWindow * pWindow);
BOOL IsAttaching();
DWORD GetAttachingType();
DWORD GetAttachingIndex();
DWORD GetAttachingSlotNumber();
void GetAttachingIconSize(BYTE * pbyWidth, BYTE * pbyHeight);
void AttachIcon(DWORD dwType, DWORD dwIndex, DWORD dwSlotNumber, BYTE byWidth, BYTE byHeight);
void DeattachIcon();
void SetAttachingFlag(BOOL bFlag);
void OnceIgnoreMouseLeftButtonUpEvent();
void LockWindow(CWindow * pWin);
void UnlockWindow();
void ActivateWindow(CWindow * pWin);
void DeactivateWindow();
CWindow * GetActivateWindow();
void SetTop(CWindow * pWin);
void SetTopUIWindow();
void ResetCapture();
void Update();
void Render();
void RunMouseMove(long x, long y);
void RunMouseLeftButtonDown(long x, long y);
void RunMouseLeftButtonUp(long x, long y);
void RunMouseLeftButtonDoubleClick(long x, long y);
void RunMouseRightButtonDown(long x, long y);
void RunMouseRightButtonUp(long x, long y);
void RunMouseRightButtonDoubleClick(long x, long y);
void RunMouseMiddleButtonDown(long x, long y);
void RunMouseMiddleButtonUp(long x, long y);
void RunKeyDown(int vkey);
void RunKeyUp(int vkey);
void RunPressEscapeKey();
void RunPressExitKey();
private:
void SetMousePosition(long x, long y);
CWindow * __PickWindow(long x, long y);
CWindow * __NewWindow(PyObject * po, DWORD dwWndType);
void __ClearReserveDeleteWindowList();
private:
long m_lWidth;
long m_lHeight;
int m_iVres;
int m_iHres;
long m_lMouseX, m_lMouseY;
long m_lDragX, m_lDragY;
long m_lPickedX, m_lPickedY;
BOOL m_bOnceIgnoreMouseLeftButtonUpEventFlag;
int m_iIgnoreEndTime;
PyObject * m_poMouseHandler;
BOOL m_bAttachingFlag;
DWORD m_dwAttachingType;
DWORD m_dwAttachingIndex;
DWORD m_dwAttachingSlotNumber;
BYTE m_byAttachingIconWidth;
BYTE m_byAttachingIconHeight;
CWindow * m_pActiveWindow;
TWindowContainer m_ActiveWindowList;
CWindow * m_pLockWindow;
TWindowContainer m_LockWindowList;
CWindow * m_pPointWindow;
CWindow * m_pLeftCaptureWindow;
CWindow * m_pRightCaptureWindow;
CWindow * m_pMiddleCaptureWindow;
TKeyCaptureWindowMap m_KeyCaptureWindowMap;
TWindowContainer m_ReserveDeleteWindowList;
TWindowContainer m_PickAlwaysWindowList;
CWindow * m_pRootWindow;
TWindowContainer m_LayerWindowList;
TLayerContainer m_LayerWindowMap;
};
PyObject * BuildEmptyTuple();
}
File diff suppressed because it is too large Load Diff
+76
View File
@@ -0,0 +1,76 @@
#pragma once
#include "legacy_cipher.h"
#include "../third_party/ava2-lzo/lzo1x.h"
#include <cstring>
#include <bit>
#include <map>
namespace ava2 {
struct ItemProtoRecord {
uint32_t vnum=0,range=0,refined=0;
uint32_t antiFlags=0,flags=0,wearFlags=0,immuneFlags=0,buyPrice=0,sellPrice=0;
uint16_t refineSet=0;
std::string name,internalName;
uint8_t type=0,subtype=0,size=0,weight=0,alterToMagicPercent=0,specular=0,gainSocketPercent=0;
std::array<int32_t,6> values{};
std::array<int32_t,8> sockets{};
std::array<std::pair<uint8_t,int32_t>,2> limits{};
std::array<std::pair<uint8_t,int32_t>,3> applies{};
};
class ItemProto {
public:
std::map<uint32_t,ItemProtoRecord> records;
std::vector<uint32_t> ranges;
const ItemProtoRecord* find(uint32_t id) const {
auto exact=records.find(id);if(exact!=records.end())return &exact->second;
for(auto base:ranges){auto it=records.find(base);if(it==records.end())continue;const auto& item=it->second;
if(item.vnum<id&&id<uint32_t(item.vnum+item.range))return &item;}
return nullptr;
}
bool load(const std::string& bytes) {
try {
auto input=std::span(reinterpret_cast<const uint8_t*>(bytes.data()),bytes.size());
if(input.size()<12)return false;
size_t base=12;uint32_t stride=176;bool legacy=false;
if(!std::memcmp(input.data(),"MIPX",4)){if(input.size()<20||wire::read32(input,4)!=1)return false;stride=wire::read32(input,8);base=20;}
else if(std::memcmp(input.data(),"MIPT",4))return false;
else legacy=true;
if(stride!=172&&stride!=176&&stride!=178)return false;
uint32_t count=wire::read32(input,base-8),block=wire::read32(input,base-4);
if(!count||block<20||block>input.size()-base)return false;
auto blob=input.subspan(base,block);if(std::memcmp(blob.data(),"MCOZ",4))return false;
uint32_t encrypted=wire::read32(blob,4),compressed=wire::read32(blob,8),real=wire::read32(blob,12);
if(real>64*1024*1024||(!legacy&&uint64_t(count)*stride!=real))return false;
wire::Bytes decoded;std::span<const uint8_t> packed;
if(encrypted){if(encrypted%8||encrypted>block-16)return false;decoded=wire::decrypt(blob.subspan(16,encrypted),{173217,72619434,408587239,27973291});if(decoded.size()<4||std::memcmp(decoded.data(),"MCOZ",4)||compressed>decoded.size()-4)return false;packed=std::span<const uint8_t>(decoded).subspan(4,compressed);}
else {if(compressed>block-20)return false;packed=blob.subspan(20,compressed);}
std::vector<uint8_t> raw(real);lzo_uint size=real;
if(lzo1x_decompress_safe(packed.data(),packed.size(),raw.data(),&size,nullptr)!=LZO_E_OK||size!=real)return false;
// AVA2's active ENABLE_PROTOSTRUCT_AUTODETECT leaves dwStride0 for MIPT.
// TItemTableAll::Process has no case0, so every destination stays zeroed.
if(legacy){records[0]=ItemProtoRecord{};return true;}
std::map<uint32_t,ItemProtoRecord> loaded;std::vector<uint32_t> loadedRanges;
for(uint32_t i=0;i<count;++i){auto r=std::span<const uint8_t>(raw).subspan(size_t(i)*stride,stride);size_t shift=stride==172?0:4;ItemProtoRecord item;
item.vnum=wire::read32(r,0);if(shift)item.range=wire::read32(r,4);
const char* name=reinterpret_cast<const char*>(r.data()+29+shift);item.name.assign(name,strnlen(name,25));
const char* internal=reinterpret_cast<const char*>(r.data()+4+shift);item.internalName.assign(internal,strnlen(internal,25));
item.type=r[54+shift];item.subtype=r[55+shift];item.size=r[57+shift];
item.weight=r[56+shift];
item.antiFlags=wire::read32(r,58+shift);item.flags=wire::read32(r,62+shift);
item.wearFlags=wire::read32(r,66+shift);item.immuneFlags=wire::read32(r,70+shift);
item.buyPrice=wire::read32(r,74+shift);item.sellPrice=wire::read32(r,78+shift);
for(size_t j=0;j<2;++j)item.limits[j]={r[82+shift+5*j],std::bit_cast<int32_t>(wire::read32(r,83+shift+5*j))};
for(size_t j=0;j<3;++j)item.applies[j]={r[92+shift+5*j],std::bit_cast<int32_t>(wire::read32(r,93+shift+5*j))};
for(size_t j=0;j<6;++j)item.values[j]=std::bit_cast<int32_t>(wire::read32(r,107+shift+4*j));
for(size_t j=0;j<8;++j)item.sockets[j]=std::bit_cast<int32_t>(wire::read32(r,131+shift+4*j));
item.refined=wire::read32(r,163+shift);item.refineSet=uint16_t(r[167+shift])|(uint16_t(r[168+shift])<<8);
item.alterToMagicPercent=r[169+shift];item.specular=r[170+shift];item.gainSocketPercent=r[171+shift];
if(item.range)loadedRanges.push_back(item.vnum);
loaded[item.vnum]=std::move(item);
}
for(auto& [id,item]:loaded)records[id]=std::move(item);
ranges.insert(ranges.end(),loadedRanges.begin(),loadedRanges.end());
return true;
}catch(const std::exception&){return false;}
}
};
}
+38
View File
@@ -0,0 +1,38 @@
#include "legacy_cipher.h"
#include <stdexcept>
namespace ava2::wire {
std::uint32_t read32(std::span<const std::uint8_t> b, std::size_t offset) {
if(offset>b.size() || b.size()-offset<4) throw std::out_of_range("wire u32 truncated");
std::uint32_t out=0; for(int i=0;i<4;++i) out|=std::uint32_t(b[offset+i])<<(8*i); return out;
}
void append32(Bytes& out, std::uint32_t v) { for(int i=0;i<4;++i) out.push_back(static_cast<std::uint8_t>(v>>(8*i))); }
Key locale_key() { constexpr char text[]="1234abcd5678efgh"; Key key{}; for(int i=0;i<16;++i) key[i/4]|=std::uint32_t(text[i])<<(8*(i%4)); return key; }
// Original EterBase/tea.cpp calls this TEA; its round function is XTEA.
// In AVA2 NetStream, encryption/decryption operates on 8-byte blocks with zero-padded resizing.
static Bytes transform(std::span<const std::uint8_t> input, const Key& key, bool reverse) {
if(reverse && input.size()%8) throw std::invalid_argument("ciphertext must contain complete 8-byte blocks");
Bytes padded(input.begin(),input.end()), out; padded.resize((padded.size()+7)/8*8,0); out.reserve(padded.size());
for(std::size_t i=0;i<padded.size();i+=8) {
std::uint32_t y=read32(padded,i), z=read32(padded,i+4), sum=reverse?0xc6ef3720u:0;
for(int n=0;n<32;++n) {
if(!reverse) { y+=((z<<4 ^ z>>5)+z)^(sum+key[sum&3]); sum+=0x9e3779b9u; z+=((y<<4 ^ y>>5)+y)^(sum+key[(sum>>11)&3]); }
else { z-=((y<<4 ^ y>>5)+y)^(sum+key[(sum>>11)&3]); sum-=0x9e3779b9u; y-=((z<<4 ^ z>>5)+z)^(sum+key[sum&3]); }
}
append32(out,y); append32(out,z);
}
return out;
}
Bytes encrypt(std::span<const std::uint8_t> b,const Key& k) { return transform(b,k,false); }
Bytes decrypt(std::span<const std::uint8_t> b,const Key& k) { return transform(b,k,true); }
Key derive_receive_key(const Key& client) {
Bytes table(1938*4,0); std::uint32_t seed=1491971513u;
// The original loop re-evaluates BYTE(seed) each iteration.
for(std::size_t i=0;i<static_cast<std::uint8_t>(seed);++i) {
seed^=2148941891u; seed+=3592385981u;
for(int j=0;j<4;++j) table[i*4+j]=static_cast<std::uint8_t>(seed>>(8*j));
}
Key derived{}; for(int i=0;i<4;++i) derived[i]=read32(table,37+i*4);
Bytes serialized; for(auto v:client) append32(serialized,v);
auto cipher=encrypt(serialized,derived); for(int i=0;i<4;++i) derived[i]=read32(cipher,i*4); return derived;
}
}
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include "protocol.h"
#include <array>
#include <span>
namespace ava2::wire {
using Key = std::array<std::uint32_t,4>;
Key locale_key();
Key derive_receive_key(const Key& client);
Bytes encrypt(std::span<const std::uint8_t> plain, const Key& key);
Bytes decrypt(std::span<const std::uint8_t> cipher, const Key& key);
std::uint32_t read32(std::span<const std::uint8_t> bytes, std::size_t offset);
void append32(Bytes& out, std::uint32_t value);
}
+89
View File
@@ -0,0 +1,89 @@
#include "login_session.h"
#include <sys/socket.h>
#include <netdb.h>
#include <poll.h>
#include <fcntl.h>
#include <unistd.h>
#include <cerrno>
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <random>
#include <stdexcept>
#include <string>
namespace {
struct Socket {
int fd=-1;
~Socket() { if(fd>=0) close(fd); }
void connect_to(const char* host,const char* port) {
if(fd>=0) { close(fd);fd=-1; }
addrinfo hint{};hint.ai_socktype=SOCK_STREAM;hint.ai_family=AF_UNSPEC;addrinfo* result=nullptr;
if(getaddrinfo(host,port,&hint,&result)!=0) throw std::runtime_error("cannot resolve endpoint");
std::unique_ptr<addrinfo,decltype(&freeaddrinfo)> addresses(result,freeaddrinfo);
for(auto* a=result;a;a=a->ai_next) {
fd=socket(a->ai_family,a->ai_socktype,a->ai_protocol);if(fd<0) continue;
#ifdef SO_NOSIGPIPE
int one=1;setsockopt(fd,SOL_SOCKET,SO_NOSIGPIPE,&one,sizeof(one));
#endif
int original_flags=fcntl(fd,F_GETFL,0);
if(original_flags<0 || fcntl(fd,F_SETFL,original_flags|O_NONBLOCK)<0) { close(fd);fd=-1;continue; }
int connected=connect(fd,a->ai_addr,a->ai_addrlen);
if(connected<0 && errno==EINPROGRESS) {
pollfd writable{fd,POLLOUT,0};int ready=poll(&writable,1,5000);
int error=0;socklen_t size=sizeof(error);
connected=(ready>0 && getsockopt(fd,SOL_SOCKET,SO_ERROR,&error,&size)==0 && error==0)?0:-1;
}
if(connected==0 && fcntl(fd,F_SETFL,original_flags)==0) {
timeval timeout{5,0};setsockopt(fd,SOL_SOCKET,SO_SNDTIMEO,&timeout,sizeof(timeout));return;
}
close(fd);fd=-1;
}
throw std::runtime_error("cannot connect endpoint");
}
void send_all(const ava2::wire::Bytes& bytes) {
std::size_t offset=0;
while(offset<bytes.size()) {
#ifdef MSG_NOSIGNAL
constexpr int flags=MSG_NOSIGNAL;
#else
constexpr int flags=0;
#endif
auto n=send(fd,bytes.data()+offset,bytes.size()-offset,flags);
if(n<0 && errno==EINTR) continue;
if(n<=0) throw std::runtime_error("send failed");offset+=n;
}
}
};
}
int main(int argc,char** argv) {
if(argc!=6) { std::cerr<<"Usage: ava2_login AUTH_HOST AUTH_PORT GAME_HOST GAME_PORT ACCOUNT\nPassword is read from AVA2_PASSWORD; no default server.\n";return 2; }
const char* password=std::getenv("AVA2_PASSWORD");if(!password) { std::cerr<<"AVA2_PASSWORD is required\n";return 2; }
try {
std::random_device random;ava2::wire::Key key{};for(auto& word:key) word=random();
ava2::LoginSession session(argv[5],password,key);unsetenv("AVA2_PASSWORD");Socket socket;socket.connect_to(argv[1],argv[2]);
auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(15);
while(std::chrono::steady_clock::now()<deadline) {
pollfd readable{socket.fd,POLLIN,0};int ready=poll(&readable,1,100);
if(ready<0 && errno==EINTR) continue;if(ready<0) throw std::runtime_error("poll failed");
if(!ready) continue;
std::uint8_t buffer[4096];auto n=recv(socket.fd,buffer,sizeof(buffer),0);
if(n<0 && errno==EINTR) continue;if(n<=0) throw std::runtime_error("server disconnected before selection");
session.feed({buffer,static_cast<std::size_t>(n)});
for(const auto& bytes:session.take_output()) socket.send_all(bytes);
if(session.state()==ava2::LoginSession::State::Failed) throw std::runtime_error(session.failure());
if(session.state()==ava2::LoginSession::State::Authenticated) {
std::cout<<"Authentication accepted; connecting game endpoint\n";
session.begin_game();socket.connect_to(argv[3],argv[4]);
}
if(session.state()==ava2::LoginSession::State::Selecting) {
std::cout<<"Select phase: "<<session.characters().size()<<" slots\n";
for(std::size_t i=0;i<session.characters().size();++i) {
auto& c=session.characters()[i];std::cout<<"slot="<<i<<" id="<<c.id<<" name="<<c.name<<" level="<<unsigned(c.level)<<" job="<<unsigned(c.job)<<"\n";
}
return 0;
}
}
throw std::runtime_error("login timed out");
} catch(const std::exception& error) { std::cerr<<"Login failed: "<<error.what()<<"\n";return 1; }
}
+157
View File
@@ -0,0 +1,157 @@
#include "login_client.h"
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <poll.h>
#include <fcntl.h>
#include <unistd.h>
#include <atomic>
#include <cerrno>
#include <cstring>
#include <mutex>
#include <random>
#include <stdexcept>
#include <algorithm>
#include <thread>
namespace ava2 {
struct LoginClient::Resolution {
struct Address { sockaddr_storage address{}; socklen_t size=0; int family=0; };
std::atomic<bool> ready{false}; std::vector<Address> addresses; std::string error;
};
LoginClient::~LoginClient() {
close_socket();
}
void LoginClient::close_socket() { if(fd_>=0) close(fd_);fd_=-1; }
void LoginClient::cancel() {
++generation_;close_socket();resolution_.reset();session_.reset();outgoing_.clear();events_.clear();send_offset_=0;status_=Status::Idle;direct_enter_=false;
}
void LoginClient::notify(EventType type,std::string reason,bool connection_failure) { events_.push_back({type,std::move(reason),connection_failure,generation_}); }
void LoginClient::fail(std::string reason,bool connection_failure) {
if(status_==Status::Failed) return;
close_socket();resolution_.reset();outgoing_.clear();status_=Status::Failed;auto type=on_game_ && reason=="server disconnected"?EventType::RemoteDisconnect:EventType::Failure;notify(type,std::move(reason),connection_failure);
}
void LoginClient::connect(Endpoint auth,Endpoint game,std::string account,std::string password) {
if(auth.host.empty() || game.host.empty() || auth.port<1 || auth.port>65535 || game.port<1 || game.port>65535) throw std::invalid_argument("invalid auth/game endpoint");
std::random_device random;wire::Key key{};for(auto& v:key) v=random();
auto candidate=std::make_unique<LoginSession>(std::move(account),std::move(password),key);
cancel();session_=std::move(candidate);game_=std::move(game);on_game_=false;handshake_notified_=false;login_notified_=selection_notified_=loading_notified_=false;
deadline_=std::chrono::steady_clock::now()+std::chrono::seconds(15);start_endpoint(auth);
}
void LoginClient::start_endpoint(const Endpoint& endpoint) {
close_socket();outgoing_.clear();send_offset_=0;address_index_=0;
resolution_=std::make_shared<Resolution>();status_=Status::Resolving;
// Each request owns its result; cancelled/old DNS requests cannot touch client state.
auto result=resolution_;
std::thread([result,endpoint] {
addrinfo hint{};hint.ai_family=AF_UNSPEC;hint.ai_socktype=SOCK_STREAM;
addrinfo* list=nullptr;auto service=std::to_string(endpoint.port);
int code=getaddrinfo(endpoint.host.c_str(),service.c_str(),&hint,&list);
if(code) result->error="cannot resolve endpoint";
else {
for(auto* a=list;a;a=a->ai_next) {
if(a->ai_addrlen>sizeof(sockaddr_storage)) continue;
Resolution::Address copy;copy.family=a->ai_family;copy.size=a->ai_addrlen;std::memcpy(&copy.address,a->ai_addr,a->ai_addrlen);result->addresses.push_back(copy);
}
freeaddrinfo(list);
}
result->ready.store(true,std::memory_order_release);
}).detach();
}
bool LoginClient::try_next_address() {
close_socket();
while(address_index_<resolution_->addresses.size()) {
const auto& a=resolution_->addresses[address_index_++];fd_=socket(a.family,SOCK_STREAM,0);if(fd_<0) continue;
int flags=fcntl(fd_,F_GETFL,0);if(flags<0 || fcntl(fd_,F_SETFL,flags|O_NONBLOCK)<0) { close_socket();continue; }
#ifdef SO_NOSIGPIPE
int one=1;setsockopt(fd_,SOL_SOCKET,SO_NOSIGPIPE,&one,sizeof(one));
#endif
int rc=::connect(fd_,reinterpret_cast<const sockaddr*>(&a.address),a.size);
if(rc==0) { status_=Status::Authenticating;return true; }
if(errno==EINPROGRESS) { status_=Status::Connecting;return true; }
close_socket();
}
fail("cannot connect endpoint",true);return false;
}
void LoginClient::enqueue() {
for(auto& bytes:session_->take_output()) outgoing_.push_back(std::move(bytes));
std::size_t total=0;for(const auto& bytes:outgoing_) total+=bytes.size();
if(total>128*1024) fail("send queue limit exceeded");
}
void LoginClient::flush() {
// Limit work per frame and retain unsent suffixes across EAGAIN/short writes.
std::size_t budget=64*1024;
while(!outgoing_.empty() && budget && fd_>=0) {
auto& bytes=outgoing_.front();auto count=std::min(budget,bytes.size()-send_offset_);
#ifdef MSG_NOSIGNAL
constexpr int flags=MSG_NOSIGNAL;
#else
constexpr int flags=0;
#endif
auto n=send(fd_,bytes.data()+send_offset_,count,flags);
if(n<0 && errno==EINTR) continue;
if(n<0 && (errno==EWOULDBLOCK || errno==EAGAIN)) return;
if(n<=0) { fail("connection lost while sending");return; }
send_offset_+=n;budget-=n;if(send_offset_==bytes.size()) { outgoing_.pop_front();send_offset_=0; }
}
}
void LoginClient::pump() {
if(status_==Status::Idle || status_==Status::Failed) return;
if(status_!=Status::Selecting && status_!=Status::Loading && std::chrono::steady_clock::now()>deadline_) { fail("connection timed out",status_==Status::Resolving || status_==Status::Connecting);return; }
if(status_==Status::Resolving) {
if(!resolution_->ready.load(std::memory_order_acquire)) return;
if(!resolution_->error.empty()) { fail(resolution_->error,true);return; }
if(!try_next_address()) return;
}
if(status_==Status::Connecting) {
pollfd writable{fd_,POLLOUT,0};int ready=poll(&writable,1,0);if(ready<0 && errno==EINTR) return;
if(ready<0) { fail("connect poll failed",true);return; }if(!ready) return;
int error=0;socklen_t size=sizeof(error);
if(getsockopt(fd_,SOL_SOCKET,SO_ERROR,&error,&size)!=0 || error) { if(!try_next_address() || status_==Status::Connecting) return; }
else status_=Status::Authenticating;
}
flush();if(status_==Status::Failed) return;
for(int iteration=0;iteration<16;++iteration) {
std::uint8_t buffer[4096];auto n=recv(fd_,buffer,sizeof(buffer),0);
if(n<0 && errno==EINTR) continue;
if(n<0 && (errno==EAGAIN || errno==EWOULDBLOCK)) break;
if(n<=0) { fail("server disconnected");return; }
session_->feed({buffer,static_cast<std::size_t>(n)});enqueue();if(status_==Status::Failed) return;
if(session_->state()==LoginSession::State::Failed) { fail(session_->failure());return; }
if(session_->state()==LoginSession::State::Authenticated && !on_game_) {
on_game_=true;session_->begin_game();start_endpoint(game_);return;
}
if(on_game_ && session_->handshake_phase_entered() && !handshake_notified_) { handshake_notified_=true;if(!direct_enter_) notify(EventType::Handshake); }
if(on_game_ && session_->game_login_sent() && !login_notified_) { login_notified_=true;if(!direct_enter_) notify(EventType::LoginStart); }
if(session_->state()==LoginSession::State::Selecting && !selection_notified_) {
selection_notified_=true;status_=Status::Selecting;notify(direct_enter_?EventType::DirectEnterReady:EventType::SelectReady);
}
if(session_->state()==LoginSession::State::Loading && !loading_notified_) {
loading_notified_=true;status_=Status::Loading;notify(EventType::Loading);return;
}
flush();if(status_==Status::Failed) return;
}
}
wire::Bytes LoginClient::take_game_input() { return session_?session_->take_game_input():wire::Bytes{}; }
void LoginClient::send_game_packet(wire::Bytes packet) {
if(status_!=Status::Loading || !session_) throw std::logic_error("game transport is not ready");
session_->send_game_packet(std::move(packet));enqueue();flush();
}
void LoginClient::direct_enter(std::uint8_t slot) {
if(!session_ || status_!=Status::Selecting || slot>=session_->characters().size() || !session_->characters()[slot].id)
throw std::invalid_argument("DirectEnter requires an occupied character slot");
const auto character=session_->characters()[slot];
// Windows CNetworkAddress::Set(DWORD) copies the little-endian wire DWORD to sin_addr.
in_addr address{};address.s_addr=character.address;
char host[INET_ADDRSTRLEN]{};
if(!character.address || !character.port || !inet_ntop(AF_INET,&address,host,sizeof(host)))
throw std::invalid_argument("character server endpoint is missing");
session_->reconnect_game();
direct_enter_=true;handshake_notified_=false;login_notified_=selection_notified_=loading_notified_=false;
deadline_=std::chrono::steady_clock::now()+std::chrono::seconds(15);
start_endpoint({host,character.port});
}
void LoginClient::select(std::uint8_t slot) {
if(!session_) throw std::logic_error("not connected");session_->select(slot);status_=Status::Entering;deadline_=std::chrono::steady_clock::now()+std::chrono::seconds(15);enqueue();
}
std::vector<LoginClient::Event> LoginClient::take_events() { auto events=std::move(events_);events_.clear();return events; }
}
+54
View File
@@ -0,0 +1,54 @@
#pragma once
#include "login_session.h"
#include <chrono>
#include <deque>
#include <memory>
#include <thread>
namespace ava2 {
class LoginClient {
public:
struct Endpoint { std::string host; int port=0; };
enum class Status { Idle, Resolving, Connecting, Authenticating, Selecting, Entering, Loading, Failed };
enum class EventType { Handshake, RemoteDisconnect, LoginStart, SelectReady, DirectEnterReady, Loading, Failure };
struct Event { EventType type; std::string reason; bool connection_failure=false; std::uint64_t generation=0; };
LoginClient()=default;
~LoginClient();
LoginClient(const LoginClient&)=delete;
LoginClient& operator=(const LoginClient&)=delete;
void connect(Endpoint auth,Endpoint game,std::string account,std::string password);
void cancel();
void pump(); // no blocking socket operation or DNS lookup on the caller thread
void select(std::uint8_t slot);
void direct_enter(std::uint8_t slot);
wire::Bytes take_game_input();
void send_game_packet(wire::Bytes packet);
std::vector<Event> take_events();
Status status() const { return status_; }
const LoginSession* session() const { return session_.get(); }
bool is_connected() const { return on_game_ && fd_>=0 && (status_==Status::Authenticating || status_==Status::Selecting || status_==Status::Entering || status_==Status::Loading); }
bool is_direct_enter() const { return direct_enter_; }
std::uint64_t generation() const { return generation_; }
private:
struct Resolution;
void start_endpoint(const Endpoint& endpoint);
bool try_next_address();
void close_socket();
void flush();
void enqueue();
void fail(std::string reason,bool connection_failure=false);
void notify(EventType type,std::string reason={},bool connection_failure=false);
int fd_=-1; std::size_t address_index_=0;
Status status_=Status::Idle;
std::unique_ptr<LoginSession> session_;
std::shared_ptr<Resolution> resolution_;
Endpoint game_;
bool direct_enter_=false;
bool handshake_notified_=false;
bool on_game_=false, login_notified_=false, selection_notified_=false, loading_notified_=false;
std::uint64_t generation_=0;
std::deque<wire::Bytes> outgoing_;
std::size_t send_offset_=0;
std::vector<Event> events_;
std::chrono::steady_clock::time_point deadline_;
};
}
+137
View File
@@ -0,0 +1,137 @@
#include "login_session.h"
#include <algorithm>
#include <stdexcept>
namespace ava2 {
using namespace wire;
namespace {
constexpr std::uint8_t sequences[]={
#include "sequence_table.inc"
};
void text(Bytes& out,const std::string& value,std::size_t max) {
auto start=out.size(); out.resize(start+max+1,0); std::copy(value.begin(),value.end(),out.begin()+start);
}
std::string string_at(std::span<const std::uint8_t> b,std::size_t offset,std::size_t width) {
auto end=std::find(b.begin()+offset,b.begin()+offset+width,0); return {b.begin()+offset,end};
}
}
LoginSession::LoginSession(std::string account,std::string password,Key client)
:account_(std::move(account)),password_(std::move(password)),client_key_(client),receive_key_(derive_receive_key(client)),tx_(locale_key()),rx_(locale_key()) {
if(account_.empty() || account_.size()>30 || password_.empty() || password_.size()>16 || account_.find('\0')!=std::string::npos || password_.find('\0')!=std::string::npos)
throw std::invalid_argument("AVA2 account/password must fit 30/16-byte fields without NUL");
}
LoginSession::~LoginSession() { clear_password(); }
void LoginSession::clear_password() { volatile char* p=password_.empty()?nullptr:password_.data(); for(std::size_t i=0;i<password_.size();++i) p[i]=0; password_.clear(); }
void LoginSession::fail(std::string reason) { failure_=std::move(reason); state_=State::Failed; clear_password(); output_.clear(); }
void LoginSession::begin_game() {
if(state_!=State::Authenticated) throw std::logic_error("game connection requires successful authentication");
game_=true; handshake_phase_entered_=false; encrypted_=false; sequence_=0; raw_.clear(); plain_.clear(); output_.clear(); tx_=rx_=locale_key(); state_=State::Handshake;
}
void LoginSession::reconnect_game() {
if(state_!=State::Selecting) throw std::logic_error("DirectEnter requires a selected account session");
handshake_phase_entered_=false;encrypted_=false; sequence_=0; raw_.clear(); plain_.clear(); output_.clear();
tx_=rx_=locale_key(); state_=State::Handshake;
roster_received_=select_phase_received_=game_login_sent_=false;
}
void LoginSession::emit(Bytes bytes,bool sequence) {
if(sequence) { bytes.push_back(sequences[sequence_]); sequence_=(sequence_+1)%std::size(sequences); }
output_.push_back(encrypted_?encrypt(bytes,tx_):std::move(bytes));
}
std::vector<Bytes> LoginSession::take_output() { auto out=std::move(output_); output_.clear(); return out; }
void LoginSession::feed(std::span<const std::uint8_t> input) {
if(state_==State::Failed) return;
if(input.size()>128*1024 || raw_.size()+plain_.size()+input.size()>128*1024) { fail("receive buffer limit exceeded"); return; }
raw_.insert(raw_.end(),input.begin(),input.end());
while(!raw_.empty() && state_!=State::Failed) {
std::size_t n=encrypted_?8:1;
if(raw_.size()<n) break;
Bytes next(raw_.begin(),raw_.begin()+n); raw_.erase(raw_.begin(),raw_.begin()+n);
if(encrypted_) next=decrypt(next,rx_);
plain_.insert(plain_.end(),next.begin(),next.end());
while(state_!=State::Failed && process_packet()) {}
}
}
bool LoginSession::process_packet() {
if(plain_.empty() || state_==State::Loading) return false;
auto header=plain_[0]; std::size_t size=0;
switch(header) {
case 0:size=1;break; case 253:size=2;break; case 255:size=13;break; case 44:size=1;break;
case 254:size=7;break; // legacy UDP binding, not used by this TCP bootstrap
case 151:size=289;break; // Panama pack IV metadata
case 152: case 153:
if(plain_.size()<7) return false;
size=plain_[1]|(std::size_t(plain_[2])<<8);
if(size<7 || read32(plain_,3)!=size-7) { fail("invalid pack metadata packet length");return false; }
break;
case 150:size=6;break; case 7:size=10;break; case 90:size=2;break;
case 32:size=444;break; // 5 * (70-byte player + 4-byte guild id + 13-byte guild name) + 9
default:fail("unsupported login packet header "+std::to_string(header));return false;
}
if(plain_.size()<size) return false;
Bytes packet(plain_.begin(),plain_.begin()+size); plain_.erase(plain_.begin(),plain_.begin()+size);
if(header==0 || header==254) return true;
if(header==151 || header==152 || header==153) {
std::size_t stored=0; for(const auto& metadata:pack_metadata_) stored+=metadata.size();
if(stored+packet.size()>128*1024) { fail("pack metadata limit exceeded");return false; }
// Retained for a future encrypted-pack backend; decoded assets require no IV application.
pack_metadata_.push_back(std::move(packet));return true;
}
if(header==255) {
auto time=read32(packet,5),delta=read32(packet,9);
Bytes reply{255};append32(reply,read32(packet,1));append32(reply,time+delta+delta);append32(reply,0);emit(std::move(reply),false);
} else if(header==44) { emit({254},encrypted_); }
else if(header==7) { fail(string_at(packet,1,9)); }
else if(header==253) {
auto phase=packet[1];
if(phase==0) { fail("server closed connection"); }
else if(phase==1 && state_==State::Handshake) { handshake_phase_entered_=true; }
else if(phase==10 && !game_ && state_==State::Handshake) {
encrypted_=true; state_=State::Authenticating;
Bytes login{111};text(login,account_,30);text(login,password_,16); for(auto v:client_key_) append32(login,v);
clear_password();emit(std::move(login),true);
} else if(phase==2 && game_ && state_==State::Handshake) {
encrypted_=true; state_=State::LoggingIn; game_login_sent_=true;
Bytes login{109};text(login,account_,30);append32(login,login_key_);for(auto v:client_key_) append32(login,v);
emit(std::move(login),true);tx_=client_key_;rx_=receive_key_;
} else if(phase==3 && game_ && state_==State::LoggingIn) { select_phase_received_=true; if(roster_received_) state_=State::Selecting; }
else if(phase==4 && game_ && state_==State::Entering) { state_=State::Loading; }
else { fail("unexpected login phase "+std::to_string(phase)); }
} else if(header==150) {
if(game_ || state_!=State::Authenticating) fail("authentication result in wrong state");
else if(!packet[5] || read32(packet,1)==0) fail("BESAMEKEY");
else { login_key_=read32(packet,1);state_=State::Authenticated; }
} else if(header==32) {
if(!game_ || state_!=State::LoggingIn) { fail("character roster in wrong state"); return false; }
characters_.clear();
for(std::size_t i=0;i<5;++i) {
std::size_t o=1+i*70; Character c;
c.id=read32(packet,o);c.name=string_at(packet,o+4,25);c.job=packet[o+29];c.level=packet[o+30];
c.play_minutes=read32(packet,o+31);c.strength=packet[o+35];c.health=packet[o+36];c.dexterity=packet[o+37];c.intelligence=packet[o+38];
c.main_part=packet[o+39]|(std::uint16_t(packet[o+40])<<8);c.change_name=packet[o+41];
c.hair_part=packet[o+42]|(std::uint16_t(packet[o+43])<<8);c.sash_part=packet[o+44]|(std::uint16_t(packet[o+45])<<8);
c.guild_id=read32(packet,351+i*4);c.guild_name=string_at(packet,371+i*13,13);
for(std::size_t j=0;j<4;++j) c.sungma[j]=packet[o+66+j];
c.x=static_cast<std::int32_t>(read32(packet,o+50));c.y=static_cast<std::int32_t>(read32(packet,o+54));
c.address=read32(packet,o+58);c.port=packet[o+62]|(std::uint16_t(packet[o+63])<<8);c.skill_group=packet[o+64];c.conqueror_level=packet[o+65];characters_.push_back(std::move(c));
}
roster_received_=true; if(select_phase_received_) state_=State::Selecting;
} else if(header==90) {
if(!game_ || (state_!=State::LoggingIn && state_!=State::Selecting)) fail("empire packet in wrong state");
else empire_=packet[1];
}
return true;
}
wire::Bytes LoginSession::take_game_input() {
if(state_!=State::Loading) return {};
auto bytes=std::move(plain_);plain_.clear();return bytes;
}
void LoginSession::send_game_packet(wire::Bytes packet) {
if(state_!=State::Loading) throw std::logic_error("game packet before loading handoff");
if(packet.empty() || packet.size()>65535) throw std::invalid_argument("invalid game packet size");
emit(std::move(packet),true);
}
void LoginSession::select(std::uint8_t slot) {
if(state_!=State::Selecting) throw std::logic_error("selection requires character roster and select phase");
if(slot>=characters_.size() || characters_[slot].id==0) throw std::invalid_argument("cannot select an empty character slot");
emit(select_character(slot),true);state_=State::Entering;
}
}
+52
View File
@@ -0,0 +1,52 @@
#pragma once
#include "legacy_cipher.h"
#include <string>
#include <vector>
namespace ava2 {
struct Character {
std::uint32_t id=0; std::string name; std::uint8_t job=0, level=0, skill_group=0, conqueror_level=0;
std::uint32_t play_minutes=0, guild_id=0; std::string guild_name;
std::uint8_t strength=0, health=0, dexterity=0, intelligence=0, change_name=0;
std::uint16_t main_part=0, hair_part=0, sash_part=0;
std::array<std::uint8_t,4> sungma{};
std::int32_t x=0,y=0; std::uint32_t address=0; std::uint16_t port=0;
};
class LoginSession {
public:
enum class State { Handshake, Authenticating, Authenticated, LoggingIn, Selecting, Entering, Loading, Failed };
LoginSession(std::string account,std::string password,wire::Key client_key);
~LoginSession();
void begin_game();
void reconnect_game();
void feed(std::span<const std::uint8_t> input);
std::vector<wire::Bytes> take_output();
void select(std::uint8_t slot);
wire::Bytes take_game_input();
void send_game_packet(wire::Bytes packet);
State state() const { return state_; }
const std::string& failure() const { return failure_; }
const std::vector<wire::Bytes>& pack_metadata() const { return pack_metadata_; }
const std::vector<Character>& characters() const { return characters_; }
bool handshake_phase_entered() const { return handshake_phase_entered_; }
bool game_login_sent() const { return game_login_sent_; }
std::uint8_t empire() const { return empire_; }
std::uint32_t login_key() const { return login_key_; }
private:
bool process_packet();
void emit(wire::Bytes bytes,bool sequence);
void fail(std::string reason);
void clear_password();
State state_=State::Handshake;
bool handshake_phase_entered_=false;
bool game_=false, encrypted_=false, roster_received_=false, select_phase_received_=false, game_login_sent_=false;
std::uint8_t empire_=0;
std::string account_,password_,failure_;
wire::Key client_key_,receive_key_,tx_,rx_;
std::uint32_t login_key_=0;
std::size_t sequence_=0;
wire::Bytes raw_,plain_;
std::vector<wire::Bytes> output_;
std::vector<Character> characters_;
std::vector<wire::Bytes> pack_metadata_;
};
}
+1825
View File
File diff suppressed because it is too large Load Diff
+30
View File
@@ -0,0 +1,30 @@
#pragma once
#include <cstdint>
#include <sstream>
#include <string>
#include <vector>
namespace ava2 {
// AVA2 MapManager::__LoadMapInfoVector and PythonBackground coordinate rules.
struct AtlasMap { std::string name; uint32_t x,y,endX,endY; };
class MapCoordinates {
public:
std::vector<AtlasMap> maps;
uint32_t baseX=0,baseY=0;
void load(const std::string& text) {
maps.clear(); std::istringstream input(text); std::string line;
while(std::getline(input,line)) {
std::istringstream row(line); std::string name; uint32_t x,y,w,h;
if(row>>name>>x>>y>>w>>h) maps.push_back({name,x,y,x+w*25600u,y+h*25600u});
}
}
const AtlasMap* find(uint32_t x,uint32_t y) const {
for(const auto& map:maps) if(x>=map.x && x<map.endX && y>=map.y && y<map.endY) return &map;
return nullptr;
}
static int32_t signedBits(uint32_t n) {
return n<=0x7fffffffu?static_cast<int32_t>(n):static_cast<int32_t>(int64_t(n)-0x100000000ll);
}
void toLocal(int32_t& x,int32_t& y) const { x=signedBits(uint32_t(x)-baseX); y=signedBits(uint32_t(y)-baseY); }
void toGlobal(int32_t& x,int32_t& y) const { x=signedBits(uint32_t(x)+baseX); y=signedBits(uint32_t(y)+baseY); }
};
}
+56
View File
@@ -0,0 +1,56 @@
#include "nonplayer_data.h"
#include "legacy_cipher.h"
#include "../third_party/ava2-lzo/lzo1x.h"
#include <cstring>
namespace ava2 {
NonPlayerData& NonPlayerData::Instance() { static NonPlayerData data; return data; }
const MobRecord* NonPlayerData::get(uint32_t vnum) const { auto it=records.find(vnum);return it==records.end()?nullptr:&it->second; }
bool UseNonPlayerName(uint32_t race) {
if(race>=30000 && race<=30020) return false;
static const uint32_t excluded[]={20101,20102,20103,20104,20105,20106,20107,20108,20109,0,1,2,3,4,5,6,7,8,9,34041,34042,34043,34044,34045,34046,34047,34048,34049,34050,34051,34052,34053,34054,34001,34003,34009,34010,34011,34012,34008,34007,34005,34006,34016,34023,34024,34025,34026,34027,34028,34021,34022,34015};
for(auto value:excluded) if(value==race) return false;
return true;
}
bool GetNonPlayerName(uint32_t race,std::string& name) { const auto* mob=NonPlayerData::Instance().get(race);if(!mob) return false;name=mob->name;return true; }
bool NonPlayerData::load(const std::string& data) {
// Original PythonNonPlayer::LoadNonPlayerData key and EterBase MCOZ layout.
try {
auto input=std::span(reinterpret_cast<const uint8_t*>(data.data()),data.size());
if(input.size()<32 || std::memcmp(input.data(),"MMPT",4) || std::memcmp(input.data()+12,"MCOZ",4)) return false;
uint32_t count=wire::read32(input,4),block=wire::read32(input,8);
uint32_t encrypted=wire::read32(input,16),compressed=wire::read32(input,20),real=wire::read32(input,24);
if(!count || real>64*1024*1024 || block>input.size()-12 || block<20) return false;
wire::Bytes decoded;
std::span<const uint8_t> packed;
if(encrypted) {
if(encrypted%8 || encrypted>block-16 || encrypted<4) return false;
decoded=wire::decrypt(input.subspan(28,encrypted),{4813894,18955,552631,6822045});
if(decoded.size()<4 || std::memcmp(decoded.data(),"MCOZ",4) || compressed>decoded.size()-4) return false;
packed=std::span<const uint8_t>(decoded).subspan(4,compressed);
} else {
if(compressed>block-20) return false;
packed=input.subspan(32,compressed);
}
std::vector<uint8_t> raw(real);lzo_uint size=raw.size();
if(lzo1x_decompress_safe(packed.data(),packed.size(),raw.data(),&size,nullptr)!=LZO_E_OK || size!=real || real%count) return false;
uint32_t stride=real/count;
// Original TMobTableAll::Process copies destination fields by source index.
if(stride!=235 && stride!=255 && stride!=256 && stride!=262 && stride!=263) return false;
const size_t prefixShift=stride>=262?1:0; // bLvlPct inserted before bSize.
const size_t resistShift=stride>=262?2:(stride==256?1:0);
std::vector<MobRecord> loaded;loaded.reserve(count);
for(uint32_t i=0;i<count;++i) {
auto row=std::span<const uint8_t>(raw).subspan(i*stride,stride);MobRecord m;
m.vnum=wire::read32(row,0);const char* name=reinterpret_cast<const char*>(row.data()+29);
m.name.assign(name,strnlen(name,25));m.type=row[54];m.rank=row[55];m.level=row[57];
m.goldMin=wire::read32(row,59+prefixShift);m.goldMax=wire::read32(row,63+prefixShift);m.exp=wire::read32(row,67+prefixShift);m.hp=wire::read32(row,71+prefixShift);
m.regenCycle=row[75+prefixShift];m.regenPercent=row[76+prefixShift];m.raceFlags=wire::read32(row,83+prefixShift);m.st=row[91+prefixShift];m.dx=row[92+prefixShift];
m.damageMin=wire::read32(row,95+prefixShift);m.damageMax=wire::read32(row,99+prefixShift);m.event=row[138+prefixShift+resistShift];
for(int j=0;j<11;++j) m.resists[j]=row[118+prefixShift+j]<128?row[118+prefixShift+j]:int(row[118+prefixShift+j])-256;
uint32_t bits=wire::read32(row,205+prefixShift+resistShift);std::memcpy(&m.damageMultiply,&bits,4);loaded.push_back(std::move(m));
}
for(auto& m:loaded) records.emplace(m.vnum,std::move(m)); // Original insert preserves first record.
return true;
} catch(const std::exception&) { return false; }
}
}
+27
View File
@@ -0,0 +1,27 @@
#pragma once
#include <cstdint>
#include <string>
#include <map>
#include <vector>
namespace ava2 {
struct MobRecord {
uint32_t vnum=0; std::string name;
uint8_t type=0,rank=0,level=0,event=0;
uint32_t hp=0,exp=0,raceFlags=0,damageMin=0,damageMax=0,goldMin=0,goldMax=0;
uint8_t regenCycle=0,regenPercent=0,st=0,dx=0;
float damageMultiply=0;
int8_t resists[11]={};
};
class NonPlayerData {
public:
static NonPlayerData& Instance();
bool load(const std::string& data);
const MobRecord* get(uint32_t vnum) const;
void clear() { records.clear(); }
const std::map<uint32_t,MobRecord>& all() const { return records; }
private:
std::map<uint32_t,MobRecord> records;
};
bool UseNonPlayerName(uint32_t race);
bool GetNonPlayerName(uint32_t race,std::string& name);
}
+111
View File
@@ -0,0 +1,111 @@
#include "protocol.h"
#include <stdexcept>
#include <cstring>
namespace ava2::wire {
namespace {
void u16(Bytes& out, std::uint16_t v) {
out.push_back(static_cast<std::uint8_t>(v & 0xFF));
out.push_back(static_cast<std::uint8_t>((v >> 8) & 0xFF));
}
void u32(Bytes& out, std::uint32_t v) {
for (int shift=0; shift<32; shift+=8) out.push_back(static_cast<std::uint8_t>(v >> shift));
}
}
Bytes select_character(std::uint8_t slot) {
if (slot >= 5) throw std::out_of_range("AVA2 character slot must be 0..4");
return {6, slot};
}
Bytes attack(std::uint8_t type, std::uint32_t victim, std::uint8_t process_crc, std::uint8_t file_crc) {
Bytes out{225, type};
u32(out, victim);
out.push_back(process_crc);
out.push_back(file_crc);
return out;
}
Bytes pickup(std::uint32_t vid) {
Bytes out{15};
u32(out, vid);
return out;
}
Bytes character_move(std::uint8_t func, std::uint8_t arg, std::uint8_t rot, std::int32_t x, std::int32_t y, std::uint32_t time) {
Bytes out{7, func, arg, rot};
u32(out, static_cast<std::uint32_t>(x));
u32(out, static_cast<std::uint32_t>(y));
u32(out, time);
return out;
}
Bytes item_use(std::uint8_t window_type, std::uint16_t cell) {
Bytes out{11, window_type};
u16(out, cell);
return out;
}
Bytes item_move(std::uint8_t src_window, std::uint16_t src_cell, std::uint8_t dst_window, std::uint16_t dst_cell, std::uint32_t count) {
Bytes out{13, src_window};
u16(out, src_cell);
out.push_back(dst_window);
u16(out, dst_cell);
u32(out, count);
return out;
}
Bytes item_drop(std::uint8_t window_type, std::uint16_t cell, std::uint32_t count) {
Bytes out{224, window_type};
u16(out, cell);
u32(out, count);
return out;
}
Bytes chat(const std::string& text, std::uint8_t type) {
if(text.empty() || text.size()>=512) return {};
Bytes out{231};
std::uint16_t size = static_cast<std::uint16_t>(5 + text.size());
u16(out, size);
out.push_back(type);
out.insert(out.end(), text.begin(), text.end());
out.push_back(0);
return out;
}
Bytes whisper(const std::string& name, const std::string& text) {
if(text.size()>=255) return {};
Bytes out{19};
std::uint16_t size = static_cast<std::uint16_t>(3 + 25 + text.size() + 1);
u16(out, size);
char nameBuf[25] = {0};
std::strncpy(nameBuf, name.c_str(), sizeof(nameBuf) - 1);
out.insert(out.end(), nameBuf, nameBuf + sizeof(nameBuf));
out.insert(out.end(), text.begin(), text.end());
out.push_back(0);
return out;
}
Bytes entergame(std::uint8_t language) {
return {10,language};
}
Bytes on_click(std::uint32_t vid) {
Bytes out{26};
u32(out, vid);
return out;
}
Bytes warp() {
return {65};
}
Bytes fly_targeting(std::uint32_t target_vid, std::int32_t x, std::int32_t y) {
Bytes out{51};
u32(out, target_vid);
u32(out, static_cast<std::uint32_t>(x));
u32(out, static_cast<std::uint32_t>(y));
return out;
}
} // namespace ava2::wire
+23
View File
@@ -0,0 +1,23 @@
#pragma once
#include <cstdint>
#include <vector>
#include <string>
namespace ava2::wire {
using Bytes = std::vector<std::uint8_t>;
// AVA2 Packet.h, packed Win32 wire format. Independent from host ABI.
Bytes select_character(std::uint8_t slot);
Bytes attack(std::uint8_t type, std::uint32_t victim, std::uint8_t process_crc = 0, std::uint8_t file_crc = 0);
Bytes pickup(std::uint32_t vid);
Bytes character_move(std::uint8_t func, std::uint8_t arg, std::uint8_t rot, std::int32_t x, std::int32_t y, std::uint32_t time);
Bytes item_use(std::uint8_t window_type, std::uint16_t cell);
Bytes item_move(std::uint8_t src_window, std::uint16_t src_cell, std::uint8_t dst_window, std::uint16_t dst_cell, std::uint32_t count);
Bytes item_drop(std::uint8_t window_type, std::uint16_t cell, std::uint32_t count);
Bytes chat(const std::string& text, std::uint8_t type = 0);
Bytes whisper(const std::string& name, const std::string& text);
Bytes entergame(std::uint8_t language=1);
Bytes on_click(std::uint32_t vid);
Bytes warp();
Bytes fly_targeting(std::uint32_t target_vid, std::int32_t x, std::int32_t y);
}
+298
View File
@@ -0,0 +1,298 @@
#include "python_app.h"
#include "server_clock.h"
#include "generated_app_constants.h"
#include "../upstream/ava2-client/UserInterface/Locale_inc.h"
#include "src/eter_image/MarkManager.h"
#include <Python.h>
#include <chrono>
#include <string>
namespace ava2 {
namespace {
std::uint32_t local_milliseconds() { return static_cast<std::uint32_t>(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count()); }
std::int64_t unix_seconds() { return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count(); }
ServerClock server_clock(local_milliseconds());
auto app_start=std::chrono::steady_clock::now();
float s_camera_distance = 1500.0f;
float s_camera_pitch = 30.0f;
float s_camera_rotation = 0.0f;
float s_camera_height = 180.0f;
bool s_hair_specular = false;
bool s_armor_specular = false;
bool s_weapon_specular = false;
int twoHandedAttackSpeedDecrease=0;
PyObject* set_twohand_decrease(PyObject*,PyObject* args){int value;if(!PyArg_ParseTuple(args,"i",&value))return nullptr;twoHandedAttackSpeedDecrease=value;Py_RETURN_NONE;}
std::string s_locale_service_name = "EUROPE";
std::string s_locale_name = "en";
std::string s_locale_path = "locale/en";
bool s_test_server_flag=false;
PyObject* app_enable_test_server(PyObject*,PyObject*) { s_test_server_flag=true;Py_RETURN_NONE; }
PyObject* app_is_test_server(PyObject*,PyObject*) { return PyInt_FromLong(s_test_server_flag); }
PyObject* app_get_time(PyObject*, PyObject*) {
float sec=std::chrono::duration<float>(std::chrono::steady_clock::now()-app_start).count();
return PyFloat_FromDouble(sec);
}
PyObject* app_get_global_time(PyObject*, PyObject*) {
return PyInt_FromLong(server_clock.milliseconds(local_milliseconds()));
}
PyObject* app_get_global_timestamp(PyObject*, PyObject*) {
return PyInt_FromLong(server_clock.timestamp(unix_seconds()));
}
PyObject* app_set_camera(PyObject*, PyObject* args) {
if (!PyArg_ParseTuple(args, "ffff", &s_camera_distance, &s_camera_pitch, &s_camera_rotation, &s_camera_height)) return nullptr;
Py_RETURN_NONE;
}
PyObject* app_set_hair_color_enable(PyObject*, PyObject* args) { int f = 0; if(!PyArg_ParseTuple(args, "i", &f)) return nullptr; Py_RETURN_NONE; }
PyObject* app_set_armor_specular_enable(PyObject*, PyObject* args) { int f = 0; if(!PyArg_ParseTuple(args, "i", &f)) return nullptr; s_armor_specular = (f != 0); Py_RETURN_NONE; }
PyObject* app_set_weapon_specular_enable(PyObject*, PyObject* args) { int f = 0; if(!PyArg_ParseTuple(args, "i", &f)) return nullptr; s_weapon_specular = (f != 0); Py_RETURN_NONE; }
PyObject* app_set_mouse_handler(PyObject*, PyObject* args) { Py_RETURN_NONE; }
PyObject* app_create(PyObject*, PyObject* args) { Py_RETURN_NONE; }
PyObject* app_loop(PyObject*, PyObject*) { Py_RETURN_NONE; }
PyObject* app_exit(PyObject*, PyObject*) { Py_RETURN_NONE; }
PyObject* app_abort(PyObject*, PyObject*) { Py_RETURN_NONE; }
PyObject* app_is_pressed(PyObject*, PyObject* args) { return PyInt_FromLong(0); }
PyObject* app_get_locale_service_name(PyObject*, PyObject*) {
return PyString_FromString(s_locale_service_name.c_str());
}
PyObject* app_get_locale_name(PyObject*, PyObject*) {
return PyString_FromString(s_locale_name.c_str());
}
PyObject* app_get_locale_path(PyObject*, PyObject*) {
return PyString_FromString(s_locale_path.c_str());
}
PyObject* app_get_default_codepage(PyObject*, PyObject*) {
return PyInt_FromLong(1252);
}
PyObject* app_dummy_none(PyObject*, PyObject*) { Py_RETURN_NONE; }
PyObject* app_dummy_zero(PyObject*, PyObject*) { return PyInt_FromLong(0); }
PyObject* app_dummy_one(PyObject*, PyObject*) { return PyInt_FromLong(1); }
PyObject* app_dummy_float_zero(PyObject*, PyObject*) { return PyFloat_FromDouble(0.0); }
PyObject* app_dummy_str(PyObject*, PyObject*) { return PyString_FromString(""); }
PyObject* app_dummy_tuple2(PyObject*, PyObject*) { return Py_BuildValue("ii", 0, 0); }
PyObject* app_dummy_tuple3(PyObject*, PyObject*) { return Py_BuildValue("iii", 0, 0, 0); }
PyObject* app_set_guild_mark_path(PyObject*, PyObject* args) {
const char* path = nullptr;
if (PyArg_ParseTuple(args, "s", &path) && path) {
std::string p(path);
size_t dot = p.find_last_of('.');
if (dot != std::string::npos) p = p.substr(0, dot);
ava2::GuildMarkManager::Instance().SetMarkPathPrefix(p);
}
Py_RETURN_NONE;
}
} // namespace
std::int32_t GetServerTimeStamp() { return server_clock.timestamp(unix_seconds()); }
void SetServerTime(std::int32_t time) { server_clock.set(time,local_milliseconds(),unix_seconds()); }
void ResetPythonAppState() { server_clock=ServerClock(local_milliseconds());app_start=std::chrono::steady_clock::now();s_test_server_flag=false;twoHandedAttackSpeedDecrease=0; }
std::uint8_t GetEnterGameLanguage() {
const char* locales[]={"ymir","en","de","tr","pt","es","fr","ro","pl","it","cz","hu"};
for(std::uint8_t i=1;i<12;++i) if(s_locale_name==locales[i]) return i;
return 1;
}
int GetTwoHandedAttackSpeedDecrease(){return twoHandedAttackSpeedDecrease;}
bool IsYmirLocale() { return s_locale_name=="ymir"; }
void initapp() {
static PyMethodDef methods[] = {
{"IsDevStage", app_dummy_zero, METH_VARARGS, nullptr},
{"IsTestStage", app_dummy_zero, METH_VARARGS, nullptr},
{"IsLiveStage", app_dummy_one, METH_VARARGS, nullptr},
{"SetTextTailLivingTime", app_dummy_none, METH_VARARGS, nullptr},
{"EnablePerformanceTime", app_dummy_none, METH_VARARGS, nullptr},
{"SetHairColorEnable", app_set_hair_color_enable, METH_VARARGS, nullptr},
{"SetArmorSpecularEnable", app_set_armor_specular_enable, METH_VARARGS, nullptr},
{"SetWeaponSpecularEnable", app_set_weapon_specular_enable, METH_VARARGS, nullptr},
{"SetSkillEffectUpgradeEnable", app_dummy_none, METH_VARARGS, nullptr},
{"SetTwoHandedWeaponAttSpeedDecreaseValue", set_twohand_decrease, METH_VARARGS, nullptr},
{"SetRideHorseEnable", app_dummy_none, METH_VARARGS, nullptr},
{"SetCameraMaxDistance", app_dummy_none, METH_VARARGS, nullptr},
{"SetMinFog", app_dummy_none, METH_VARARGS, nullptr},
{"SetFrameSkip", app_dummy_none, METH_VARARGS, nullptr},
{"GetImageInfo", app_dummy_zero, METH_VARARGS, nullptr},
{"GetInfo", app_dummy_zero, METH_VARARGS, nullptr},
{"UpdateGame", app_dummy_none, METH_VARARGS, nullptr},
{"RenderGame", app_dummy_none, METH_VARARGS, nullptr},
{"Loop", app_loop, METH_VARARGS, nullptr},
{"Create", app_create, METH_VARARGS, nullptr},
{"Process", app_dummy_none, METH_VARARGS, nullptr},
{"Exit", app_exit, METH_VARARGS, nullptr},
{"Abort", app_abort, METH_VARARGS, nullptr},
{"SetMouseHandler", app_set_mouse_handler, METH_VARARGS, nullptr},
{"IsExistFile", app_dummy_zero, METH_VARARGS, nullptr},
{"GetFileList", app_dummy_zero, METH_VARARGS, nullptr},
{"SetCamera", app_set_camera, METH_VARARGS, nullptr},
{"GetCamera", app_dummy_zero, METH_VARARGS, nullptr},
{"GetCameraPitch", app_dummy_float_zero, METH_VARARGS, nullptr},
{"GetCameraRotation", app_dummy_float_zero, METH_VARARGS, nullptr},
{"GetTime", app_get_time, METH_VARARGS, nullptr},
{"GetGlobalTime", app_get_global_time, METH_VARARGS, nullptr},
{"GetGlobalTimeStamp", app_get_global_timestamp, METH_VARARGS, nullptr},
{"GetUpdateFPS", app_dummy_zero, METH_VARARGS, nullptr},
{"GetRenderFPS", app_dummy_zero, METH_VARARGS, nullptr},
{"RotateCamera", app_dummy_none, METH_VARARGS, nullptr},
{"PitchCamera", app_dummy_none, METH_VARARGS, nullptr},
{"ZoomCamera", app_dummy_none, METH_VARARGS, nullptr},
{"MovieRotateCamera", app_dummy_none, METH_VARARGS, nullptr},
{"MoviePitchCamera", app_dummy_none, METH_VARARGS, nullptr},
{"MovieZoomCamera", app_dummy_none, METH_VARARGS, nullptr},
{"MovieResetCamera", app_dummy_none, METH_VARARGS, nullptr},
{"GetAvailableTextureMemory", app_dummy_str, METH_VARARGS, nullptr},
{"GetRenderTime", app_dummy_zero, METH_VARARGS, nullptr},
{"GetUpdateTime", app_dummy_zero, METH_VARARGS, nullptr},
{"GetLoad", app_dummy_zero, METH_VARARGS, nullptr},
{"GetFaceSpeed", app_dummy_zero, METH_VARARGS, nullptr},
{"GetFaceCount", app_dummy_zero, METH_VARARGS, nullptr},
{"SetFPS", app_dummy_none, METH_VARARGS, nullptr},
{"SetGlobalCenterPosition", app_dummy_none, METH_VARARGS, nullptr},
{"SetCenterPosition", app_dummy_none, METH_VARARGS, nullptr},
{"GetCursorPosition", app_dummy_tuple2, METH_VARARGS, nullptr},
{"GetRandom", app_dummy_zero, METH_VARARGS, nullptr},
{"RunPythonFile", app_dummy_none, METH_VARARGS, nullptr},
{"IsWebPageMode", app_dummy_zero, METH_VARARGS, nullptr},
{"ShowWebPage", app_dummy_none, METH_VARARGS, nullptr},
{"MoveWebPage", app_dummy_none, METH_VARARGS, nullptr},
{"HideWebPage", app_dummy_none, METH_VARARGS, nullptr},
{"IsPressed", app_is_pressed, METH_VARARGS, nullptr},
{"SetCursor", app_dummy_none, METH_VARARGS, nullptr},
{"GetCursor", app_dummy_zero, METH_VARARGS, nullptr},
{"ShowCursor", app_dummy_none, METH_VARARGS, nullptr},
{"HideCursor", app_dummy_none, METH_VARARGS, nullptr},
{"IsShowCursor", app_dummy_zero, METH_VARARGS, nullptr},
{"IsLiarCursorOn", app_dummy_zero, METH_VARARGS, nullptr},
{"SetSoftwareCursor", app_dummy_none, METH_VARARGS, nullptr},
{"SetHardwareCursor", app_dummy_none, METH_VARARGS, nullptr},
{"SetConnectData", app_dummy_none, METH_VARARGS, nullptr},
{"GetConnectData", app_dummy_zero, METH_VARARGS, nullptr},
{"GetRotatingDirection", app_dummy_zero, METH_VARARGS, nullptr},
{"GetDegreeDifference", app_dummy_zero, METH_VARARGS, nullptr},
{"Sleep", app_dummy_none, METH_VARARGS, nullptr},
{"SetDefaultFontName", app_dummy_none, METH_VARARGS, nullptr},
{"SetGuildSymbolPath", app_dummy_none, METH_VARARGS, nullptr},
{"EnableSpecialCameraMode", app_dummy_none, METH_VARARGS, nullptr},
{"SetCameraSpeed", app_dummy_none, METH_VARARGS, nullptr},
{"SaveCameraSetting", app_dummy_none, METH_VARARGS, nullptr},
{"LoadCameraSetting", app_dummy_none, METH_VARARGS, nullptr},
{"SetDefaultCamera", app_dummy_none, METH_VARARGS, nullptr},
{"SetCameraSetting", app_dummy_none, METH_VARARGS, nullptr},
{"SetSightRange", app_dummy_none, METH_VARARGS, nullptr},
{"IsFileExist", app_dummy_zero, METH_VARARGS, nullptr},
{"OpenTextFile", app_dummy_none, METH_VARARGS, nullptr},
{"CloseTextFile", app_dummy_none, METH_VARARGS, nullptr},
{"GetTextFileLineCount", app_dummy_str, METH_VARARGS, nullptr},
{"GetTextFileLine", app_dummy_str, METH_VARARGS, nullptr},
{"GetLocaleServiceName", app_get_locale_service_name, METH_VARARGS, nullptr},
{"GetLocaleName", app_get_locale_name, METH_VARARGS, nullptr},
{"GetLocalePath", app_get_locale_path, METH_VARARGS, nullptr},
{"ForceSetLocale", app_dummy_none, METH_VARARGS, nullptr},
{"LoadLocaleAddr", app_dummy_none, METH_VARARGS, nullptr},
{"LoadLocaleData", app_dummy_none, METH_VARARGS, nullptr},
{"SetCHEONMA", app_dummy_none, METH_VARARGS, nullptr},
{"IsCHEONMA", app_dummy_zero, METH_VARARGS, nullptr},
{"GetDefaultCodePage", app_get_default_codepage, METH_VARARGS, nullptr},
{"SetControlFP", app_dummy_none, METH_VARARGS, nullptr},
{"SetSpecularSpeed", app_dummy_none, METH_VARARGS, nullptr},
{"testGetAccumulationTime", app_dummy_none, METH_VARARGS, nullptr},
{"testResetAccumulationTime", app_dummy_none, METH_VARARGS, nullptr},
{"testSetSpecularColor", app_dummy_none, METH_VARARGS, nullptr},
{"SetVisibleNotice", app_dummy_none, METH_VARARGS, nullptr},
{"IsVisibleNotice", app_dummy_zero, METH_VARARGS, nullptr},
{"IsEnableTestServerFlag", app_is_test_server, METH_VARARGS, nullptr},
{"EnableTestServerFlag", app_enable_test_server, METH_VARARGS, nullptr},
{"SetGuildMarkPath", app_set_guild_mark_path, METH_VARARGS, nullptr},
{"OnLogoUpdate", app_dummy_none, METH_VARARGS, nullptr},
{"OnLogoRender", app_dummy_none, METH_VARARGS, nullptr},
{"OnLogoOpen", app_dummy_none, METH_VARARGS, nullptr},
{"OnLogoClose", app_dummy_none, METH_VARARGS, nullptr},
{"FlashApplication", app_dummy_none, METH_VARARGS, nullptr},
{"SetMultiFarmExeIcon", app_dummy_none, METH_VARARGS, nullptr},
{"WindowStatus", app_dummy_none, METH_VARARGS, nullptr},
{"IsVisible", app_dummy_zero, METH_VARARGS, nullptr},
{"SetTitle", app_dummy_none, METH_VARARGS, nullptr},
{"SetMessage", app_dummy_none, METH_VARARGS, nullptr},
{"IsCanOpenRender", app_dummy_zero, METH_VARARGS, nullptr},
{nullptr, nullptr, 0, nullptr}
};
auto* module = Py_InitModule("app", methods);
register_app_constants(module);
#ifdef ENABLE_MANAGER_BANK_SYSTEM
PyModule_AddIntConstant(module, "ENABLE_MANAGER_BANK_SYSTEM", 1);
#else
PyModule_AddIntConstant(module, "ENABLE_MANAGER_BANK_SYSTEM", 0);
#endif
#ifdef ENABLE_WOLFMAN_CHARACTER
PyModule_AddIntConstant(module, "ENABLE_WOLFMAN_CHARACTER", 1);
#else
PyModule_AddIntConstant(module, "ENABLE_WOLFMAN_CHARACTER", 0);
#endif
#ifdef ENABLE_SASH_SYSTEM
PyModule_AddIntConstant(module, "ENABLE_SASH_SYSTEM", 1);
#else
PyModule_AddIntConstant(module, "ENABLE_SASH_SYSTEM", 0);
#endif
#ifdef ENABLE_CONQUEROR_LEVEL
PyModule_AddIntConstant(module, "ENABLE_CONQUEROR_LEVEL", 1);
#else
PyModule_AddIntConstant(module, "ENABLE_CONQUEROR_LEVEL", 0);
#endif
#ifdef ENABLE_DISCORD_STUFF
PyModule_AddIntConstant(module, "ENABLE_DISCORD_STUFF", 1);
#else
PyModule_AddIntConstant(module, "ENABLE_DISCORD_STUFF", 0);
#endif
PyModule_AddIntConstant(module, "ENABLE_OFFLINESHOP_SYSTEM", 1);
PyModule_AddIntConstant(module, "ENABLE_STONEMINIMAP", 1);
PyModule_AddIntConstant(module, "TOURNAMENT_PVP_SYSTEM", 0);
PyModule_AddIntConstant(module, "RACE_HEIGHT", 1);
// DIK Keycodes strictly 1:1 with win32 dinput DIK_*
PyModule_AddIntConstant(module, "DIK_ESCAPE", 0x01);
PyModule_AddIntConstant(module, "DIK_ESC", 0x01);
PyModule_AddIntConstant(module, "DIK_1", 0x02);
PyModule_AddIntConstant(module, "DIK_2", 0x03);
PyModule_AddIntConstant(module, "DIK_3", 0x04);
PyModule_AddIntConstant(module, "DIK_4", 0x05);
PyModule_AddIntConstant(module, "DIK_5", 0x06);
PyModule_AddIntConstant(module, "DIK_6", 0x07);
PyModule_AddIntConstant(module, "DIK_7", 0x08);
PyModule_AddIntConstant(module, "DIK_8", 0x09);
PyModule_AddIntConstant(module, "DIK_9", 0x0A);
PyModule_AddIntConstant(module, "DIK_0", 0x0B);
PyModule_AddIntConstant(module, "DIK_RETURN", 0x1C);
PyModule_AddIntConstant(module, "DIK_TAB", 0x0F);
PyModule_AddIntConstant(module, "DIK_SPACE", 0x39);
PyModule_AddIntConstant(module, "DIK_BACK", 0x0E);
PyModule_AddIntConstant(module, "DIK_UP", 0xC8);
PyModule_AddIntConstant(module, "DIK_DOWN", 0xD0);
PyModule_AddIntConstant(module, "DIK_LEFT", 0xCB);
PyModule_AddIntConstant(module, "DIK_RIGHT", 0xCD);
PyModule_AddIntConstant(module, "INFO_ITEM", 0);
PyModule_AddIntConstant(module, "INFO_ACTOR", 1);
PyModule_AddIntConstant(module, "INFO_EFFECT", 2);
PyModule_AddIntConstant(module, "INFO_TEXTTAIL", 3);
}
} // namespace ava2
+12
View File
@@ -0,0 +1,12 @@
#pragma once
#include <cstdint>
namespace ava2 {
int GetTwoHandedAttackSpeedDecrease();
void initapp();
bool IsYmirLocale();
std::int32_t GetServerTimeStamp();
void SetServerTime(std::int32_t time);
void ResetPythonAppState();
std::uint8_t GetEnterGameLanguage();
}
+59
View File
@@ -0,0 +1,59 @@
#include "python_dbg.h"
#include <Python.h>
#include <iostream>
#include <string>
namespace ava2 {
namespace {
PyObject* dbg_logbox(PyObject*, PyObject* args) {
char* msg = nullptr;
char* caption = nullptr;
if (!PyArg_ParseTuple(args, "s|s", &msg, &caption)) return nullptr;
std::cout << "[AVA2 LogBox] (" << (caption ? caption : "Message") << "): " << (msg ? msg : "") << std::endl;
Py_RETURN_NONE;
}
PyObject* dbg_trace(PyObject*, PyObject* args) {
char* msg = nullptr;
if (!PyArg_ParseTuple(args, "s", &msg)) return nullptr;
std::cout << (msg ? msg : "") << std::flush;
Py_RETURN_NONE;
}
PyObject* dbg_tracen(PyObject*, PyObject* args) {
char* msg = nullptr;
if (!PyArg_ParseTuple(args, "s", &msg)) return nullptr;
std::cout << "[AVA2 Trace] " << (msg ? msg : "") << std::endl;
Py_RETURN_NONE;
}
PyObject* dbg_trace_error(PyObject*, PyObject* args) {
char* msg = nullptr;
if (!PyArg_ParseTuple(args, "s", &msg)) return nullptr;
std::cerr << "[AVA2 TraceError] " << (msg ? msg : "") << std::endl;
Py_RETURN_NONE;
}
PyObject* dbg_register_exception_string(PyObject*, PyObject* args) {
char* msg = nullptr;
if (!PyArg_ParseTuple(args, "s", &msg)) return nullptr;
std::cerr << "[AVA2 Exception] " << (msg ? msg : "") << std::endl;
Py_RETURN_NONE;
}
} // namespace
void initdbg() {
static PyMethodDef methods[] = {
{"LogBox", dbg_logbox, METH_VARARGS, nullptr},
{"Trace", dbg_trace, METH_VARARGS, nullptr},
{"Tracen", dbg_tracen, METH_VARARGS, nullptr},
{"TraceError", dbg_trace_error, METH_VARARGS, nullptr},
{"RegisterExceptionString", dbg_register_exception_string, METH_VARARGS, nullptr},
{nullptr, nullptr, 0, nullptr}
};
Py_InitModule("dbg", methods);
}
} // namespace ava2
+5
View File
@@ -0,0 +1,5 @@
#pragma once
namespace ava2 {
void initdbg();
}
File diff suppressed because it is too large Load Diff
+59
View File
@@ -0,0 +1,59 @@
#pragma once
#include "eter_render/RenderCommands3D.h"
#include "eter_net/Packet.h"
#include <vector>
#include <functional>
namespace ava2 {
void initItem();
void initPlayer();
void initchrmgr();
void initchr();
void initChat();
void initsnd();
void initBackground();
void GlobalToLocalPosition(int32_t& x,int32_t& y);
void LocalToGlobalPosition(int32_t& x,int32_t& y);
bool WarpBackgroundMap(uint32_t x,uint32_t y);
using SkillCastCallback = std::function<void(int quickSlot, int skillIndex)>;
void SetPlayerSkillCastCallback(SkillCastCallback cb);
void SetSkillCoolTime(int skillIndex, float coolTime);
void SetSkillCoolTimeAt(int skillIndex,float coolTime,float now);
struct PlayerItemSlot {
uint32_t vnum = 0;
int count = 0;
std::array<long, 8> sockets{};
std::array<std::pair<int, int>, 15> attrs{};
};
PlayerItemSlot GetPlayerItem(int slot);
void SetPlayerItem(int slot, uint32_t vnum, int count);
void ResetPlayerState();
void ClearPlayerPythonWindow();
void SetPlayerSkill(int slot,int index);
void SetPlayerSkillLevel(int index,int grade,int level);
void SetPlayerLegacySkillLevel(int index,int level);
void AddPlayerQuickSlot(int index,uint8_t type,uint8_t pos);
void DeletePlayerQuickSlot(int index);
void SwapPlayerQuickSlots(int source,int target);
void SetPlayerItemData(uint8_t window, uint16_t cell, const TItemData& data);
TItemData GetPlayerItemData(uint8_t window, uint16_t cell);
bool UsePlayerItem(int window, int slot, std::string& outEquippedWeaponModel, std::string& outActionMessage);
bool MovePlayerItem(int srcWindow, int srcSlot, int dstWindow, int dstSlot, int count, std::string& outEquippedWeaponModel);
std::string GetWeaponModelPathByVnum(uint32_t vnum);
std::vector<Render3DDraw> GetAllActiveChrDraws();
void SetMainCharacterPosition(float x, float y, float z);
void SetMainCharacterName(const std::string& name);
long long GetPlayerStatusPoint(int type);
void SetPlayerStatusPoint(int type, long long value);
class TerrainHeightmap;
TerrainHeightmap* GetActiveBackgroundTerrain();
void SetActiveBackgroundTerrain(std::unique_ptr<TerrainHeightmap> terrain);
bool LoadBackgroundMap(const std::string& mapName, float x = 0.0f, float y = 0.0f, float z = 0.0f);
} // namespace ava2
+315
View File
@@ -0,0 +1,315 @@
#include "python_grp.h"
#include "eter_image/GrpDevice.h"
#include <SDL3/SDL.h>
#include <Python.h>
#include <string>
#include <vector>
#include <algorithm>
namespace ava2 {
namespace {
PyObject* dummy_none(PyObject*, PyObject*) { Py_RETURN_NONE; }
PyObject* dummy_zero(PyObject*, PyObject*) { return PyInt_FromLong(0); }
PyObject* dummy_one(PyObject*, PyObject*) { return PyInt_FromLong(1); }
PyObject* dummy_float_zero(PyObject*, PyObject*) { return PyFloat_FromDouble(0.0); }
PyObject* dummy_str(PyObject*, PyObject*) { return PyString_FromString(""); }
PyObject* dummy_tuple2(PyObject*, PyObject*) { return Py_BuildValue("ii", 0, 0); }
PyObject* dummy_tuple3(PyObject*, PyObject*) { return Py_BuildValue("iii", 0, 0, 0); }
PyObject* dummy_tuple4(PyObject*, PyObject*) { return Py_BuildValue("iiii", 0, 0, 0, 0); }
static uint32_t s_currentColor = 0xFFFFFFFF;
static uint32_t s_diffuseColor = 0xFFFFFFFF;
static uint32_t s_clearColor = 0xFF000000;
static float s_alpha = 1.0f;
static PyObject* grp_GenerateColor(PyObject*, PyObject* args) {
float r = 0.0f, g = 0.0f, b = 0.0f, a = 1.0f;
if (!PyArg_ParseTuple(args, "ffff", &r, &g, &b, &a)) {
PyErr_Clear();
int ir = 0, ig = 0, ib = 0, ia = 255;
if (PyArg_ParseTuple(args, "iiii", &ir, &ig, &ib, &ia)) {
uint32_t color = ((uint32_t)(ia & 0xFF) << 24) |
((uint32_t)(ir & 0xFF) << 16) |
((uint32_t)(ig & 0xFF) << 8) |
(uint32_t)(ib & 0xFF);
return PyLong_FromUnsignedLong(color);
}
return PyLong_FromUnsignedLong(0xFFFFFFFF);
}
uint8_t ur = (uint8_t)std::clamp((int)(r * 255.0f), 0, 255);
uint8_t ug = (uint8_t)std::clamp((int)(g * 255.0f), 0, 255);
uint8_t ub = (uint8_t)std::clamp((int)(b * 255.0f), 0, 255);
uint8_t ua = (uint8_t)std::clamp((int)(a * 255.0f), 0, 255);
uint32_t color = ((uint32_t)ua << 24) | ((uint32_t)ur << 16) | ((uint32_t)ug << 8) | (uint32_t)ub;
return PyLong_FromUnsignedLong(color);
}
static PyObject* grp_SetColor(PyObject*, PyObject* args) {
unsigned long color = 0;
if (PyArg_ParseTuple(args, "k", &color)) {
s_currentColor = (uint32_t)color;
} else {
PyErr_Clear();
int icolor = 0;
if (PyArg_ParseTuple(args, "i", &icolor)) {
s_currentColor = (uint32_t)icolor;
}
}
Py_RETURN_NONE;
}
static PyObject* grp_SetAlpha(PyObject*, PyObject* args) {
float a = 1.0f;
if (PyArg_ParseTuple(args, "f", &a)) {
s_alpha = std::clamp(a, 0.0f, 1.0f);
uint8_t ua = (uint8_t)(s_alpha * 255.0f);
s_currentColor = (s_currentColor & 0x00FFFFFF) | ((uint32_t)ua << 24);
}
Py_RETURN_NONE;
}
static PyObject* grp_SetDiffuseColor(PyObject*, PyObject* args) {
float r = 1.0f, g = 1.0f, b = 1.0f, a = 1.0f;
if (PyArg_ParseTuple(args, "ffff", &r, &g, &b, &a)) {
uint8_t ur = (uint8_t)std::clamp((int)(r * 255.0f), 0, 255);
uint8_t ug = (uint8_t)std::clamp((int)(g * 255.0f), 0, 255);
uint8_t ub = (uint8_t)std::clamp((int)(b * 255.0f), 0, 255);
uint8_t ua = (uint8_t)std::clamp((int)(a * 255.0f), 0, 255);
s_diffuseColor = ((uint32_t)ua << 24) | ((uint32_t)ur << 16) | ((uint32_t)ug << 8) | (uint32_t)ub;
}
Py_RETURN_NONE;
}
static PyObject* grp_SetClearColor(PyObject*, PyObject* args) {
float r = 0.0f, g = 0.0f, b = 0.0f;
if (PyArg_ParseTuple(args, "fff", &r, &g, &b)) {
uint8_t ur = (uint8_t)std::clamp((int)(r * 255.0f), 0, 255);
uint8_t ug = (uint8_t)std::clamp((int)(g * 255.0f), 0, 255);
uint8_t ub = (uint8_t)std::clamp((int)(b * 255.0f), 0, 255);
s_clearColor = 0xFF000000 | ((uint32_t)ur << 16) | ((uint32_t)ug << 8) | (uint32_t)ub;
}
Py_RETURN_NONE;
}
static PyObject* grp_RenderBar(PyObject*, PyObject* args) {
int x = 0, y = 0, w = 0, h = 0;
if (PyArg_ParseTuple(args, "iiii", &x, &y, &w, &h)) {
auto* renderer = CGraphicDevice::Instance().GetRenderer();
if (renderer && w > 0 && h > 0) {
uint8_t a = (s_currentColor >> 24) & 0xFF;
uint8_t r = (s_currentColor >> 16) & 0xFF;
uint8_t g = (s_currentColor >> 8) & 0xFF;
uint8_t b = s_currentColor & 0xFF;
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawColor(renderer, r, g, b, a);
SDL_FRect rect{ (float)x, (float)y, (float)w, (float)h };
SDL_RenderFillRect(renderer, &rect);
}
}
Py_RETURN_NONE;
}
static PyObject* grp_RenderLine(PyObject*, PyObject* args) {
int x = 0, y = 0, dx = 0, dy = 0;
if (PyArg_ParseTuple(args, "iiii", &x, &y, &dx, &dy)) {
auto* renderer = CGraphicDevice::Instance().GetRenderer();
if (renderer) {
uint8_t a = (s_currentColor >> 24) & 0xFF;
uint8_t r = (s_currentColor >> 16) & 0xFF;
uint8_t g = (s_currentColor >> 8) & 0xFF;
uint8_t b = s_currentColor & 0xFF;
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawColor(renderer, r, g, b, a);
SDL_RenderLine(renderer, (float)x, (float)y, (float)(x + dx), (float)(y + dy));
}
}
Py_RETURN_NONE;
}
static PyObject* grp_RenderBox(PyObject*, PyObject* args) {
int x = 0, y = 0, w = 0, h = 0;
if (PyArg_ParseTuple(args, "iiii", &x, &y, &w, &h)) {
auto* renderer = CGraphicDevice::Instance().GetRenderer();
if (renderer && w > 0 && h > 0) {
uint8_t a = (s_currentColor >> 24) & 0xFF;
uint8_t r = (s_currentColor >> 16) & 0xFF;
uint8_t g = (s_currentColor >> 8) & 0xFF;
uint8_t b = s_currentColor & 0xFF;
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawColor(renderer, r, g, b, a);
SDL_FRect rect{ (float)x, (float)y, (float)w, (float)h };
SDL_RenderRect(renderer, &rect);
}
}
Py_RETURN_NONE;
}
static PyObject* grp_RenderRoundBox(PyObject*, PyObject* args) {
int x = 0, y = 0, w = 0, h = 0;
if (PyArg_ParseTuple(args, "iiii", &x, &y, &w, &h)) {
auto* renderer = CGraphicDevice::Instance().GetRenderer();
if (renderer && w > 0 && h > 0) {
uint8_t a = (s_currentColor >> 24) & 0xFF;
uint8_t r = (s_currentColor >> 16) & 0xFF;
uint8_t g = (s_currentColor >> 8) & 0xFF;
uint8_t b = s_currentColor & 0xFF;
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawColor(renderer, r, g, b, a);
SDL_FRect rect{ (float)x, (float)y, (float)w, (float)h };
SDL_RenderRect(renderer, &rect);
}
}
Py_RETURN_NONE;
}
static PyObject* grp_RenderGradationBar(PyObject*, PyObject* args) {
int x = 0, y = 0, w = 0, h = 0;
unsigned long startCol = 0, endCol = 0;
if (PyArg_ParseTuple(args, "iiiikk", &x, &y, &w, &h, &startCol, &endCol)) {
auto* renderer = CGraphicDevice::Instance().GetRenderer();
if (renderer && w > 0 && h > 0) {
uint8_t sa = (startCol >> 24) & 0xFF, sr = (startCol >> 16) & 0xFF, sg = (startCol >> 8) & 0xFF, sb = startCol & 0xFF;
uint8_t ea = (endCol >> 24) & 0xFF, er = (endCol >> 16) & 0xFF, eg = (endCol >> 8) & 0xFF, eb = endCol & 0xFF;
SDL_FColor c1{ sr/255.0f, sg/255.0f, sb/255.0f, sa/255.0f };
SDL_FColor c2{ er/255.0f, eg/255.0f, eb/255.0f, ea/255.0f };
SDL_Vertex verts[4];
verts[0] = { { (float)x, (float)y }, c1, {0, 0} };
verts[1] = { { (float)(x+w), (float)y }, c1, {0, 0} };
verts[2] = { { (float)(x+w), (float)(y+h) }, c2, {0, 0} };
verts[3] = { { (float)x, (float)(y+h) }, c2, {0, 0} };
int indices[6] = { 0, 1, 2, 0, 2, 3 };
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
SDL_RenderGeometry(renderer, nullptr, verts, 4, indices, 6);
}
}
Py_RETURN_NONE;
}
} // namespace
void initgrp() {
static PyMethodDef methods[] = {
{"InitScreenEffect", dummy_none, METH_VARARGS, nullptr},
{"Culling", dummy_none, METH_VARARGS, nullptr},
{"ClearDepthBuffer", dummy_none, METH_VARARGS, nullptr},
{"Identity", dummy_none, METH_VARARGS, nullptr},
{"GenerateColor", grp_GenerateColor, METH_VARARGS, nullptr},
{"PopState", dummy_none, METH_VARARGS, nullptr},
{"PushState", dummy_none, METH_VARARGS, nullptr},
{"PushMatrix", dummy_none, METH_VARARGS, nullptr},
{"PopMatrix", dummy_none, METH_VARARGS, nullptr},
{"Translate", dummy_none, METH_VARARGS, nullptr},
{"Rotate", dummy_none, METH_VARARGS, nullptr},
{"SetColorRenderState", dummy_none, METH_VARARGS, nullptr},
{"SetAroundCamera", dummy_none, METH_VARARGS, nullptr},
{"SetPositionCamera", dummy_none, METH_VARARGS, nullptr},
{"SetEyeCamera", dummy_none, METH_VARARGS, nullptr},
{"SetPerspective", dummy_none, METH_VARARGS, nullptr},
{"SetOrtho2d", dummy_none, METH_VARARGS, nullptr},
{"SetOrtho3d", dummy_none, METH_VARARGS, nullptr},
{"SetColor", grp_SetColor, METH_VARARGS, nullptr},
{"SetAlpha", grp_SetAlpha, METH_VARARGS, nullptr},
{"SetDiffuseColor", grp_SetDiffuseColor, METH_VARARGS, nullptr},
{"SetClearColor", grp_SetClearColor, METH_VARARGS, nullptr},
{"GetCursorPosition3d", dummy_tuple2, METH_VARARGS, nullptr},
{"SetCursorPosition", dummy_none, METH_VARARGS, nullptr},
{"RenderLine", grp_RenderLine, METH_VARARGS, nullptr},
{"RenderBox", grp_RenderBox, METH_VARARGS, nullptr},
{"RenderRoundBox", grp_RenderRoundBox, METH_VARARGS, nullptr},
{"RenderBox3d", dummy_none, METH_VARARGS, nullptr},
{"RenderBar", grp_RenderBar, METH_VARARGS, nullptr},
{"RenderBar3d", dummy_none, METH_VARARGS, nullptr},
{"RenderGradationBar", grp_RenderGradationBar, METH_VARARGS, nullptr},
{"RenderCube", dummy_none, METH_VARARGS, nullptr},
{"RenderDownButton", dummy_none, METH_VARARGS, nullptr},
{"RenderUpButton", dummy_none, METH_VARARGS, nullptr},
{"GetAvailableMemory", dummy_zero, METH_VARARGS, nullptr},
{"SaveScreenShot", dummy_none, METH_VARARGS, nullptr},
{"SaveScreenShotToPath", dummy_none, METH_VARARGS, nullptr},
{"SetGamma", dummy_none, METH_VARARGS, nullptr},
{"SetInterfaceRenderState", dummy_none, METH_VARARGS, nullptr},
{"SetGameRenderState", dummy_none, METH_VARARGS, nullptr},
{"SetViewport", dummy_none, METH_VARARGS, nullptr},
{"RestoreViewport", dummy_none, METH_VARARGS, nullptr},
{"SetOmniLight", dummy_none, METH_VARARGS, nullptr},
{"GetCameraPosition", dummy_tuple2, METH_VARARGS, nullptr},
{"GetTargetPosition", dummy_tuple2, METH_VARARGS, nullptr},
{"CreateTextBar", dummy_none, METH_VARARGS, nullptr},
{"CreateBigTextBar", dummy_none, METH_VARARGS, nullptr},
{"DestroyTextBar", dummy_none, METH_VARARGS, nullptr},
{"RenderTextBar", dummy_none, METH_VARARGS, nullptr},
{"TextBarTextOut", dummy_none, METH_VARARGS, nullptr},
{"TextBarSetTextColor", dummy_none, METH_VARARGS, nullptr},
{"TextBarGetTextExtent", dummy_none, METH_VARARGS, nullptr},
{"ClearTextBar", dummy_none, METH_VARARGS, nullptr},
{"SetTextBarClipRect", dummy_none, METH_VARARGS, nullptr},
{nullptr, nullptr, 0, nullptr}
};
auto* module = Py_InitModule("grp", methods);
}
void initgrpImage() {
static PyMethodDef methods[] = {
{"Render", dummy_none, METH_VARARGS, nullptr},
{"SetPosition", dummy_none, METH_VARARGS, nullptr},
{"Generate", dummy_none, METH_VARARGS, nullptr},
{"GenerateExpanded", dummy_none, METH_VARARGS, nullptr},
{"GenerateFromHandle", dummy_none, METH_VARARGS, nullptr},
{"Delete", dummy_none, METH_VARARGS, nullptr},
{"DeleteExpanded", dummy_none, METH_VARARGS, nullptr},
{"SetFileName", dummy_none, METH_VARARGS, nullptr},
{"SetOrigin", dummy_none, METH_VARARGS, nullptr},
{"SetRotation", dummy_none, METH_VARARGS, nullptr},
{"SetScale", dummy_none, METH_VARARGS, nullptr},
{"SetRenderingRect", dummy_none, METH_VARARGS, nullptr},
{"SetDiffuseColor", dummy_none, METH_VARARGS, nullptr},
{"GetWidth", dummy_zero, METH_VARARGS, nullptr},
{"GetHeight", dummy_zero, METH_VARARGS, nullptr},
{nullptr, nullptr, 0, nullptr}
};
auto* module = Py_InitModule("grpImage", methods);
}
void initgrpText() {
static PyMethodDef methods[] = {
{"Update", dummy_none, METH_VARARGS, nullptr},
{"Render", dummy_none, METH_VARARGS, nullptr},
{"Generate", dummy_none, METH_VARARGS, nullptr},
{"Destroy", dummy_none, METH_VARARGS, nullptr},
{"SetFontName", dummy_none, METH_VARARGS, nullptr},
{"SetFontColor", dummy_none, METH_VARARGS, nullptr},
{"SetOutLineColor", dummy_none, METH_VARARGS, nullptr},
{"SetSecret", dummy_none, METH_VARARGS, nullptr},
{"SetOutline", dummy_none, METH_VARARGS, nullptr},
{"SetText", dummy_none, METH_VARARGS, nullptr},
{"GetText", dummy_str, METH_VARARGS, nullptr},
{"GetSize", dummy_tuple2, METH_VARARGS, nullptr},
{"SetPosition", dummy_none, METH_VARARGS, nullptr},
{"ShowCursor", dummy_none, METH_VARARGS, nullptr},
{"HideCursor", dummy_none, METH_VARARGS, nullptr},
{"SetHorizontalAlign", dummy_none, METH_VARARGS, nullptr},
{"SetVerticalAlign", dummy_none, METH_VARARGS, nullptr},
{"SetMax", dummy_none, METH_VARARGS, nullptr},
{"GetSplitingTextLineCount", dummy_str, METH_VARARGS, nullptr},
{"GetSplitingTextLine", dummy_str, METH_VARARGS, nullptr},
{"PixelPositionToCharacterPosition", dummy_none, METH_VARARGS, nullptr},
{nullptr, nullptr, 0, nullptr}
};
auto* module = Py_InitModule("grpText", methods);
}
void initgrpThing() {
static PyMethodDef methods[] = {
{"Update", dummy_none, METH_VARARGS, nullptr},
{"Render", dummy_none, METH_VARARGS, nullptr},
{"SetPosition", dummy_none, METH_VARARGS, nullptr},
{"Generate", dummy_none, METH_VARARGS, nullptr},
{"Delete", dummy_none, METH_VARARGS, nullptr},
{"SetFileName", dummy_none, METH_VARARGS, nullptr},
{"SetRotation", dummy_none, METH_VARARGS, nullptr},
{"SetScale", dummy_none, METH_VARARGS, nullptr},
{nullptr, nullptr, 0, nullptr}
};
auto* module = Py_InitModule("grpThing", methods);
}
} // namespace ava2
+8
View File
@@ -0,0 +1,8 @@
#pragma once
namespace ava2 {
void initgrp();
void initgrpImage();
void initgrpText();
void initgrpThing();
} // namespace ava2
+185
View File
@@ -0,0 +1,185 @@
#include "python_ime.h"
#include <Python.h>
#include <string>
namespace ava2 {
namespace {
std::string s_text = "";
int s_max = 64;
int s_user_max = 64;
int s_cursor_pos = 0;
int s_input_mode = 0;
bool s_paste_enabled = true;
PyObject* ime_enable(PyObject*, PyObject*) { Py_RETURN_NONE; }
PyObject* ime_disable(PyObject*, PyObject*) { Py_RETURN_NONE; }
PyObject* ime_enable_capture_input(PyObject*, PyObject*) { Py_RETURN_NONE; }
PyObject* ime_disable_capture_input(PyObject*, PyObject*) { Py_RETURN_NONE; }
PyObject* ime_set_max(PyObject*, PyObject* args) {
if (!PyArg_ParseTuple(args, "i", &s_max)) return nullptr;
Py_RETURN_NONE;
}
PyObject* ime_set_user_max(PyObject*, PyObject* args) {
if (!PyArg_ParseTuple(args, "i", &s_user_max)) return nullptr;
Py_RETURN_NONE;
}
PyObject* ime_set_text(PyObject*, PyObject* args) {
const char* str = nullptr;
if (!PyArg_ParseTuple(args, "s", &str)) return nullptr;
s_text = str ? str : "";
s_cursor_pos = static_cast<int>(s_text.length());
Py_RETURN_NONE;
}
PyObject* ime_get_text(PyObject*, PyObject* args) {
return PyString_FromString(s_text.c_str());
}
PyObject* ime_get_code_page(PyObject*, PyObject*) {
return PyInt_FromLong(1252);
}
PyObject* ime_get_candidate_count(PyObject*, PyObject*) {
return PyInt_FromLong(0);
}
PyObject* ime_get_candidate(PyObject*, PyObject* args) {
return Py_BuildValue("si", "", 0);
}
PyObject* ime_get_candidate_selection(PyObject*, PyObject*) {
return PyInt_FromLong(0);
}
PyObject* ime_get_reading(PyObject*, PyObject*) {
return PyString_FromString("");
}
PyObject* ime_get_reading_error(PyObject*, PyObject*) {
return PyInt_FromLong(0);
}
PyObject* ime_enable_ime(PyObject*, PyObject*) { Py_RETURN_NONE; }
PyObject* ime_disable_ime(PyObject*, PyObject*) { Py_RETURN_NONE; }
PyObject* ime_get_input_mode(PyObject*, PyObject*) {
return PyInt_FromLong(s_input_mode);
}
PyObject* ime_set_input_mode(PyObject*, PyObject* args) {
if (!PyArg_ParseTuple(args, "i", &s_input_mode)) return nullptr;
Py_RETURN_NONE;
}
PyObject* ime_set_number_mode(PyObject*, PyObject*) { Py_RETURN_NONE; }
PyObject* ime_set_string_mode(PyObject*, PyObject*) { Py_RETURN_NONE; }
PyObject* ime_add_except_key(PyObject*, PyObject*) { Py_RETURN_NONE; }
PyObject* ime_clear_except_key(PyObject*, PyObject*) { Py_RETURN_NONE; }
PyObject* ime_move_left(PyObject*, PyObject*) {
if (s_cursor_pos > 0) --s_cursor_pos;
Py_RETURN_NONE;
}
PyObject* ime_move_right(PyObject*, PyObject*) {
if (s_cursor_pos < static_cast<int>(s_text.length())) ++s_cursor_pos;
Py_RETURN_NONE;
}
PyObject* ime_move_home(PyObject*, PyObject*) {
s_cursor_pos = 0;
Py_RETURN_NONE;
}
PyObject* ime_move_end(PyObject*, PyObject*) {
s_cursor_pos = static_cast<int>(s_text.length());
Py_RETURN_NONE;
}
PyObject* ime_set_cursor_position(PyObject*, PyObject* args) {
if (!PyArg_ParseTuple(args, "i", &s_cursor_pos)) return nullptr;
Py_RETURN_NONE;
}
PyObject* ime_delete(PyObject*, PyObject*) {
if (s_cursor_pos < static_cast<int>(s_text.length())) {
s_text.erase(s_cursor_pos, 1);
}
Py_RETURN_NONE;
}
PyObject* ime_paste_string(PyObject*, PyObject* args) {
const char* str = nullptr;
if (!PyArg_ParseTuple(args, "s", &str)) return nullptr;
if (str) {
s_text.insert(s_cursor_pos, str);
s_cursor_pos += static_cast<int>(strlen(str));
}
Py_RETURN_NONE;
}
PyObject* ime_paste_backspace(PyObject*, PyObject*) {
if (s_cursor_pos > 0 && !s_text.empty()) {
s_text.erase(s_cursor_pos - 1, 1);
--s_cursor_pos;
}
Py_RETURN_NONE;
}
PyObject* ime_paste_return(PyObject*, PyObject*) { Py_RETURN_NONE; }
PyObject* ime_paste_text_from_clipboard(PyObject*, PyObject*) { Py_RETURN_NONE; }
PyObject* ime_enable_paste(PyObject*, PyObject* args) {
int flag = 1;
if (!PyArg_ParseTuple(args, "i", &flag)) return nullptr;
s_paste_enabled = (flag != 0);
Py_RETURN_NONE;
}
} // namespace
void initime() {
static PyMethodDef methods[] = {
{"Enable", ime_enable, METH_VARARGS, nullptr},
{"Disable", ime_disable, METH_VARARGS, nullptr},
{"EnableCaptureInput", ime_enable_capture_input, METH_VARARGS, nullptr},
{"DisableCaptureInput", ime_disable_capture_input, METH_VARARGS, nullptr},
{"SetMax", ime_set_max, METH_VARARGS, nullptr},
{"SetUserMax", ime_set_user_max, METH_VARARGS, nullptr},
{"SetText", ime_set_text, METH_VARARGS, nullptr},
{"GetText", ime_get_text, METH_VARARGS, nullptr},
{"GetCodePage", ime_get_code_page, METH_VARARGS, nullptr},
{"GetCandidateCount", ime_get_candidate_count, METH_VARARGS, nullptr},
{"GetCandidate", ime_get_candidate, METH_VARARGS, nullptr},
{"GetCandidateSelection", ime_get_candidate_selection, METH_VARARGS, nullptr},
{"GetReading", ime_get_reading, METH_VARARGS, nullptr},
{"GetReadingError", ime_get_reading_error, METH_VARARGS, nullptr},
{"EnableIME", ime_enable_ime, METH_VARARGS, nullptr},
{"DisableIME", ime_disable_ime, METH_VARARGS, nullptr},
{"GetInputMode", ime_get_input_mode, METH_VARARGS, nullptr},
{"SetInputMode", ime_set_input_mode, METH_VARARGS, nullptr},
{"SetNumberMode", ime_set_number_mode, METH_VARARGS, nullptr},
{"SetStringMode", ime_set_string_mode, METH_VARARGS, nullptr},
{"AddExceptKey", ime_add_except_key, METH_VARARGS, nullptr},
{"ClearExceptKey", ime_clear_except_key, METH_VARARGS, nullptr},
{"MoveLeft", ime_move_left, METH_VARARGS, nullptr},
{"MoveRight", ime_move_right, METH_VARARGS, nullptr},
{"MoveHome", ime_move_home, METH_VARARGS, nullptr},
{"MoveEnd", ime_move_end, METH_VARARGS, nullptr},
{"SetCursorPosition", ime_set_cursor_position, METH_VARARGS, nullptr},
{"Delete", ime_delete, METH_VARARGS, nullptr},
{"PasteString", ime_paste_string, METH_VARARGS, nullptr},
{"PasteBackspace", ime_paste_backspace, METH_VARARGS, nullptr},
{"PasteReturn", ime_paste_return, METH_VARARGS, nullptr},
{"PasteTextFromClipBoard", ime_paste_text_from_clipboard, METH_VARARGS, nullptr},
{"EnablePaste", ime_enable_paste, METH_VARARGS, nullptr},
{nullptr, nullptr, 0, nullptr}
};
Py_InitModule("ime", methods);
}
} // namespace ava2
+7
View File
@@ -0,0 +1,7 @@
#pragma once
namespace ava2 {
void initime();
} // namespace ava2
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More