| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056 |
- /*
- * Copyright (C) 2022 The V-Gears Team
- *
- * This file is part of V-Gears
- *
- * V-Gears is free software: you can redistribute it and/or modify it under
- * terms of the GNU General Public License as published by the Free Software
- * Foundation, version 3.0 (GPLv3) of the License.
- *
- * V-Gears is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- */
- #include <algorithm>
- #include <cstdlib>
- #include <iostream>
- #include <cmath>
- #include <limits>
- #include <OgreEntity.h>
- #include <OgreRoot.h>
- #include <OgreViewport.h>
- #include "core/CameraManager.h"
- #include "core/ConfigVar.h"
- #include "core/DebugDraw.h"
- #include "core/EntityManager.h"
- #include "core/EntityModel.h"
- #include "core/InputManager.h"
- #include "core/Logger.h"
- #include "core/ScriptManager.h"
- #include "core/Timer.h"
- #include "core/DialogsManager.h"
- /**
- * Entity manager singleton.
- */
- /**
- * Priority of the script that runs when the player presses OK in front of an entity.
- *
- * It has to run before the scripts that fields leave running on an entity (the loops that play an
- * animation, requested with priority 5 or 6), or the entity could not be talked to. But it can't
- * be the highest: a script of the same entity that is requested with a higher priority (3 or
- * smaller) has to be able to run while the talk script waits for it, as in the scenes where a
- * talk script asks its own entity to do something and waits for it to start.
- */
- static const int INTERACT_SCRIPT_PRIORITY = 4;
- template<>EntityManager *Ogre::Singleton<EntityManager>::msSingleton = nullptr;
- ConfigVar cv_debug_grid("debug_grid", "Draw debug grid", "false");
- ConfigVar cv_debug_axis("debug_axis", "Draw debug axis", "false");
- ConfigVar cv_encounter_multiplier(
- "encounter_multiplier", "Multiplier of the random encounter rate (0 disables them)", "1"
- );
- ConfigVar cv_debug_encounters("debug_encounters", "Log random encounter checks", "false");
- /**
- * Frames of walking (at 30 frames per second) between two encounter checks. The original game
- * checks every 8 frames.
- */
- static const float ENCOUNTER_CHECK_FRAMES = 8.0f;
- /**
- * Value added to the encounter accumulator in each check, before dividing it by the rate of the
- * table. The original game uses the speed of the player, which is not known here, so this is tuned
- * to a battle every 15-30 seconds of walking in most fields. The encounter_multiplier cvar scales
- * it.
- */
- static const float ENCOUNTER_STEP_VALUE = 5.0f;
- const float EntityManager::SCENE_SCALE = 1.0f / 255.0f;
- const unsigned int EntityManager::BATTLE_BACKGROUND_ID = 1000;
- const unsigned int EntityManager::WORLD_MAP_BACKGROUND_ID = 1001;
- float EntityManager::GetTriangleHeight(int triangle, float x, float y, float fallback) const{
- if (IsBattleModule() || triangle < 0 || triangle >= walkmesh_.GetNumberOfTriangles())
- return fallback;
- const float height = PointElevation(
- Ogre::Vector2(x, y), walkmesh_.GetA(triangle), walkmesh_.GetB(triangle),
- walkmesh_.GetC(triangle)
- );
- return std::isfinite(height) ? height : fallback;
- }
- float EntityManager::PointElevation(
- const Ogre::Vector2& point, const Ogre::Vector3& a, const Ogre::Vector3& b, const Ogre::Vector3& c
- ){
- float _a = a.z * (b.y - c.y) + b.z * (c.y - a.y) + c.z * (a.y - b.y);
- float _b = a.y * (b.x - c.x) + b.y * (c.x - a.x) + c.y * (a.x - b.x);
- float _c = a.x * (b.z - c.z) + b.x * (c.z - a.z) + c.x * (a.z - b.z);
- float _d
- = a.x * (b.z * c.y - c.z * b.y) + b.x * (c.z * a.y - a.z * c.y)
- + c.x * (a.z * b.y - b.z * a.y);
- return (_d - _c * point.y - _a * point.x) / _b;
- }
- float EntityManager::SideOfVector(
- const Ogre::Vector2& point, const Ogre::Vector2& p1, const Ogre::Vector2& p2
- ){
- Ogre::Vector2 AB = p2 - p1;
- Ogre::Vector2 AP = point - p1;
- return AB.x * AP.y - AB.y * AP.x;
- }
- float EntityManager::SquareDistanceToLine(
- const Ogre::Vector3& point, const Ogre::Vector3& point_a, const Ogre::Vector3& point_b,
- Ogre::Vector3& proj
- ){
- float temp =
- -((point_a.x - point.x) * (point_b.x - point_a.x) + (point_a.y - point.y)
- * (point_b.y - point_a.y) + (point_a.z - point.z) * (point_b.z - point_a.z))
- / ((point_b.x - point_a.x) * (point_b.x - point_a.x) + (point_b.y - point_a.y)
- * (point_b.y - point_a.y) + (point_b.z - point_a.z) * (point_b.z - point_a.z));
- proj.x = temp * (point_b.x - point_a.x) + point_a.x;
- proj.y = temp * (point_b.y - point_a.y) + point_a.y;
- proj.z = temp * (point_b.z - point_a.z) + point_a.z;
- if (
- ((point_a.x >= proj.x && point_b.x <= proj.x) || (point_a.x < proj.x && point_b.x >= proj.x))
- && (
- (point_a.y >= proj.y && point_b.y <= proj.y) || (point_a.y < proj.y && point_b.y >= proj.y)
- )
- ){
- return (proj.x - point.x) * (proj.x - point.x) + (proj.y - point.y)
- * (proj.y - point.y) + (proj.z - point.z) * (proj.z - point.z);
- }
- return -1;
- }
- Ogre::Degree EntityManager::GetDirectionToPoint(
- const Ogre::Vector3& current_point, const Ogre::Vector3& direction_point
- ){
- // TODO: Declare function in header file.
- Ogre::Vector2 up(0.0f, -1.0f);
- Ogre::Vector2 dir(direction_point.x - current_point.x, direction_point.y - current_point.y);
- // Angle between vectors
- Ogre::Degree angle(Ogre::Radian(SafeAcos(dir.dotProduct(up), dir.length() * up.length())));
- return (dir.x < 0) ? Ogre::Degree(360) - angle : angle;
- }
- EntityManager::EntityManager():
- background_3d_(nullptr),
- player_entity_(nullptr),
- player_move_(Ogre::Vector3::ZERO),
- player_move_rotation_(0),
- player_lock_(false),
- player_run_(false),
- random_encounters_(false),
- encounter_rate_(0),
- encounter_table_(1),
- encounter_distance_(0.0f),
- encounter_last_position_(Ogre::Vector3::ZERO),
- encounter_last_position_valid_(false),
- encounter_safe_steps_(0)
- {
- LOG_TRIVIAL("EntityManager created.");
- scene_node_ = Ogre::Root::getSingleton().getSceneManager("Scene")
- ->getRootSceneNode()->createChildSceneNode("EntityManager");
- //grid_ = Ogre::Root::getSingleton().getSceneManager("Scene")
- // ->createEntity("Grid", "system/grid.mesh");
- grid_ = Ogre::Root::getSingleton().getSceneManager("Scene")->createEntity("Grid", "grid.mesh");
- scene_node_->attachObject(grid_);
- //axis_ = Ogre::Root::getSingleton().getSceneManager("Scene")
- // ->createEntity("Axis", "system/axis.mesh");
- axis_ = Ogre::Root::getSingleton().getSceneManager("Scene")->createEntity("Axis", "axis.mesh");
- scene_node_->attachObject(axis_);
- }
- EntityManager::~EntityManager(){
- if (grid_ != nullptr) Ogre::Root::getSingleton().getSceneManager("Scene")->destroyEntity(grid_);
- if (axis_ != nullptr) Ogre::Root::getSingleton().getSceneManager("Scene")->destroyEntity(axis_);
- Clear();
- Ogre::Root::getSingleton().getSceneManager("Scene")->getRootSceneNode()->removeAndDestroyChild(
- "EntityManager"
- );
- LOG_TRIVIAL("EntityManager destroyed.");
- }
- void EntityManager::Input(const VGears::Event& event){
- background_2d_.InputDebug(event);
- if (paused_ == true) return;
- if (ignore_held_walk_){
- InputManager& input = InputManager::getSingleton();
- if (
- !input.IsGameEventPressed("walk_left") && !input.IsGameEventPressed("walk_right")
- && !input.IsGameEventPressed("walk_up") && !input.IsGameEventPressed("walk_down")
- ) ignore_held_walk_ = false;
- }
- if (player_entity_ != NULL && player_lock_ == false){
- // Keys held since the world map are ignored until they are released.
- const bool key_ignored = ignore_held_walk_ && (
- event.event == "walk_left" || event.event == "walk_right" || event.event == "walk_up"
- || event.event == "walk_down" || event.event == "run"
- );
- if (!key_ignored){
- if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_left") player_move_.x = -1;
- else if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_right")
- player_move_.x = 1;
- if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_down") player_move_.y = -1;
- else if (event.type == VGears::ET_KEY_REPEAT && event.event == "walk_up")
- player_move_.y = 1;
- if (event.type == VGears::ET_KEY_REPEAT && event.event == "run") player_run_ = true;
- }
- if (event.type == VGears::ET_KEY_PRESS && event.event == "CONFIRM"){
- CheckEntityInteract();
- for (unsigned int i = 0; i < entity_triggers_.size(); ++ i){
- if (
- entity_triggers_[i]->IsEnabled() == true
- && entity_triggers_[i]->CheckApproached() == true
- ){
- ScriptEntity* scr_entity = ScriptManager::getSingleton().GetScriptEntityByName(
- ScriptManager::ENTITY, entity_triggers_[i]->GetName()
- );
- bool added = ScriptManager::getSingleton().ScriptRequest(
- scr_entity, "on_interact", INTERACT_SCRIPT_PRIORITY, "", "", false, false
- );
- if (added == false){
- LOG_WARNING(
- "Script 'on_interact' for entity '" + entity_triggers_[i]->GetName()
- + "' doesn't exist."
- );
- }
- }
- }
- }
- }
- }
- void EntityManager::UpdateField(){
- // Update all entity scripts
- ScriptManager::getSingleton().Update(ScriptManager::ENTITY);
- // The player is walking if there is a move set by the input.
- const bool walked = player_entity_ != nullptr && player_move_ != Ogre::Vector3::ZERO;
- // Set move point for player entity
- if (player_entity_ != nullptr && player_move_ != Ogre::Vector3::ZERO){
- Entity::State state = player_entity_->GetState();
- if (state == Entity::WALKMESH || state == Entity::NONE){
- // The directional keys are relative to the screen. Rotate them to the field's move
- // rotation here, once per frame. This can't be done in Input, which runs once for each
- // event, so the rotation would be applied several times when there is more than one
- // event in the frame (diagonals, running, ...). player_move_ stays as the raw input,
- // which is what ladders need.
- // A scripted walk of an entity that isn't the player keeps the last triangle when it
- // goes over an edge, so the stored triangle can be far from the position. Reattach to
- // the walkmesh before moving manually, otherwise every move would be blocked.
- const int current_triangle = player_entity_->GetMoveTriangleId();
- bool in_current_triangle = false;
- if (current_triangle >= 0 && current_triangle < walkmesh_.GetNumberOfTriangles()){
- const Ogre::Vector3 position = player_entity_->GetPosition();
- const Ogre::Vector3 A = walkmesh_.GetA(current_triangle);
- const Ogre::Vector3 B = walkmesh_.GetB(current_triangle);
- const Ogre::Vector3 C = walkmesh_.GetC(current_triangle);
- in_current_triangle = Ogre::Math::pointInTri2D(
- Ogre::Vector2(position.x, position.y), Ogre::Vector2(A.x, A.y),
- Ogre::Vector2(B.x, B.y), Ogre::Vector2(C.x, C.y)
- );
- }
- if (!in_current_triangle) SetEntityOnWalkmesh(player_entity_);
- Ogre::Quaternion rotation;
- rotation.FromAngleAxis(player_move_rotation_, Ogre::Vector3::UNIT_Z);
- // Normalized, so diagonals aren't faster than straight moves.
- Ogre::Vector3 input = player_move_;
- input.normalise();
- const Ogre::Vector3 walk_move = rotation * input
- * (player_entity_->GetMoveWalkSpeed() * Timer::getSingleton().GetGameTimeDelta());
- player_entity_->SetMovePosition(player_entity_->GetPosition() + walk_move);
- player_entity_->SetState(Entity::WALKMESH);
- }
- // HACK: If manually moving, make playable entity solid.
- // Some scripts 'forget' to make the playable entity solid at the end
- // of them, and if it remains non-solid, it can't interact with lines
- // (i.e. it cant' use gateways).
- player_entity_->SetSolid(true);
- }
- for (unsigned int i = 0; i < entity_.size(); ++ i){
- entity_[i]->Update();
- // It's not needed to update movements it delta time == 0 (for example
- // if time is stopped)
- if (Timer::getSingleton().GetGameTimeDelta() == 0) continue;
- // Update screen scroll.
- Entity* scroll_entity = background_2d_.GetAutoScrollEntity();
- if (scroll_entity == entity_[i])
- background_2d_.SetScroll(background_2d_.GetEntityScroll(scroll_entity));
- // Update offset.
- if (entity_[i]->GetOffsetType() != AT_NONE) SetNextOffsetStep(entity_[i]);
- // Update turn.
- if (entity_[i]->GetTurnType() != AT_NONE) SetNextTurnStep(entity_[i]);
- // Update movement.
- switch(entity_[i]->GetState()){
- case Entity::WALKMESH:
- {
- // Try set entity on walkmesh if it's still don't has triangle.
- if (entity_[i]->GetMoveTriangleId() == -1){
- if (SetEntityOnWalkmesh(entity_[i]) == false){
- LOG_TRIVIAL(
- "Can't set entity '" + entity_[i]->GetName()
- + "' on walkmesh. Finish move."
- );
- entity_[i]->UnsetMove();
- }
- }
- // Perform move
- if (entity_[i]->GetState() == Entity::WALKMESH){
- float speed = 0;
- if (player_lock_ == false && player_entity_ == entity_[i]){
- speed = entity_[i]->GetMoveWalkSpeed();
- // TODO: Set as a constant.
- // Or even better, as a configurable variable.
- // The run key inverts the default movement.
- if (player_run_ != player_default_run_) speed *= 4;
- }
- else speed = entity_[i]->GetMoveAutoSpeed();
- float remaining_time = Timer::getSingleton().GetGameTimeDelta();
- bool is_move = false;
- if (entity_[i]->IsScriptedMove() && speed > 0.0f){
- const float max_step_time = 0.2f / speed;
- while (remaining_time > 0.0f && entity_[i]->GetState() == Entity::WALKMESH){
- const float step_time = std::min(remaining_time, max_step_time);
- const bool moved = PerformWalkmeshMove(entity_[i], speed, step_time);
- is_move = is_move || moved;
- if (!moved) break;
- remaining_time -= step_time;
- }
- }
- else is_move = PerformWalkmeshMove(entity_[i], speed, remaining_time);
- // The scripts set the animation of a scene as the default one (DFANM) and
- // don't set it back, but the player stands normally again as soon as they
- // walk in the original game (blin67_3, where Cloud ends the scene crouched).
- if (
- is_move == true && player_lock_ == false && player_entity_ == entity_[i]
- && entity_[i]->GetDefaultAnimationName() != "Idle"
- ){
- entity_[i]->ScriptSetDefaultAnimation("Idle");
- }
- if (entity_[i]->GetMoveAutoAnimation() == true){
- if (is_move == true){
- if (speed >= entity_[i]->GetMoveRunSpeed()){
- entity_[i]->PlayAnimationContinue(
- entity_[i]->GetMoveAnimationRunName()
- );
- }
- else{
- entity_[i]->PlayAnimationContinue(
- entity_[i]->GetMoveAnimationWalkName()
- );
- }
- }
- else if (
- entity_[i]->GetAnimationState() != Entity::REQUESTED_ANIMATION
- ){
- entity_[i]->PlayAnimationContinue(
- entity_[i]->GetDefaultAnimationName()
- );
- }
- }
- }
- }
- break;
- case Entity::LINEAR:
- CheckTriggers(entity_[i], entity_[i]->GetPosition());
- SetNextLinearStep(entity_[i]);
- break;
- case Entity::JUMP:
- SetNextJumpStep(entity_[i]);
- break;
- case Entity::NEEDS_TO_REATTACH:
- if (SetEntityOnWalkmesh(entity_[i])) entity_[i]->SetState(Entity::WALKMESH);
- else entity_[i]->SetState(Entity::NONE);
- case Entity::NONE:
- CheckTriggers(entity_[i], entity_[i]->GetPosition());
- if (entity_[i]->GetAnimationState() != Entity::REQUESTED_ANIMATION)
- entity_[i]->PlayAnimationContinue(entity_[i]->GetDefaultAnimationName());
- break;
- }
- }
- CheckEntityContacts();
- // Reset player move. It already must be handled in update
- player_move_ = Ogre::Vector3::ZERO;
- player_run_ = false;
- if (background_2d_.GetScrollType() != Background2D::NONE) SetNextScrollStep();
- background_2d_.Update();
- // This can start a battle and change the module, so it's the last thing to do.
- UpdateEncounters(walked);
- // The movie follows the speed of the game, so the scenes that are timed with it stay in sync.
- // Its sound doesn't, so at any other speed they drift apart.
- movie_player_.Update(Timer::getSingleton().GetGameTimeDelta());
- screen_fade_.Update(Timer::getSingleton().GetGameTimeDelta());
- }
- void EntityManager::UpdateBattle(){
- ScriptManager::getSingleton().Update(ScriptManager::BATTLE);
- if (background_3d_ != nullptr){
- background_3d_->Update();
- background_3d_->PlayAnimationContinue(background_3d_->GetDefaultAnimationName());
- }
- for (unsigned int i = 0; i < battle_entity_.size(); ++ i){
- battle_entity_[i]->Update();
- // Go back to the default animation, unless an animation has been requested. Requested
- // animations that are not looped go back to the default one by themselves when they end.
- if (battle_entity_[i]->GetAnimationState() != Entity::REQUESTED_ANIMATION){
- battle_entity_[i]->PlayAnimationContinue(battle_entity_[i]->GetDefaultAnimationName());
- }
- }
- //CameraManager::getSingleton().GetCurrentCamera()->roll(Ogre::Radian(0.01));
- }
- void EntityManager::UpdateWorld(){
- ScriptManager::getSingleton().Update(ScriptManager::ENTITY);
- for (Entity* entity : entity_){
- entity->Update();
- }
- player_move_ = Ogre::Vector3::ZERO;
- player_run_ = false;
- }
- void EntityManager::AddFieldOrWorldMapEntity(
- const Ogre::String& name, const Ogre::String& file_name, const Ogre::Vector3& position,
- const Ogre::Degree& rotation, const Ogre::Vector3& scale,
- const Ogre::Quaternion& root_orientation, const int index
- ){
- if (module_ != Module::FIELD){
- LOG_ERROR("Tried to add field or world Entity but the EntityManager is in battle mode.");
- return;
- }
- Ogre::SceneNode* node = scene_node_->createChildSceneNode("Model_" + name);
- EntityModel* entity = new EntityModel(name, file_name, node);
- entity->SetPosition(position);
- entity->SetRotation(rotation);
- entity->setScale(scale);
- entity->SetIndex(index);
- entity->setRootOrientation(root_orientation);
- // The models of a field are visible, solid and talkable until a script changes it (VISI 0,
- // SOLID 1, TLKON 1). Many entities, such as the doors of mds6_2 or the people of mrkt2, are
- // never turned on by a script. Setting a position doesn't turn them on.
- entity->SetVisible(true);
- entity->SetSolid(true);
- entity->SetTalkable(true);
- entity_.push_back(entity);
- ScriptManager::getSingleton().AddEntity(ScriptManager::ENTITY, entity->GetName(), entity);
- }
- EntityModel* EntityManager::AddWorldMapEntity(
- const Ogre::String& name, const Ogre::String& file_name,
- const Ogre::Vector3& position, const Ogre::Degree& rotation,
- const Ogre::Vector3& scale, const Ogre::String& resource_group
- ){
- if (!IsWorldModule()){
- LOG_ERROR("Tried to add a world-map entity outside world-map mode.");
- return nullptr;
- }
- if (GetEntity(name) != nullptr){
- LOG_ERROR("Tried to add duplicate world-map entity '" + name + "'.");
- return nullptr;
- }
- Ogre::SceneNode* node = scene_node_->createChildSceneNode("Model_" + name);
- EntityModel* entity = new EntityModel(name, file_name, node, resource_group);
- entity->SetPosition(position);
- entity->SetRotation(rotation);
- entity->setScale(scale);
- entity->SetVisible(true);
- entity_.push_back(entity);
- ScriptManager::getSingleton().AddEntity(ScriptManager::ENTITY, entity->GetName(), entity);
- return entity;
- }
- void EntityManager::AddBattleEntity(
- const Ogre::String& name, const Ogre::String& file_name, const Ogre::Vector3& position,
- const Ogre::Degree& rotation, const Ogre::Vector3& scale,
- const Ogre::Quaternion& root_orientation, const int index
- ){
- if (module_ != Module::BATTLE){
- LOG_ERROR("Tried to add battle Entity but the EntityManager is not in battle mode.");
- return;
- }
- Ogre::SceneNode* node = scene_node_->createChildSceneNode("Battle_" + name);
- // Battle models must be reoriented.
- node->setOrientation(root_orientation);
- EntityModel* entity = new EntityModel(name, file_name, node);
- entity->SetPosition(position);
- entity->SetRotation(rotation);
- entity->setScale(scale);
- entity->SetIndex(index);
- entity->SetVisible(true);
- battle_entity_.push_back(entity);
- ScriptManager::getSingleton().AddEntity(ScriptManager::BATTLE, entity->GetName(), entity);
- /*std::cout << "BATTLE ANIMATIONS FOR " << name << std::endl;
- const std::map<Ogre::String, Ogre::AnimationState*>& anims
- = entity->GetModel()->getAllAnimationStates()->getAnimationStates();
- int size = anims.size();
- std::cout << " " << std::to_string(size) << " TOTAL " << std::endl;
- for (auto anim = anims.begin(); anim != anims.end(); ++ anim){
- std::cout << " - " << anim->first << ", " << anim->second << std::endl;
- }*/
- /* Animations have the following names:
- * XX_00,
- * XX_01,
- * XX_02,
- * ...
- * where XX is the first two characters of file_name, without the path.
- */
- Ogre::String anim = file_name.substr(file_name.find_last_of("/\\") + 1).substr(0, 2) + "_00";
- //std::cout << " Playing " << anim << std::endl;
- entity->ScriptSetDefaultAnimation(anim.c_str());
- }
- void EntityManager::RemoveBattleEntity(const Ogre::String& name){
- if (module_ != Module::BATTLE) return;
- for (auto it = battle_entity_.begin(); it != battle_entity_.end(); ++ it){
- Entity* entity = *it;
- if (entity->GetName() != name) continue;
- ScriptManager::getSingleton().RemoveEntity(ScriptManager::BATTLE, name);
- battle_entity_.erase(it);
- // The entity is not deleted, as its destructor would destroy the model again, like in
- // ClearBattle. So what the model holds (a weapon) has to be destroyed here.
- entity->ScriptAttachModel("", -1, 0.0f, 0.0f, 0.0f);
- Ogre::Root::getSingleton().getSceneManager("Scene")->destroyEntity(name);
- scene_node_->removeAndDestroyChild("Battle_" + name);
- entity->ReleaseResources();
- return;
- }
- }
- void EntityManager::RemoveWorldMapEntity(const Ogre::String& name){
- if (!IsWorldModule()) return;
- for (auto it = entity_.begin(); it != entity_.end(); ++ it){
- Entity* entity = *it;
- if (entity->GetName() != name) continue;
- if (entity == player_entity_) return;
- ScriptManager::getSingleton().RemoveEntity(ScriptManager::ENTITY, name);
- entity_.erase(it);
- // The destructor of the model destroys it.
- delete entity;
- scene_node_->removeAndDestroyChild("Model_" + name);
- return;
- }
- }
- Entity* EntityManager::GetBackground3D() const{
- if (IsFieldModule()){
- LOG_WARNING("Tried to retrieve a 3D background while the EntityManager is in field mode.");
- return nullptr;
- }
- return background_3d_;
- }
- void EntityManager::SetBackground3D(const Ogre::String& name, const Ogre::String& file_name){
- if (IsFieldModule()){
- LOG_ERROR("Tried to add a 3D background while the EntityManager is in field mode.");
- return;
- }
- Ogre::SceneNode* node = scene_node_->createChildSceneNode("bg_" + name);
- background_3d_ = new EntityModel(name, file_name, node);
- background_3d_->SetPosition(Ogre::Vector3(0, 0, 0));
- background_3d_->SetRotation(Ogre::Degree(0));
- background_3d_->setScale(Ogre::Vector3(SCENE_SCALE, SCENE_SCALE, SCENE_SCALE));
- background_3d_->SetIndex(IsBattleModule() ? BATTLE_BACKGROUND_ID : WORLD_MAP_BACKGROUND_ID);
- background_3d_->SetVisible(true);
- // Backgrounds must be reoriented.
- node->setOrientation(1, 1, 0, 0);
- // Probably don't need a script for the 3d background.
- /*ScriptManager::getSingleton().AddEntity(
- ScriptManager::BATTLE, background_3d_->GetName(), background_3d_
- );*/
- }
- void EntityManager::UpdateDebug(){
- // Only the world map fades the debug text with the distance to the camera.
- DEBUG_DRAW.SetFadeEnabled(module_ == Module::WORLD);
- grid_->setVisible(cv_debug_grid.GetB());
- axis_->setVisible(cv_debug_axis.GetB());
- if (module_ == Module::BATTLE){
- if (background_3d_ != nullptr) background_3d_->UpdateDebug();
- for (unsigned int i = 0; i < battle_entity_.size(); ++ i) battle_entity_[i]->UpdateDebug();
- }
- else{
- for (unsigned int i = 0; i < entity_.size(); ++ i) entity_[i]->UpdateDebug();
- for (unsigned int i = 0; i < entity_triggers_.size(); ++ i)
- entity_triggers_[i]->UpdateDebug();
- for (unsigned int i = 0; i < entity_points_.size(); ++ i) entity_points_[i]->UpdateDebug();
- walkmesh_.UpdateDebug();
- background_2d_.UpdateDebug();
- }
- }
- void EntityManager::OnResize(){background_2d_.OnResize();}
- void EntityManager::ClearField(){
- ClearEncounterTables();
- entities_hidden_by_battle_.clear();
- entities_in_contact_.clear();
- walkmesh_.Clear();
- background_2d_.Clear();
- screen_fade_.Clear();
- player_slip_ = true;
- DialogsManager::getSingleton().Clear();
- for (unsigned int i = 0; i < entity_.size(); ++ i){
- ScriptManager::getSingleton().RemoveEntity(ScriptManager::ENTITY, entity_[i]->GetName());
- delete entity_[i];
- }
- entity_.clear();
- player_entity_ = nullptr;
- player_move_ = Ogre::Vector3::ZERO;
- player_move_rotation_ = 0;
- player_lock_ = false;
- for (unsigned int i = 0; i < entity_triggers_.size(); ++ i){
- ScriptManager::getSingleton().RemoveEntity(
- ScriptManager::ENTITY, entity_triggers_[i]->GetName()
- );
- delete entity_triggers_[i];
- }
- entity_triggers_.clear();
- for (unsigned int i = 0; i < entity_points_.size(); ++ i) delete entity_points_[i];
- entity_points_.clear();
- for (unsigned int i = 0; i < entity_scripts_.size(); ++ i)
- ScriptManager::getSingleton().RemoveEntity(ScriptManager::ENTITY, entity_scripts_[i]);
- scene_node_->removeAndDestroyAllChildren();
- }
- void EntityManager::ClearBattle(){
- for (unsigned int i = 0; i < battle_entity_.size(); ++ i){
- ScriptManager::getSingleton().RemoveEntity(
- ScriptManager::ENTITY, battle_entity_[i]->GetName()
- );
- // The model held in a bone (a weapon) is another Ogre entity, and the next battle creates
- // one with the same name.
- battle_entity_[i]->ScriptAttachModel("", -1, 0.0f, 0.0f, 0.0f);
- Ogre::Root::getSingleton().getSceneManager("Scene")->destroyEntity(
- battle_entity_[i]->GetName()
- );
- scene_node_->removeAndDestroyChild("Battle_" + battle_entity_[i]->GetName());
- }
- battle_entity_.clear();
- if (background_3d_ != nullptr){
- Ogre::Root::getSingleton().getSceneManager("Scene")->destroyEntity(
- "bg_" + background_3d_->GetName()
- );
- /*ScriptManager::getSingleton().RemoveEntity(
- ScriptManager::ENTITY, background_3d_->GetName()
- );*/
- scene_node_->getChild("bg_" + background_3d_->GetName())->removeAllChildren();
- scene_node_->removeAndDestroyChild("bg_" + background_3d_->GetName());
- Ogre::Root::getSingleton().getSceneManager("Scene")->destroyEntity(
- background_3d_->GetName()
- );
- background_3d_ = nullptr;
- }
- }
- void EntityManager::ClearWorld(){
- walkmesh_.Clear();
- for (Entity* entity : entity_){
- ScriptManager::getSingleton().RemoveEntity(ScriptManager::ENTITY, entity->GetName());
- delete entity;
- }
- entity_.clear();
- player_entity_ = nullptr;
- player_move_ = Ogre::Vector3::ZERO;
- player_move_rotation_ = 0;
- player_lock_ = false;
- player_run_ = false;
- for (EntityTrigger* trigger : entity_triggers_){
- ScriptManager::getSingleton().RemoveEntity(ScriptManager::ENTITY, trigger->GetName());
- delete trigger;
- }
- entity_triggers_.clear();
- for (EntityPoint* point : entity_points_) delete point;
- entity_points_.clear();
- for (const Ogre::String& script : entity_scripts_){
- ScriptManager::getSingleton().RemoveEntity(ScriptManager::ENTITY, script);
- }
- entity_scripts_.clear();
- scene_node_->removeAndDestroyAllChildren();
- }
- Walkmesh* EntityManager::GetWalkmesh(){return &walkmesh_;}
- bool EntityManager::IsWorldPositionBlocked(
- const Entity* moving_entity, const Ogre::Vector3& position
- ) const{
- if (!IsWorldModule() || moving_entity == nullptr) return false;
- for (const Entity* other : entity_){
- if (other == moving_entity || !other->IsSolid()) continue;
- const Ogre::Vector3 other_position = other->GetPosition();
- const Ogre::Real dx = position.x - other_position.x;
- const Ogre::Real dz = position.z - other_position.z;
- const Ogre::Real radius = moving_entity->GetSolidRadius() + other->GetSolidRadius();
- if (dx * dx + dz * dz >= radius * radius) continue;
- const Ogre::Real moving_top = position.y + moving_entity->GetHeight();
- const Ogre::Real other_top = other_position.y + other->GetHeight();
- if (position.y < other_top && other_position.y < moving_top) return true;
- }
- return false;
- }
- Background2D* EntityManager::GetBackground2D(){return &background_2d_;}
- ScreenFade* EntityManager::GetScreenFade(){return &screen_fade_;}
- MoviePlayer* EntityManager::GetMoviePlayer(){return &movie_player_;}
- void EntityManager::AddEntity(
- const Ogre::String& name, const Ogre::String& file_name,
- const Ogre::Vector3& position, const Ogre::Degree& rotation, int index
- ){
- AddEntity(
- name, file_name, position, rotation,
- Ogre::Vector3::UNIT_SCALE, Ogre::Quaternion::IDENTITY, index
- );
- }
- void EntityManager::AddEntity(
- const Ogre::String& name, const Ogre::String& file_name, const Ogre::Vector3& position,
- const Ogre::Degree& rotation, const Ogre::Vector3& scale,
- const Ogre::Quaternion& root_orientation, const int index
- ){
- if (IsBattleModule())
- AddBattleEntity(name, file_name, position, rotation, scale, root_orientation, index);
- else
- AddFieldOrWorldMapEntity(
- name, file_name, position, rotation, scale, root_orientation, index
- );
- }
- void EntityManager::ScriptAddEntity(
- const char* name, const char* file_name,
- const float x, const float y, const float z, const float rotation, int index
- ){AddEntity(name, file_name, Ogre::Vector3(x, y, z), Ogre::Degree(rotation), index);}
- void EntityManager::AddEntityTrigger(
- const Ogre::String& name,
- const Ogre::Vector3& point1, const Ogre::Vector3& point2, const bool enabled
- ){
- if (IsBattleModule()){
- LOG_WARNING("Tried to add an entity trigger but the EntityManager is in battle mode.");
- return;
- }
- EntityTrigger* trigger = new EntityTrigger(name);
- trigger->SetPoints(point1, point2);
- trigger->SetEnabled(enabled);
- entity_triggers_.push_back(trigger);
- ScriptManager::getSingleton().AddEntity(ScriptManager::ENTITY, trigger->GetName(), nullptr);
- }
- void EntityManager::AddEntityPoint(
- const Ogre::String& name, const Ogre::Vector3& position, const float rotation
- ){
- if (IsBattleModule()){
- LOG_WARNING("Tried to add an entity point but the EntityManager is in battle mode.");
- return;
- }
- EntityPoint* entity_point = new EntityPoint(name);
- entity_point->SetPosition(position);
- entity_point->SetRotation(rotation);
- entity_points_.push_back(entity_point);
- }
- void EntityManager::AddEntityScript(const Ogre::String& name){
- // TODO: Should call to this be prevented while in battle mode?
- entity_scripts_.push_back(name);
- ScriptManager::getSingleton().AddEntity(ScriptManager::ENTITY, name, nullptr);
- }
- void EntityManager::ScriptAddEntityScript(const char* name){AddEntityScript(name);}
- Entity* EntityManager::GetEntity(const Ogre::String& name) const{
- if (IsBattleModule()){
- for (unsigned int i = 0; i < battle_entity_.size(); ++ i)
- if (battle_entity_[i]->GetName() == name) return battle_entity_[i];
- }
- else{
- for (unsigned int i = 0; i < entity_.size(); ++ i)
- if (entity_[i]->GetName() == name) return entity_[i];
- }
- return nullptr;
- }
- Entity* EntityManager::GetEntityFromIndex(const int index) const{
- if (IsBattleModule()){
- if (background_3d_ != nullptr && background_3d_->GetIndex() == index)
- return background_3d_;
- for (unsigned int i = 0; i < battle_entity_.size(); ++ i)
- if (battle_entity_[i]->GetIndex() == index) return battle_entity_[i];
- }
- else{
- for (unsigned int i = 0; i < entity_.size(); ++ i)
- if (entity_[i]->GetIndex() == index) return entity_[i];
- }
- return nullptr;
- }
- Entity* EntityManager::GetEntityFromCharacterId(const int id) const{
- if (IsBattleModule()){
- for (unsigned int i = 0; i < battle_entity_.size(); ++ i)
- if (battle_entity_[i]->IsCharacter() && battle_entity_[i]->GetCharacterId() == id)
- return battle_entity_[i];
- }
- else{
- for (unsigned int i = 0; i < entity_.size(); ++ i)
- if (entity_[i]->IsCharacter() && entity_[i]->GetCharacterId() == id) return entity_[i];
- }
- return nullptr;
- }
- Entity* EntityManager::ScriptGetEntity(const char* name) const{
- return GetEntity(Ogre::String(name));
- }
- EntityPoint* EntityManager::ScriptGetEntityPoint(const char* name) const{
- for (unsigned int i = 0; i < entity_points_.size(); ++ i)
- if (entity_points_[i]->GetName() == name) return entity_points_[i];
- return nullptr;
- }
- void EntityManager::ScriptSetPlayerEntity(const char* name){
- if (IsBattleModule()){
- LOG_WARNING("Tried to set a player entity but the EntityManager is in battle mode.");
- return;
- }
- for (unsigned int i = 0; i < entity_.size(); ++ i){
- if (entity_[i]->GetName() == name){
- // A script can read the walkmesh triangle of the player right after this, so if it was
- // placed by position the triangle has to be known. Done before it's the player entity
- // so that the entity not being on the walkmesh yet isn't logged as an error.
- if (entity_[i]->GetMoveTriangleId() == -1 && entity_[i]->GetPosition().isZeroLength()){
- // A model that has no position of its own (the fields put the dressed Cloud away
- // until a script makes it the player) takes the place of the previous player,
- // which is where the field entry put the party, as in the original game.
- if (player_entity_ != nullptr && player_entity_ != entity_[i]){
- entity_[i]->SetPosition(player_entity_->GetPosition());
- entity_[i]->SetRotation(player_entity_->GetRotation());
- }
- }
- if (entity_[i]->GetMoveTriangleId() == -1) SetEntityOnWalkmesh(entity_[i]);
- LOG_TRIVIAL("Player entity set to '" + std::string(name) + "'.");
- // The camera that follows the player keeps following it when another entity takes over
- // (Cloud and the dressed Cloud, for example); a camera that follows some other entity
- // is left as it is.
- if (player_entity_ != nullptr && background_2d_.GetAutoScrollEntity() == player_entity_)
- background_2d_.ScriptAutoScrollToEntity(entity_[i]);
- // The camera follows the player when no script has said anything about it (the fields
- // without a Director, such as ujunon1, have no opcode that starts it).
- else if (!background_2d_.HasScrollControl())
- background_2d_.ScriptAutoScrollToEntity(entity_[i]);
- player_entity_ = entity_[i];
- // Also, make it non-talkable. Visibility and solidity are left to the scripts, as in
- // the original game: some fields use hidden helper entities (like the 'camera') as
- // the player entity to scroll the screen, and they must stay invisible and
- // non-solid. When the player moves manually, UpdateField makes it solid anyway.
- entity_[i]->SetTalkable(false);
- }
- }
- }
- void EntityManager::ScriptPlacePlayerAtFieldEntry(
- const float x, const float y, const int triangle_id, const float direction
- ){
- if (player_entity_ == nullptr || walkmesh_.GetNumberOfTriangles() <= 0) return;
- int safe_triangle_id = triangle_id;
- if (safe_triangle_id < 0 || safe_triangle_id >= walkmesh_.GetNumberOfTriangles()){
- LOG_WARNING("World-map field entry has an invalid walkmesh triangle; using triangle 0.");
- safe_triangle_id = 0;
- }
- player_entity_->SetPosition(Ogre::Vector3(
- x, y, walkmesh_.GetA(static_cast<unsigned int>(safe_triangle_id)).z
- ));
- player_entity_->SetRotation(Ogre::Degree(direction));
- player_entity_->SetMoveTriangleId(safe_triangle_id);
- // In the WALKMESH state the entity walks to its move position: without this one it walks to
- // whatever it had (the origin of the field), and the player enters the town walking.
- player_entity_->SetMovePosition(player_entity_->GetPosition());
- player_entity_->SetState(Entity::WALKMESH);
- // The player starts standing still: no move or run from the world map, and the held keys
- // don't count until they are released.
- player_move_ = Ogre::Vector3::ZERO;
- player_run_ = false;
- ignore_held_walk_ = true;
- player_entity_->PlayAnimationContinue(player_entity_->GetDefaultAnimationName());
- }
- Entity* EntityManager::ScriptGetPlayerEntity() const{
- if (IsBattleModule()){
- LOG_WARNING("Tried to set a player entity but the EntityManager is in battle mode.");
- return nullptr;
- }
- return player_entity_;
- }
- void EntityManager::ScriptUnsetPlayerEntity(){
- if (IsBattleModule()){
- LOG_WARNING("Tried to unset a player entity but the EntityManager is in battle mode.");
- return;
- }
- player_entity_ = nullptr;
- }
- void EntityManager::ScriptSetPlayerSlip(const bool slip){player_slip_ = slip;}
- void EntityManager::ScriptPlayerLock(const bool lock){
- if (IsBattleModule()){
- LOG_WARNING("Tried to set player lock but the EntityManager is in battle mode.");
- return;
- }
- player_lock_ = lock;
- if (lock == true) player_move_ = Ogre::Vector3::ZERO;
- // A field with no entity for the leader of the party (the parade of junonr4, where the player
- // is a soldier that no PC opcode names) gives the control to the entity whose script lets go
- // of it.
- else if (player_entity_ == nullptr && IsFieldModule()){
- const ScriptId script = ScriptManager::getSingleton().GetCurrentScriptId();
- Entity* entity = GetEntity(script.entity);
- if (entity != nullptr && !entity->IsLine()){
- LOG_TRIVIAL("The control goes to '" + script.entity + "', there is no player entity.");
- ScriptSetPlayerEntity(script.entity.c_str());
- if (!background_2d_.HasScrollControl()) background_2d_.ScriptAutoScrollToEntity(entity);
- }
- }
- }
- bool EntityManager::IsPlayerLocked() const{return player_lock_;}
- void EntityManager::SetPlayerDefaultRun(const bool run){player_default_run_ = run;}
- void EntityManager::SetPlayerMoveRotation(const Ogre::Radian rotation){
- if (IsBattleModule()){
- LOG_WARNING("Tried to set player move rotation the EntityManager is in battle mode.");
- return;
- }
- player_move_rotation_ = rotation;
- }
- bool EntityManager::GetRandomEncounters(){return random_encounters_;}
- float EntityManager::GetEncounterMultiplier() const{return cv_encounter_multiplier.GetF();}
- bool EntityManager::IsDebugEncounters() const{return cv_debug_encounters.GetB();}
- void EntityManager::SetRandomEncounters(bool active){random_encounters_ = active;}
- float EntityManager::GetEncounterRate(){return encounter_rate_;}
- void EntityManager::HideFieldEntities(){
- entities_hidden_by_battle_.clear();
- for (Entity* entity : entity_){
- if (entity->IsVisible()){
- entities_hidden_by_battle_.push_back(entity);
- entity->SetVisible(false);
- }
- }
- }
- void EntityManager::ShowFieldEntities(){
- // Only the ones that still exist: the field could have been changed during the battle.
- for (Entity* hidden : entities_hidden_by_battle_){
- if (std::find(entity_.begin(), entity_.end(), hidden) != entity_.end()) hidden->SetVisible(true);
- }
- entities_hidden_by_battle_.clear();
- }
- void EntityManager::ClearEncounterTables(){
- encounter_tables_.clear();
- encounter_table_ = 1;
- encounter_distance_ = 0.0f;
- encounter_last_position_valid_ = false;
- encounter_accumulator_ = 0;
- encounter_last_battle_ = -1;
- }
- void EntityManager::AddEncounterTable(
- const int id, const int rate, const std::vector<std::pair<int, int>>& battles,
- const std::vector<std::pair<int, int>>& specials
- ){
- EncounterTable table;
- table.rate = rate;
- table.battles = battles;
- table.specials = specials;
- encounter_tables_[id] = table;
- }
- void EntityManager::ScriptSetEncounterTable(const int id){encounter_table_ = id;}
- int EntityManager::ScriptRollEncounterBattle() const{
- auto found = encounter_tables_.find(encounter_table_);
- if (found == encounter_tables_.end()) return -1;
- const EncounterTable& table = found->second;
- // Like the original game: a roll out of 64 is checked against the special battles one after
- // the other (each one adds its probability). If none is hit, a new roll chooses a standard
- // battle, the last one being the default.
- int roll = std::rand() % 64;
- int sum = 0;
- for (const auto& special : table.specials){
- sum += special.second;
- if (roll < sum) return special.first;
- }
- if (table.battles.empty()) return -1;
- roll = std::rand() % 64;
- sum = 0;
- for (const auto& battle : table.battles){
- sum += battle.second;
- if (roll < sum) return battle.first;
- }
- return table.battles.back().first;
- }
- void EntityManager::UpdateEncounters(const bool walked){
- if (player_entity_ == nullptr){
- encounter_last_position_valid_ = false;
- return;
- }
- const Ogre::Vector3 position = player_entity_->GetPosition();
- const float distance
- = encounter_last_position_valid_ ? (position - encounter_last_position_).length() : 0.0f;
- encounter_last_position_ = position;
- encounter_last_position_valid_ = true;
- // Only walking counts: not scripted movements, and not jumps to another place.
- if (!walked || player_lock_ || distance > 2.0f) return;
- if (!random_encounters_ || encounter_tables_.empty()) return;
- auto found = encounter_tables_.find(encounter_table_);
- if (found == encounter_tables_.end()) return;
- const float multiplier = cv_encounter_multiplier.GetF();
- if (multiplier <= 0.0f) return;
- // Same as the original game. Every few frames of walking the accumulator grows by a value
- // divided by the rate (the lower the rate, the more often the encounters), and an encounter
- // starts if a random number is lower than the accumulator.
- const int rate = found->second.rate;
- if (rate <= 0) return;
- encounter_distance_ += Timer::getSingleton().GetGameTimeDelta() * 30.0f;
- while (encounter_distance_ >= ENCOUNTER_CHECK_FRAMES){
- encounter_distance_ -= ENCOUNTER_CHECK_FRAMES;
- // Enemy Away and Enemy Lure materia change the rate of the party (see Party.get_encounter_modifier).
- const float materia_multiplier
- = ScriptManager::getSingleton().EvaluateNumber("Party.get_encounter_modifier()", 1.0f);
- encounter_accumulator_ += static_cast<int>(ENCOUNTER_STEP_VALUE * multiplier * materia_multiplier * 256.0f) / rate;
- const int roll = std::rand() % 256 * 256;
- if (cv_debug_encounters.GetB()){
- LOG_TRIVIAL(
- "Encounter check: rate " + std::to_string(rate) + ", accumulator "
- + std::to_string(encounter_accumulator_ / 256.0f) + "/256, roll "
- + std::to_string(roll / 256)
- );
- }
- if (roll >= encounter_accumulator_) continue;
- int battle = ScriptRollEncounterBattle();
- // The same battle is not repeated: it's rolled again once.
- if (battle == encounter_last_battle_) battle = ScriptRollEncounterBattle();
- if (battle < 0) return;
- encounter_distance_ = 0.0f;
- encounter_accumulator_ = 0;
- encounter_last_battle_ = battle;
- LOG_TRIVIAL("Random encounter: battle " + std::to_string(battle));
- // The battle is started by a script, as it has to change the module of every manager.
- ScriptManager::getSingleton().RunString("Encounter.start(" + std::to_string(battle) + ")");
- return;
- }
- }
- void EntityManager::SetEncounterRate(float rate){
- if (rate >= 1.0f) encounter_rate_ = 1.0f;
- else if (rate <= 0.0f) encounter_rate_ = 0.0f;
- else encounter_rate_ = rate;
- }
- bool EntityManager::IsStartKeyRead() const{
- return std::chrono::steady_clock::now() - start_key_read_time_ < std::chrono::milliseconds(300);
- }
- bool EntityManager::IsKeyOn(unsigned int key_code){
- if (key_code & 2048) start_key_read_time_ = std::chrono::steady_clock::now();
- // The keys are read even if the player is locked: scenes lock the player and still ask for a
- // button, as the minigames that need to be pressed at the right time do. The scripts that
- // must not read the keys at some point (while a message is open, for example) have their own
- // flag for it. The triggers that check keys aren't run while the player is locked.
- // The key code of the scripts is a mask of the pad buttons, and the check is true if any of
- // them is pressed. Translate each to its game event (see bind_game_event in config.cfg), so
- // the keys chosen in the controller settings are the ones that count. For example 32 is
- // "Circle/Action", the OK button.
- static const struct{unsigned int mask; const char* event;} BUTTONS[] = {
- {1, "L2"}, {2, "R2"}, {4, "L1"}, {8, "R1"}, {16, "MENU"}, {32, "CONFIRM"}, {64, "CANCEL"},
- {128, "EXTRA"}, {256, "SELECT"}, {2048, "START"},
- {4096, "Up"}, {8192, "Right"}, {16384, "Down"}, {32768, "Left"}
- };
- for (const auto& entry : BUTTONS)
- if ((key_code & entry.mask) && InputManager::getSingleton().IsGameEventPressed(entry.event))
- return true;
- // TODO: In the original game the button that makes the player run is the Cancel button (64),
- // so scripts that check Cancel are checking if the player runs (the sneak out of ealin_2, for
- // example). Here running has its own game event, "run", so it counts as Cancel too. Scripts
- // that really want the Cancel button would see it pressed while running. Check which scripts
- // need which, and maybe split them.
- if ((key_code & 64) && InputManager::getSingleton().IsGameEventPressed("run")) return true;
- return false;
- }
- bool EntityManager::IsKeyOff(unsigned int key_code){return !IsKeyOn(key_code);}
- void EntityManager::SetEntityToCharacter(const char* entity_name, unsigned int char_id){
- if (IsBattleModule()){
- for (unsigned int i = 0; i < battle_entity_.size(); ++ i){
- if (battle_entity_[i]->GetName() == entity_name){
- battle_entity_[i]->SetCharacter(char_id);
- return;
- }
- }
- }
- else{
- for (unsigned int i = 0; i < entity_.size(); ++ i){
- if (entity_[i]->GetName() == entity_name){
- entity_[i]->SetCharacter(char_id);
- return;
- }
- }
- }
- LOG_WARNING(
- "Unabe to assigne character ID " + std::to_string(char_id) + " to entity '" + entity_name
- + "'. No entity by that name exists."
- );
- }
- bool EntityManager::SetEntityOnWalkmesh(Entity* entity){
- if (IsBattleModule()){
- LOG_WARNING("Tried to set entity on the walkmesh, but the EntityManager is in battle mode");
- return false;
- }
- Ogre::Vector3 position3 = entity->GetPosition();
- Ogre::Vector2 position2;
- position2.x = position3.x;
- position2.y = position3.y;
- std::vector<std::pair<int, float>> triangles;
- // Search for possible triangles.
- for (int i = 0; i < walkmesh_.GetNumberOfTriangles(); ++ i){
- Ogre::Vector3 A3 = walkmesh_.GetA(i);
- Ogre::Vector3 B3 = walkmesh_.GetB(i);
- Ogre::Vector3 C3 = walkmesh_.GetC(i);
- Ogre::Vector2 A2(A3.x, A3.y);
- Ogre::Vector2 B2(B3.x, B3.y);
- Ogre::Vector2 C2(C3.x, C3.y);
- if (Ogre::Math::pointInTri2D(position2, A2, B2, C2) == true){
- triangles.push_back(std::make_pair(i, PointElevation(
- position2, walkmesh_.GetA(i), walkmesh_.GetB(i), walkmesh_.GetC(i)
- )));
- }
- }
- // If the coordinates doesn't match any triangle, exit.
- if (triangles.size() == 0 && entity == player_entity_){
- LOG_ERROR(
- "Can't find any triangle to place entity '" + entity->GetName() + "' on walkmesh."
- );
- return false;
- }
- // From the possible triangles, select the closest one (on the Z edge).
- int closest_z_triangle = -1;
- float closest_z_distance = 9999.0f;
- float pos_z = position3.z;
- for (size_t i = 0; i < triangles.size(); ++ i){
- if (std::abs(pos_z - triangles[i].second) < closest_z_distance){
- closest_z_triangle = triangles[i].first;
- closest_z_distance = std::abs(pos_z - triangles[i].second);
- }
- }
- if (closest_z_triangle == -1 && entity == player_entity_){
- LOG_ERROR(
- "Can't find nearby triangle to place entity '" + entity->GetName() + "' on walkmesh."
- );
- return false;
- }
- entity->SetPosition(Ogre::Vector3(position2.x, position2.y, pos_z));
- entity->SetMoveTriangleId(closest_z_triangle);
- return true;
- }
- float EntityManager::TriggerReach(float solid_radius){
- // The radius an entity has when a script doesn't change it.
- const float default_radius = 0.21f;
- return solid_radius < 0.01f ? default_radius : solid_radius;
- }
- bool EntityManager::WalkmeshEdgeBlocks(bool is_player, bool scripted_move){
- return is_player || !scripted_move;
- }
- bool EntityManager::IsBetterInteractionTarget(
- float angle, float distance, float best_angle, float best_distance
- ){
- const float same_angle = 0.001f;
- if (angle < best_angle - same_angle) return true;
- return std::fabs(angle - best_angle) <= same_angle && distance < best_distance;
- }
- float EntityManager::ScriptedMoveStep(float distance, float stop_distance, float max_step){
- return std::min(max_step, std::max(0.0f, distance - stop_distance));
- }
- bool EntityManager::PerformWalkmeshMove(Entity* entity, const float speed, const float delta_time){
- if (IsBattleModule()){
- LOG_WARNING("Tried to perform a walkmesh move, but the EntityManager is in battle mode");
- return false;
- }
- Ogre::Vector3 start_point = entity->GetPosition();
- Ogre::Vector3 move_vector = entity->GetMovePosition() - start_point;
- Ogre::Vector2 direction(move_vector.x, move_vector.y);
- const float distance_to_target = direction.length();
- const bool scripted_move = entity->IsScriptedMove();
- const float stop_distance = entity->GetMoveStopDistance();
- if (scripted_move && distance_to_target <= stop_distance + 0.0001f){
- entity->UnsetMove();
- return false;
- }
- direction.normalise();
- direction *= delta_time;
- direction *= speed;
- if (scripted_move && !direction.isZeroLength()){
- direction.normalise();
- direction *= ScriptedMoveStep(
- distance_to_target, stop_distance, speed * delta_time
- );
- }
- // If movement is still needed but speed or time don't allow it, just return for now.
- if (direction.isZeroLength() == true){
- if (player_entity_ == entity) CheckTriggers(entity, entity->GetPosition());
- return false;
- }
- int current_triangle = entity->GetMoveTriangleId();
- // A character that is not on the walkmesh (Jenova of shpin_3, that is placed outside it and
- // moves with FMOVE) is walked in a straight line, or the scene that waits for it would never go
- // on.
- if (current_triangle == -1 && scripted_move && entity != player_entity_){
- const float step = std::min(direction.length(), distance_to_target);
- Ogre::Vector2 move = direction;
- if (!move.isZeroLength()) move.normalise();
- move *= step;
- entity->SetPosition(Ogre::Vector3(start_point.x + move.x, start_point.y + move.y, start_point.z));
- if (distance_to_target - step <= stop_distance + 0.0001f) entity->UnsetMove();
- return step > 0.0f;
- }
- if (current_triangle == -1){
- // The entities that a scene places later (the soldiers of the parade of junonr4) are asked
- // to move before it, and wait. Only the player has to be on the walkmesh.
- if (entity == player_entity_)
- LOG_ERROR("Entity '" + entity->GetName() + "' not placed on walkmesh and can't move.");
- return false;
- }
- Ogre::Vector3 rotation(0.0f, 0.0f, 0.0f);
- Ogre::Quaternion q1(0.0f, 0.0f, 0.0f, 1.0f);
- Ogre::Vector3 end_point(0.0f, 0.0f, 0.0f);
- Ogre::Vector3 end_point2(0.0f, 0.0f, 0.0f);
- bool first_triangle_check = false;
- bool second_triangle_check = false;
- bool third_triangle_check = false;
- bool last_triangle_check = false;
- bool first_entity_check = false;
- bool second_entity_check = false;
- bool third_entity_check = false;
- // Shorten move vector by triangle angle
- end_point.x = start_point.x + direction.x;
- end_point.y = start_point.y + direction.y;
- Ogre::Vector3 A3 = walkmesh_.GetA(current_triangle);
- Ogre::Vector3 B3 = walkmesh_.GetB(current_triangle);
- Ogre::Vector3 C3 = walkmesh_.GetC(current_triangle);
- end_point.z = PointElevation(Ogre::Vector2(end_point.x, end_point.y), A3, B3, C3);
- Ogre::Vector3 temp = end_point - start_point;
- temp.normalise();
- temp = temp * direction.length();
- direction.x = temp.x;
- direction.y = temp.y;
- // Set the direction for the entity if it has to move.
- if (entity->GetMoveAutoRotation() == true){
- Ogre::Vector2 up(0.0f, -1.0f);
- // Angle between vectors
- Ogre::Degree angle(Ogre::Radian(SafeAcos(
- direction.dotProduct(up), direction.length() * up.length()
- )));
- angle = (direction.x < 0) ? Ogre::Degree(360) - angle : angle;
- entity->SetRotation(Ogre::Degree(angle));
- }
- // A scripted walk (also of the player entity, while a scene has it locked) must end, or the
- // scene waiting for it would never go on. Several scripts place solid entities next to where
- // another one has to walk to, so they don't block it: only the walkmesh does. A manual move
- // of the player is never scripted.
- // The same goes for the points around the end of the step: they are there for the player and
- // NPCs to slide along walls, and a destination next to an edge of the walkmesh would never be
- // reached. The end point itself is still checked.
- const bool check_probes = !scripted_move;
- float solid = (entity->IsSolid() == true) ? entity->GetSolidRadius() : 0.01f;
- // For not playable entities, be a bit more lenient with solid collisions.
- // Don't use the solid radius.
- if (entity != player_entity_) solid /= 10;
- // Get ending point.
- end_point.z = start_point.z;
- for (
- int i = 0;
- (entity == player_entity_ && i < 16)
- || (entity == player_entity_ && i < 3)
- || (entity != player_entity_ && i <= 16);
- ++ i
- ){
- end_point = Ogre::Vector3(
- start_point.x + direction.x, start_point.y + direction.y, start_point.z
- );
- // 1st check.
- // Rotate move_vector +45.
- q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(45)), Ogre::Vector3::UNIT_Z);
- rotation.x = direction.x;
- rotation.y = direction.y;
- rotation.z = 0;
- rotation.normalise();
- rotation = q1 * rotation;
- // Multiply move_vector by solid range
- rotation = rotation * solid;
- end_point2.x = end_point.x + rotation.x;
- end_point2.y = end_point.y + rotation.y;
- // Check_triangle.
- first_triangle_check = check_probes && WalkmeshBorderCross(entity, end_point2, direction);
- entity->SetMoveTriangleId(current_triangle);
- // Model check.
- first_entity_check = check_probes && CheckSolidCollisions(entity, end_point2);
- // 2nd check.
- // Rotate move_vector +45.
- q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(-45)), Ogre::Vector3::UNIT_Z);
- rotation.x = direction.x;
- rotation.y = direction.y;
- rotation.z = 0;
- rotation.normalise();
- rotation = q1 * rotation;
- // Multiply move_vector by solid range.
- rotation = rotation * solid;
- end_point2.x = end_point.x + rotation.x;
- end_point2.y = end_point.y + rotation.y;
- // Check triangle.
- second_triangle_check = check_probes && WalkmeshBorderCross(entity, end_point2, direction);
- entity->SetMoveTriangleId(current_triangle);
- // Model check.
- second_entity_check = check_probes && CheckSolidCollisions(entity, end_point2);
- // 3rd check.
- rotation.x = direction.x;
- rotation.y = direction.y;
- rotation.z = 0;
- rotation.normalise();
- rotation = rotation * solid;
- end_point2.x = end_point.x + rotation.x;
- end_point2.y = end_point.y + rotation.y;
- // Check triangle.
- third_triangle_check = check_probes && WalkmeshBorderCross(entity, end_point2, direction);
- entity->SetMoveTriangleId(current_triangle);
- // Model check.
- third_entity_check = check_probes && CheckSolidCollisions(entity, end_point2);
- // Check condition and modify move_vector.
- if (
- first_triangle_check != false || second_triangle_check != false
- || third_triangle_check != false || first_entity_check != false
- || second_entity_check != false || third_entity_check != false
- ){
- // Only for NPC.
- if (entity != player_entity_){
- // If the entity collides only directly into a triangle border.
- if (
- first_triangle_check == false
- && second_triangle_check == false
- && third_triangle_check != false
- ){
- q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(-7)), Ogre::Vector3::UNIT_Z);
- rotation.x = direction.x;
- rotation.y = direction.y;
- rotation = q1 * rotation;
- direction.x = rotation.x;
- direction.y = rotation.y;
- }
- // Or if the entity only collides into other entity directly.
- else if (
- first_entity_check == false && second_entity_check == false
- && third_entity_check != false
- ){
- q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(-11.25f)), Ogre::Vector3::UNIT_Z);
- rotation.x = direction.x;
- rotation.y = direction.y;
- rotation = q1 * rotation;
- direction.x = rotation.x;
- direction.y = rotation.y;
- }
- // If not both left and right check failed.
- if (first_triangle_check == false || second_triangle_check == false){
- if (
- (first_triangle_check == false && first_entity_check != false)
- || (first_triangle_check != false && second_triangle_check == false)
- ){
- q1.FromAngleAxis(
- Ogre::Radian(Ogre::Degree(-11.25f)), Ogre::Vector3::UNIT_Z
- );
- rotation.x = direction.x;
- rotation.y = direction.y;
- rotation = q1 * rotation;
- direction.x = rotation.x;
- direction.y = rotation.y;
- }
- if (
- first_triangle_check == false
- && first_entity_check == false
- && (second_triangle_check != false || second_entity_check != false
- )
- ){
- q1.FromAngleAxis(Ogre::Radian(Ogre::Degree(11.25f)), Ogre::Vector3::UNIT_Z);
- rotation.x = direction.x;
- rotation.y = direction.y;
- rotation = q1 * rotation;
- direction.x = rotation.x;
- direction.y = rotation.y;
- }
- continue;
- }
- break;
- }
- // Only for playable character.
- else{
- if (
- first_entity_check == false
- && second_entity_check == false
- && third_entity_check == false
- ){
- // If not both left and right check failed
- if (first_triangle_check == false || second_triangle_check == false){
- // With SLIP off the move is not turned along the wall: it stays blocked.
- if (!player_slip_) break;
- if (first_triangle_check != false && second_triangle_check == false){
- q1.FromAngleAxis(
- Ogre::Radian(Ogre::Degree(-11.25f)), Ogre::Vector3::UNIT_Z
- );
- rotation.x = direction.x;
- rotation.y = direction.y;
- rotation = q1 * rotation;
- direction.x = rotation.x;
- direction.y = rotation.y;
- }
- if (first_triangle_check == false && second_triangle_check != false){
- q1.FromAngleAxis(
- Ogre::Radian(Ogre::Degree(11.25f)), Ogre::Vector3::UNIT_Z
- );
- rotation.x = direction.x;
- rotation.y = direction.y;
- rotation = q1 * rotation;
- direction.x = rotation.x;
- direction.y = rotation.y;
- }
- continue;
- }
- break;
- }
- }
- }
- }
- // Set new X, Y and Z
- last_triangle_check = WalkmeshBorderCross(entity, end_point, direction);
- if (
- first_triangle_check != false || second_triangle_check != false
- || third_triangle_check != false || last_triangle_check != false
- || first_entity_check != false || second_entity_check != false
- || third_entity_check != false
- ){
- // Event if the entity can't move, check for triggers, but use current position.
- if (player_entity_ == entity) CheckTriggers(entity, entity->GetPosition());
- return false;
- }
- // Check triggers before set entity position because move line is checked.
- if (player_entity_ == entity) CheckTriggers(entity, end_point);
- entity->SetPosition(end_point);
- // If the entity has come to destination point, finish movement.
- Ogre::Vector3 final = entity->GetMovePosition() - end_point;
- const float tolerance = scripted_move ? 0.0001f : speed / 10;
- if (Ogre::Vector2(final.x, final.y).length() <= stop_distance + tolerance)
- entity->UnsetMove();
- return true;
- }
- bool EntityManager::WalkmeshBorderCross(
- Entity* entity, Ogre::Vector3& position, const Ogre::Vector2& move_vector
- ){
- if (IsBattleModule()){
- LOG_WARNING("Tried to check for walkmesh cross, but the EntityManager is in battle mode");
- return false;
- }
- int current_triangle = entity->GetMoveTriangleId();
- if (current_triangle == -1) return true;
- // While a scene has the player locked, the scene walks the player like any other character,
- // and it can lead over the edge of the walkmesh.
- const bool free_walk = !WalkmeshEdgeBlocks(
- entity == player_entity_ && !player_lock_, entity->IsScriptedMove()
- );
- Ogre::Vector2 pos = Ogre::Vector2(position.x, position.y);
- bool searched_other_triangle = false;
- for (;;){
- Ogre::Vector3 A3 = walkmesh_.GetA(current_triangle);
- Ogre::Vector3 B3 = walkmesh_.GetB(current_triangle);
- Ogre::Vector3 C3 = walkmesh_.GetC(current_triangle);
- Ogre::Vector2 A(A3.x, A3.y);
- Ogre::Vector2 B(B3.x, B3.y);
- Ogre::Vector2 C(C3.x, C3.y);
- float sign1 = SideOfVector(pos, B, A);
- float sign2 = SideOfVector(pos, C, B);
- float sign3 = SideOfVector(pos, A, C);
- int next_triangle = -1;
- if (sign1 < 0) next_triangle = walkmesh_.GetAccessSide(current_triangle, 0);
- else if (sign2 < 0) next_triangle = walkmesh_.GetAccessSide(current_triangle, 1);
- else if (sign3 < 0) next_triangle = walkmesh_.GetAccessSide(current_triangle, 2);
- else{
- position.z = PointElevation(pos, A3, B3, C3);
- entity->SetMoveTriangleId(current_triangle);
- return false;
- }
- if (next_triangle >= 0){
- bool lock = walkmesh_.IsLocked(next_triangle);
- if (lock == false || free_walk){
- current_triangle = next_triangle;
- continue;
- }
- }
- // A walk of a script goes on over the edge: it keeps the last triangle, unless the point is
- // inside another one (the triangles apart from the rest, that scenes use to put a character
- // higher than the floor, are not joined to it: the character would keep that height after
- // leaving it).
- if (free_walk && !searched_other_triangle){
- searched_other_triangle = true;
- int other_triangle = -1;
- float other_distance = 9999.0f;
- for (int i = 0; i < walkmesh_.GetNumberOfTriangles(); ++ i){
- if (i == current_triangle) continue;
- const Ogre::Vector3 a = walkmesh_.GetA(i);
- const Ogre::Vector3 b = walkmesh_.GetB(i);
- const Ogre::Vector3 c = walkmesh_.GetC(i);
- if (!Ogre::Math::pointInTri2D(
- pos, Ogre::Vector2(a.x, a.y), Ogre::Vector2(b.x, b.y), Ogre::Vector2(c.x, c.y)
- )) continue;
- const float distance = std::abs(position.z - PointElevation(pos, a, b, c));
- if (distance < other_distance){
- other_distance = distance;
- other_triangle = i;
- }
- }
- if (other_triangle >= 0){
- current_triangle = other_triangle;
- continue;
- }
- }
- position.z = PointElevation(pos, A3, B3, C3);
- entity->SetMoveTriangleId(current_triangle);
- // A walk of a script goes on over the edge, keeping the last triangle.
- return !free_walk;
- }
- }
- bool EntityManager::CheckSolidCollisions(Entity* entity, Ogre::Vector3& position){
- if (IsBattleModule()){
- LOG_WARNING("Tried to check for solid collisions, but the EntityManager is in battle mode");
- return false;
- }
- if (entity->IsSolid() == false) return false;
- for (size_t i = 0; i < entity_.size(); ++ i){
- if (entity_[i]->IsSolid() == false) continue;
- if (entity_[i] == entity) continue;
- Ogre::Vector3 pos1 = entity_[i]->GetPosition();
- float solid_range = entity_[i]->GetSolidRadius();
- solid_range *= solid_range;
- float height = (pos1.z < position.z) ? entity_[i]->GetHeight() : entity->GetHeight();
- if (
- ((pos1.z - position.z + height) < (height * 2)) && ((pos1.z - position.z + height) >= 0)
- ){
- float distance
- = (pos1.x - position.x) * (pos1.x - position.x)
- + (pos1.y - position.y) * (pos1.y - position.y);
- if (distance < solid_range) return true;
- }
- }
- return false;
- }
- void EntityManager::CheckTriggers(Entity* entity, const Ogre::Vector3& position){
- if (IsBattleModule()){
- LOG_WARNING("Tried to check for triggers, but the EntityManager is in battle mode");
- return;
- }
- if (entity->IsSolid() == false) return;
- if (player_entity_ != entity) return;
- if (player_entity_->IsSolid() == false) return;
- if (player_lock_) return;
- bool is_moving = true;
- if (
- std::fabs(entity->GetPosition().x - position.x) < 0.005f
- && std::fabs(entity->GetPosition().y - position.y) < 0.005f
- && std::fabs(entity->GetPosition().z - position.z) < 0.005f
- ){
- is_moving = false;
- }
- for (unsigned int i = 0; i < entity_triggers_.size(); ++ i){
- ScriptEntity* trigger = ScriptManager::getSingleton().GetScriptEntityByName(
- ScriptManager::ENTITY, entity_triggers_[i]->GetName()
- );
- if (trigger != nullptr && entity_triggers_[i]->IsEnabled() == true){
- Ogre::Vector3 point_a = entity_triggers_[i]->GetPoint1();
- Ogre::Vector3 point_b = entity_triggers_[i]->GetPoint2();
- Ogre::Vector3 entity_position = entity->GetPosition();
- Ogre::Vector3 proj;
- // Calculate distance
- float square_dist = SquareDistanceToLine(entity_position, point_a, point_b, proj);
- float solid_radius = TriggerReach(entity->GetSolidRadius());
- // Calculate direction.
- const Ogre::Degree direction_to_line = GetDirectionToPoint(entity_position, proj);
- const Ogre::Degree destination_direction_to_line = GetDirectionToPoint(position, proj);
- const Ogre::Degree movement_direction = entity->GetRotation();
- Ogre::Degree angle = direction_to_line - movement_direction + Ogre::Degree(90);
- angle = (angle > Ogre::Degree(360)) ? angle - Ogre::Degree(360) : angle;
- // Check on enter line.
- // Must happen only once when the solid radius touches the line, while facing the line,
- // while the entity is manually moving, and only if not already triggered.
- if (
- square_dist != -1 && square_dist <= solid_radius * solid_radius
- && angle < Ogre::Degree(180) && angle > Ogre::Degree(0)
- && entity_triggers_[i]->CheckApproached() == false
- && is_moving
- ){
- entity_triggers_[i]->SetApproached(true);
- //std::cout << " [TRIGGER] " << entity->GetName() << " on_approach "
- // << entity_triggers_[i]->GetName() << std::endl;
- ScriptManager::getSingleton().ScriptRequest(
- trigger, "on_approach", 1, entity->GetName(), "", false, false
- );
- }
- // Check on move to line.
- // Must happen only once when the entity center touches the line, if the entity has
- // previously entered the line.
- if (
- square_dist != -1 && square_dist < 1
- && entity_triggers_[i]->CheckCrossed() == false
- && entity_triggers_[i]->CheckApproached() == true
- ){
- entity_triggers_[i]->SetCrossed(true);
- //std::cout << " [TRIGGER] " << entity->GetName() << " on_cross "
- // << entity_triggers_[i]->GetName() << std::endl;
- ScriptManager::getSingleton().ScriptRequest(
- trigger, "on_cross", 1, entity->GetName(), "", false, false
- );
- }
- // Check on cross line.
- // Must happen on every frame while the entity solid radius collides with the line, if
- // the entity has previously entered the line.
- if (
- square_dist != -1 && square_dist <= solid_radius * solid_radius
- && entity_triggers_[i]->CheckApproached() == true
- ){
- // TODO: Fix this hack.
- // After the on_near script is run, set a cooltime of 5 frames before running
- // it again. This is because most of the time this trigger checks for a key, and
- // if its pressed, is run multiple times.
- if (entity_triggers_[i]->GetNearEventCooldown() == 0){
- //std::cout << " [TRIGGER] " << entity->GetName()
- // << " on_near " << entity_triggers_[i]->GetName() << std::endl;
- ScriptManager::getSingleton().ScriptRequest(
- trigger, "on_near", 1, entity->GetName(), "", true, true
- );
- entity_triggers_[i]->ResetNearEventCooldown();
- }
- else entity_triggers_[i]->DecreaseNearEventCooldown();
- }
- // Check on cross line once.
- // The same as on cross line, but only once.
- if (
- square_dist != -1 && square_dist < solid_radius * solid_radius
- && entity_triggers_[i]->CheckNearSingleEventTriggered() == false
- && entity_triggers_[i]->CheckApproached() == true
- ){
- entity_triggers_[i]->SetNearSingleEventTriggered(true);
- //std::cout << " [TRIGGER] " << entity->GetName()
- // << " on_near_once " << entity_triggers_[i]->GetName() << std::endl;
- ScriptManager::getSingleton().ScriptRequest(
- trigger, "on_near_once", 1, entity->GetName(), "", false, false
- );
- }
- // Check on leave line.
- // Must be triggered once when the line is not in the entity solid radius, but only if
- // on enter script has been triggered previously.
- if (
- square_dist != -1 && square_dist > solid_radius * solid_radius
- && entity_triggers_[i]->CheckApproached()
- ){
- //std::cout << " [TRIGGER] " << entity->GetName() << " on_leave "
- // << entity_triggers_[i]->GetName() << std::endl;
- ScriptManager::getSingleton().ScriptRequest(
- trigger, "on_leave", 1, entity->GetName(), "", false, false
- );
- }
- // If the entity is far enough from the line, mark every trigger as inactive
- if (square_dist == -1 || square_dist > solid_radius * solid_radius){
- entity_triggers_[i]->Clear();
- //std::cout << " [TRIGGER] " << entity->GetName() << " clear of "
- // << entity_triggers_[i]->GetName() << std::endl;
- }
- }
- }
- }
- void EntityManager::ScriptSetLine(
- const char* name, const float x1, const float y1, const float z1, const float x2, const float y2,
- const float z2
- ){
- for (EntityTrigger* trigger : entity_triggers_){
- if (trigger->GetName() == name){
- trigger->SetPoints(Ogre::Vector3(x1, y1, z1), Ogre::Vector3(x2, y2, z2));
- return;
- }
- }
- }
- void EntityManager::CheckEntityContacts(){
- if (IsBattleModule() || !IsFieldModule()) return;
- if (player_entity_ == nullptr || player_lock_ || !player_entity_->IsSolid()){
- entities_in_contact_.clear();
- return;
- }
- const Ogre::Vector3 player_position = player_entity_->GetPosition();
- for (Entity* entity : entity_){
- if (entity == player_entity_ || entity->IsLine() || !entity->IsSolid()) continue;
- const Ogre::Vector3 position = entity->GetPosition();
- const float height = (position.z < player_position.z)
- ? entity->GetHeight() : player_entity_->GetHeight();
- const float distance_z = position.z - player_position.z + height;
- bool touching = false;
- if (distance_z < height * 2 && distance_z >= 0){
- const float reach = player_entity_->GetSolidRadius() + entity->GetSolidRadius() + 0.05f;
- const float dx = position.x - player_position.x;
- const float dy = position.y - player_position.y;
- touching = dx * dx + dy * dy < reach * reach;
- }
- if (!touching){
- entities_in_contact_.erase(entity);
- continue;
- }
- if (!entities_in_contact_.insert(entity).second) continue;
- ScriptEntity* script_entity = ScriptManager::getSingleton().GetScriptEntityByName(
- ScriptManager::ENTITY, entity->GetName()
- );
- // Most entities have no script for it: nothing to say then.
- if (script_entity != nullptr){
- ScriptManager::getSingleton().ScriptRequest(
- script_entity, "script_2", INTERACT_SCRIPT_PRIORITY, "", "", false, false
- );
- }
- }
- }
- void EntityManager::CheckEntityInteract(){
- if (IsBattleModule()){
- LOG_WARNING(
- "Tried to check for entity interaction, but the EntityManager is in battle mode"
- );
- return;
- }
- if (player_entity_ == NULL || player_lock_ == true || player_entity_->IsSolid() == false)
- return;
- Ogre::Degree angle_pc = player_entity_->GetRotation();
- Entity* entity_to_interact = NULL;
- Ogre::Degree less_angle(90);
- float best_distance = std::numeric_limits<float>::max();
- Ogre::Real nearest_worldmap_distance = -1.0f;
- for (unsigned int i = 0; i < entity_.size(); ++ i){
- if (entity_[i]->IsTalkable() == false) continue;
- if (entity_[i] == player_entity_) continue;
- Ogre::Vector3 pos1 = entity_[i]->GetPosition();
- float interact_range = entity_[i]->GetTalkRadius();
- Ogre::Vector3 pos2 = player_entity_->GetPosition();
- float solid_range = player_entity_->GetSolidRadius();
- if (IsWorldModule()){
- const Ogre::Real target_bottom = pos1.y;
- const Ogre::Real player_bottom = pos2.y;
- const Ogre::Real talk_range
- = interact_range + solid_range + 0.05f;
- const Ogre::Real distance
- = (pos1.x - pos2.x) * (pos1.x - pos2.x)
- + (pos1.z - pos2.z) * (pos1.z - pos2.z);
- const bool height_overlap
- = player_bottom <= target_bottom + entity_[i]->GetHeight()
- && player_bottom + player_entity_->GetHeight() >= target_bottom;
- if (
- height_overlap && distance <= talk_range * talk_range
- && (nearest_worldmap_distance < 0 || distance < nearest_worldmap_distance)
- ){
- entity_to_interact = entity_[i];
- nearest_worldmap_distance = distance;
- }
- continue;
- }
- int height = (pos1.z < pos2.z) ? entity_[i]->GetHeight() : player_entity_->GetHeight();
- if (((pos1.z - pos2.z + height) < (height * 2)) && ((pos1.z - pos2.z + height) >= 0)){
- interact_range = (interact_range + solid_range) * (interact_range + solid_range);
- float distance
- = (pos1.x - pos2.x) * (pos1.x - pos2.x) + (pos1.y - pos2.y) * (pos1.y - pos2.y);
- if (distance < interact_range + solid_range){
- Ogre::Degree angle_to_model = GetDirectionToPoint(pos2, pos1);
- Ogre::Degree angle = angle_pc - angle_to_model;
- angle = (angle < Ogre::Degree(0)) ? -angle : angle;
- angle = (angle >= Ogre::Degree(180)) ? Ogre::Degree(360) - angle : angle;
- // With several entities in range, interact with the one the player faces most.
- // Nobody 90 degrees or more away from where the player faces is considered.
- if (
- angle < Ogre::Degree(90) && IsBetterInteractionTarget(
- angle.valueDegrees(), distance, less_angle.valueDegrees(), best_distance
- )
- ){
- less_angle = angle;
- best_distance = distance;
- entity_to_interact = entity_[i];
- }
- }
- }
- }
- if (entity_to_interact != NULL && entity_to_interact->IsLine() == false){
- Ogre::String name = entity_to_interact->GetName();
- ScriptEntity* scr_entity = ScriptManager::getSingleton().GetScriptEntityByName(
- ScriptManager::ENTITY, name
- );
- bool added = ScriptManager::getSingleton().ScriptRequest(
- scr_entity, "on_interact", INTERACT_SCRIPT_PRIORITY, "", "", false, false
- );
- if (added == false){
- LOG_WARNING("Script 'on_interact' for entity '" + name + "' doesn't exist.");
- }
- }
- }
- void EntityManager::SetNextOffsetStep(Entity* entity){
- // TODO: Allow this while on battle mode?
- ActionType type = entity->GetOffsetType();
- float total = entity->GetOffsetSeconds();
- float current = entity->GetOffsetCurrentSeconds();
- current += Timer::getSingleton().GetGameTimeDelta();
- current = (current > total) ? total : current;
- Ogre::Vector3 start = entity->GetOffsetPositionStart();
- Ogre::Vector3 end = entity->GetOffsetPositionEnd();
- // An offset of zero seconds is done at once. Dividing would give NaN.
- float x = (total > 0.0f) ? current / total : 1.0f;
- if (std::isnan(x)) x = 0.0f;
- float smooth_modifier = (type == AT_SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
- Ogre::Vector3 offset = start + (end - start) * smooth_modifier;
- entity->SetOffset(offset);
- if (current == total) entity->UnsetOffset();
- else entity->SetOffsetCurrentSeconds(current);
- }
- void EntityManager::SetNextTurnStep(Entity* entity){
- // TODO: Allow this while on battle mode?
- ActionType type = entity->GetTurnType();
- float total = entity->GetTurnSeconds();
- float current = entity->GetTurnCurrentSeconds();
- current += Timer::getSingleton().GetGameTimeDelta();
- current = (current > total) ? total : current;
- Ogre::Degree start = entity->GetTurnDirectionStart();
- Ogre::Degree end = entity->GetTurnDirectionEnd();
- // A turn of zero seconds is done at once. Dividing would give NaN, and a NaN rotation breaks
- // the bounding box of the entity.
- float x = (total > 0.0f) ? current / total : 1.0f;
- float smooth_modifier = (type == AT_SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
- Ogre::Degree rotation = start + (end - start) * smooth_modifier;
- entity->SetRotation(rotation);
- if (current == total) entity->UnsetTurn();
- else entity->SetTurnCurrentSeconds(current);
- }
- void EntityManager::SetNextLinearStep(Entity* entity){
- if (IsBattleModule()){
- LOG_WARNING("Tried to set next linear step, but the EntityManager is in battle mode");
- return;
- }
- bool to_end = true;
- bool is_move = false;
- Ogre::Vector3 start = entity->GetLinearStart();
- Ogre::Vector3 end = entity->GetLinearEnd();
- Ogre::Vector3 current = entity->GetPosition();
- float delta = Timer::getSingleton().GetGameTimeDelta();
- // The player climbs a ladder with the directional keys. While a scene has the player locked
- // the keys have no effect, and the scene makes the player move on its own, as with any other
- // entity.
- if (entity == player_entity_ && !player_lock_){
- LinearMovement move = entity->GetLinearMovement();
- if (move == LM_DOWN_TO_UP || move == LM_UP_TO_DOWN){
- if (player_move_.y > 0){ // move up
- to_end = (move == LM_DOWN_TO_UP) ? true : false;
- is_move = true;
- }
- else if (player_move_.y < 0){ // move down
- to_end = (move == LM_DOWN_TO_UP) ? false : true;
- is_move = true;
- }
- }
- else if (move == LM_LEFT_TO_RIGHT || move == LM_RIGHT_TO_LEFT){
- if (player_move_.x > 0){ // move right
- to_end = (move == LM_LEFT_TO_RIGHT) ? true : false;
- is_move = true;
- }
- else if (player_move_.x < 0){ // move left
- to_end = (move == LM_LEFT_TO_RIGHT) ? false : true;
- is_move = true;
- }
- }
- }
- else is_move = true;
- if (is_move == true && (end - start).length() < 0.0001f){
- // Start and end are the same place, so there is nothing to walk. Dividing by the time to
- // cross the line (zero) would give a NaN position. Just finish the move.
- entity->UnsetLinear();
- if (to_end == true) entity->SetMoveTriangleId(entity->GetLinearDestTriangle());
- SetEntityOnWalkmesh(entity);
- entity->SetPosition(to_end ? end : start);
- }
- else if (is_move == true){
- Ogre::Vector3 position;
- if (to_end == true){
- Ogre::Vector3 end_start = end - start;
- // Move across the whole line by this number of seconds.
- float time = end_start.length() / 1.2f;
- position.x = current.x + (end_start.x / time) * delta;
- position.y = current.y + (end_start.y / time) * delta;
- position.z = current.z + (end_start.z / time) * delta;
- position.x = (end_start.x < 0)
- ? std::max(position.x, end.x) : std::min(position.x, end.x);
- position.y = (end_start.y < 0)
- ? std::max(position.y, end.y) : std::min(position.y, end.y);
- position.z = (end_start.z < 0)
- ? std::max(position.z, end.z) : std::min(position.z, end.z);
- // Compared with a tolerance: if the entity starts a bit off the end in one of the
- // axes (the entry points are written with a few digits only), that axis could move
- // less than the precision of a float per frame and never be exactly equal.
- if ((position - end).length() < 0.0001f){
- position = end;
- entity->UnsetLinear();
- entity->SetMoveTriangleId(entity->GetLinearDestTriangle());
- SetEntityOnWalkmesh(entity);
- }
- }
- else{
- Ogre::Vector3 end_start = start - end;
- // Move across the whole line by this number of seconds.
- float time = end_start.length() / 1.2f;
- position.x = current.x + (end_start.x / time) * delta;
- position.y = current.y + (end_start.y / time) * delta;
- position.z = current.z + (end_start.z / time) * delta;
- position.x = (end_start.x < 0)
- ? std::max(position.x, start.x) : std::min(position.x, start.x);
- position.y = (end_start.y < 0)
- ? std::max(position.y, start.y) : std::min(position.y, start.y);
- position.z = (end_start.z < 0)
- ? std::max(position.z, start.z) : std::min(position.z, start.z);
- if ((position - start).length() < 0.0001f){
- position = start;
- entity->UnsetLinear();
- SetEntityOnWalkmesh(entity);
- }
- }
- entity->SetPosition(position);
- entity->UpdateAnimation((to_end == true) ? delta : -delta);
- }
- }
- void EntityManager::SetNextJumpStep(Entity* entity){
- if (IsBattleModule()){
- LOG_WARNING("Tried to set next jump step, but the EntityManager is in battle mode");
- return;
- }
- float total = entity->GetJumpSeconds();
- float current = entity->GetJumpCurrentSeconds();
- current += Timer::getSingleton().GetGameTimeDelta();
- // A jump of zero seconds lands at once, without dividing by zero.
- if (total <= 0.0f) total = 0.0001f;
- current = (current > total) ? total : current;
- Ogre::Vector3 start_position = entity->GetJumpStart();
- Ogre::Vector3 end_position = entity->GetJumpEnd();
- Ogre::Vector3 position;
- position.x = start_position.x + ((end_position.x - start_position.x) / total) * current;
- position.y = start_position.y + ((end_position.y - start_position.y) / total) * current;
- position.z = current * current * -1.0f + current
- * ((end_position.z - start_position.z) / total + total * 1.0f) + start_position.z;
- entity->SetPosition(position);
- if (total == current){
- entity->UnsetJump();
- entity->SetMoveTriangleId(entity->GetJumpDestTriangle());
- SetEntityOnWalkmesh(entity);
- // The scripts set the animation of the jump as the default one (DFANM) and don't set it
- // back, but the player stands normally after landing in the original game (the scene of
- // mds6_2 where Cloud jumps down, for example). The scripts that do set it, do it after
- // the jump, so they aren't affected.
- if (entity == player_entity_){
- entity->ScriptSetDefaultAnimation("Idle");
- entity->PlayAnimationContinue("Idle");
- }
- }
- else entity->SetJumpCurrentSeconds(current);
- }
- void EntityManager::SetNextScrollStep(){
- // TODO: Allow this on battle mode?
- background_2d_.UpdateScrollTarget();
- Background2D::SCROLL_TYPE type = background_2d_.GetScrollType();
- float total = background_2d_.GetScrollSeconds();
- float current = background_2d_.GetScrollCurrentSeconds();
- current += Timer::getSingleton().GetGameTimeDelta();
- current = (current > total) ? total : current;
- Ogre::Vector2 start = background_2d_.GetScrollPositionStart();
- Ogre::Vector2 end = background_2d_.GetScrollPositionEnd();
- float x = (total > 0.0f) ? current / total : 1.0f;
- float smooth_modifier = (type == Background2D::SMOOTH) ? -2 * x * x * x + 3 * x * x : x;
- Ogre::Vector2 scroll = start + (end - start) * smooth_modifier;
- background_2d_.SetScroll(scroll);
- if (current == total) background_2d_.UnsetScroll();
- else background_2d_.SetScrollCurrentSeconds(current);
- }
|