This repository has been archived by the owner on Jul 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathpie_noon_game.cpp
2935 lines (2650 loc) · 114 KB
/
pie_noon_game.cpp
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
// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "precompiled.h"
#include "SDL_events.h"
#include "analytics_tracking.h"
#include "audio_config_generated.h"
#include "character_state_machine.h"
#include "character_state_machine_def_generated.h"
#include "config_generated.h"
#include "motive/init.h"
#include "motive/io/flatbuffers.h"
#include "motive/math/angle.h"
#include "multiplayer_generated.h"
#include "pie_noon_common_generated.h"
#include "pie_noon_game.h"
#include "pindrop/pindrop.h"
#include "timeline_generated.h"
#include "touchscreen_controller.h"
#include "SDL.h"
#ifdef ANDROID_HMD
#include "fplbase/glplatform.h"
#include "fplbase/renderer_hmd.h"
#endif // ANDROID_HMD
using motive::Angle;
using mathfu::mat3;
#ifdef _WIN32
#define snprintf(buffer, count, format, ...) \
_snprintf_s(buffer, count, count, format, __VA_ARGS__)
#endif // _WIN32
namespace fpl {
namespace pie_noon {
static const int kQuadNumVertices = 4;
static const int kQuadNumIndices = 6;
static const char* kCategoryUi = "Ui";
static const char* kActionClickedButton = "Clicked button";
static const char* kActionViewedTutorialSlide = "Viewed tutorial slide";
static const char* kActionViewedMSTutorialSlide = "MSX-Viewed tutorial slide";
static const char* kLabelSlideDurationFmt = "Slide #%i duration";
static const char* kLabelMSSlideDurationFmt = "MSX-Slide #%i duration";
static const char* kLabelSignInOutButton = "Sign In/Out";
static const char* kLabelLicenseButton = "License";
static const char* kLabelAboutButton = "About";
static const char* kLabelStartButton = "Start";
static const char* kLabelPauseButton = "Pause";
static const char* kLabelUnpauseButton = "Unpause";
static const char* kLabelAchievementsButton = "Achievements";
static const char* kLabelExtrasButton = "Extras";
static const char* kLabelExtrasBackButton = "Extras back button";
static const char* kLabelHowToPlayButton = "How to play";
static const char* kLabelLeaderboardButton = "Leaderboard";
static const char* kLabelMultiscreenButton = "Multiscreen";
static const char* kLabelCardboardButton = "Cardboard";
static const char* kLabelGameModesButton = "Game Modes";
#ifdef PIE_NOON_USES_GOOGLE_PLAY_GAMES
static const char* kCategoryMultiscreen = "Multiscreen";
static const char* kActionStart = "Start";
static const char* kActionFinish = "Finish";
static const char* kActionError = "Error";
static const char* kLabelAdvertising = "Advertising";
static const char* kLabelDiscovery = "Discovery";
static const char* kLabelGameHost = "GameHost";
static const char* kLabelGameClient = "GameClient";
static const char* kLabelReconnection = "Reconnection";
static const char* kLabelHostDisconnected = "HostDisconnect";
static const char* kLabelClientsDisconnected = "ClientDisconnect";
static const char* kLabelConnectionLost = "ConnectionLost";
#endif // PIE_NOON_USES_GOOGLE_PLAY_GAMES
static const unsigned short kQuadIndices[] = {0, 1, 2, 2, 1, 3};
static const fplbase::Attribute kQuadMeshFormat[] = {
fplbase::kPosition3f, fplbase::kTexCoord2f, fplbase::kNormal3f,
fplbase::kTangent4f, fplbase::kEND
};
static const char kAssetsDir[] = "assets";
static const char kConfigFileName[] = "config.pieconfig";
static const char kDefaultOverlayFile[] = "default_overlay.txt";
#ifdef ANDROID_HMD
static const char kCardboardConfigFileName[] = "cardboard_config.pieconfig";
#endif
#ifdef __ANDROID__
static const int kAndroidMaxScreenWidth = 1920;
static const int kAndroidMaxScreenHeight = 1080;
#endif
#ifdef PIE_NOON_USES_GOOGLE_PLAY_GAMES
static GPGManager::GPGIds gpg_ids[kMaxStats];
static std::vector<std::string> achievement_ids;
#endif
std::string PieNoonGame::overlay_name_;
// Return the elapsed milliseconds since the start of the program. This number
// will loop back to 0 after about 49 days; always take the difference to
// properly handle the wrap-around case.
static inline WorldTime CurrentWorldTime(const fplbase::InputSystem& input) {
return static_cast<WorldTime>(input.Time() * 1000);
}
static inline const UiGroup* TitleScreenButtons(const Config& config) {
#ifdef __ANDROID__
const bool android_title_screen = true;
#else
const bool android_title_screen =
config.always_use_android_title_screen() != 0;
#endif
return android_title_screen ? config.title_screen_buttons_android()
: config.title_screen_buttons_non_android();
}
/// kVersion is used by Google developers to identify which
/// applications uploaded to Google Play are derived from this application.
/// This allows the development team at Google to determine the popularity of
/// this application.
/// How it works: Applications that are uploaded to the Google Play Store are
/// scanned for this version string. We track which applications are using it
/// to measure popularity. You are free to remove it (of course) but we would
/// appreciate if you left it in.
static const char kVersion[] = "Pie Noon 1.2.0";
PieNoonGame::PieNoonGame()
: state_(kUninitialized),
state_entry_time_(0),
matman_(renderer_),
stick_front_(nullptr),
stick_back_(nullptr),
shader_lit_textured_normal_(nullptr),
shader_simple_shadow_(nullptr),
shader_textured_(nullptr),
shader_grayscale_(nullptr),
shadow_mat_(nullptr),
prev_world_time_(0),
debug_previous_states_(),
full_screen_fader_(&renderer_),
fade_exit_state_(kUninitialized),
ambience_channel_(),
stinger_channel_(),
music_channel_(),
next_achievement_index_(0) {
fplbase::SetLoadFileFunction(PieNoonGame::LoadFile);
version_ = kVersion;
for (size_t i = 0; i < RenderableId_Count; ++i) {
cardboard_backs_[i] = nullptr;
}
}
PieNoonGame::~PieNoonGame() {
for (int i = 0; i < RenderableId_Count; ++i) {
std::vector<fplbase::Mesh*>& fronts = cardboard_fronts_[i];
for (size_t j = 0; j < fronts.size(); ++j) {
delete fronts[j];
fronts[j] = nullptr;
}
delete cardboard_backs_[i];
cardboard_backs_[i] = nullptr;
}
delete stick_front_;
stick_front_ = nullptr;
delete stick_back_;
stick_back_ = nullptr;
}
bool PieNoonGame::InitializeConfig() {
if (!LoadFile(kConfigFileName, &config_source_)) {
fplbase::LogError(fplbase::kError, "can't load %s\n", kConfigFileName);
return false;
}
return true;
}
#ifdef ANDROID_HMD
bool PieNoonGame::InitializeCardboardConfig() {
if (!LoadFile(kCardboardConfigFileName, &cardboard_config_source_)) {
fplbase::LogError(fplbase::kError, "can't load %s\n", kCardboardConfigFileName);
return false;
}
return true;
}
#endif // ANDROID_HMD
// Initialize the 'renderer_' member. No other members have been initialized at
// this point.
bool PieNoonGame::InitializeRenderer() {
const Config& config = GetConfig();
#ifdef __ANDROID__
auto max_screen_size =
fplbase::Vec2i(kAndroidMaxScreenWidth, kAndroidMaxScreenHeight);
auto window_size = &max_screen_size;
#else
auto window_size = config.window_size();
#endif
assert(window_size);
if (!renderer_.Initialize(LoadVec2i(window_size),
config.window_title()->c_str())) {
fplbase::LogError(fplbase::kError, "Renderer initialization error: %s\n",
renderer_.last_error().c_str());
return false;
}
#ifdef __ANDROID__
// Restart the app if HW scaler setting failed.
auto retry = fplbase::LoadPreference("HWScalerRetry", 0);
const auto kMaxRetry = 3;
auto current_window_size = fplbase::AndroidGetScalerResolution();
if (current_window_size.x() != window_size->x() ||
current_window_size.y() != window_size->y()) {
if (retry < kMaxRetry) {
fplbase::LogError("HW Scalar failed. Restarting application.");
fplbase::SavePreference("HWScalerRetry", retry + 1);
fplbase::RelaunchApplication();
return false;
}
// The HW may not support the API. Fallback to native resolution pass until
// the API success next time.
} else {
// HW scaler setting was success. Clear retry counter.
fplbase::SavePreference("HWScalerRetry", 0);
}
#endif
#ifdef ANDROID_HMD
vec2i size = fplbase::AndroidGetScalerResolution();
const vec2i viewport_size =
size.x() && size.y() ? size : renderer_.window_size();
fplbase::InitializeUndistortFramebuffer(viewport_size.x(), viewport_size.y());
#endif
renderer_.set_color(mathfu::kOnes4f);
// Initialize the first frame as black.
renderer_.ClearFrameBuffer(mathfu::kZeros4f);
return true;
}
struct NormalMappedVertex {
mathfu::vec3_packed pos;
mathfu::vec2_packed tc;
mathfu::vec3_packed norm;
mathfu::vec4_packed tangent;
};
// Initializes 'vertices' at the specified position, aligned up-and-down.
// 'vertices' must be an array of length kQuadNumVertices.
static void CreateVerticalQuad(const vec3& offset, const vec2& geo_size,
const vec2& texture_coord_size,
NormalMappedVertex* vertices) {
const float half_width = geo_size[0] * 0.5f;
const vec3 bottom_left = offset + vec3(-half_width, 0.0f, 0.0f);
const vec3 top_right = offset + vec3(half_width, geo_size[1], 0.0f);
vertices[0].pos = bottom_left;
vertices[1].pos = vec3(top_right[0], bottom_left[1], offset[2]);
vertices[2].pos = vec3(bottom_left[0], top_right[1], offset[2]);
vertices[3].pos = top_right;
const float coord_half_width = texture_coord_size[0] * 0.5f;
const vec2 coord_bottom_left(0.5f - coord_half_width, 1.0f);
const vec2 coord_top_right(0.5f + coord_half_width,
1.0f - texture_coord_size[1]);
vertices[0].tc = coord_bottom_left;
vertices[1].tc = vec2(coord_top_right[0], coord_bottom_left[1]);
vertices[2].tc = vec2(coord_bottom_left[0], coord_top_right[1]);
vertices[3].tc = coord_top_right;
fplbase::Mesh::ComputeNormalsTangents(vertices, &kQuadIndices[0],
kQuadNumVertices, kQuadNumIndices);
}
// Creates a mesh of a single quad (two triangles) vertically upright.
// The quad's has x and y size determined by the size of the texture.
// The quad is offset in (x,y,z) space by the 'offset' variable.
// Returns a mesh with the quad and texture, or nullptr if anything went wrong.
fplbase::Mesh* PieNoonGame::CreateVerticalQuadMesh(
const flatbuffers::String* material_name, const vec3& offset,
const vec2& pixel_bounds, float pixel_to_world_scale) {
// Don't try to load obviously invalid materials. Suppresses error logs from
// the material manager.
if (material_name == nullptr || material_name->c_str()[0] == '\0')
return nullptr;
// Load the material from file, and check validity.
auto material = matman_.LoadMaterial(material_name->c_str());
bool material_valid = material != nullptr && material->textures().size() > 0;
if (!material_valid) return nullptr;
// Create vertex geometry in proportion to the texture size.
// This is nice for the artist since everything is at the scale of the
// original artwork.
assert(pixel_bounds.x() && pixel_bounds.y());
const vec2 texture_size = vec2(mathfu::RoundUpToPowerOf2(pixel_bounds.x()),
mathfu::RoundUpToPowerOf2(pixel_bounds.y()));
const vec2 texture_coord_size = pixel_bounds / texture_size;
const vec2 geo_size = pixel_bounds * vec2(pixel_to_world_scale);
// Initialize a vertex array in the requested position.
NormalMappedVertex vertices[kQuadNumVertices];
CreateVerticalQuad(offset, geo_size, texture_coord_size, vertices);
// Create mesh and add in quad indices.
auto mesh = new fplbase::Mesh(vertices, kQuadNumVertices,
sizeof(NormalMappedVertex), kQuadMeshFormat);
mesh->AddIndices(kQuadIndices, kQuadNumIndices, material);
return mesh;
}
// Load textures for cardboard into 'materials_'. The 'renderer_' and 'matman_'
// members have been initialized at this point.
bool PieNoonGame::InitializeRenderingAssets() {
const Config& config = GetConfig();
// Check data validity.
if (config.renderables()->Length() != RenderableId_Count) {
fplbase::LogError(fplbase::kError,
"%s's 'renderables' array has %d entries, needs %d.\n",
kConfigFileName, config.renderables()->Length(),
RenderableId_Count);
return false;
}
// Force these textures to be queued up first, since we want to use them for
// the loading screen.
matman_.LoadMaterial(config.loading_material()->c_str());
matman_.LoadMaterial(config.loading_logo()->c_str());
matman_.LoadMaterial(config.fade_material()->c_str());
// Create a mesh for the front and back of each cardboard cutout.
const vec3 front_z_offset(0.0f, 0.0f, config.cardboard_front_z_offset());
const vec3 back_z_offset(0.0f, 0.0f, config.cardboard_back_z_offset());
for (int id = 0; id < RenderableId_Count; ++id) {
auto renderable = config.renderables()->Get(id);
const vec3 offset = renderable->offset() == nullptr
? mathfu::kZeros3f
: LoadVec3(renderable->offset());
const vec3 front_offset = offset + front_z_offset;
const vec3 back_offset = offset + back_z_offset;
const auto pixel_bounds_ptr = renderable->pixel_bounds();
const vec2 pixel_bounds(pixel_bounds_ptr == nullptr
? mathfu::kZeros2i
: LoadVec2i(pixel_bounds_ptr));
const float pixel_to_world_scale =
renderable->geometry_scale() * config.pixel_to_world_scale();
const auto front = renderable->cardboard_fronts();
cardboard_fronts_[id].resize(front->size(), nullptr);
for (size_t i = 0; i < front->size(); ++i) {
cardboard_fronts_[id][i] = CreateVerticalQuadMesh(
front->Get(i), front_offset, pixel_bounds, pixel_to_world_scale);
}
cardboard_backs_[id] =
CreateVerticalQuadMesh(renderable->cardboard_back(), back_offset,
pixel_bounds, pixel_to_world_scale);
}
// We default to the invalid texture, so it has to exist.
if (!cardboard_fronts_[RenderableId_Invalid][0]) {
fplbase::LogError(fplbase::kError, "Can't load backup texture.\n");
return false;
}
// Create stick front and back meshes.
const vec3 stick_front_offset(0.0f, config.stick_y_offset(),
config.stick_front_z_offset());
const vec3 stick_back_offset(0.0f, config.stick_y_offset(),
config.stick_back_z_offset());
stick_front_ = CreateVerticalQuadMesh(
config.stick_front(), stick_front_offset, LoadVec2(config.stick_bounds()),
config.pixel_to_world_scale());
stick_back_ = CreateVerticalQuadMesh(config.stick_back(), stick_back_offset,
LoadVec2(config.stick_bounds()),
config.pixel_to_world_scale());
// Load all shaders we use:
shader_lit_textured_normal_ =
matman_.LoadShader("shaders/lit_textured_normal");
shader_cardboard = matman_.LoadShader("shaders/cardboard");
shader_simple_shadow_ = matman_.LoadShader("shaders/simple_shadow");
shader_textured_ = matman_.LoadShader("shaders/textured");
shader_grayscale_ = matman_.LoadShader("shaders/grayscale");
if (!(shader_lit_textured_normal_ && shader_cardboard &&
shader_simple_shadow_ && shader_textured_ && shader_grayscale_))
return false;
// Load shadow material:
shadow_mat_ = matman_.LoadMaterial("materials/floor_shadows.fplmat");
if (!shadow_mat_) return false;
// Load debug shader if available
gui_menu_.LoadDebugShaderAndOptions(&config, &matman_);
// Load all the menu textures.
gui_menu_.LoadAssets(TitleScreenButtons(config), &matman_);
gui_menu_.LoadAssets(config.touchscreen_zones(), &matman_);
gui_menu_.LoadAssets(config.pause_screen_buttons(), &matman_);
gui_menu_.LoadAssets(config.multiplayer_host(), &matman_);
gui_menu_.LoadAssets(config.multiplayer_client(), &matman_);
gui_menu_.LoadAssets(config.join_screen_buttons(), &matman_);
gui_menu_.LoadAssets(config.extras_screen_buttons(), &matman_);
gui_menu_.LoadAssets(config.msx_screen_buttons(), &matman_);
gui_menu_.LoadAssets(config.msx_pleasewait_screen_buttons(), &matman_);
gui_menu_.LoadAssets(config.msx_waitingforplayers_screen_buttons(), &matman_);
gui_menu_.LoadAssets(config.msx_waitingforgame_screen_buttons(), &matman_);
gui_menu_.LoadAssets(config.msx_searching_screen_buttons(), &matman_);
gui_menu_.LoadAssets(config.msx_connecting_screen_buttons(), &matman_);
gui_menu_.LoadAssets(config.msx_cant_host_game_screen_buttons(), &matman_);
gui_menu_.LoadAssets(config.msx_connection_lost_screen_buttons(), &matman_);
gui_menu_.LoadAssets(config.msx_host_disconnected_screen_buttons(), &matman_);
gui_menu_.LoadAssets(config.msx_all_players_disconnected_screen_buttons(),
&matman_);
gui_menu_.LoadAssets(config.game_modes_screen_buttons(), &matman_);
// Configure the full screen fader.
full_screen_fader_.set_material(
matman_.FindMaterial(config.fade_material()->c_str()));
full_screen_fader_.set_shader(shader_textured_);
// Start the thread that actually loads all assets we requested above.
matman_.StartLoadingTextures();
return true;
}
// Create state matchines, characters, controllers, etc. present in
// 'gamestate_'.
bool PieNoonGame::InitializeGameState() {
const Config& config = GetConfig();
game_state_.set_config(&config);
game_state_.set_cardboard_config(&GetCardboardConfig());
// Register the motivator types with the MotiveEngine.
motive::OvershootInit::Register();
motive::SplineInit::Register();
motive::MatrixInit::Register();
// Load flatbuffer into buffer.
if (!LoadFile("character_state_machine_def.piestate",
&state_machine_source_)) {
fplbase::LogError(fplbase::kError,
"Error loading character state machine.\n");
return false;
}
// Grab the state machine from the buffer.
auto state_machine_def = GetStateMachine();
if (!CharacterStateMachineDef_Validate(state_machine_def)) {
fplbase::LogError(fplbase::kError, "State machine is invalid.\n");
return false;
}
for (int i = 0; i < ControlScheme::kDefinedControlSchemeCount; i++) {
PlayerController* controller = new PlayerController();
controller->Initialize(&input_, ControlScheme::GetDefaultControlScheme(i));
AddController(controller);
}
// Add a touch screen controller into the controller list, so that touch
// inputs are processed correctly and assigned a character:
touch_controller_ = new TouchscreenController();
vec2 window_size = vec2(static_cast<float>(renderer_.window_size().x()),
static_cast<float>(renderer_.window_size().y()));
touch_controller_->Initialize(&input_, window_size, &config, &game_state_);
AddController(touch_controller_);
// Add a cardboard controller into the controller list, so that input
// from a cardboard device can be handled correctly
cardboard_controller_ = new CardboardController();
cardboard_controller_->Initialize(&game_state_, &input_);
AddController(cardboard_controller_);
// Create characters.
for (unsigned int i = 0; i < config.character_count(); ++i) {
AiController* controller = new AiController();
controller->Initialize(&game_state_, &config, i);
game_state_.characters().push_back(std::unique_ptr<Character>(
new Character(i, controller, config, state_machine_def)));
AddController(controller);
controller->Initialize(&game_state_, &config, i);
}
multiplayer_director_.reset(new MultiplayerDirector());
multiplayer_director_->Initialize(&game_state_, &config);
#ifdef PIE_NOON_USES_GOOGLE_PLAY_GAMES
multiplayer_director_->RegisterGPGMultiplayer(&gpg_multiplayer_);
#else
multiplayer_director_->SetDebugInputSystem(&input_);
#endif
for (unsigned int i = 0; i < config.character_count(); ++i) {
MultiplayerController* controller = new MultiplayerController();
controller->Initialize(&game_state_, &config);
AddController(controller);
#ifdef PIE_NOON_USES_GOOGLE_PLAY_GAMES
multiplayer_director_->RegisterController(controller);
#endif
}
debug_previous_states_.resize(config.character_count(), -1);
game_state_.RegisterMultiplayerDirector(multiplayer_director_.get());
return true;
}
class AudioEngineVolumeControl {
public:
AudioEngineVolumeControl(pindrop::AudioEngine* audio) : audio_(audio) {}
void operator()(void* userdata) {
SDL_Event* event = static_cast<SDL_Event*>(userdata);
switch (event->type) {
case SDL_APP_WILLENTERBACKGROUND:
audio_->Pause(true);
break;
case SDL_APP_DIDENTERFOREGROUND:
audio_->Pause(false);
break;
default:
break;
}
}
private:
pindrop::AudioEngine* audio_;
};
bool PieNoonGame::InitializeGpgIds() {
#ifdef PIE_NOON_USES_GOOGLE_PLAY_GAMES
const Config& config = GetConfig();
// Load the Google Play Games ids from Android resources.
std::vector<std::string> leaderboards;
std::vector<std::string> events;
StringArrayResource(config.gpg_leaderboards_resource()->c_str(),
&leaderboards);
StringArrayResource(config.gpg_events_resource()->c_str(), &events);
StringArrayResource(config.gpg_achievements_resource()->c_str(),
&achievement_ids);
const bool ids_valid = static_cast<int>(leaderboards.size()) == kMaxStats &&
static_cast<int>(events.size()) == kMaxStats;
if (!ids_valid) return false;
// Convert them to our global variable that stores values.
// TODO: Load directly into these arrays to eliminate this copy.
for (int i = 0; i < kMaxStats; ++i) {
gpg_ids[i].leaderboard = leaderboards[i];
gpg_ids[i].event = events[i];
}
#endif // PIE_NOON_USES_GOOGLE_PLAY_GAMES
return true;
}
bool PieNoonGame::LoadFile(const char* filename, std::string* dest) {
const char* read_filename = filename;
std::string overlay;
if (!overlay_name_.empty()) {
overlay = "overlays/" + overlay_name_ + "/" + std::string(filename);
const char* overlay_filename = overlay.c_str();
auto handle = SDL_RWFromFile(overlay_filename, "rb");
if (handle) {
SDL_RWclose(handle);
read_filename = overlay_filename;
}
}
return fplbase::LoadFileRaw(read_filename, dest);
}
// Initialize each member in turn. This is logically just one function, since
// the order of initialization cannot be changed. However, it's nice for
// debugging and readability to have each section lexographically separate.
bool PieNoonGame::Initialize(const char* const binary_directory) {
fplbase::LogInfo(fplbase::kApplication, "PieNoon initializing...\n");
if (!fplbase::ChangeToUpstreamDir(binary_directory, kAssetsDir)) return false;
if (overlay_name_ == "") {
std::string default_overlay;
if (LoadFile(kDefaultOverlayFile, &default_overlay)) {
// trim whitespace from the end of the file contents
default_overlay.erase(default_overlay.find_last_not_of(" \n\r\t") + 1);
if (default_overlay != "") {
fplbase::LogInfo(fplbase::kApplication,
"Forcing default overlay of %s\n",
default_overlay.c_str());
PieNoonGame::SetOverlayName(default_overlay.c_str());
}
}
}
if (!InitializeConfig()) return false;
#ifdef ANDROID_HMD
if (!InitializeCardboardConfig()) return false;
#endif
if (!InitializeGpgIds()) return false;
if (!InitializeRenderer()) return false;
if (!InitializeRenderingAssets()) return false;
input_.Initialize();
// Some people are having trouble loading the audio engine, and it's not
// strictly necessary for gameplay, so don't die if the audio engine fails to
// initialize.
if (!audio_engine_.Initialize(GetConfig().audio())) {
fplbase::LogError(fplbase::kApplication,
"Failed to initialize audio engine.\n");
}
if (!audio_engine_.LoadSoundBank("sound_banks/sound_assets.pinbank")) {
fplbase::LogError(fplbase::kApplication, "Failed to load sound bank.\n");
}
// Start loading sounds
audio_engine_.StartLoadingSoundFiles();
input_.AddAppEventCallback(AudioEngineVolumeControl(&audio_engine_));
if (!InitializeGameState()) return false;
#ifdef PIE_NOON_USES_GOOGLE_PLAY_GAMES
if (!gpg_manager.Initialize(fplbase::LoadPreference("logged_in", 1) != 0))
return false;
if (!gpg_multiplayer_.Initialize(GetConfig()
.multiscreen_options()
->nearby_connections_service_id()
->c_str())) {
fplbase::LogError(fplbase::kApplication,
"GPGMultiplayer::Initialize failed\n");
return false;
}
for (unsigned int i = 0; i < GetConfig()
.multiscreen_options()
->nearby_connections_app_identifiers()
->Length();
i++) {
auto app_id = GetConfig()
.multiscreen_options()
->nearby_connections_app_identifiers()
->Get(i);
gpg_multiplayer_.AddAppIdentifier(app_id->c_str());
}
gpg_multiplayer_.set_max_connected_players_allowed(
GetConfig().multiscreen_options()->max_players());
#endif
fplbase::LogInfo(fplbase::kApplication, "PieNoon initialization complete\n");
return true;
}
// Returns the mesh for renderable_id, if we have one, or the pajama mesh
// (a mesh with a texture that's obviously wrong), if we don't.
fplbase::Mesh* PieNoonGame::GetCardboardFront(int renderable_id, int variant) {
// Return the invalid mesh if the indices are out of bounds.
auto invalid_front = cardboard_fronts_[RenderableId_Invalid][0];
if (renderable_id < 0 || RenderableId_Count <= renderable_id) {
return invalid_front;
}
// Clamp the variant to the valid range.
// Return it, if available. Otherwise, return the invalid front.
auto& fronts = cardboard_fronts_[renderable_id];
const int variant_clamped =
mathfu::Clamp(variant, 0, static_cast<int>(fronts.size()) - 1);
auto front = fronts[variant_clamped];
return front == nullptr ? invalid_front : front;
}
void PieNoonGame::RenderCardboard(const SceneDescription& scene,
const mat4& camera_transform) {
const Config& config = GetConfig();
for (size_t i = 0; i < scene.renderables().size(); ++i) {
const auto& renderable = scene.renderables()[i];
const int id = renderable->id();
// Set up vertex transformation into projection space.
const mat4 mvp = camera_transform * renderable->world_matrix();
renderer_.set_model_view_projection(mvp);
// Set the camera and light positions in object space.
const mat4 world_matrix_inverse = renderable->world_matrix().Inverse();
renderer_.set_camera_pos(world_matrix_inverse *
game_state_.camera().Position());
// TODO: check amount of lights.
renderer_.set_light_pos(world_matrix_inverse * (*scene.lights()[0]));
// The popsicle stick and cardboard back are always uncolored.
renderer_.set_color(mathfu::kOnes4f);
// Note: Draw order is back-to-front, so draw the cardboard back, then
// popsicle stick, then cardboard front--in that order.
//
// If we have a back, draw the back too, slightly offset.
// The back is the *inside* of the cardboard, representing corrugation.
if (cardboard_backs_[id]) {
shader_cardboard->Set(renderer_);
cardboard_backs_[id]->Render(renderer_);
}
// Draw the popsicle stick that props up the cardboard.
if (config.renderables()->Get(id)->stick() && stick_front_ != nullptr &&
stick_back_ != nullptr) {
shader_textured_->Set(renderer_);
stick_front_->Render(renderer_);
stick_back_->Render(renderer_);
}
renderer_.set_color(renderable->color());
if (config.renderables()->Get(id)->cardboard()) {
shader_cardboard->Set(renderer_);
shader_cardboard->SetUniform(
"ambient_material", LoadVec3(config.cardboard_ambient_material()));
shader_cardboard->SetUniform(
"diffuse_material", LoadVec3(config.cardboard_diffuse_material()));
shader_cardboard->SetUniform(
"specular_material", LoadVec3(config.cardboard_specular_material()));
shader_cardboard->SetUniform("shininess", config.cardboard_shininess());
shader_cardboard->SetUniform("normalmap_scale",
config.cardboard_normalmap_scale());
} else {
shader_textured_->Set(renderer_);
}
auto front = GetCardboardFront(id, renderable->variant());
front->Render(renderer_);
}
}
void PieNoonGame::Render(const SceneDescription& scene) {
if (game_state_.is_in_cardboard()) {
RenderForCardboard(scene);
} else {
RenderForDefault(scene);
}
}
void PieNoonGame::RenderForDefault(const SceneDescription& scene) {
RenderScene(scene, mat4::Identity(), renderer_.window_size());
}
void PieNoonGame::RenderForCardboard(const SceneDescription& scene) {
#ifdef ANDROID_HMD
fplbase::HeadMountedDisplayViewSettings view_settings;
HeadMountedDisplayRenderStart(
input_.head_mounted_display_input(), &renderer_, mathfu::kZeros4f,
game_state_.use_undistort_rendering(), &view_settings);
auto res = renderer_.window_size();
vec2i half_res(res.x() / 2.0f, res.y());
// Perform two render passes, one for each half of the screen
for (int i = 0; i < 2; i++) {
GL_CALL(glViewport(view_settings.viewport_extents[i][0],
view_settings.viewport_extents[i][1],
view_settings.viewport_extents[i][2],
view_settings.viewport_extents[i][3]));
// Convert the transforms from cardboard space to game space
CorrectCardboardCamera(view_settings.viewport_transforms[i]);
RenderScene(scene, view_settings.viewport_transforms[i], half_res);
}
HeadMountedDisplayRenderEnd(&renderer_,
game_state_.use_undistort_rendering());
#else
(void)scene;
#endif // ANDROID_HMD
}
void PieNoonGame::RenderScene(const SceneDescription& scene,
const mat4& additional_camera_changes,
const vec2i& resolution) {
const Config& config = GetConfig();
const Config& cardboard_config = GetCardboardConfig();
float viewport_angle = game_state_.is_in_cardboard()
? cardboard_config.viewport_angle()
: config.viewport_angle();
// Final matrix that applies the view frustum to bring into screen space.
mat4 perspective_matrix_ = mat4::Perspective(
viewport_angle, resolution.x() / static_cast<float>(resolution.y()),
config.viewport_near_plane(), config.viewport_far_plane(), -1.0f);
const mat4 camera_transform =
perspective_matrix_ * (additional_camera_changes * scene.camera());
// Render a ground plane.
// TODO: Replace with a regular environment prop. Calculate scale_bias from
// environment prop size.
renderer_.set_model_view_projection(camera_transform);
renderer_.set_color(mathfu::kOnes4f);
shader_textured_->Set(renderer_);
auto ground_mat = matman_.LoadMaterial("materials/floor.fplmat");
assert(ground_mat);
ground_mat->Set(renderer_);
const float ground_width = game_state_.is_in_cardboard()
? cardboard_config.ground_plane_width()
: config.ground_plane_width();
const float ground_depth = game_state_.is_in_cardboard()
? cardboard_config.ground_plane_depth()
: config.ground_plane_depth();
fplbase::Mesh::RenderAAQuadAlongX(vec3(-ground_width, 0, 0),
vec3(ground_width, 0, ground_depth), vec2(0, 0),
vec2(1.0f, 1.0f));
const vec4 world_scale_bias(1.0f / (2.0f * ground_width), 1.0f / ground_depth,
0.5f, 0.0f);
// Render shadows for all Renderables first, with depth testing off so
// they blend properly.
renderer_.DepthTest(false);
// This is a bit of a hack - We want to be in kBlendModeAlpha, but
// FPLBase's renderer assumes that no one else is messing with the openGL
// settings besides it. Since cardboard mode makes its own openGL calls,
// we have to set some other blend mode first, so that it will recognize
// that things have change, and it should call glBlendMode(GL_ENABLE) again.
renderer_.SetBlendMode(fplbase::kBlendModeOff);
renderer_.SetBlendMode(fplbase::kBlendModeAlpha);
renderer_.set_model_view_projection(camera_transform);
renderer_.set_light_pos(*scene.lights()[0]); // TODO: check amount of lights.
shader_simple_shadow_->SetUniform("world_scale_bias", world_scale_bias);
for (size_t i = 0; i < scene.renderables().size(); ++i) {
const auto& renderable = scene.renderables()[i];
const int id = renderable->id();
auto front = GetCardboardFront(id, renderable->variant());
if (config.renderables()->Get(id)->shadow()) {
renderer_.set_model(renderable->world_matrix());
shader_simple_shadow_->Set(renderer_);
// The first texture of the shadow shader has to be that of the
// billboard.
shadow_mat_->textures()[0] = front->GetMaterial(0)->textures()[0];
shadow_mat_->Set(renderer_);
front->Render(renderer_, true);
}
}
renderer_.DepthTest(true);
// Now render the Renderables normally, on top of the shadows.
RenderCardboard(scene, camera_transform);
// Render any UI/HUD/Splash on top
Render2DElements(scene, additional_camera_changes);
}
void PieNoonGame::Render2DElements(const SceneDescription& scene,
const mat4& additional_camera_changes) {
// Set up an ortho camera for all 2D elements, with (0, 0) in the top left,
// and the bottom right the windows size in pixels.
mathfu::vec2i res = renderer_.window_size();
if (!game_state_.is_in_cardboard()) {
mat4 ortho_mat = mathfu::OrthoHelper<float>(
0.0f, static_cast<float>(res.x()), static_cast<float>(res.y()), 0.0f,
-1.0f, 1.0f);
renderer_.set_model_view_projection(ortho_mat);
} else {
// Center it at 0, 0
const mat4 translate_mat =
mat4::FromTranslationVector(vec3(-res.x() / 2, -res.y() / 2, 0));
// Scale it into a more reasonable size:
const mat4 scale_mat = mat4::FromScaleVector(vec3(0.010f, -0.010f, -1.0f));
// Move it to a nice spot in world space:
const mat4 translate2_mat =
mat4::FromTranslationVector(vec3(0.0f, 4.0f, 12.6f));
const Config& config = GetConfig();
const Config& cardboard_config = GetCardboardConfig();
float viewport_angle = cardboard_config.viewport_angle();
mat4 perspective_matrix_ = mat4::Perspective(
viewport_angle, res.x() / static_cast<float>(res.y()),
config.viewport_near_plane(), config.viewport_far_plane(), -1.0f);
const mat4 camera_transform =
perspective_matrix_ * (additional_camera_changes * scene.camera());
mat4 rotate_towards_camera = mat4::FromRotationMatrix(
mathfu::quat::FromAngleAxis(0.5f * static_cast<float>(M_PI) / 2.0f,
mathfu::kAxisY3f)
.ToMatrix());
renderer_.set_model_view_projection(camera_transform * translate2_mat *
rotate_towards_camera * scale_mat *
translate_mat);
}
// Update the currently drawing Google Play Games image. Displays "Sign In"
// when currently signed-out, and "Sign Out" when currently signed in.
#ifdef PIE_NOON_USES_GOOGLE_PLAY_GAMES
bool is_logged_in = gpg_manager.LoggedIn();
const int material_index = is_logged_in ? 0 : 1;
auto gpg_button = gui_menu_.FindButtonById(ButtonId_MenuSignIn);
if (gpg_button) gpg_button->set_current_up_material(material_index);
auto gpg_text = gui_menu_.FindImageById(ButtonId_MenuSignInText);
if (gpg_text) gpg_text->set_current_material_index(material_index);
auto achievements_button =
gui_menu_.FindButtonById(ButtonId_MenuAchievements);
if (achievements_button) achievements_button->set_is_active(is_logged_in);
auto leaderboards_button = gui_menu_.FindButtonById(ButtonId_MenuLeaderboard);
if (leaderboards_button) leaderboards_button->set_is_active(is_logged_in);
#endif
if (!fplbase::SupportsHeadMountedDisplay()) {
auto cardboard_button = gui_menu_.FindButtonById(ButtonId_MenuCardboard);
if (cardboard_button) cardboard_button->set_is_visible(false);
}
auto sushi_button = gui_menu_.FindButtonById(ButtonId_Sushi);
if (sushi_button) {
bool show_sushi_button = false;
#ifdef PIE_NOON_USES_GOOGLE_PLAY_GAMES
// Magic strings comes from res/values/play_games.xml
// if the first achievement is unlocked, display the sushi.
show_sushi_button = (show_sushi_button ||
gpg_manager.IsAchievementUnlocked(achievement_ids[0]));
#endif // PIE_NOON_USES_GOOGLE_PLAY_GAMES
sushi_button->set_is_visible(show_sushi_button);
}
// Loop through the 2D elements. Draw each subsequent one slightly closer
// to the camera so that they appear on top of the previous ones.
gui_menu_.Render(&renderer_);
}
void PieNoonGame::CorrectCardboardCamera(mat4& cardboard_camera) {
// The game's coordinate system has x and y reversed from the cardboard
const mat4 rotation = mat4::FromScaleVector(vec3(-1, -1, 1));
cardboard_camera = rotation * cardboard_camera * rotation;
}
// Debug function to print out state machine transitions.
void PieNoonGame::DebugPrintCharacterStates() {
// Display the state changes, at least until we get real rendering up.
for (size_t i = 0; i < game_state_.characters().size(); ++i) {
auto& character = game_state_.characters()[i];
auto id = character->state_machine()->current_state()->id();
if (debug_previous_states_[i] != id) {
fplbase::LogInfo(fplbase::kApplication,
"character %d - Health %2d, State %s [%d]\n", i,
character->health(), EnumNameStateId(id), id);
debug_previous_states_[i] = id;
}
}
}
// Debug function to print out the state of each AirbornePie.
void PieNoonGame::DebugPrintPieStates() {
for (unsigned int i = 0; i < game_state_.pies().size(); ++i) {
auto& pie = game_state_.pies()[i];
const vec3 position = pie->Position();
fplbase::LogInfo(fplbase::kApplication,
"Pie from [%i]->[%i] w/ %i dmg at pos[%.2f, %.2f, %.2f]\n",
pie->source(), pie->target(), pie->damage(), position.x(),
position.y(), position.z());
}
}
const Config& PieNoonGame::GetConfig() const {
return *fpl::pie_noon::GetConfig(config_source_.c_str());
}
const Config& PieNoonGame::GetCardboardConfig() const {
#ifdef ANDROID_HMD
return *fpl::pie_noon::GetConfig(cardboard_config_source_.c_str());
#else
return GetConfig();
#endif