hx3d  1
2D/3D Simple Game Framework
fit_viewport.cpp
1 /*
2  Fit viewport.
3  Inspired by LibGDX fit viewport.
4  Automatically fit the rendering in the screen.
5 
6  Copyright (C) 2015 Denis BOURGE
7 
8  This library is free software; you can redistribute it and/or
9  modify it under the terms of the GNU Lesser General Public
10  License as published by the Free Software Foundation; either
11  version 2.1 of the License, or (at your option) any later version.
12 
13  This library is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  Lesser General Public License for more details.
17 
18  You should have received a copy of the GNU Lesser General Public
19  License along with this library; if not, write to the Free Software
20  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
21  USA
22 */
23 
24 #include "hx3d/graphics/viewports/fit_viewport.hpp"
25 
26 #include <cmath>
27 
28 #include "hx3d/utils/log.hpp"
29 
30 namespace hx3d {
31 namespace graphics {
32 namespace viewports {
33 
34 FitViewport::FitViewport(const float worldWidth, const float worldHeight) {
35  _worldWidth = worldWidth;
36  _worldHeight = worldHeight;
37 }
38 
40  float tgtRatio, srcRatio, scale;
41 
43  tgtRatio = _screenWidth / _screenHeight;
44  srcRatio = _worldWidth / _worldHeight;
45  scale = tgtRatio > srcRatio ? _screenWidth / _worldWidth : _screenHeight / _worldHeight;
46  } else {
47  tgtRatio = _screenWidth / _screenHeight;
48  srcRatio = _worldWidth / _worldHeight;
49  scale = tgtRatio < srcRatio ? _screenWidth / _worldWidth : _screenHeight / _worldHeight;
50  }
51 
52  int nx = std::floor(_worldWidth * scale);
53  int ny = std::floor(_worldHeight * scale);
54 
55  _screenX = (_screenWidth - nx) / 2.f;
56  _screenY = (_screenHeight - ny) / 2.f;
57  _screenWidth = nx;
58  _screenHeight = ny;
59 
60  apply(camera);
61 }
62 
63 } /* viewports */
64 } /* graphics */
65 } /* hx3d */
2D/3D camera.
Definition: camera.hpp:41
hx3d framework namespace
Definition: audio.hpp:26
void apply(Camera &camera)
Apply the viewport on the screen, centering the camera.
Definition: viewport.cpp:42
float _worldHeight
World height.
Definition: viewport.hpp:95
virtual void internalUpdate(Camera &camera) override
Update the viewport, centering the camera (internal).
int _screenHeight
Screen height.
Definition: viewport.hpp:104
FitViewport(const float worldWidth, const float worldHeight)
Create a fit viewport using a world width and height.
float _worldWidth
World width.
Definition: viewport.hpp:93