Background2D.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. /*
  2. * Copyright (C) 2022 The V-Gears Team
  3. *
  4. * This file is part of V-Gears
  5. *
  6. * V-Gears is free software: you can redistribute it and/or modify it under
  7. * terms of the GNU General Public License as published by the Free Software
  8. * Foundation, version 3.0 (GPLv3) of the License.
  9. *
  10. * V-Gears is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. */
  15. #include <OgreLogManager.h>
  16. #include <OgreException.h>
  17. #include <OgreViewport.h>
  18. #include <OgreTextureManager.h>
  19. #include <OgreHardwarePixelBuffer.h>
  20. #include <algorithm>
  21. #include "engine/graphics/Background2D.h"
  22. #include "engine/graphics/CameraManager.h"
  23. #include "engine/entity/EntityManager.h"
  24. #include "engine/config/ConfigVar.h"
  25. #include "engine/graphics/DebugDraw.h"
  26. #include "common/Logger.h"
  27. #include "engine/Timer.h"
  28. ConfigVar cv_debug_background2d("debug_background2d", "Draw background debug info", "false");
  29. ConfigVar cv_show_background2d("show_background2d", "Draw background", "true");
  30. ConfigVar cv_background2d_manual("background2d_manual", "Manual 2d background scrolling", "false");
  31. Background2D::Background2D():
  32. alpha_tiles_(VGears::B_ALPHA, "Background2DAlpha", MAX_TILES),
  33. add_tiles_(VGears::B_ADD, "Background2DAdd", MAX_TILES),
  34. subtract_tiles_(VGears::B_SUBTRACT, "Background2DSubtract", MAX_SUBTRACT_TILES),
  35. scroll_([](const ScriptId& script){
  36. ScriptManager::getSingleton().ContinueScriptExecution(script);
  37. }),
  38. offset_(Ogre::Vector2::ZERO),
  39. position_real_(Ogre::Vector2::ZERO),
  40. screen_scale_(1),
  41. screen_proportion_(1, 1),
  42. virtual_screen_size_(320, 240) // FFVII original resolution
  43. {
  44. scene_manager_ = Ogre::Root::getSingleton().getSceneManager("Scene");
  45. render_system_ = Ogre::Root::getSingletonPtr()->getRenderSystem();
  46. ResetLayers();
  47. scene_manager_->addRenderQueueListener(this);
  48. }
  49. Background2D::~Background2D(){
  50. scene_manager_->removeRenderQueueListener(this);
  51. for (unsigned int i = 0; i < animations_.size(); ++ i) delete animations_[i];
  52. }
  53. void Background2D::InputDebug(const VGears::Event& event){
  54. if (cv_background2d_manual.GetB() == true && event.type == VGears::ET_KEY_IMPULSE){
  55. if (event.param1 == OIS::KC_W) position_real_.y += 2;
  56. else if (event.param1 == OIS::KC_A) position_real_.x += 2;
  57. else if (event.param1 == OIS::KC_S) position_real_.y -= 2;
  58. else if (event.param1 == OIS::KC_D) position_real_.x -= 2;
  59. CameraManager::getSingleton().Set2DScroll(position_real_);
  60. }
  61. }
  62. void Background2D::Hide(){scene_manager_->removeRenderQueueListener(this);}
  63. void Background2D::Show(){scene_manager_->addRenderQueueListener(this);}
  64. void Background2D::Update(){
  65. if (scroll_.ApplyPending()) applyScroll();
  66. UpdatePalette();
  67. const float delta = Timer::getSingleton().GetGameTimeDelta();
  68. UpdateShake(delta);
  69. // The layers that scroll by themselves.
  70. for (int layer = 0; layer < LAYER_COUNT; ++ layer){
  71. layer_scroll_offset_[layer][0] += layer_scroll_speed_[layer][0] * delta;
  72. layer_scroll_offset_[layer][1] += layer_scroll_speed_[layer][1] * delta;
  73. }
  74. UpdateAnimations(delta);
  75. }
  76. void Background2D::UpdateAnimations(const float delta){
  77. for (AnimationPlayed& played : animation_played_){
  78. for (Background2DAnimation* animation : animations_){
  79. if (animation->GetName() != played.name) continue;
  80. const float time = animation->GetTime();
  81. const float end_time = animation->GetLength();
  82. if (time + delta < end_time) animation->AddTime(delta);
  83. else{
  84. // Set to last frame of animation.
  85. if (time != end_time) animation->SetTime(end_time);
  86. if (played.state == Background2DAnimation::ONCE){
  87. for (const ScriptId& script : played.sync)
  88. ScriptManager::getSingleton().ContinueScriptExecution(script);
  89. played.sync.clear();
  90. // Mark to delete this way:
  91. played.name = "";
  92. }
  93. // In case of looped, sync with end:
  94. else animation->SetTime(time + delta - end_time);
  95. }
  96. }
  97. }
  98. // Remove stopped animations.
  99. animation_played_.erase(
  100. std::remove_if(
  101. animation_played_.begin(), animation_played_.end(),
  102. [](const AnimationPlayed& played){return played.name == "";}
  103. ), animation_played_.end()
  104. );
  105. }
  106. void Background2D::UpdateDebug(){
  107. // TODO: is this necessary? does it cost to apply camera 2d Scroll?
  108. // if so maybe move this check to applyScroll
  109. if (position_real_ != GetScreenScroll()) applyScroll();
  110. if (cv_debug_background2d.GetB() == true){
  111. DEBUG_DRAW.SetTextAlignment(DEBUG_DRAW.LEFT);
  112. DEBUG_DRAW.SetScreenSpace(true);
  113. DEBUG_DRAW.SetColour(Ogre::ColourValue(0.0f, 0.8f, 0.8f, 1.0f));
  114. for (unsigned int i = 0; i < animation_played_.size(); ++ i){
  115. DEBUG_DRAW.Text(
  116. 150.0f, static_cast<float>(34 + i * 12),
  117. "Background 2D animation: " + animation_played_[i].name
  118. );
  119. }
  120. }
  121. }
  122. void Background2D::calculateScreenScale(){
  123. Ogre::Viewport *viewport(CameraManager::getSingleton().getViewport());
  124. Ogre::Real scale_width = static_cast<Ogre::Real>(viewport->getActualWidth());
  125. Ogre::Real scale_height = static_cast<Ogre::Real>(viewport->getActualHeight());
  126. scale_width /= virtual_screen_size_.x;
  127. scale_height /= virtual_screen_size_.y;
  128. screen_scale_ = scale_height;
  129. screen_proportion_.x = screen_scale_ / scale_width;
  130. screen_proportion_.y = screen_scale_ / scale_height;
  131. }
  132. void Background2D::OnResize(){
  133. calculateScreenScale();
  134. for (unsigned int i = 0; i < tiles_.size(); ++ i) WriteTilePosition(tiles_[i]);
  135. applyScroll();
  136. }
  137. void Background2D::WriteTilePosition(const Tile& tile){
  138. BackgroundTileBuffer* buffer = BufferFor(tile.blending);
  139. if (buffer == nullptr) return;
  140. QuadWriter::Corners corners = TileCorners(tile);
  141. // A tile that is not drawn has all its corners in the same point.
  142. if (!tile.visible) corners.fill(corners[0]);
  143. buffer->SetPositions(tile.start_vertex_index, corners);
  144. }
  145. QuadWriter::Corners Background2D::TileCorners(const Tile& tile) const{
  146. const Ogre::Real left = static_cast<Ogre::Real>(tile.x);
  147. const Ogre::Real top = static_cast<Ogre::Real>(-tile.y);
  148. const Ogre::Real right = static_cast<Ogre::Real>(tile.x + tile.width);
  149. const Ogre::Real bottom = static_cast<Ogre::Real>(-(tile.y + tile.height));
  150. QuadWriter::Corners corners{{{left, top}, {right, top}, {right, bottom}, {left, bottom}}};
  151. for (Ogre::Vector2& corner : corners) virtualScreenToWorldSpace(corner);
  152. return corners;
  153. }
  154. BackgroundTileBuffer* Background2D::BufferFor(const Blending blending){
  155. if (blending == VGears::B_ALPHA) return &alpha_tiles_;
  156. if (blending == VGears::B_ADD) return &add_tiles_;
  157. if (blending == VGears::B_SUBTRACT) return &subtract_tiles_;
  158. return nullptr;
  159. }
  160. bool Background2D::IsAreaStateOn(const int area, const int layers) const{
  161. const auto it = area_states_on_.find(area);
  162. return it != area_states_on_.end() && (it->second & static_cast<unsigned int>(layers)) != 0;
  163. }
  164. void Background2D::RefreshArea(const int area){
  165. for (Tile& tile : tiles_){
  166. if (tile.area != area) continue;
  167. const bool visible = IsAreaStateOn(tile.area, tile.state);
  168. if (visible == tile.visible) continue;
  169. tile.visible = visible;
  170. WriteTilePosition(tile);
  171. }
  172. }
  173. void Background2D::ScriptAreaOn(const int area, const int layer){
  174. LOG_TRIVIAL(
  175. "Background2d area " + std::to_string(area) + " layer " + std::to_string(layer) + " on."
  176. );
  177. if (layer < 0 || layer > 31){
  178. LOG_WARNING("Background2d layer " + std::to_string(layer) + " is out of range.");
  179. return;
  180. }
  181. area_states_on_[area] |= 1u << layer;
  182. RefreshArea(area);
  183. }
  184. void Background2D::ScriptAreaOff(const int area, const int layer){
  185. LOG_TRIVIAL(
  186. "Background2d area " + std::to_string(area) + " layer " + std::to_string(layer) + " off."
  187. );
  188. if (layer < 0 || layer > 31){
  189. LOG_WARNING("Background2d layer " + std::to_string(layer) + " is out of range.");
  190. return;
  191. }
  192. const auto it = area_states_on_.find(area);
  193. if (it != area_states_on_.end()) it->second &= ~(1u << layer);
  194. RefreshArea(area);
  195. }
  196. void Background2D::UpdateShake(const float delta){
  197. if (!shake_.Update(delta)) return;
  198. // The shake is in pixels of the original screen.
  199. shake_offset_ = shake_.Offset() * (virtual_screen_size_.x / 320.0f);
  200. applyScroll();
  201. }
  202. void Background2D::ScriptShake(
  203. const int type, const int x_amplitude, const int x_frames, const int y_amplitude,
  204. const int y_frames
  205. ){
  206. LOG_TRIVIAL("Background2d shake type " + std::to_string(type) + ".");
  207. if (!shake_.Set(type, x_amplitude, x_frames, y_amplitude, y_frames))
  208. LOG_WARNING("Background2d shake type " + std::to_string(type) + " is unknown.");
  209. }
  210. void Background2D::ScriptAreaClear(const int area){
  211. LOG_TRIVIAL("Background2d area " + std::to_string(area) + " cleared.");
  212. area_states_on_.erase(area);
  213. RefreshArea(area);
  214. }
  215. void Background2D::SetPalette(const Ogre::String& name){
  216. if (palette_.Load(name)){
  217. palette_image_loaded_ = false;
  218. Ogre::LogManager::getSingleton().stream() << "Background2D: palette file loaded " << name;
  219. }
  220. }
  221. void Background2D::ScriptPaletteStore(int page, int slot, int count){
  222. palette_.Store(page, slot, count);
  223. }
  224. void Background2D::ScriptPaletteLoad(int slot, int page, int count){
  225. palette_.Load(slot, page, count);
  226. }
  227. void Background2D::ScriptPaletteCopy(int source, int destination, int count){
  228. palette_.Copy(source, destination, count);
  229. }
  230. void Background2D::ScriptPaletteMultiply(
  231. int source, int destination, int start, int count, int red, int green, int blue
  232. ){
  233. palette_.Multiply(source, destination, start, count, red, green, blue);
  234. }
  235. void Background2D::ScriptPaletteAdd(
  236. int source, int destination, int red, int green, int blue, int count
  237. ){
  238. palette_.Add(source, destination, red, green, blue, count);
  239. }
  240. void Background2D::UpdatePalette(){
  241. if (palette_.IsEmpty() || image_name_.empty()) return;
  242. if (!palette_image_loaded_){
  243. try{
  244. palette_image_.load(
  245. image_name_, Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME
  246. );
  247. }
  248. catch (const Ogre::Exception& e){
  249. LOG_ERROR("Background palette: can't load image '" + image_name_ + "': " + e.what());
  250. palette_.Clear();
  251. return;
  252. }
  253. palette_image_loaded_ = true;
  254. }
  255. if (!palette_.Paint(palette_image_)) return;
  256. Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(image_name_);
  257. if (!texture){
  258. texture = Ogre::TextureManager::getSingleton().load(
  259. image_name_, Ogre::ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME
  260. );
  261. }
  262. if (texture){
  263. texture->getBuffer()->blitFromMemory(palette_image_.getPixelBox());
  264. }
  265. }
  266. void Background2D::Clear(){
  267. scroll_.Clear();
  268. position_real_ = Ogre::Vector2::ZERO;
  269. offset_ = Ogre::Vector2::ZERO;
  270. for (Background2DAnimation* animation : animations_) delete animation;
  271. animations_.clear();
  272. for (const AnimationPlayed& played : animation_played_){
  273. for (const ScriptId& script : played.sync)
  274. ScriptManager::getSingleton().ContinueScriptExecution(script);
  275. }
  276. animation_played_.clear();
  277. tiles_.clear();
  278. area_states_on_.clear();
  279. palette_.Clear();
  280. palette_image_loaded_ = false;
  281. shake_ = BackgroundShake();
  282. shake_offset_ = Ogre::Vector2::ZERO;
  283. alpha_tiles_.Clear();
  284. add_tiles_.Clear();
  285. subtract_tiles_.Clear();
  286. ResetLayers();
  287. }
  288. void Background2D::ScriptAutoScrollToEntity(Entity* entity){scroll_.Follow(entity);}
  289. Entity* Background2D::GetAutoScrollEntity() const{return scroll_.FollowedEntity();}
  290. bool Background2D::HasScrollControl() const{return scroll_.HasControl();}
  291. void Background2D::ScriptScrollToPlayer(const SCROLL_TYPE type, const float seconds){
  292. Entity* player = EntityManager::getSingleton().ScriptGetPlayerEntity();
  293. if (player == nullptr) return;
  294. // The camera follows the player when the scroll ends, whatever the transition: scenes end with
  295. // SCRLC (scroll to the player) and give the control back without any other camera opcode, as
  296. // the first visit of mrkt2 does.
  297. if (scroll_.ToEntity(player, GetEntityScroll(player), type, seconds)) applyScroll();
  298. }
  299. void Background2D::ScriptScrollToEntity(
  300. Entity* entity, const SCROLL_TYPE type, const float seconds
  301. ){
  302. if (entity == nullptr){
  303. LOG_WARNING("Background2d can't scroll to an entity that doesn't exist.");
  304. return;
  305. }
  306. if (scroll_.ToEntity(entity, GetEntityScroll(entity), type, seconds)) applyScroll();
  307. }
  308. void Background2D::UpdateScrollTarget(){
  309. if (scroll_.TargetEntity() != nullptr)
  310. scroll_.SetTargetPosition(GetEntityScroll(scroll_.TargetEntity()));
  311. }
  312. const Ogre::Vector2 Background2D::GetEntityScroll(const Entity* entity) const{
  313. CameraManager &camera_manager(CameraManager::getSingleton());
  314. const Ogre::Vector3 view = camera_manager.ProjectPointToScreen(entity->GetPosition());
  315. const Ogre::Vector2 scroll = GetScreenScroll();
  316. const Ogre::Viewport* viewport(camera_manager.getViewport());
  317. const float width = static_cast<float>(viewport->getActualWidth());
  318. const float height = static_cast<float>(viewport->getActualHeight());
  319. return Ogre::Vector2(
  320. scroll.x + width / 2 - view.x, scroll.y + height / 2 - view.y
  321. ) / screen_scale_;
  322. }
  323. void Background2D::ScriptScrollToPosition(
  324. const float x, const float y, const SCROLL_TYPE type, const float seconds
  325. ){
  326. LOG_TRIVIAL(
  327. "Background2d set scroll to position '"
  328. + Ogre::StringConverter::toString(Ogre::Vector2(x, y)) + "'."
  329. );
  330. scroll_.ToPosition(Ogre::Vector2(x, y), type, seconds);
  331. }
  332. int Background2D::ScriptScrollSync(){
  333. // Nothing would ever wake the script up if there is no scroll to wait for.
  334. if (scroll_.Type() == NONE) return 1;
  335. ScriptId script = ScriptManager::getSingleton().GetCurrentScriptId();
  336. LOG_TRIVIAL(
  337. "Wait Background2d scroll for function '"
  338. + script.function + "' in script entity '" + script.entity + "'."
  339. );
  340. scroll_.Wait(script);
  341. return -1;
  342. }
  343. void Background2D::ScriptOffset(const float x, const float y){
  344. LOG_TRIVIAL(
  345. "Background2d offset '" + Ogre::StringConverter::toString(Ogre::Vector2(x, y)) + "'."
  346. );
  347. offset_.x = x;
  348. offset_.y = y;
  349. position_real_.x += offset_.x;
  350. position_real_.y += offset_.y;
  351. CameraManager::getSingleton().Set2DScroll(position_real_);
  352. }
  353. void Background2D::UnsetScroll(){scroll_.Stop();}
  354. const Ogre::Vector2& Background2D::GetScrollPositionStart() const{return scroll_.Start();}
  355. const Ogre::Vector2& Background2D::GetScrollPositionEnd() const{return scroll_.End();}
  356. Background2D::SCROLL_TYPE Background2D::GetScrollType() const{return scroll_.Type();}
  357. float Background2D::GetScrollSeconds() const{return scroll_.Seconds();}
  358. void Background2D::SetScrollCurrentSeconds(const float seconds){
  359. scroll_.SetCurrentSeconds(seconds);
  360. }
  361. float Background2D::GetScrollCurrentSeconds() const{return scroll_.CurrentSeconds();}
  362. void Background2D::SetScroll(const Ogre::Vector2& position){
  363. scroll_.SetPosition(position);
  364. applyScroll();
  365. }
  366. void Background2D::applyScroll(){
  367. if(cv_background2d_manual.GetB() != true){
  368. position_real_ = (GetScroll() + shake_offset_) * screen_scale_;
  369. position_real_.x += offset_.x;
  370. position_real_.y += offset_.y;
  371. CameraManager::getSingleton().Set2DScroll(position_real_);
  372. }
  373. }
  374. const Ogre::Vector2& Background2D::GetScroll() const{return scroll_.Position();}
  375. const Ogre::Vector2 Background2D::GetScreenScroll() const{return GetScroll() * screen_scale_;}
  376. void Background2D::SetImage(const Ogre::String& image){
  377. Ogre::LogManager::getSingleton().stream() << "Background2D::SetImage " << image;
  378. image_name_ = image;
  379. palette_image_loaded_ = false;
  380. alpha_tiles_.SetImage(image);
  381. add_tiles_.SetImage(image);
  382. subtract_tiles_.SetImage(image);
  383. }
  384. void Background2D::SetRange(const Ogre::Vector4& range){
  385. SetRange((int)range.x, (int)range.y, (int)range.z, (int)range.w);
  386. }
  387. void Background2D::SetRange(const int min_x, const int min_y, const int max_x, const int max_y){
  388. Ogre::LogManager::getSingleton().stream()
  389. << "Background2D::SetRange " << min_x << " " << min_y << " " << max_x << " " << max_y;
  390. // The proportion of the screen is needed for the limits.
  391. calculateScreenScale();
  392. Ogre::Vector2 half_virtual_screen_size(virtual_screen_size_ / 2);
  393. half_virtual_screen_size /= screen_proportion_;
  394. // The scroll is the opposite of the position of the center of the camera (the scripts give it
  395. // like that, and the scene is moved, not the camera), so the limits of the camera are the
  396. // opposite ones. It only shows in the fields whose range is not centered (nivl_b1): the
  397. // camera went beyond the background.
  398. Ogre::AxisAlignedBox range;
  399. range.setMaximum(
  400. -(min_x + half_virtual_screen_size.x), -(min_y + half_virtual_screen_size.y), 1
  401. );
  402. range.setMinimum(
  403. -(max_x - half_virtual_screen_size.x), -(max_y - half_virtual_screen_size.y), 0
  404. );
  405. scroll_.SetRange(range);
  406. Ogre::LogManager::getSingleton().stream() << "Background2D::SetRange " << range;
  407. }
  408. float Background2D::TileDepthToBuffer(const float depth, const Ogre::Matrix4& projection){
  409. Ogre::Vector4 result = projection * Ogre::Vector4(0, 0, -depth, 1);
  410. result /= result.w;
  411. // Starting from this depth the projected values are too close to each other for the depth
  412. // buffer to tell them apart.
  413. const float far_group_start = 127.0f;
  414. if (depth >= far_group_start){
  415. Ogre::Vector4 start = projection * Ogre::Vector4(0, 0, -far_group_start, 1);
  416. start /= start.w;
  417. // The depth of the render system goes from -1 to 1 (OpenGL), so between the start of the
  418. // group and the far plane there are about 1.4e-5 to use. With 1e-5 per unit of depth,
  419. // tiles whose depths differ by 0.06 (127.938 and 128) end up several steps of a 24 bit
  420. // depth buffer apart, and the biggest depth used (128) is still in front of the far plane.
  421. const float far_group_step = 0.00001f;
  422. return std::min(start.z + (depth - far_group_start) * far_group_step, 0.9999995f);
  423. }
  424. return result.z;
  425. }
  426. void Background2D::AddTile(const VGears::Tile& tile){
  427. // TODO: move depth calculation to flevelBackgroundLoader maybe? and let
  428. // Backgorund2D only handle 0 <= depth <= 1 or so?
  429. // Maybe just move the < 4095 part to flevel background loader?
  430. // The tiles that are less than one unit away (the pieces of a model that a script puts in,
  431. // for example) are only a hair away from the camera, but they keep their order: all of them at
  432. // the same depth made the tile that is drawn last cover the others, wherever it was.
  433. Ogre::Real depth(0.0001f + std::max(tile.depth, 0.0f) * 0.00005f);
  434. if (tile.depth >= 1){
  435. if (tile.depth < 4095){
  436. depth = TileDepthToBuffer(
  437. tile.depth,
  438. CameraManager::getSingleton().GetCurrentCamera()->getProjectionMatrixWithRSDepth()
  439. );
  440. }
  441. else depth = 0.9999f;
  442. }
  443. AddTile(
  444. static_cast<int>(tile.destination.x), static_cast<int>(tile.destination.y),
  445. tile.width, tile.height, depth, tile.uv.x, tile.uv.y, tile.uv.z, tile.uv.w, tile.blending,
  446. tile.area, tile.state
  447. );
  448. }
  449. void Background2D::AddTile(
  450. const Ogre::Vector2& destination, const int width, const int height,
  451. const float depth, const Ogre::Vector4& uv, const Blending blending
  452. ){
  453. AddTile(
  454. static_cast<int>(destination.x), static_cast<int>(destination.y),
  455. width, height, depth, uv.x, uv.y, uv.z, uv.w, blending
  456. );
  457. }
  458. void Background2D::virtualScreenToWorldSpace(Ogre::Vector2& pos) const{
  459. pos.x /= virtual_screen_size_.x / 2;
  460. pos.y /= virtual_screen_size_.y / 2;
  461. pos.x *= screen_proportion_.x;
  462. pos.y *= screen_proportion_.y;
  463. }
  464. void Background2D::AddTile(
  465. const int x, const int y, const int width, const int height, const float depth, const float u1,
  466. const float v1, const float u2, const float v2, const Blending blending, const int area,
  467. const int state, const int layer, const float intensity
  468. ){
  469. BackgroundTileBuffer* buffer = BufferFor(blending);
  470. if (buffer == nullptr){
  471. LOG_ERROR("Unknown blending type.");
  472. return;
  473. }
  474. if (buffer->IsFull()){
  475. LOG_ERROR(
  476. "Max number of tiles reached. Can't create more than "
  477. + Ogre::StringConverter::toString(buffer->MaxTiles()) + " tiles."
  478. );
  479. return;
  480. }
  481. Tile tile;
  482. tile.x = x;
  483. tile.y = y;
  484. tile.width = width;
  485. tile.height = height;
  486. tile.blending = blending;
  487. tile.area = area;
  488. tile.state = state;
  489. tile.visible = (area == 0) || IsAreaStateOn(area, state);
  490. tile.start_vertex_index = buffer->Add(
  491. TileCorners(tile), {u1, v1, u2, v2}, depth, intensity, layer
  492. );
  493. tiles_.push_back(tile);
  494. // Tiles of an area that is off are written at their position, and then collapsed.
  495. if (!tile.visible) WriteTilePosition(tile);
  496. }
  497. void Background2D::UpdateTileUV(
  498. const unsigned int tile_id, const float u1, const float v1, const float u2, const float v2
  499. ){
  500. if (tile_id >= tiles_.size()){
  501. LOG_ERROR("Tile with id " + Ogre::StringConverter::toString( tile_id ) + " doesn't exist.");
  502. return;
  503. }
  504. const Tile& tile = tiles_[tile_id];
  505. BufferFor(tile.blending)->SetTexture(tile.start_vertex_index, {u1, v1, u2, v2});
  506. }
  507. void Background2D::AddAnimation(Background2DAnimation* animation){animations_.push_back(animation);}
  508. void Background2D::PlayAnimation(
  509. const Ogre::String& animation, const Background2DAnimation::State state
  510. ){
  511. bool found = false;
  512. for (unsigned int i = 0; i < animations_.size(); ++ i){
  513. if (animations_[i]->GetName() == animation){
  514. found = true;
  515. animations_[i]->SetTime(0);
  516. animations_[i]->AddTime(0);
  517. }
  518. }
  519. for (unsigned int i = 0; i < animation_played_.size(); ++ i){
  520. if (animation_played_[i].name == animation)
  521. animation_played_.erase(animation_played_.begin() + i);
  522. }
  523. if(found == true){
  524. AnimationPlayed anim;
  525. anim.name = animation;
  526. anim.state = state;
  527. animation_played_.push_back(anim);
  528. }
  529. else LOG_ERROR("Background2D doesn't has animation '" + animation + "'.");
  530. }
  531. void Background2D::ScriptPlayAnimationLooped(const char* name){
  532. PlayAnimation(Ogre::String(name), Background2DAnimation::LOOPED);
  533. }
  534. void Background2D::ScriptPlayAnimationOnce(const char* name){
  535. PlayAnimation(Ogre::String(name), Background2DAnimation::ONCE);
  536. }
  537. int Background2D::ScriptAnimationSync(const char* animation){
  538. for (unsigned int i = 0; i < animation_played_.size(); ++ i){
  539. if (animation_played_[i].name == animation){
  540. ScriptId script = ScriptManager::getSingleton().GetCurrentScriptId();
  541. animation_played_[i].sync.push_back(script);
  542. return -1;
  543. }
  544. }
  545. return 1;
  546. }
  547. void Background2D::renderQueueEnded(
  548. Ogre::uint8 queue_group_id, const Ogre::String& invocation, bool& repeat_this_invocation
  549. ){
  550. if (cv_show_background2d.GetB() == false) return;
  551. // The movie takes the place of the background, and the models are drawn over it.
  552. if (EntityManager::getSingleton().GetMoviePlayer()->IsDrawnBehind()) return;
  553. if (queue_group_id == Ogre::RENDER_QUEUE_MAIN){
  554. Ogre::GpuProgramParametersPtr rs_params = render_system_->getFixedFunctionParams(
  555. Ogre::TVC_NONE, Ogre::FOG_NONE
  556. );
  557. rs_params->setConstant(
  558. Ogre::GpuProgramParameters::ACT_WORLD_MATRIX, Ogre::Matrix4::IDENTITY
  559. );
  560. rs_params->setConstant(
  561. Ogre::GpuProgramParameters::ACT_PROJECTION_MATRIX, Ogre::Matrix4::IDENTITY
  562. );
  563. Ogre::Viewport *viewport(CameraManager::getSingleton().getViewport());
  564. float width = static_cast<float>(viewport->getActualWidth());
  565. float height = static_cast<float>(viewport->getActualHeight());
  566. SetView(position_real_, rs_params, width, height);
  567. RenderBuffer(alpha_tiles_, rs_params, width, height);
  568. RenderBuffer(add_tiles_, rs_params, width, height);
  569. RenderBuffer(subtract_tiles_, rs_params, width, height);
  570. }
  571. }
  572. void Background2D::ResetLayers(){
  573. for (int layer = 0; layer < LAYER_COUNT; ++ layer){
  574. layer_parallax_[layer][0] = layer_parallax_[layer][1] = 1.0f;
  575. layer_scroll_speed_[layer][0] = layer_scroll_speed_[layer][1] = 0.0f;
  576. layer_scroll_offset_[layer][0] = layer_scroll_offset_[layer][1] = 0.0f;
  577. }
  578. }
  579. bool Background2D::HasLayerScroll() const{
  580. for (int layer = 0; layer < LAYER_COUNT; ++ layer){
  581. if (
  582. layer_parallax_[layer][0] != 1.0f || layer_parallax_[layer][1] != 1.0f
  583. || layer_scroll_speed_[layer][0] != 0.0f || layer_scroll_speed_[layer][1] != 0.0f
  584. ) return true;
  585. }
  586. return false;
  587. }
  588. void Background2D::ScriptSetLayerParallax(const int layer, const int distance){
  589. if (layer < 0 || layer >= LAYER_COUNT) return;
  590. const float ratio = static_cast<float>(distance) / 4096.0f;
  591. layer_parallax_[layer][0] = ratio;
  592. layer_parallax_[layer][1] = ratio;
  593. }
  594. void Background2D::ScriptSetLayerScroll(const int layer, const int x, const int y){
  595. if (layer < 0 || layer >= LAYER_COUNT) return;
  596. // 1/256 of a pixel of the original screen for each frame, at 30 frames per second. The
  597. // virtual screen is 3 times as big as the one of the original game.
  598. const float to_virtual_pixels_per_second = 30.0f * 3.0f / 256.0f;
  599. layer_scroll_speed_[layer][0] = static_cast<float>(x) * to_virtual_pixels_per_second;
  600. layer_scroll_speed_[layer][1] = static_cast<float>(y) * to_virtual_pixels_per_second;
  601. }
  602. void Background2D::RenderBuffer(
  603. BackgroundTileBuffer& buffer, Ogre::GpuProgramParametersPtr& rs_params, const float width,
  604. const float height
  605. ){
  606. if (buffer.IsEmpty()) return;
  607. if (!buffer.Layers().AreContiguous() || !HasLayerScroll()){
  608. // The view the layers of other buffers could have left.
  609. SetView(position_real_, rs_params, width, height);
  610. buffer.Draw(*scene_manager_, *render_system_);
  611. return;
  612. }
  613. for (int layer = 0; layer < LAYER_COUNT; ++ layer){
  614. const BackgroundLayerRanges::Range& range = buffer.Layers().Of(layer);
  615. if (range.count == 0) continue;
  616. // The scroll of the background, changed by the parallax of the layer, plus the one it has
  617. // by itself. The scroll by itself is in pixels of the virtual screen.
  618. const Ogre::Vector2 by_itself(
  619. layer_scroll_offset_[layer][0] * screen_scale_,
  620. layer_scroll_offset_[layer][1] * screen_scale_
  621. );
  622. SetView(
  623. Ogre::Vector2(
  624. position_real_.x * layer_parallax_[layer][0] + by_itself.x,
  625. position_real_.y * layer_parallax_[layer][1] + by_itself.y
  626. ), rs_params, width, height
  627. );
  628. buffer.Draw(*scene_manager_, *render_system_, range);
  629. }
  630. }
  631. void Background2D::SetView(
  632. const Ogre::Vector2& position, Ogre::GpuProgramParametersPtr& rs_params, const float width,
  633. const float height
  634. ){
  635. Ogre::Matrix4 view;
  636. view.makeTrans(Ogre::Vector3(position.x / width, -position.y / height, 0));
  637. // TODO This is deprecated, but if not done , the background image disappears.
  638. render_system_->_setViewMatrix(view);
  639. rs_params->setConstant(Ogre::GpuProgramParameters::ACT_VIEW_MATRIX, view);
  640. render_system_->applyFixedFunctionParams(rs_params, Ogre::GPV_GLOBAL);
  641. }
  642. void Background2D::load(const VGears::Background2DFilePtr& background){
  643. assert(background != nullptr);
  644. background->load();
  645. SetImage(background->GetTextureName());
  646. if (!background->GetPaletteName().empty()) SetPalette(background->GetPaletteName());
  647. virtual_screen_size_ = background->GetClip();
  648. SetRange(background->GetRange());
  649. const Ogre::Vector3& position(background->GetPosition());
  650. const Ogre::Quaternion& orientation(background->GetOrientation());
  651. const Ogre::Radian& fov(background->GetFov());
  652. CameraManager::getSingleton().Set2DCamera(position, orientation, fov);
  653. load(background->GetTiles());
  654. }
  655. void Background2D::load(const VGears::Background2DFile::TileList& tiles){
  656. VGears::Background2DFile::TileList::const_iterator it(tiles.begin());
  657. VGears::Background2DFile::TileList::const_iterator it_end(tiles.end());
  658. size_t tile_index(0);
  659. size_t area_tiles(0);
  660. while (it != it_end) {
  661. AddTile(*it);
  662. load(tile_index ++, it->animations);
  663. if (it->area != 0) ++ area_tiles;
  664. ++ it;
  665. }
  666. LOG_TRIVIAL(
  667. "Background2D: " + std::to_string(tile_index) + " tiles loaded, " + std::to_string(area_tiles)
  668. + " of them in scripted areas."
  669. );
  670. }
  671. void Background2D::load(const size_t tile_index, const VGears::AnimationMap& animations){
  672. VGears::AnimationMap::const_iterator it(animations.begin());
  673. VGears::AnimationMap::const_iterator it_end(animations.end());
  674. while(it != it_end){
  675. const VGears::String& name(it->first);
  676. const VGears::Animation& animation(it->second);
  677. Background2DAnimation* anim(new Background2DAnimation(name, this, tile_index));
  678. anim->SetLength(animation.length);
  679. VGears::KeyFrameList::const_iterator itk(animation.key_frames.begin());
  680. VGears::KeyFrameList::const_iterator itk_end(animation.key_frames.end());
  681. while(itk != itk_end) anim->AddUVKeyFrame(*(itk++));
  682. AddAnimation(anim);
  683. ++ it;
  684. }
  685. }