Debian Codegraph @

engine/core/view/camera.cpp

raw
1 /***************************************************************************
2 * Copyright (C) 2005-2019 by the FIFE team *
3 * http://www.fifengine.net *
4 * This file is part of FIFE. *
5 * *
6 * FIFE is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Lesser General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2.1 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
14 * Lesser General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Lesser General Public *
17 * License along with this library; if not, write to the *
18 * Free Software Foundation, Inc., *
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
20 ***************************************************************************/
21
22 // Standard C++ library includes
23
24 // 3rd party library includes
25
26 // FIFE includes
27 // These includes are split up in two parts, separated by one empty line
28 // First block: files included from the FIFE root src directory
29 // Second block: files included from the same folder
30
31 #include "model/metamodel/grids/cellgrid.h"
32 #include "model/metamodel/action.h"
33 #include "model/metamodel/timeprovider.h"
34 #include "model/structures/map.h"
35 #include "model/structures/layer.h"
36 #include "model/structures/instancetree.h"
37 #include "model/structures/instance.h"
38 #include "model/structures/location.h"
39 #include "util/log/logger.h"
40 #include "util/math/fife_math.h"
41 #include "util/math/angles.h"
42 #include "util/time/timemanager.h"
43 #include "video/renderbackend.h"
44 #include "video/image.h"
45 #include "video/animation.h"
46 #include "video/imagemanager.h"
47
48 #include "camera.h"
49 #include "layercache.h"
50 #include "visual.h"
51
52
53 namespace FIFE {
54 static Logger _log(LM_CAMERA);
55
56 // to avoid std::bad_alloc errors, we determine the maximum size of batches
57 const uint32_t MAX_BATCH_SIZE = 100000;
58
59 class MapObserver : public MapChangeListener {
60 Camera* m_camera;
61
62 public:
63 MapObserver(Camera* camera) {
64 m_camera = camera;
65 }
66 virtual ~MapObserver() {}
67
68 virtual void onMapChanged(Map* map, std::vector<Layer*>& changedLayers) {
69 }
70
71 virtual void onLayerCreate(Map* map, Layer* layer) {
72 m_camera->addLayer(layer);
73 }
74
75 virtual void onLayerDelete(Map* map, Layer* layer) {
76 m_camera->removeLayer(layer);
77 }
78 };
79
80 Camera::Camera(const std::string& id, Map* map, const Rect& viewport, RenderBackend* renderbackend) :
81 m_id(id),
82 m_map(map),
83 m_viewport(viewport),
84 m_renderbackend(renderbackend),
85 m_position(ExactModelCoordinate(0, 0, 0)),
86 m_matrix(),
87 m_inverse_matrix(),
88 m_tilt(0),
89 m_rotation(0),
90 m_zoom(1),
91 m_zToY(0),
92 m_enabledZToY(false),
93 m_location(),
94 m_curOrigin(ScreenPoint(0, 0, 0)),
95 m_mapViewPort(),
96 m_mapViewPortUpdated(false),
97 m_screenCellWidth(1),
98 m_screenCellHeight(1),
99 m_referenceScaleX(1),
100 m_referenceScaleY(1),
101 m_enabled(true),
102 m_attachedTo(NULL),
103 m_transform(NoneTransform),
104 m_renderers(),
105 m_pipeline(),
106 m_updated(false),
107 m_layerToInstances(),
108 m_lighting(false),
109 m_light_colors(),
110 m_col_overlay(false),
111 m_img_overlay(false),
112 m_ani_overlay(false) {
113
114 m_map_observer = new MapObserver(this);
115 init();
116 }
117
118 Camera::~Camera() {
119 // Trigger removal of LayerCaches and MapObserver
120 if (m_map) {
121 m_map->removeChangeListener(m_map_observer);
122 const std::list<Layer*>& layers = m_map->getLayers();
123 for (std::list<Layer*>::const_iterator i = layers.begin(); i != layers.end(); ++i) {
124 removeLayer(*i);
125 }
126 }
127
128 std::map<std::string, RendererBase*>::iterator r_it = m_renderers.begin();
129 for(; r_it != m_renderers.end(); ++r_it) {
130 r_it->second->reset();
131 delete r_it->second;
132 }
133 m_renderers.clear();
134 delete m_map_observer;
135 }
136
137 void Camera::init() {
138 m_transform |= PositionTransform;
139 updateMatrices();
140
141 m_curOrigin = toScreenCoordinates(m_position);
142
143 // Trigger addition of LayerCaches and MapObserver
144 m_map->addChangeListener(m_map_observer);
145 const std::list<Layer*>& layers = m_map->getLayers();
146 for (std::list<Layer*>::const_iterator i = layers.begin(); i != layers.end(); ++i) {
147 addLayer(*i);
148 }
149 }
150
151 void Camera::setTilt(double tilt) {
152 if (!Mathd::Equal(m_tilt, tilt)) {
153 m_transform |= TiltTransform;
154 m_tilt = tilt;
155 updateReferenceScale();
156 updateMatrices();
157 }
158 }
159
160 double Camera::getTilt() const {
161 return m_tilt;
162 }
163
164 void Camera::setRotation(double rotation) {
165 if (!Mathd::Equal(m_rotation, rotation)) {
166 m_transform |= RotationTransform;
167 m_rotation = rotation;
168 updateReferenceScale();
169 updateMatrices();
170 }
171 }
172
173 double Camera::getRotation() const {
174 return m_rotation;
175 }
176
177 void Camera::setZoom(double zoom) {
178 if (!Mathd::Equal(m_zoom, zoom)) {
179 m_transform |= ZoomTransform;
180 m_zoom = zoom;
181 if (m_zoom < 0.001) {
182 m_zoom = 0.001;
183 }
184 updateMatrices();
185 }
186 }
187
188 double Camera::getZoom() const {
189 return m_zoom;
190 }
191
192 double Camera::getOriginalZToY() const {
193 DoubleMatrix matrix;
194 matrix.loadScale(m_referenceScaleX, m_referenceScaleY, m_referenceScaleX);
195 if (m_location.getLayer()) {
196 CellGrid* cg = m_location.getLayer()->getCellGrid();
197 if (cg) {
198 ExactModelCoordinate pt = m_location.getMapCoordinates();
199 matrix.applyTranslate(-pt.x*m_referenceScaleX, -pt.y*m_referenceScaleY, -pt.z*m_referenceScaleX);
200 }
201 }
202 matrix.applyRotate(-m_rotation, 0.0, 0.0, 1.0);
203 matrix.applyRotate(-m_tilt, 1.0, 0.0, 0.0);
204 return matrix.m9 * -1.0;
205 }
206
207 void Camera::setZToY(double zToY) {
208 m_enabledZToY = true;
209 if (!Mathd::Equal(m_zToY, zToY)) {
210 m_transform |= ZTransform;
211 m_zToY = zToY;
212 updateMatrices();
213 }
214 }
215
216 double Camera::getZToY() const {
217 return m_zToY;
218 }
219
220 void Camera::setZToYEnabled(bool enabled) {
221 m_enabledZToY = enabled;
222 }
223
224 bool Camera::isZToYEnabled() const {
225 return m_enabledZToY;
226 }
227
228 void Camera::setCellImageDimensions(uint32_t width, uint32_t height) {
229 m_screenCellWidth = width;
230 m_screenCellHeight = height;
231 updateReferenceScale();
232 updateMatrices();
233 m_transform |= PositionTransform;
234 }
235
236 void Camera::setLocation(const Location& location) {
237 if (m_location == location) {
238 return;
239 }
240
241 CellGrid* cell_grid = NULL;
242 if (location.getLayer()) {
243 cell_grid = location.getLayer()->getCellGrid();
244 if (!cell_grid) {
245 throw Exception("Location layer without cellgrid given to Camera::setLocation");
246 }
247 }
248 else {
249 throw Exception("Location without layer given to Camera::setLocation");
250 }
251
252 m_transform |= PositionTransform;
253 m_location = location;
254 m_position = m_location.getMapCoordinates();
255 updateMatrices();
256 m_curOrigin = toScreenCoordinates(m_position);
257 }
258
259 Point Camera::getCellImageDimensions() {
260 return Point(m_screenCellWidth, m_screenCellHeight);
261 }
262
263 Point Camera::getCellImageDimensions(Layer* layer) {
264 Point p;
265 DoublePoint dimensions = getLogicalCellDimensions(layer);
266 p.x = static_cast<int32_t>(round(m_referenceScaleX * dimensions.x));
267 p.y = static_cast<int32_t>(round(m_referenceScaleY * dimensions.y));
268 return p;
269 }
270
271 Location Camera::getLocation() {
272 if (m_location.getLayer()) {
273 m_location.setMapCoordinates(m_position);
274 return m_location;
275 }
276 Location loc = Location();
277 if (m_map && m_map->getLayerCount() > 0) {
278 loc.setLayer(m_map->getLayers().back());
279 loc.setMapCoordinates(m_position);
280 }
281 return loc;
282 }
283
284 void Camera::setViewPort(const Rect& viewport) {
285 m_viewport = viewport;
286 refresh();
287 }
288
289 const Rect& Camera::getViewPort() const {
290 return m_viewport;
291 }
292
293 const Rect& Camera::getMapViewPort() {
294 if (!m_mapViewPortUpdated) {
295 ScreenPoint sp1(m_viewport.x, m_viewport.y);
296 ScreenPoint sp2(m_viewport.x, m_viewport.y + m_viewport.h);
297 ScreenPoint sp3(m_viewport.x + m_viewport.w, m_viewport.y);
298 ScreenPoint sp4(m_viewport.x + m_viewport.w, m_viewport.y + m_viewport.h);
299
300 std::vector<ExactModelCoordinate> coords;
301 coords.push_back(toMapCoordinates(sp2, false));
302 coords.push_back(toMapCoordinates(sp3, false));
303 coords.push_back(toMapCoordinates(sp4, false));
304
305 ExactModelCoordinate emc = toMapCoordinates(sp1, false);
306 ModelCoordinate min(static_cast<int32_t>(emc.x), static_cast<int32_t>(emc.y));
307 ModelCoordinate max(static_cast<int32_t>(emc.x+0.5), static_cast<int32_t>(emc.y+0.5));
308 std::vector<ExactModelCoordinate>::iterator it = coords.begin();
309 for (; it != coords.end(); ++it) {
310 min.x = std::min(min.x, static_cast<int32_t>((*it).x));
311 min.y = std::min(min.y, static_cast<int32_t>((*it).y));
312 max.x = std::max(max.x, static_cast<int32_t>((*it).x+0.5));
313 max.y = std::max(max.y, static_cast<int32_t>((*it).y+0.5));
314 }
315 // makes the viewport a bit larger
316 m_mapViewPort.x = min.x - 1;
317 m_mapViewPort.y = min.y - 1;
318 m_mapViewPort.w = ABS(max.x - min.x) + 2;
319 m_mapViewPort.h = ABS(max.y - min.y) + 2;
320 m_mapViewPortUpdated = true;
321 }
322
323 return m_mapViewPort;
324 }
325
326 Rect Camera::getLayerViewPort(Layer* layer) {
327 Rect mapView = getMapViewPort();
328 Location loc(layer);
329 ExactModelCoordinate emc(mapView.x, mapView.y);
330 loc.setMapCoordinates(emc);
331 emc.x = mapView.x+mapView.w;
332 emc.y = mapView.y+mapView.h;
333 mapView.x = loc.getLayerCoordinates().x;
334 mapView.y = loc.getLayerCoordinates().y;
335 loc.setMapCoordinates(emc);
336 mapView.w = ABS(loc.getLayerCoordinates().x - mapView.x);
337 mapView.h = ABS(loc.getLayerCoordinates().y - mapView.y);
338
339 return mapView;
340 }
341
342 void Camera::setEnabled(bool enabled) {
343 m_enabled = enabled;
344 }
345
346 bool Camera::isEnabled() {
347 return m_enabled;
348 }
349
350 void Camera::setPosition(const ExactModelCoordinate& position) {
351 if (Mathd::Equal(m_position.x, position.x) && Mathd::Equal(m_position.y, position.y)) {
352 return;
353 }
354 m_transform |= PositionTransform;
355 m_position = position;
356 updateMatrices();
357 m_curOrigin = toScreenCoordinates(m_position);
358 }
359
360 ExactModelCoordinate Camera::getPosition() const {
361 return m_position;
362 }
363
364 Point3D Camera::getOrigin() const {
365 return m_curOrigin;
366 }
367
368 void Camera::updateMatrices() {
369 m_matrix.loadScale(m_referenceScaleX, m_referenceScaleY, m_referenceScaleX);
370 m_vs_matrix.loadScale(m_referenceScaleX, m_referenceScaleY, m_referenceScaleX);
371
372 m_matrix.applyTranslate(-m_position.x*m_referenceScaleX, -m_position.y*m_referenceScaleY, -m_position.z*m_referenceScaleX);
373
374 m_matrix.applyRotate(-m_rotation, 0.0, 0.0, 1.0);
375 m_matrix.applyRotate(-m_tilt, 1.0, 0.0, 0.0);
376 if (m_enabledZToY) {
377 m_matrix.m9 = -m_zToY; // z -> y height in pixels
378 }
379 double scale = m_zoom;
380 m_matrix.applyScale(scale, scale, scale);
381 m_matrix.applyTranslate(+m_viewport.x+m_viewport.w/2, +m_viewport.y+m_viewport.h/2, 0);
382 m_inverse_matrix = m_matrix.inverse();
383
384 m_vs_matrix.applyRotate(-m_rotation, 0.0, 0.0, 1.0);
385 m_vs_matrix.applyRotate(-m_tilt, 1.0, 0.0, 0.0);
386 if (m_enabledZToY) {
387 m_vs_matrix.m9 = -m_zToY; // z -> y height in pixels
388 }
389 m_vs_inverse_matrix = m_vs_matrix.inverse();
390
391 // calculate the screen<->virtual screen transformation
392 // this explicitly ignores the z-value.
393 m_vscreen_2_screen = m_matrix;
394 // NOTE: mult4by4 is an in-place modification.
395 m_vscreen_2_screen.mult4by4(m_vs_inverse_matrix);
396 // set the z transformation to unity
397 const int32_t N=4;
398 for(int32_t i=0; i!=N; ++i) {
399 m_vscreen_2_screen[2*N + i] = 0;
400 m_vscreen_2_screen[i*N + 2] = 0;
401 }
402 m_vscreen_2_screen[2*N + 2] = 1;
403 m_screen_2_vscreen = m_vscreen_2_screen.inverse();
404
405 m_mapViewPortUpdated = false;
406 // FL_WARN(_log, LMsg("matrix: ") << m_matrix << " 1: " << m_matrix.inverse().mult4by4(m_matrix));
407 // FL_WARN(_log, LMsg("vs2s matrix: ") << m_vscreen_2_screen << " s2vs matrix: " << m_screen_2_vscreen);
408 }
409
410 void Camera::calculateZValue(DoublePoint3D& screen_coords) {
411 int32_t dy = -(screen_coords.y - toScreenCoordinates(m_position).y);
412 screen_coords.z = Mathd::Tan(m_tilt * (Mathd::pi() / 180.0)) * static_cast<double>(dy);
413 }
414
415 ExactModelCoordinate Camera::toMapCoordinates(ScreenPoint screen_coords, bool z_calculated) {
416 DoublePoint3D double_screen_coords = intPt2doublePt(screen_coords);
417 if (!z_calculated) {
418 calculateZValue(double_screen_coords);
419 }
420 return m_inverse_matrix * double_screen_coords;
421 }
422
423 ScreenPoint Camera::toScreenCoordinates(const ExactModelCoordinate& elevation_coords) {
424 ScreenPoint pt = doublePt2intPt(m_matrix * elevation_coords);
425 return pt;
426 }
427
428 DoublePoint3D Camera::toVirtualScreenCoordinates(const ExactModelCoordinate& elevation_coords) {
429 DoublePoint3D pt = (m_vs_matrix * elevation_coords);
430 return pt;
431 }
432
433 ScreenPoint Camera::virtualScreenToScreen(const DoublePoint3D& p) {
434 return doublePt2intPt(m_vscreen_2_screen * p);
435 }
436
437 DoublePoint3D Camera::screenToVirtualScreen(const ScreenPoint& p) {
438 return m_screen_2_vscreen * intPt2doublePt(p);
439 }
440
441 DoublePoint Camera::getLogicalCellDimensions(Layer* layer) {
442 assert(layer);
443 CellGrid* cg = layer->getCellGrid();
444 assert(cg);
445
446 ModelCoordinate cell(0,0);
447 std::vector<ExactModelCoordinate> vertices;
448 cg->getVertices(vertices, cell);
449
450 DoubleMatrix mtx;
451 mtx.loadRotate(m_rotation, 0.0, 0.0, 1.0);
452 mtx.applyRotate(m_tilt, 1.0, 0.0, 0.0);
453
454 double x1 = 0;
455 double x2 = 0;
456 double y1 = 0;
457 double y2 = 0;
458
459 for (uint32_t i = 0; i < vertices.size(); i++) {
460 vertices[i] = cg->toMapCoordinates(vertices[i]);
461 vertices[i] = mtx * vertices[i];
462 if (i == 0) {
463 x1 = x2 = vertices[0].x;
464 y1 = y2 = vertices[0].y;
465 } else {
466 x1 = std::min(vertices[i].x, x1);
467 x2 = std::max(vertices[i].x, x2);
468 y1 = std::min(vertices[i].y, y1);
469 y2 = std::max(vertices[i].y, y2);
470 }
471 }
472 return DoublePoint( x2 - x1, y2 - y1 );
473 }
474
475 DoublePoint Camera::getLogicalCellDimensions() {
476 std::vector<ExactModelCoordinate> vertices;
477 vertices.push_back(ExactModelCoordinate(-0.5, -0.5));
478 vertices.push_back(ExactModelCoordinate(0.5, -0.5));
479 vertices.push_back(ExactModelCoordinate(0.5, 0.5));
480 vertices.push_back(ExactModelCoordinate(-0.5, 0.5));
481
482 DoubleMatrix mtx;
483 mtx.loadRotate(m_rotation, 0.0, 0.0, 1.0);
484 mtx.applyRotate(m_tilt, 1.0, 0.0, 0.0);
485
486 double x1 = 0;
487 double x2 = 0;
488 double y1 = 0;
489 double y2 = 0;
490
491 for (uint32_t i = 0; i < vertices.size(); i++) {
492 vertices[i] = mtx * vertices[i];
493 if (i == 0) {
494 x1 = x2 = vertices[0].x;
495 y1 = y2 = vertices[0].y;
496 }
497 else {
498 x1 = std::min(vertices[i].x, x1);
499 x2 = std::max(vertices[i].x, x2);
500 y1 = std::min(vertices[i].y, y1);
501 y2 = std::max(vertices[i].y, y2);
502 }
503 }
504 return DoublePoint(x2 - x1, y2 - y1);
505 }
506
507 void Camera::updateReferenceScale() {
508 DoublePoint dim = getLogicalCellDimensions();
509 m_referenceScaleX = static_cast<double>(m_screenCellWidth) / dim.x;
510 m_referenceScaleY = static_cast<double>(m_screenCellHeight) / dim.y;
511
512 FL_DBG(_log, "Updating reference scale");
513 FL_DBG(_log, LMsg(" tilt=") << m_tilt << " rot=" << m_rotation);
514 FL_DBG(_log, LMsg(" m_screenCellWidth=") << m_screenCellWidth);
515 FL_DBG(_log, LMsg(" m_screenCellHeight=") << m_screenCellHeight);
516 FL_DBG(_log, LMsg(" m_referenceScaleX=") << m_referenceScaleX);
517 FL_DBG(_log, LMsg(" m_referenceScaleY=") << m_referenceScaleY);
518 }
519
520 RenderList& Camera::getRenderListRef(Layer* layer) {
521 return m_layerToInstances[layer];
522 }
523
524 void Camera::getMatchingInstances(ScreenPoint screen_coords, Layer& layer, std::list<Instance*>& instances, uint8_t alpha) {
525 instances.clear();
526 bool zoomed = !Mathd::Equal(m_zoom, 1.0);
527 bool special_alpha = alpha != 0;
528
529 const RenderList& layer_instances = m_layerToInstances[&layer];
530 RenderList::const_iterator instance_it = layer_instances.end();
531 while (instance_it != layer_instances.begin()) {
532 --instance_it;
533 Instance* i = (*instance_it)->instance;
534 const RenderItem& vc = **instance_it;
535 if ((vc.dimensions.contains(Point(screen_coords.x, screen_coords.y)))) {
536 if(vc.image->isSharedImage()) {
537 vc.image->forceLoadInternal();
538 }
539 uint8_t r, g, b, a = 0;
540 int32_t x = screen_coords.x - vc.dimensions.x;
541 int32_t y = screen_coords.y - vc.dimensions.y;
542 if (zoomed) {
543 double fx = static_cast<double>(x);
544 double fy = static_cast<double>(y);
545 double fow = static_cast<double>(vc.image->getWidth());
546 double foh = static_cast<double>(vc.image->getHeight());
547 double fsw = static_cast<double>(vc.dimensions.w);
548 double fsh = static_cast<double>(vc.dimensions.h);
549 x = static_cast<int32_t>(round(fx / fsw * fow));
550 y = static_cast<int32_t>(round(fy / fsh * foh));
551 }
552 if (vc.getAnimationOverlay()) {
553 std::vector<ImagePtr>* ao = vc.getAnimationOverlay();
554 std::vector<ImagePtr>::iterator it = ao->begin();
555 for (; it != ao->end(); ++it) {
556 if ((*it)->isSharedImage()) {
557 (*it)->forceLoadInternal();
558 }
559 (*it)->getPixelRGBA(x, y, &r, &g, &b, &a);
560 // instance is hit with mouse if not totally transparent
561 if (a == 0 || (special_alpha && a < alpha)) {
562 continue;
563 }
564 instances.push_back(i);
565 break;
566 }
567 } else {
568 vc.image->getPixelRGBA(x, y, &r, &g, &b, &a);
569 // instance is hit with mouse if not totally transparent
570 if (a == 0 || (special_alpha && a < alpha)) {
571 continue;
572 }
573 instances.push_back(i);
574 }
575 }
576 }
577 }
578
579 void Camera::getMatchingInstances(Rect screen_rect, Layer& layer, std::list<Instance*>& instances, uint8_t alpha) {
580 instances.clear();
581 bool zoomed = !Mathd::Equal(m_zoom, 1.0);
582 bool special_alpha = alpha != 0;
583
584 const RenderList& layer_instances = m_layerToInstances[&layer];
585 RenderList::const_iterator instance_it = layer_instances.end();
586 while (instance_it != layer_instances.begin()) {
587 --instance_it;
588 Instance* i = (*instance_it)->instance;;
589 const RenderItem& vc = **instance_it;
590 if ((vc.dimensions.intersects(screen_rect))) {
591 if(vc.image->isSharedImage()) {
592 vc.image->forceLoadInternal();
593 }
594 uint8_t r, g, b, a = 0;
595 int32_t intersection_left = std::max(screen_rect.x, vc.dimensions.x);
596 int32_t intersection_right = std::min(screen_rect.right(), vc.dimensions.right());
597 int32_t intersection_top = std::max(screen_rect.y, vc.dimensions.y);
598 int32_t intersection_bottom = std::min(screen_rect.bottom(), vc.dimensions.bottom());
599
600 for(int32_t xx = intersection_left; xx < intersection_right; xx++) {
601 for(int32_t yy = intersection_top; yy < intersection_bottom; yy++) {
602 int32_t x = xx - vc.dimensions.x;
603 int32_t y = yy - vc.dimensions.y;
604 if (zoomed) {
605 double fx = static_cast<double>(x);
606 double fy = static_cast<double>(y);
607 double fow = static_cast<double>(vc.image->getWidth());
608 double foh = static_cast<double>(vc.image->getHeight());
609 double fsw = static_cast<double>(vc.dimensions.w);
610 double fsh = static_cast<double>(vc.dimensions.h);
611 x = static_cast<int32_t>(round(fx / fsw * fow));
612 y = static_cast<int32_t>(round(fy / fsh * foh));
613 }
614 if (vc.getAnimationOverlay()) {
615 std::vector<ImagePtr>* ao = vc.getAnimationOverlay();
616 std::vector<ImagePtr>::iterator it = ao->begin();
617 for (; it != ao->end(); ++it) {
618 if ((*it)->isSharedImage()) {
619 (*it)->forceLoadInternal();
620 }
621 (*it)->getPixelRGBA(x, y, &r, &g, &b, &a);
622 // instance is hit with mouse if not totally transparent
623 if (a == 0 || (special_alpha && a < alpha)) {
624 continue;
625 }
626 instances.push_back(i);
627 goto found_non_transparent_pixel;
628 }
629 } else {
630 vc.image->getPixelRGBA(x, y, &r, &g, &b, &a);
631 // instance is hit with mouse if not totally transparent
632 if (a == 0 || (special_alpha && a < alpha)) {
633 continue;
634 }
635 instances.push_back(i);
636 goto found_non_transparent_pixel;
637 }
638 }
639 }
640 found_non_transparent_pixel:;
641 }
642 }
643 }
644
645 void Camera::getMatchingInstances(Location& loc, std::list<Instance*>& instances, bool use_exactcoordinates) {
646 instances.clear();
647 Layer* layer = loc.getLayer();
648 if(!layer) {
649 return;
650 }
651
652 const RenderList& layer_instances = m_layerToInstances[layer];
653 RenderList::const_iterator instance_it = layer_instances.end();
654 while (instance_it != layer_instances.begin()) {
655 --instance_it;
656 Instance* i = (*instance_it)->instance;
657 if (use_exactcoordinates) {
658 if (i->getLocationRef().getExactLayerCoordinatesRef() == loc.getExactLayerCoordinatesRef()) {
659 instances.push_back(i);
660 }
661 } else {
662 if (i->getLocationRef().getLayerCoordinates() == loc.getLayerCoordinates()) {
663 instances.push_back(i);
664 }
665 }
666 }
667 }
668
669 void Camera::attach(Instance *instance) {
670 if (instance && instance != m_attachedTo) {
671 m_attachedTo = instance;
672 }
673 }
674
675 void Camera::detach() {
676 m_attachedTo = NULL;
677 }
678
679 void Camera::update() {
680 if (!m_attachedTo) {
681 return;
682 }
683 ExactModelCoordinate pos = m_attachedTo->getLocationRef().getMapCoordinates();
684 if (Mathd::Equal(m_position.x, pos.x) && Mathd::Equal(m_position.y, pos.y)) {
685 return;
686 }
687 m_transform |= PositionTransform;
688 m_position = pos;
689 updateMatrices();
690 m_curOrigin = toScreenCoordinates(m_position);
691 }
692
693 void Camera::refresh() {
694 updateMatrices();
695 m_transform |= RotationTransform;
696 m_curOrigin = toScreenCoordinates(m_position);
697 }
698
699 void Camera::resetUpdates() {
700 if (m_transform == NoneTransform) {
701 m_updated = false;
702 } else {
703 m_updated = true;
704 }
705 m_transform = NoneTransform;
706 }
707
708 bool pipelineSort(const RendererBase* lhs, const RendererBase* rhs) {
709 return (lhs->getPipelinePosition() < rhs->getPipelinePosition());
710 }
711
712 void Camera::addRenderer(RendererBase* renderer) {
713 renderer->setRendererListener(this);
714 m_renderers[renderer->getName()] = renderer;
715 if (renderer->isEnabled()) {
716 m_pipeline.push_back(renderer);
717 }
718 m_pipeline.sort(pipelineSort);
719 }
720
721 void Camera::onRendererPipelinePositionChanged(RendererBase* renderer) {
722 m_pipeline.sort(pipelineSort);
723 }
724
725 void Camera::onRendererEnabledChanged(RendererBase* renderer) {
726 assert(m_renderers[renderer->getName()]);
727 if (renderer->isEnabled()) {
728 FL_LOG(_log, LMsg("Enabling renderer ") << renderer->getName());
729 m_pipeline.push_back(renderer);
730 m_pipeline.sort(pipelineSort);
731 } else {
732 m_pipeline.remove(renderer);
733 }
734 }
735
736 RendererBase* Camera::getRenderer(const std::string& name) {
737 return m_renderers[name];
738 }
739
740 void Camera::resetRenderers() {
741 std::map<std::string, RendererBase*>::iterator r_it = m_renderers.begin();
742 for (; r_it != m_renderers.end(); ++r_it) {
743 r_it->second->reset();
744 }
745 }
746
747 void Camera::addLayer(Layer* layer) {
748 m_cache[layer] = new LayerCache(this);
749 m_cache[layer]->setLayer(layer);
750 m_layerToInstances[layer] = RenderList();
751 refresh();
752 }
753
754 void Camera::removeLayer(Layer* layer) {
755 delete m_cache[layer];
756 m_cache.erase(layer);
757 m_layerToInstances.erase(layer);
758 if (m_location.getLayer() == layer) {
759 m_location.reset();
760 }
761 refresh();
762 }
763
764 void Camera::setLightingColor(float red, float green, float blue) {
765 m_lighting = true;
766 m_light_colors.clear();
767 m_light_colors.push_back(red);
768 m_light_colors.push_back(green);
769 m_light_colors.push_back(blue);
770 }
771
772 std::vector<float> Camera::getLightingColor() {
773 if(m_light_colors.empty()) {
774 for(int32_t colors = 0; colors != 3; ++colors) {
775 m_light_colors.push_back(1.0f);
776 }
777 }
778 return m_light_colors;
779 }
780
781 void Camera::resetLightingColor() {
782 m_lighting = false;
783 m_renderbackend->resetLighting();
784 }
785
786 void Camera::setOverlayColor(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha) {
787 m_col_overlay = true;
788 m_overlay_color.r = red;
789 m_overlay_color.g = green;
790 m_overlay_color.b = blue;
791 m_overlay_color.a = alpha;
792 }
793
794 std::vector<uint8_t> Camera::getOverlayColor() {
795 std::vector<uint8_t> colors;
796 if (m_col_overlay) {
797 colors.push_back(m_overlay_color.r);
798 colors.push_back(m_overlay_color.g);
799 colors.push_back(m_overlay_color.b);
800 colors.push_back(m_overlay_color.a);
801 } else {
802 for(uint8_t cc = 0; cc != 4; ++cc) {
803 colors.push_back(255);
804 }
805 }
806 return colors;
807 }
808
809 void Camera::resetOverlayColor() {
810 m_col_overlay = false;
811 }
812
813 void Camera::setOverlayImage(int32_t id, bool fill) {
814 m_img_overlay = true;
815 m_img_id = id;
816 m_img_fill = fill;
817 }
818
819 int32_t Camera::getOverlayImage() {
820 int32_t id = -1;
821 if (m_img_overlay) {
822 id = m_img_id;
823 }
824 return id;
825 }
826
827 void Camera::resetOverlayImage() {
828 m_img_overlay = false;
829 m_img_id = -1;
830 }
831
832 void Camera::setOverlayAnimation(AnimationPtr anim, bool fill) {
833 m_ani_overlay = true;
834 m_ani_ptr = anim;
835 m_ani_fill = fill;
836 m_start_time = 0;
837 }
838
839 AnimationPtr Camera::getOverlayAnimation() {
840 return m_ani_ptr;
841 }
842
843 void Camera::resetOverlayAnimation() {
844 m_ani_overlay = false;
845 m_ani_ptr.reset();
846 }
847
848 void Camera::renderOverlay() {
849 if (!m_col_overlay && !m_img_overlay && !m_ani_overlay) {
850 return;
851 }
852 uint16_t width = m_viewport.w;
853 uint16_t height = m_viewport.h;
854 Point pm = Point(m_viewport.x + width/2, m_viewport.y + height/2);
855 Rect r;
856
857 // color overlay
858 if (m_col_overlay) {
859 Point p = Point(m_viewport.x, m_viewport.y);
860 m_renderbackend->fillRectangle(p, width, height, m_overlay_color.r, m_overlay_color.g, m_overlay_color.b, m_overlay_color.a);
861 }
862 // image overlay
863 if (m_img_overlay) {
864 ImagePtr resptr = ImageManager::instance()->get(m_img_id);
865 Image* img = resptr.get();
866 if (img) {
867 if (m_img_fill) {
868 r.w = width;
869 r.h = height;
870 } else {
871 r.w = img->getWidth();
872 r.h = img->getHeight();
873 }
874 r.x = pm.x-r.w/2;
875 r.y = pm.y-r.h/2;
876 img->render(r);
877 }
878 }
879 // animation overlay
880 if (m_ani_overlay) {
881 assert(m_ani_ptr != 0);
882
883 if (m_start_time == 0) {
884 m_start_time = TimeManager::instance()->getTime();
885 }
886 uint32_t animtime = scaleTime(1.0, TimeManager::instance()->getTime() - m_start_time) % m_ani_ptr->getDuration();
887 ImagePtr img = m_ani_ptr->getFrameByTimestamp(animtime);
888 if (img) {
889 if (m_ani_fill) {
890 r.w = width;
891 r.h = height;
892 } else {
893 r.w = img->getWidth();
894 r.h = img->getHeight();
895 }
896 r.x = pm.x-r.w/2;
897 r.y = pm.y-r.h/2;
898 img->render(r);
899 }
900 }
901 }
902
903 void Camera::renderStaticLayer(Layer* layer, bool update) {
904 // ToDo: Remove this function from the camera class to something like engine pre-render.
905 // ToDo: Check if partial rendering of only updated RenderItems to existing FBO is possible/faster in our case.
906 // ToDo: Add and fix support for SDL backend, for SDL it works only on the lowest layer(alpha/transparent bug).
907 LayerCache* cache = m_cache[layer];
908 ImagePtr cacheImage = cache->getCacheImage();
909 if (!cacheImage.get()) {
910 // the cacheImage name will be, camera id + _virtual_layer_image_ + layer id
911 cacheImage = ImageManager::instance()->loadBlank(m_id+"_virtual_layer_image_"+layer->getId(), m_viewport.w, m_viewport.h);
912 cache->setCacheImage(cacheImage);
913 update = true;
914 }
915 if (update) {
916 // for the case that the viewport size is not the same as the screen size,
917 // we have to change the values for OpenGL backend
918 Rect rec(0, m_renderbackend->getHeight()-m_viewport.h, m_viewport.w, m_viewport.h);
919 if (m_renderbackend->getName() == "SDL") {
920 rec = m_viewport;
921 }
922 m_renderbackend->attachRenderTarget(cacheImage, true);
923 // here we use the new viewport size
924 m_renderbackend->pushClipArea(rec, false);
925 // render stuff to texture
926 RenderList& instancesToRender = m_layerToInstances[layer];
927 // split the RenderList into smaller parts
928 if (instancesToRender.size() > MAX_BATCH_SIZE) {
929 uint8_t batches = ceil(instancesToRender.size() / static_cast<float>(MAX_BATCH_SIZE));
930 uint32_t residual = instancesToRender.size() % MAX_BATCH_SIZE;
931 for (uint8_t i = 0; i < batches; ++i) {
932 uint32_t start = i*MAX_BATCH_SIZE;
933 uint32_t end = start + ((i+1 == batches) ? residual : MAX_BATCH_SIZE);
934 RenderList tempList(instancesToRender.begin() + start, instancesToRender.begin() + end);
935 std::list<RendererBase*>::iterator r_it = m_pipeline.begin();
936 for (; r_it != m_pipeline.end(); ++r_it) {
937 if ((*r_it)->isActivedLayer(layer)) {
938 (*r_it)->render(this, layer, tempList);
939 m_renderbackend->renderVertexArrays();
940 }
941 }
942 }
943 } else {
944 std::list<RendererBase*>::iterator r_it = m_pipeline.begin();
945 for (; r_it != m_pipeline.end(); ++r_it) {
946 if ((*r_it)->isActivedLayer(layer)) {
947 (*r_it)->render(this, layer, instancesToRender);
948 m_renderbackend->renderVertexArrays();
949 }
950 }
951 }
952 m_renderbackend->detachRenderTarget();
953 m_renderbackend->popClipArea();
954 }
955 }
956
957 void Camera::updateRenderLists() {
958 if (!m_map) {
959 FL_ERR(_log, "No map for camera found");
960 return;
961 }
962
963 const std::list<Layer*>& layers = m_map->getLayers();
964 std::list<Layer*>::const_iterator layer_it = layers.begin();
965 for (;layer_it != layers.end(); ++layer_it) {
966 LayerCache* cache = m_cache[*layer_it];
967 if(!cache) {
968 addLayer(*layer_it);
969 cache = m_cache[*layer_it];
970 FL_ERR(_log, LMsg("Layer Cache miss! (This shouldn't happen!)") << (*layer_it)->getId());
971 }
972 RenderList& instancesToRender = m_layerToInstances[*layer_it];
973 if ((*layer_it)->isStatic() && m_transform == NoneTransform) {
974 continue;
975 }
976 cache->update(m_transform, instancesToRender);
977 }
978 resetUpdates();
979 }
980
981 void Camera::render() {
982 updateRenderLists();
983
984 if (!m_map) {
985 return;
986 }
987
988 uint32_t lm = m_renderbackend->getLightingModel();
989 if (lm != 0) {
990 m_renderbackend->resetStencilBuffer(0);
991 if (m_lighting) {
992 m_renderbackend->setLighting(m_light_colors[0], m_light_colors[1], m_light_colors[2]);
993 }
994 }
995
996 const std::list<Layer*>& layers = m_map->getLayers();
997 std::list<Layer*>::const_iterator layer_it = layers.begin();
998 for ( ; layer_it != layers.end(); ++layer_it) {
999 // layer with static flag will rendered as one texture
1000 if ((*layer_it)->isStatic()) {
1001 renderStaticLayer(*layer_it, m_updated);
1002 continue;
1003 }
1004 }
1005
1006 m_renderbackend->pushClipArea(getViewPort());
1007
1008 layer_it = layers.begin();
1009 for ( ; layer_it != layers.end(); ++layer_it) {
1010 // layer with static flag will rendered as one texture
1011 if ((*layer_it)->isStatic()) {
1012 m_cache[*layer_it]->getCacheImage()->render(m_viewport);
1013 m_renderbackend->renderVertexArrays();
1014 continue;
1015 }
1016 RenderList& instancesToRender = m_layerToInstances[*layer_it];
1017 // split the RenderList into smaller parts
1018 if (instancesToRender.size() > MAX_BATCH_SIZE) {
1019 uint8_t batches = ceil(instancesToRender.size() / static_cast<float>(MAX_BATCH_SIZE));
1020 uint32_t residual = instancesToRender.size() % MAX_BATCH_SIZE;
1021 for (uint8_t i = 0; i < batches; ++i) {
1022 uint32_t start = i*MAX_BATCH_SIZE;
1023 uint32_t end = start + ((i+1 == batches) ? residual : MAX_BATCH_SIZE);
1024 RenderList tempList(instancesToRender.begin() + start, instancesToRender.begin() + end);
1025 std::list<RendererBase*>::iterator r_it = m_pipeline.begin();
1026 for (; r_it != m_pipeline.end(); ++r_it) {
1027 if ((*r_it)->isActivedLayer(*layer_it)) {
1028 (*r_it)->render(this, *layer_it, tempList);
1029 m_renderbackend->renderVertexArrays();
1030 }
1031 }
1032 }
1033 } else {
1034 std::list<RendererBase*>::iterator r_it = m_pipeline.begin();
1035 for (; r_it != m_pipeline.end(); ++r_it) {
1036 if ((*r_it)->isActivedLayer(*layer_it)) {
1037 (*r_it)->render(this, *layer_it, instancesToRender);
1038 m_renderbackend->renderVertexArrays();
1039 }
1040 }
1041 }
1042 }
1043
1044 renderOverlay();
1045 m_renderbackend->renderVertexArrays();
1046 if (m_lighting && lm != 0) {
1047 m_renderbackend->resetLighting();
1048 }
1049 m_renderbackend->popClipArea();
1050 }
1051 }