File: GameView.cpp

package info (click to toggle)
0ad 0.0.23.1-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 78,292 kB
  • sloc: cpp: 245,166; ansic: 200,249; python: 13,754; sh: 6,104; perl: 4,620; makefile: 977; xml: 810; java: 533; ruby: 229; erlang: 46; pascal: 30; sql: 21; tcl: 4
file content (1159 lines) | stat: -rw-r--r-- 33,189 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
/* Copyright (C) 2017 Wildfire Games.
 * This file is part of 0 A.D.
 *
 * 0 A.D. is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * 0 A.D. 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.
 *
 * You should have received a copy of the GNU General Public License
 * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "precompiled.h"

#include "GameView.h"

#include "graphics/Camera.h"
#include "graphics/CinemaManager.h"
#include "graphics/ColladaManager.h"
#include "graphics/HFTracer.h"
#include "graphics/LOSTexture.h"
#include "graphics/LightEnv.h"
#include "graphics/Model.h"
#include "graphics/ObjectManager.h"
#include "graphics/Patch.h"
#include "graphics/SkeletonAnimManager.h"
#include "graphics/Terrain.h"
#include "graphics/TerrainTextureManager.h"
#include "graphics/TerritoryTexture.h"
#include "graphics/Unit.h"
#include "graphics/UnitManager.h"
#include "graphics/scripting/JSInterface_GameView.h"
#include "lib/input.h"
#include "lib/timer.h"
#include "lobby/IXmppClient.h"
#include "maths/BoundingBoxAligned.h"
#include "maths/MathUtil.h"
#include "maths/Matrix3D.h"
#include "maths/Quaternion.h"
#include "ps/ConfigDB.h"
#include "ps/Filesystem.h"
#include "ps/Game.h"
#include "ps/Globals.h"
#include "ps/Hotkey.h"
#include "ps/Joystick.h"
#include "ps/Loader.h"
#include "ps/LoaderThunks.h"
#include "ps/Profile.h"
#include "ps/Pyrogenesis.h"
#include "ps/TouchInput.h"
#include "ps/World.h"
#include "renderer/Renderer.h"
#include "renderer/WaterManager.h"
#include "simulation2/Simulation2.h"
#include "simulation2/components/ICmpPosition.h"
#include "simulation2/components/ICmpRangeManager.h"

extern int g_xres, g_yres;

// Maximum distance outside the edge of the map that the camera's
// focus point can be moved
static const float CAMERA_EDGE_MARGIN = 2.0f*TERRAIN_TILE_SIZE;

/**
 * A value with exponential decay towards the target value.
 */
class CSmoothedValue
{
public:
	CSmoothedValue(float value, float smoothness, float minDelta)
		: m_Target(value), m_Current(value), m_Smoothness(smoothness), m_MinDelta(minDelta)
	{
	}

	float GetSmoothedValue()
	{
		return m_Current;
	}

	void SetValueSmoothly(float value)
	{
		m_Target = value;
	}

	void AddSmoothly(float value)
	{
		m_Target += value;
	}

	void Add(float value)
	{
		m_Target += value;
		m_Current += value;
	}

	float GetValue()
	{
		return m_Target;
	}

	void SetValue(float value)
	{
		m_Target = value;
		m_Current = value;
	}

	float Update(float time)
	{
		if (fabs(m_Target - m_Current) < m_MinDelta)
			return 0.0f;

		double p = pow((double)m_Smoothness, 10.0 * (double)time);
		// (add the factor of 10 so that smoothnesses don't have to be tiny numbers)

		double delta = (m_Target - m_Current) * (1.0 - p);
		m_Current += delta;
		return (float)delta;
	}

	void ClampSmoothly(float min, float max)
	{
		m_Target = Clamp(m_Target, (double)min, (double)max);
	}

	// Wrap so 'target' is in the range [min, max]
	void Wrap(float min, float max)
	{
		double t = fmod(m_Target - min, (double)(max - min));
		if (t < 0)
			t += max - min;
		t += min;

		m_Current += t - m_Target;
		m_Target = t;
	}

private:
	double m_Target; // the value which m_Current is tending towards
	double m_Current;
	// (We use double because the extra precision is worthwhile here)

	float m_MinDelta; // cutoff where we stop moving (to avoid ugly shimmering effects)
public:
	float m_Smoothness;
};

class CGameViewImpl
{
	NONCOPYABLE(CGameViewImpl);
public:
	CGameViewImpl(CGame* game)
		: Game(game),
		ColladaManager(g_VFS), MeshManager(ColladaManager), SkeletonAnimManager(ColladaManager),
		ObjectManager(MeshManager, SkeletonAnimManager, *game->GetSimulation2()),
		LOSTexture(*game->GetSimulation2()),
		TerritoryTexture(*game->GetSimulation2()),
		ViewCamera(),
		CullCamera(),
		LockCullCamera(false),
		ConstrainCamera(true),
		Culling(true),
		FollowEntity(INVALID_ENTITY),
		FollowFirstPerson(false),

		// Dummy values (these will be filled in by the config file)
		ViewScrollSpeed(0),
		ViewScrollSpeedModifier(1),
		ViewRotateXSpeed(0),
		ViewRotateXMin(0),
		ViewRotateXMax(0),
		ViewRotateXDefault(0),
		ViewRotateYSpeed(0),
		ViewRotateYSpeedWheel(0),
		ViewRotateYDefault(0),
		ViewRotateSpeedModifier(1),
		ViewDragSpeed(0),
		ViewZoomSpeed(0),
		ViewZoomSpeedWheel(0),
		ViewZoomMin(0),
		ViewZoomMax(0),
		ViewZoomDefault(0),
		ViewZoomSpeedModifier(1),
		ViewFOV(DEGTORAD(45.f)),
		ViewNear(2.f),
		ViewFar(4096.f),
		JoystickPanX(-1),
		JoystickPanY(-1),
		JoystickRotateX(-1),
		JoystickRotateY(-1),
		JoystickZoomIn(-1),
		JoystickZoomOut(-1),
		HeightSmoothness(0.5f),
		HeightMin(16.f),

		PosX(0, 0, 0.01f),
		PosY(0, 0, 0.01f),
		PosZ(0, 0, 0.01f),
		Zoom(0, 0, 0.1f),
		RotateX(0, 0, 0.001f),
		RotateY(0, 0, 0.001f)
	{
	}

	CGame* Game;
	CColladaManager ColladaManager;
	CMeshManager MeshManager;
	CSkeletonAnimManager SkeletonAnimManager;
	CObjectManager ObjectManager;
	CLOSTexture LOSTexture;
	CTerritoryTexture TerritoryTexture;

	/**
	 * this camera controls the eye position when rendering
	 */
	CCamera ViewCamera;

	/**
	 * this camera controls the frustum that is used for culling
	 * and shadow calculations
	 *
	 * Note that all code that works with camera movements should only change
	 * m_ViewCamera. The render functions automatically sync the cull camera to
	 * the view camera depending on the value of m_LockCullCamera.
	 */
	CCamera CullCamera;

	/**
	 * When @c true, the cull camera is locked in place.
	 * When @c false, the cull camera follows the view camera.
	 *
	 * Exposed to JS as gameView.lockCullCamera
	 */
	bool LockCullCamera;

	/**
	 * When @c true, culling is enabled so that only models that have a chance of
	 * being visible are sent to the renderer.
	 * Otherwise, the entire world is sent to the renderer.
	 *
	 * Exposed to JS as gameView.culling
	 */
	bool Culling;

	/**
	 * Whether the camera movement should be constrained by min/max limits
	 * and terrain avoidance.
	 */
	bool ConstrainCamera;

	/**
	 * Cache global lighting environment. This is used  to check whether the
	 * environment has changed during the last frame, so that vertex data can be updated etc.
	 */
	CLightEnv CachedLightEnv;

	CCinemaManager CinemaManager;

	/**
	 * Entity for the camera to follow, or INVALID_ENTITY if none.
	 */
	entity_id_t FollowEntity;

	/**
	 * Whether to follow FollowEntity in first-person mode.
	 */
	bool FollowFirstPerson;

	////////////////////////////////////////
	// Settings
	float ViewScrollSpeed;
	float ViewScrollSpeedModifier;
	float ViewRotateXSpeed;
	float ViewRotateXMin;
	float ViewRotateXMax;
	float ViewRotateXDefault;
	float ViewRotateYSpeed;
	float ViewRotateYSpeedWheel;
	float ViewRotateYDefault;
	float ViewRotateSpeedModifier;
	float ViewDragSpeed;
	float ViewZoomSpeed;
	float ViewZoomSpeedWheel;
	float ViewZoomMin;
	float ViewZoomMax;
	float ViewZoomDefault;
	float ViewZoomSpeedModifier;
	float ViewFOV;
	float ViewNear;
	float ViewFar;
	int JoystickPanX;
	int JoystickPanY;
	int JoystickRotateX;
	int JoystickRotateY;
	int JoystickZoomIn;
	int JoystickZoomOut;
	float HeightSmoothness;
	float HeightMin;

	////////////////////////////////////////
	// Camera Controls State
	CSmoothedValue PosX;
	CSmoothedValue PosY;
	CSmoothedValue PosZ;
	CSmoothedValue Zoom;
	CSmoothedValue RotateX; // inclination around x axis (relative to camera)
	CSmoothedValue RotateY; // rotation around y (vertical) axis
};

#define IMPLEMENT_BOOLEAN_SETTING(NAME) \
bool CGameView::Get##NAME##Enabled() \
{ \
	return m->NAME; \
} \
\
void CGameView::Set##NAME##Enabled(bool Enabled) \
{ \
	m->NAME = Enabled; \
}

IMPLEMENT_BOOLEAN_SETTING(Culling);
IMPLEMENT_BOOLEAN_SETTING(LockCullCamera);
IMPLEMENT_BOOLEAN_SETTING(ConstrainCamera);

#undef IMPLEMENT_BOOLEAN_SETTING

static void SetupCameraMatrixSmooth(CGameViewImpl* m, CMatrix3D* orientation)
{
	orientation->SetIdentity();
	orientation->RotateX(m->RotateX.GetSmoothedValue());
	orientation->RotateY(m->RotateY.GetSmoothedValue());
	orientation->Translate(m->PosX.GetSmoothedValue(), m->PosY.GetSmoothedValue(), m->PosZ.GetSmoothedValue());
}

static void SetupCameraMatrixSmoothRot(CGameViewImpl* m, CMatrix3D* orientation)
{
	orientation->SetIdentity();
	orientation->RotateX(m->RotateX.GetSmoothedValue());
	orientation->RotateY(m->RotateY.GetSmoothedValue());
	orientation->Translate(m->PosX.GetValue(), m->PosY.GetValue(), m->PosZ.GetValue());
}

static void SetupCameraMatrixNonSmooth(CGameViewImpl* m, CMatrix3D* orientation)
{
	orientation->SetIdentity();
	orientation->RotateX(m->RotateX.GetValue());
	orientation->RotateY(m->RotateY.GetValue());
	orientation->Translate(m->PosX.GetValue(), m->PosY.GetValue(), m->PosZ.GetValue());
}

CGameView::CGameView(CGame *pGame):
	m(new CGameViewImpl(pGame))
{
	SViewPort vp;
	vp.m_X=0;
	vp.m_Y=0;
	vp.m_Width=g_xres;
	vp.m_Height=g_yres;
	m->ViewCamera.SetViewPort(vp);

	m->ViewCamera.SetProjection(m->ViewNear, m->ViewFar, m->ViewFOV);
	SetupCameraMatrixSmooth(m, &m->ViewCamera.m_Orientation);
	m->ViewCamera.UpdateFrustum();

	m->CullCamera = m->ViewCamera;
	g_Renderer.SetSceneCamera(m->ViewCamera, m->CullCamera);
}

CGameView::~CGameView()
{
	UnloadResources();

	delete m;
}

void CGameView::SetViewport(const SViewPort& vp)
{
	m->ViewCamera.SetViewPort(vp);
	m->ViewCamera.SetProjection(m->ViewNear, m->ViewFar, m->ViewFOV);
}

CObjectManager& CGameView::GetObjectManager() const
{
	return m->ObjectManager;
}

CCamera* CGameView::GetCamera()
{
	return &m->ViewCamera;
}

CCinemaManager* CGameView::GetCinema()
{
	return &m->CinemaManager;
};

CLOSTexture& CGameView::GetLOSTexture()
{
	return m->LOSTexture;
}

CTerritoryTexture& CGameView::GetTerritoryTexture()
{
	return m->TerritoryTexture;
}

int CGameView::Initialize()
{
	CFG_GET_VAL("view.scroll.speed", m->ViewScrollSpeed);
	CFG_GET_VAL("view.scroll.speed.modifier", m->ViewScrollSpeedModifier);
	CFG_GET_VAL("view.rotate.x.speed", m->ViewRotateXSpeed);
	CFG_GET_VAL("view.rotate.x.min", m->ViewRotateXMin);
	CFG_GET_VAL("view.rotate.x.max", m->ViewRotateXMax);
	CFG_GET_VAL("view.rotate.x.default", m->ViewRotateXDefault);
	CFG_GET_VAL("view.rotate.y.speed", m->ViewRotateYSpeed);
	CFG_GET_VAL("view.rotate.y.speed.wheel", m->ViewRotateYSpeedWheel);
	CFG_GET_VAL("view.rotate.y.default", m->ViewRotateYDefault);
	CFG_GET_VAL("view.rotate.speed.modifier", m->ViewRotateSpeedModifier);
	CFG_GET_VAL("view.drag.speed", m->ViewDragSpeed);
	CFG_GET_VAL("view.zoom.speed", m->ViewZoomSpeed);
	CFG_GET_VAL("view.zoom.speed.wheel", m->ViewZoomSpeedWheel);
	CFG_GET_VAL("view.zoom.min", m->ViewZoomMin);
	CFG_GET_VAL("view.zoom.max", m->ViewZoomMax);
	CFG_GET_VAL("view.zoom.default", m->ViewZoomDefault);
	CFG_GET_VAL("view.zoom.speed.modifier", m->ViewZoomSpeedModifier);

	CFG_GET_VAL("joystick.camera.pan.x", m->JoystickPanX);
	CFG_GET_VAL("joystick.camera.pan.y", m->JoystickPanY);
	CFG_GET_VAL("joystick.camera.rotate.x", m->JoystickRotateX);
	CFG_GET_VAL("joystick.camera.rotate.y", m->JoystickRotateY);
	CFG_GET_VAL("joystick.camera.zoom.in", m->JoystickZoomIn);
	CFG_GET_VAL("joystick.camera.zoom.out", m->JoystickZoomOut);

	CFG_GET_VAL("view.height.smoothness", m->HeightSmoothness);
	CFG_GET_VAL("view.height.min", m->HeightMin);

	CFG_GET_VAL("view.pos.smoothness", m->PosX.m_Smoothness);
	CFG_GET_VAL("view.pos.smoothness", m->PosY.m_Smoothness);
	CFG_GET_VAL("view.pos.smoothness", m->PosZ.m_Smoothness);
	CFG_GET_VAL("view.zoom.smoothness", m->Zoom.m_Smoothness);
	CFG_GET_VAL("view.rotate.x.smoothness", m->RotateX.m_Smoothness);
	CFG_GET_VAL("view.rotate.y.smoothness", m->RotateY.m_Smoothness);

	CFG_GET_VAL("view.near", m->ViewNear);
	CFG_GET_VAL("view.far", m->ViewFar);
	CFG_GET_VAL("view.fov", m->ViewFOV);

	// Convert to radians
	m->RotateX.SetValue(DEGTORAD(m->ViewRotateXDefault));
	m->RotateY.SetValue(DEGTORAD(m->ViewRotateYDefault));
	m->ViewFOV = DEGTORAD(m->ViewFOV);

	return 0;
}



void CGameView::RegisterInit()
{
	// CGameView init
	RegMemFun(this, &CGameView::Initialize, L"CGameView init", 1);

	// previously done by CGameView::InitResources
	RegMemFun(g_TexMan.GetSingletonPtr(), &CTerrainTextureManager::LoadTerrainTextures, L"LoadTerrainTextures", 60);
	RegMemFun(g_Renderer.GetSingletonPtr(), &CRenderer::LoadAlphaMaps, L"LoadAlphaMaps", 5);
}


void CGameView::BeginFrame()
{
	if (m->LockCullCamera == false)
	{
		// Set up cull camera
		m->CullCamera = m->ViewCamera;
	}
	g_Renderer.SetSceneCamera(m->ViewCamera, m->CullCamera);

	CheckLightEnv();

	m->Game->CachePlayerColors();
}

void CGameView::Render()
{
	g_Renderer.RenderScene(*this);
}

///////////////////////////////////////////////////////////
// This callback is part of the Scene interface
// Submit all objects visible in the given frustum
void CGameView::EnumerateObjects(const CFrustum& frustum, SceneCollector* c)
{
	{
	PROFILE3("submit terrain");

	CTerrain* pTerrain = m->Game->GetWorld()->GetTerrain();
	float waterHeight = g_Renderer.GetWaterManager()->m_WaterHeight + 0.001f;
	const ssize_t patchesPerSide = pTerrain->GetPatchesPerSide();

	// find out which patches will be drawn
	for (ssize_t j=0; j<patchesPerSide; ++j)
	{
		for (ssize_t i=0; i<patchesPerSide; ++i)
		{
			CPatch* patch=pTerrain->GetPatch(i,j);	// can't fail

			// If the patch is underwater, calculate a bounding box that also contains the water plane
			CBoundingBoxAligned bounds = patch->GetWorldBounds();
			if(bounds[1].Y < waterHeight)
				bounds[1].Y = waterHeight;

			if (!m->Culling || frustum.IsBoxVisible(bounds))
				c->Submit(patch);
		}
	}
	}

	m->Game->GetSimulation2()->RenderSubmit(*c, frustum, m->Culling);
}


void CGameView::CheckLightEnv()
{
	if (m->CachedLightEnv == g_LightEnv)
		return;

	if (m->CachedLightEnv.GetLightingModel() != g_LightEnv.GetLightingModel())
		g_Renderer.MakeShadersDirty();

	m->CachedLightEnv = g_LightEnv;
	CTerrain* pTerrain = m->Game->GetWorld()->GetTerrain();

	if (!pTerrain)
		return;

	PROFILE("update light env");
	pTerrain->MakeDirty(RENDERDATA_UPDATE_COLOR);

	const std::vector<CUnit*>& units = m->Game->GetWorld()->GetUnitManager().GetUnits();
	for (size_t i = 0; i < units.size(); ++i)
		units[i]->GetModel().SetDirtyRec(RENDERDATA_UPDATE_COLOR);
}


void CGameView::UnloadResources()
{
	g_TexMan.UnloadTerrainTextures();
	g_Renderer.UnloadAlphaMaps();
	g_Renderer.GetWaterManager()->UnloadWaterTextures();
}

static void FocusHeight(CGameViewImpl* m, bool smooth)
{
	/*
		The camera pivot height is moved towards ground level.
		To prevent excessive zoom when looking over a cliff,
		the target ground level is the maximum of the ground level at the camera's near and pivot points.
		The ground levels are filtered to achieve smooth camera movement.
		The filter radius is proportional to the zoom level.
		The camera height is clamped to prevent map penetration.
	*/

	if (!m->ConstrainCamera)
		return;

	CCamera targetCam = m->ViewCamera;
	SetupCameraMatrixSmoothRot(m, &targetCam.m_Orientation);

	const CVector3D position = targetCam.m_Orientation.GetTranslation();
	const CVector3D forwards = targetCam.m_Orientation.GetIn();

	// horizontal view radius
	const float radius = sqrtf(forwards.X * forwards.X + forwards.Z * forwards.Z) * m->Zoom.GetSmoothedValue();
	const float near_radius = radius * m->HeightSmoothness;
	const float pivot_radius = radius * m->HeightSmoothness;

	const CVector3D nearPoint = position + forwards * m->ViewNear;
	const CVector3D pivotPoint = position + forwards * m->Zoom.GetSmoothedValue();

	const float ground = std::max(
		m->Game->GetWorld()->GetTerrain()->GetExactGroundLevel(nearPoint.X, nearPoint.Z),
		g_Renderer.GetWaterManager()->m_WaterHeight);

	// filter ground levels for smooth camera movement
	const float filtered_near_ground = m->Game->GetWorld()->GetTerrain()->GetFilteredGroundLevel(nearPoint.X, nearPoint.Z, near_radius);
	const float filtered_pivot_ground = m->Game->GetWorld()->GetTerrain()->GetFilteredGroundLevel(pivotPoint.X, pivotPoint.Z, pivot_radius);

	// filtered maximum visible ground level in view
	const float filtered_ground = std::max(
		std::max(filtered_near_ground, filtered_pivot_ground),
		g_Renderer.GetWaterManager()->m_WaterHeight);

	// target camera height above pivot point
	const float pivot_height = -forwards.Y * (m->Zoom.GetSmoothedValue() - m->ViewNear);

	// minimum camera height above filtered ground level
	const float min_height = (m->HeightMin + ground - filtered_ground);

	const float target_height = std::max(pivot_height, min_height);
	const float height = (nearPoint.Y - filtered_ground);
	const float diff = target_height - height;

	if (fabsf(diff) < 0.0001f)
		return;

	if (smooth)
		m->PosY.AddSmoothly(diff);
	else
		m->PosY.Add(diff);
}

CVector3D CGameView::GetSmoothPivot(CCamera& camera) const
{
	return camera.m_Orientation.GetTranslation() + camera.m_Orientation.GetIn() * m->Zoom.GetSmoothedValue();
}

void CGameView::Update(const float deltaRealTime)
{
	// If camera movement is being handled by the touch-input system,
	// then we should stop to avoid conflicting with it
	if (g_TouchInput.IsEnabled())
		return;

	if (!g_app_has_focus)
		return;

	m->CinemaManager.Update(deltaRealTime);
	if (m->CinemaManager.IsEnabled())
		return;

	// Calculate mouse movement
	static int mouse_last_x = 0;
	static int mouse_last_y = 0;
	int mouse_dx = g_mouse_x - mouse_last_x;
	int mouse_dy = g_mouse_y - mouse_last_y;
	mouse_last_x = g_mouse_x;
	mouse_last_y = g_mouse_y;

	if (HotkeyIsPressed("camera.rotate.cw"))
		m->RotateY.AddSmoothly(m->ViewRotateYSpeed * deltaRealTime);
	if (HotkeyIsPressed("camera.rotate.ccw"))
		m->RotateY.AddSmoothly(-m->ViewRotateYSpeed * deltaRealTime);
	if (HotkeyIsPressed("camera.rotate.up"))
		m->RotateX.AddSmoothly(-m->ViewRotateXSpeed * deltaRealTime);
	if (HotkeyIsPressed("camera.rotate.down"))
		m->RotateX.AddSmoothly(m->ViewRotateXSpeed * deltaRealTime);

	float moveRightward = 0.f;
	float moveForward = 0.f;

	if (HotkeyIsPressed("camera.pan"))
	{
		moveRightward += m->ViewDragSpeed * mouse_dx;
		moveForward += m->ViewDragSpeed * -mouse_dy;
	}

	if (g_mouse_active)
	{
		if (g_mouse_x >= g_xres - 2 && g_mouse_x < g_xres)
			moveRightward += m->ViewScrollSpeed * deltaRealTime;
		else if (g_mouse_x <= 3 && g_mouse_x >= 0)
			moveRightward -= m->ViewScrollSpeed * deltaRealTime;

		if (g_mouse_y >= g_yres - 2 && g_mouse_y < g_yres)
			moveForward -= m->ViewScrollSpeed * deltaRealTime;
		else if (g_mouse_y <= 3 && g_mouse_y >= 0)
			moveForward += m->ViewScrollSpeed * deltaRealTime;
	}

	if (HotkeyIsPressed("camera.right"))
		moveRightward += m->ViewScrollSpeed * deltaRealTime;
	if (HotkeyIsPressed("camera.left"))
		moveRightward -= m->ViewScrollSpeed * deltaRealTime;
	if (HotkeyIsPressed("camera.up"))
		moveForward += m->ViewScrollSpeed * deltaRealTime;
	if (HotkeyIsPressed("camera.down"))
		moveForward -= m->ViewScrollSpeed * deltaRealTime;

	if (g_Joystick.IsEnabled())
	{
		// This could all be improved with extra speed and sensitivity settings
		// (maybe use pow to allow finer control?), and inversion settings

		moveRightward += g_Joystick.GetAxisValue(m->JoystickPanX) * m->ViewScrollSpeed * deltaRealTime;
		moveForward -= g_Joystick.GetAxisValue(m->JoystickPanY) * m->ViewScrollSpeed * deltaRealTime;

		m->RotateX.AddSmoothly(g_Joystick.GetAxisValue(m->JoystickRotateX) * m->ViewRotateXSpeed * deltaRealTime);
		m->RotateY.AddSmoothly(-g_Joystick.GetAxisValue(m->JoystickRotateY) * m->ViewRotateYSpeed * deltaRealTime);

		// Use a +1 bias for zoom because I want this to work with trigger buttons that default to -1
		m->Zoom.AddSmoothly((g_Joystick.GetAxisValue(m->JoystickZoomIn) + 1.0f) / 2.0f * m->ViewZoomSpeed * deltaRealTime);
		m->Zoom.AddSmoothly(-(g_Joystick.GetAxisValue(m->JoystickZoomOut) + 1.0f) / 2.0f * m->ViewZoomSpeed * deltaRealTime);
	}

	if (moveRightward || moveForward)
	{
		// Break out of following mode when the user starts scrolling
		m->FollowEntity = INVALID_ENTITY;

		float s = sin(m->RotateY.GetSmoothedValue());
		float c = cos(m->RotateY.GetSmoothedValue());
		m->PosX.AddSmoothly(c * moveRightward);
		m->PosZ.AddSmoothly(-s * moveRightward);
		m->PosX.AddSmoothly(s * moveForward);
		m->PosZ.AddSmoothly(c * moveForward);
	}

	if (m->FollowEntity)
	{
		CmpPtr<ICmpPosition> cmpPosition(*(m->Game->GetSimulation2()), m->FollowEntity);
		CmpPtr<ICmpRangeManager> cmpRangeManager(*(m->Game->GetSimulation2()), SYSTEM_ENTITY);
		if (cmpPosition && cmpPosition->IsInWorld() &&
		    cmpRangeManager && cmpRangeManager->GetLosVisibility(m->FollowEntity, m->Game->GetViewedPlayerID()) == ICmpRangeManager::VIS_VISIBLE)
		{
			// Get the most recent interpolated position
			float frameOffset = m->Game->GetSimulation2()->GetLastFrameOffset();
			CMatrix3D transform = cmpPosition->GetInterpolatedTransform(frameOffset);
			CVector3D pos = transform.GetTranslation();

			if (m->FollowFirstPerson)
			{
				float x, z, angle;
				cmpPosition->GetInterpolatedPosition2D(frameOffset, x, z, angle);
				float height = 4.f;
				m->ViewCamera.m_Orientation.SetIdentity();
				m->ViewCamera.m_Orientation.RotateX((float)M_PI/24.f);
				m->ViewCamera.m_Orientation.RotateY(angle);
				m->ViewCamera.m_Orientation.Translate(pos.X, pos.Y + height, pos.Z);

				m->ViewCamera.UpdateFrustum();
				return;
			}
			else
			{
				// Move the camera to match the unit
				CCamera targetCam = m->ViewCamera;
				SetupCameraMatrixSmoothRot(m, &targetCam.m_Orientation);

				CVector3D pivot = GetSmoothPivot(targetCam);
				CVector3D delta = pos - pivot;
				m->PosX.AddSmoothly(delta.X);
				m->PosY.AddSmoothly(delta.Y);
				m->PosZ.AddSmoothly(delta.Z);
			}
		}
		else
		{
			// The unit disappeared (died or garrisoned etc), so stop following it
			m->FollowEntity = INVALID_ENTITY;
		}
	}

	if (HotkeyIsPressed("camera.zoom.in"))
		m->Zoom.AddSmoothly(-m->ViewZoomSpeed * deltaRealTime);
	if (HotkeyIsPressed("camera.zoom.out"))
		m->Zoom.AddSmoothly(m->ViewZoomSpeed * deltaRealTime);

	if (m->ConstrainCamera)
		m->Zoom.ClampSmoothly(m->ViewZoomMin, m->ViewZoomMax);

	float zoomDelta = -m->Zoom.Update(deltaRealTime);
	if (zoomDelta)
	{
		CVector3D forwards = m->ViewCamera.m_Orientation.GetIn();
		m->PosX.AddSmoothly(forwards.X * zoomDelta);
		m->PosY.AddSmoothly(forwards.Y * zoomDelta);
		m->PosZ.AddSmoothly(forwards.Z * zoomDelta);
	}

	if (m->ConstrainCamera)
		m->RotateX.ClampSmoothly(DEGTORAD(m->ViewRotateXMin), DEGTORAD(m->ViewRotateXMax));

	FocusHeight(m, true);

	// Ensure the ViewCamera focus is inside the map with the chosen margins
	// if not so - apply margins to the camera
	if (m->ConstrainCamera)
	{
		CCamera targetCam = m->ViewCamera;
		SetupCameraMatrixSmoothRot(m, &targetCam.m_Orientation);

		CTerrain* pTerrain = m->Game->GetWorld()->GetTerrain();

		CVector3D pivot = GetSmoothPivot(targetCam);
		CVector3D delta = targetCam.m_Orientation.GetTranslation() - pivot;

		CVector3D desiredPivot = pivot;

		CmpPtr<ICmpRangeManager> cmpRangeManager(*(m->Game->GetSimulation2()), SYSTEM_ENTITY);
		if (cmpRangeManager && cmpRangeManager->GetLosCircular())
		{
			// Clamp to a circular region around the center of the map
			float r = pTerrain->GetMaxX() / 2;
			CVector3D center(r, desiredPivot.Y, r);
			float dist = (desiredPivot - center).Length();
			if (dist > r - CAMERA_EDGE_MARGIN)
				desiredPivot = center + (desiredPivot - center).Normalized() * (r - CAMERA_EDGE_MARGIN);
		}
		else
		{
			// Clamp to the square edges of the map
			desiredPivot.X = Clamp(desiredPivot.X, pTerrain->GetMinX() + CAMERA_EDGE_MARGIN, pTerrain->GetMaxX() - CAMERA_EDGE_MARGIN);
			desiredPivot.Z = Clamp(desiredPivot.Z, pTerrain->GetMinZ() + CAMERA_EDGE_MARGIN, pTerrain->GetMaxZ() - CAMERA_EDGE_MARGIN);
		}

		// Update the position so that pivot is within the margin
		m->PosX.SetValueSmoothly(desiredPivot.X + delta.X);
		m->PosZ.SetValueSmoothly(desiredPivot.Z + delta.Z);
	}

	m->PosX.Update(deltaRealTime);
	m->PosY.Update(deltaRealTime);
	m->PosZ.Update(deltaRealTime);

	// Handle rotation around the Y (vertical) axis
	{
		CCamera targetCam = m->ViewCamera;
		SetupCameraMatrixSmooth(m, &targetCam.m_Orientation);

		float rotateYDelta = m->RotateY.Update(deltaRealTime);
		if (rotateYDelta)
		{
			// We've updated RotateY, and need to adjust Pos so that it's still
			// facing towards the original focus point (the terrain in the center
			// of the screen).

			CVector3D upwards(0.0f, 1.0f, 0.0f);

			CVector3D pivot = GetSmoothPivot(targetCam);
			CVector3D delta = targetCam.m_Orientation.GetTranslation() - pivot;

			CQuaternion q;
			q.FromAxisAngle(upwards, rotateYDelta);
			CVector3D d = q.Rotate(delta) - delta;

			m->PosX.Add(d.X);
			m->PosY.Add(d.Y);
			m->PosZ.Add(d.Z);
		}
	}

	// Handle rotation around the X (sideways, relative to camera) axis
	{
		CCamera targetCam = m->ViewCamera;
		SetupCameraMatrixSmooth(m, &targetCam.m_Orientation);

		float rotateXDelta = m->RotateX.Update(deltaRealTime);
		if (rotateXDelta)
		{
			CVector3D rightwards = targetCam.m_Orientation.GetLeft() * -1.0f;

			CVector3D pivot = GetSmoothPivot(targetCam);
			CVector3D delta = targetCam.m_Orientation.GetTranslation() - pivot;

			CQuaternion q;
			q.FromAxisAngle(rightwards, rotateXDelta);
			CVector3D d = q.Rotate(delta) - delta;

			m->PosX.Add(d.X);
			m->PosY.Add(d.Y);
			m->PosZ.Add(d.Z);
		}
	}

	/* This is disabled since it doesn't seem necessary:

	// Ensure the camera's near point is never inside the terrain
	if (m->ConstrainCamera)
	{
		CMatrix3D target;
		target.SetIdentity();
		target.RotateX(m->RotateX.GetValue());
		target.RotateY(m->RotateY.GetValue());
		target.Translate(m->PosX.GetValue(), m->PosY.GetValue(), m->PosZ.GetValue());

		CVector3D nearPoint = target.GetTranslation() + target.GetIn() * defaultNear;
		float ground = m->Game->GetWorld()->GetTerrain()->GetExactGroundLevel(nearPoint.X, nearPoint.Z);
		float limit = ground + 16.f;
		if (nearPoint.Y < limit)
			m->PosY.AddSmoothly(limit - nearPoint.Y);
	}
	*/

	m->RotateY.Wrap(-(float)M_PI, (float)M_PI);

	// Update the camera matrix
	m->ViewCamera.SetProjection(m->ViewNear, m->ViewFar, m->ViewFOV);
	SetupCameraMatrixSmooth(m, &m->ViewCamera.m_Orientation);
	m->ViewCamera.UpdateFrustum();
}

float CGameView::GetCameraX()
{
	CCamera targetCam = m->ViewCamera;
	CVector3D pivot = GetSmoothPivot(targetCam);
	return pivot.X;
}

float CGameView::GetCameraZ()
{
	CCamera targetCam = m->ViewCamera;
	CVector3D pivot = GetSmoothPivot(targetCam);
	return pivot.Z;
}

float CGameView::GetCameraPosX()
{
	return m->PosX.GetValue();
}

float CGameView::GetCameraPosY()
{
	return m->PosY.GetValue();
}

float CGameView::GetCameraPosZ()
{
	return m->PosZ.GetValue();
}

float CGameView::GetCameraRotX()
{
	return m->RotateX.GetValue();
}

float CGameView::GetCameraRotY()
{
	return m->RotateY.GetValue();
}

float CGameView::GetCameraZoom()
{
	return m->Zoom.GetValue();
}

void CGameView::SetCamera(CVector3D Pos, float RotX, float RotY, float zoom)
{
	m->PosX.SetValue(Pos.X);
	m->PosY.SetValue(Pos.Y);
	m->PosZ.SetValue(Pos.Z);
	m->RotateX.SetValue(RotX);
	m->RotateY.SetValue(RotY);
	m->Zoom.SetValue(zoom);

	FocusHeight(m, false);

	SetupCameraMatrixNonSmooth(m, &m->ViewCamera.m_Orientation);
	m->ViewCamera.UpdateFrustum();

	// Break out of following mode so the camera really moves to the target
	m->FollowEntity = INVALID_ENTITY;
}

void CGameView::MoveCameraTarget(const CVector3D& target)
{
	// Maintain the same orientation and level of zoom, if we can
	// (do this by working out the point the camera is looking at, saving
	//  the difference between that position and the camera point, and restoring
	//  that difference to our new target)

	CCamera targetCam = m->ViewCamera;
	SetupCameraMatrixNonSmooth(m, &targetCam.m_Orientation);

	CVector3D pivot = GetSmoothPivot(targetCam);
	CVector3D delta = target - pivot;

	m->PosX.SetValueSmoothly(delta.X + m->PosX.GetValue());
	m->PosZ.SetValueSmoothly(delta.Z + m->PosZ.GetValue());

	FocusHeight(m, false);

	// Break out of following mode so the camera really moves to the target
	m->FollowEntity = INVALID_ENTITY;
}

void CGameView::ResetCameraTarget(const CVector3D& target)
{
	CMatrix3D orientation;
	orientation.SetIdentity();
	orientation.RotateX(DEGTORAD(m->ViewRotateXDefault));
	orientation.RotateY(DEGTORAD(m->ViewRotateYDefault));

	CVector3D delta = orientation.GetIn() * m->ViewZoomDefault;
	m->PosX.SetValue(target.X - delta.X);
	m->PosY.SetValue(target.Y - delta.Y);
	m->PosZ.SetValue(target.Z - delta.Z);
	m->RotateX.SetValue(DEGTORAD(m->ViewRotateXDefault));
	m->RotateY.SetValue(DEGTORAD(m->ViewRotateYDefault));
	m->Zoom.SetValue(m->ViewZoomDefault);

	FocusHeight(m, false);

	SetupCameraMatrixSmooth(m, &m->ViewCamera.m_Orientation);
	m->ViewCamera.UpdateFrustum();

	// Break out of following mode so the camera really moves to the target
	m->FollowEntity = INVALID_ENTITY;
}

void CGameView::ResetCameraAngleZoom()
{
	CCamera targetCam = m->ViewCamera;
	SetupCameraMatrixNonSmooth(m, &targetCam.m_Orientation);

	// Compute the zoom adjustment to get us back to the default
	CVector3D forwards = targetCam.m_Orientation.GetIn();

	CVector3D pivot = GetSmoothPivot(targetCam);
	CVector3D delta = pivot - targetCam.m_Orientation.GetTranslation();
	float dist = delta.Dot(forwards);
	m->Zoom.AddSmoothly(m->ViewZoomDefault - dist);

	// Reset orientations to default
	m->RotateX.SetValueSmoothly(DEGTORAD(m->ViewRotateXDefault));
	m->RotateY.SetValueSmoothly(DEGTORAD(m->ViewRotateYDefault));
}

void CGameView::CameraFollow(entity_id_t entity, bool firstPerson)
{
	m->FollowEntity = entity;
	m->FollowFirstPerson = firstPerson;
}

entity_id_t CGameView::GetFollowedEntity()
{
	return m->FollowEntity;
}

float CGameView::GetNear() const
{
	return m->ViewNear;
}

float CGameView::GetFar() const
{
	return m->ViewFar;
}

float CGameView::GetFOV() const
{
	return m->ViewFOV;
}

void CGameView::SetCameraProjection()
{
	m->ViewCamera.SetProjection(m->ViewNear, m->ViewFar, m->ViewFOV);
}

InReaction game_view_handler(const SDL_Event_* ev)
{
	// put any events that must be processed even if inactive here
	if (!g_app_has_focus || !g_Game || !g_Game->IsGameStarted() || g_Game->GetView()->GetCinema()->IsEnabled())
		return IN_PASS;

	CGameView *pView=g_Game->GetView();

	return pView->HandleEvent(ev);
}

InReaction CGameView::HandleEvent(const SDL_Event_* ev)
{
	switch(ev->ev.type)
	{

	case SDL_HOTKEYDOWN:
		std::string hotkey = static_cast<const char*>(ev->ev.user.data1);

		if (hotkey == "wireframe")
		{
			if (g_XmppClient && g_rankedGame == true)
				break;
			else if (g_Renderer.GetModelRenderMode() == SOLID)
			{
				g_Renderer.SetTerrainRenderMode(EDGED_FACES);
				g_Renderer.SetWaterRenderMode(EDGED_FACES);
				g_Renderer.SetModelRenderMode(EDGED_FACES);
			}
			else if (g_Renderer.GetModelRenderMode() == EDGED_FACES)
			{
				g_Renderer.SetTerrainRenderMode(WIREFRAME);
				g_Renderer.SetWaterRenderMode(WIREFRAME);
				g_Renderer.SetModelRenderMode(WIREFRAME);
			}
			else
			{
				g_Renderer.SetTerrainRenderMode(SOLID);
				g_Renderer.SetWaterRenderMode(SOLID);
				g_Renderer.SetModelRenderMode(SOLID);
			}
			return IN_HANDLED;
		}
		// Mouse wheel must be treated using events instead of polling,
		// because SDL auto-generates a sequence of mousedown/mouseup events
		// and we never get to see the "down" state inside Update().
		else if (hotkey == "camera.zoom.wheel.in")
		{
			m->Zoom.AddSmoothly(-m->ViewZoomSpeedWheel);
			return IN_HANDLED;
		}
		else if (hotkey == "camera.zoom.wheel.out")
		{
			m->Zoom.AddSmoothly(m->ViewZoomSpeedWheel);
			return IN_HANDLED;
		}
		else if (hotkey == "camera.rotate.wheel.cw")
		{
			m->RotateY.AddSmoothly(m->ViewRotateYSpeedWheel);
			return IN_HANDLED;
		}
		else if (hotkey == "camera.rotate.wheel.ccw")
		{
			m->RotateY.AddSmoothly(-m->ViewRotateYSpeedWheel);
			return IN_HANDLED;
		}
		else if (hotkey == "camera.scroll.speed.increase")
		{
			m->ViewScrollSpeed *= m->ViewScrollSpeedModifier;
			return IN_HANDLED;
		}
		else if (hotkey == "camera.scroll.speed.decrease")
		{
			m->ViewScrollSpeed /= m->ViewScrollSpeedModifier;
			return IN_HANDLED;
		}
		else if (hotkey == "camera.rotate.speed.increase")
		{
			m->ViewRotateXSpeed *= m->ViewRotateSpeedModifier;
			m->ViewRotateYSpeed *= m->ViewRotateSpeedModifier;
			return IN_HANDLED;
		}
		else if (hotkey == "camera.rotate.speed.decrease")
		{
			m->ViewRotateXSpeed /= m->ViewRotateSpeedModifier;
			m->ViewRotateYSpeed /= m->ViewRotateSpeedModifier;
			return IN_HANDLED;
		}
		else if (hotkey == "camera.zoom.speed.increase")
		{
			m->ViewZoomSpeed *= m->ViewZoomSpeedModifier;
			return IN_HANDLED;
		}
		else if (hotkey == "camera.zoom.speed.decrease")
		{
			m->ViewZoomSpeed /= m->ViewZoomSpeedModifier;
			return IN_HANDLED;
		}
		else if (hotkey == "camera.reset")
		{
			ResetCameraAngleZoom();
			return IN_HANDLED;
		}
	}

	return IN_PASS;
}