/
engine.cpp
2084 lines (1794 loc) · 87.9 KB
/
engine.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 2020-2022 The Defold Foundation
// Copyright 2014-2020 King
// Copyright 2009-2014 Ragnar Svensson, Christian Murray
// Licensed under the Defold License version 1.0 (the "License"); you may not use
// this file except in compliance with the License.
//
// You may obtain a copy of the License, together with FAQs at
// https://www.defold.com/license
//
// 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 "engine.h"
#include "engine_private.h"
#include <dmsdk/dlib/vmath.h>
#include <sys/stat.h>
#include <stdio.h>
#include <algorithm>
#include <crash/crash.h>
#include <dlib/buffer.h>
#include <dlib/dlib.h>
#include <dlib/dstrings.h>
#include <dlib/hash.h>
#include <dlib/http_client.h>
#include <dlib/log.h>
#include <dlib/math.h>
#include <dlib/memprofile.h>
#include <dlib/path.h>
#include <dlib/profile.h>
#include <dlib/socket.h>
#include <dlib/sslsocket.h>
#include <dlib/sys.h>
#include <dlib/thread.h>
#include <dlib/time.h>
#include <graphics/graphics.h>
#include <extension/extension.h>
#include <gamesys/gamesys.h>
#include <gamesys/model_ddf.h>
#include <gamesys/physics_ddf.h>
#include <gamesys/components/comp_gui.h> // For the URL callbacks etc
#include <gameobject/gameobject.h>
#include <gameobject/component.h>
#include <gameobject/gameobject_ddf.h>
#include <gameobject/gameobject_script_util.h>
#include <hid/hid.h>
#include <sound/sound.h>
#include <render/render.h>
#include <render/render_ddf.h>
#include <profiler/profiler.h>
#include <particle/particle.h>
#include <script/sys_ddf.h>
#include <liveupdate/liveupdate.h>
#include "extension.h"
#include "engine_service.h"
#include "engine_version.h"
#include "physics_debug_render.h"
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
// Embedded resources
// Unfortunately, the draw_line et. al are used in production code
extern unsigned char DEBUG_VPC[];
extern uint32_t DEBUG_VPC_SIZE;
extern unsigned char DEBUG_FPC[];
extern uint32_t DEBUG_FPC_SIZE;
#if defined(DM_RELEASE)
extern unsigned char BUILTINS_RELEASE_ARCD[];
extern uint32_t BUILTINS_RELEASE_ARCD_SIZE;
extern unsigned char BUILTINS_RELEASE_ARCI[];
extern uint32_t BUILTINS_RELEASE_ARCI_SIZE;
extern unsigned char BUILTINS_RELEASE_DMANIFEST[];
extern uint32_t BUILTINS_RELEASE_DMANIFEST_SIZE;
#else
extern unsigned char BUILTINS_ARCD[];
extern uint32_t BUILTINS_ARCD_SIZE;
extern unsigned char BUILTINS_ARCI[];
extern uint32_t BUILTINS_ARCI_SIZE;
extern unsigned char BUILTINS_DMANIFEST[];
extern uint32_t BUILTINS_DMANIFEST_SIZE;
extern unsigned char GAME_PROJECT[];
extern uint32_t GAME_PROJECT_SIZE;
#endif
#if defined(__ANDROID__)
// On Android we need to notify the activity which input method to use
// before the keyboard is brought up. This choice is stored as a
// game.project config and used in dmEngine::Init(), passed along to
// the GLFW Android implementation.
extern "C" {
extern void _glfwAndroidSetInputMethod(int);
extern void _glfwAndroidSetFullscreenParameters(int, int);
}
#endif
namespace dmEngine
{
using namespace dmVMath;
#define SYSTEM_SOCKET_NAME "@system"
dmEngineService::HEngineService g_EngineService = 0;
static void OnWindowResize(void* user_data, uint32_t width, uint32_t height)
{
uint32_t data_size = sizeof(dmRenderDDF::WindowResized);
uintptr_t descriptor = (uintptr_t)dmRenderDDF::WindowResized::m_DDFDescriptor;
dmhash_t message_id = dmRenderDDF::WindowResized::m_DDFDescriptor->m_NameHash;
dmRenderDDF::WindowResized window_resized;
window_resized.m_Width = width;
window_resized.m_Height = height;
dmMessage::URL receiver;
dmMessage::ResetURL(&receiver);
dmMessage::Result result = dmMessage::GetSocket(dmRender::RENDER_SOCKET_NAME, &receiver.m_Socket);
if (result != dmMessage::RESULT_OK)
{
dmLogError("Could not find '%s' socket.", dmRender::RENDER_SOCKET_NAME);
}
else
{
result = dmMessage::Post(0x0, &receiver, message_id, 0, descriptor, &window_resized, data_size, 0);
if (result != dmMessage::RESULT_OK)
{
dmLogError("Could not send 'window_resized' to '%s' socket.", dmRender::RENDER_SOCKET_NAME);
}
}
Engine* engine = (Engine*)user_data;
engine->m_InvPhysicalWidth = 1.0f / width;
engine->m_InvPhysicalHeight = 1.0f / height;
// update gui context if it exists
if (engine->m_GuiContext)
{
dmGui::SetPhysicalResolution(engine->m_GuiContext, width, height);
}
dmGameSystem::OnWindowResized(width, height);
}
static bool OnWindowClose(void* user_data)
{
Engine* engine = (Engine*)user_data;
engine->m_Alive = false;
// Never allow closing the window here, clean up and then close manually
return false;
}
static void Dispatch(dmMessage::Message *message_object, void* user_ptr);
static void OnWindowFocus(void* user_data, uint32_t focus)
{
Engine* engine = (Engine*)user_data;
dmExtension::Params params;
params.m_ConfigFile = engine->m_Config;
params.m_L = 0;
dmExtension::Event event;
event.m_Event = focus ? dmExtension::EVENT_ID_ACTIVATEAPP : dmExtension::EVENT_ID_DEACTIVATEAPP;
dmExtension::DispatchEvent( ¶ms, &event );
dmGameSystem::OnWindowFocus(focus != 0);
}
static void OnWindowIconify(void* user_data, uint32_t iconify)
{
Engine* engine = (Engine*)user_data;
// We reset the time on both events because
// on some platforms both events will arrive when regaining focus
engine->m_PreviousFrameTime = dmTime::GetTime(); // we might have stalled for a long time
dmExtension::Params params;
params.m_ConfigFile = engine->m_Config;
params.m_L = 0;
dmExtension::Event event;
event.m_Event = iconify ? dmExtension::EVENT_ID_ICONIFYAPP : dmExtension::EVENT_ID_DEICONIFYAPP;
dmExtension::DispatchEvent( ¶ms, &event );
dmGameSystem::OnWindowIconify(iconify != 0);
}
static void SetupComponentCreateContext(HEngine engine, dmGameObject::ComponentTypeCreateCtx& component_create_ctx)
{
component_create_ctx.m_Config = engine->m_Config;
component_create_ctx.m_Script = engine->m_GOScriptContext;
component_create_ctx.m_Register = engine->m_Register;
component_create_ctx.m_Factory = engine->m_Factory;
component_create_ctx.m_Contexts.SetCapacity(3, 8);
component_create_ctx.m_Contexts.Put(dmHashString64("graphics"), engine->m_GraphicsContext);
component_create_ctx.m_Contexts.Put(dmHashString64("render"), engine->m_RenderContext);
if (engine->m_GuiContext)
{
component_create_ctx.m_Contexts.Put(dmHashString64("gui_scriptc"), engine->m_GuiScriptContext);
component_create_ctx.m_Contexts.Put(dmHashString64("guic"), engine->m_GuiContext);
}
}
Stats::Stats()
: m_FrameCount(0)
, m_TotalTime(0.0f)
{
}
Engine::Engine(dmEngineService::HEngineService engine_service)
: m_Config(0)
, m_Alive(true)
, m_MainCollection(0)
, m_LastReloadMTime(0)
, m_MouseSensitivity(1.0f)
, m_GraphicsContext(0)
, m_RenderContext(0)
, m_SharedScriptContext(0x0)
, m_GOScriptContext(0x0)
, m_RenderScriptContext(0x0)
, m_GuiScriptContext(0x0)
, m_Factory(0x0)
, m_SystemSocket(0x0)
, m_SystemFontMap(0x0)
, m_HidContext(0x0)
, m_InputContext(0x0)
, m_GameInputBinding(0x0)
, m_DisplayProfiles(0x0)
, m_RenderScriptPrototype(0x0)
, m_Stats()
, m_WasIconified(true)
, m_QuitOnEsc(false)
, m_ConnectionAppMode(false)
, m_RunWhileIconified(0)
, m_Width(960)
, m_Height(640)
, m_InvPhysicalWidth(1.0f/960)
, m_InvPhysicalHeight(1.0f/640)
{
m_EngineService = engine_service;
m_Register = dmGameObject::NewRegister();
m_InputBuffer.SetCapacity(64);
m_ResourceTypeContexts.SetCapacity(31, 64);
m_PhysicsContext.m_Context3D = 0x0; // it'a union
m_PhysicsContext.m_Debug = false;
m_PhysicsContext.m_3D = false;
m_GuiContext = 0x0;
m_SpriteContext.m_RenderContext = 0x0;
m_SpriteContext.m_MaxSpriteCount = 0;
m_ModelContext.m_RenderContext = 0x0;
m_ModelContext.m_MaxModelCount = 0;
m_MeshContext.m_RenderContext = 0x0;
m_MeshContext.m_MaxMeshCount = 0;
m_AccumFrameTime = 0;
m_PreviousFrameTime = dmTime::GetTime();
}
HEngine New(dmEngineService::HEngineService engine_service)
{
return new Engine(engine_service);
}
void Delete(HEngine engine)
{
if (engine->m_MainCollection)
dmResource::Release(engine->m_Factory, engine->m_MainCollection);
dmGameObject::PostUpdate(engine->m_Register);
dmGameObject::DeleteRegister(engine->m_Register); // Delete all collections and game objects
dmHttpClient::ShutdownConnectionPool();
dmLiveUpdate::Finalize();
// Reregister the types before the rest of the contexts are deleted
if (engine->m_Factory) {
dmResource::DeregisterTypes(engine->m_Factory, &engine->m_ResourceTypeContexts);
}
dmGameObject::ComponentTypeCreateCtx component_create_ctx;
SetupComponentCreateContext(engine, component_create_ctx);
dmGameObject::DestroyRegisteredComponentTypes(&component_create_ctx);
dmGameSystem::ScriptLibContext script_lib_context;
script_lib_context.m_Factory = engine->m_Factory;
script_lib_context.m_Register = engine->m_Register;
if (engine->m_SharedScriptContext) {
script_lib_context.m_LuaState = dmScript::GetLuaState(engine->m_SharedScriptContext);
dmGameSystem::FinalizeScriptLibs(script_lib_context);
} else {
script_lib_context.m_LuaState = dmScript::GetLuaState(engine->m_GOScriptContext);
dmGameSystem::FinalizeScriptLibs(script_lib_context);
script_lib_context.m_LuaState = dmScript::GetLuaState(engine->m_GuiScriptContext);
dmGameSystem::FinalizeScriptLibs(script_lib_context);
}
dmHttpClient::ReopenConnectionPool();
UnloadBootstrapContent(engine);
dmSound::Finalize();
dmInput::DeleteContext(engine->m_InputContext);
dmRender::DeleteRenderContext(engine->m_RenderContext, engine->m_RenderScriptContext);
if (engine->m_HidContext)
{
dmHID::Final(engine->m_HidContext);
dmHID::DeleteContext(engine->m_HidContext);
}
if (engine->m_GuiContext)
dmGui::DeleteContext(engine->m_GuiContext, engine->m_GuiScriptContext);
if (engine->m_SharedScriptContext) {
dmScript::Finalize(engine->m_SharedScriptContext);
dmScript::DeleteContext(engine->m_SharedScriptContext);
} else {
if (engine->m_GOScriptContext) {
dmScript::Finalize(engine->m_GOScriptContext);
dmScript::DeleteContext(engine->m_GOScriptContext);
}
if (engine->m_RenderScriptContext) {
dmScript::Finalize(engine->m_RenderScriptContext);
dmScript::DeleteContext(engine->m_RenderScriptContext);
}
if (engine->m_GuiScriptContext) {
dmScript::Finalize(engine->m_GuiScriptContext);
dmScript::DeleteContext(engine->m_GuiScriptContext);
}
}
if (engine->m_Factory) {
dmResource::DeleteFactory(engine->m_Factory);
}
if (engine->m_GraphicsContext)
{
dmGraphics::CloseWindow(engine->m_GraphicsContext);
dmGraphics::DeleteContext(engine->m_GraphicsContext);
}
if (engine->m_SystemSocket)
dmMessage::DeleteSocket(engine->m_SystemSocket);
if (engine->m_PhysicsContext.m_Context3D)
{
if (engine->m_PhysicsContext.m_3D)
dmPhysics::DeleteContext3D(engine->m_PhysicsContext.m_Context3D);
else
dmPhysics::DeleteContext2D(engine->m_PhysicsContext.m_Context2D);
}
dmEngine::ExtensionAppParams app_params;
app_params.m_ConfigFile = engine->m_Config;
app_params.m_WebServer = dmEngineService::GetWebServer(engine->m_EngineService);
app_params.m_GameObjectRegister = engine->m_Register;
app_params.m_HIDContext = engine->m_HidContext;
dmExtension::AppFinalize((dmExtension::AppParams*)&app_params);
dmBuffer::DeleteContext();
if (engine->m_Config)
{
dmConfigFile::Delete(engine->m_Config);
}
delete engine;
}
dmGraphics::TextureFilter ConvertMinTextureFilter(const char* filter)
{
if (strcmp(filter, "linear") == 0)
{
return dmGraphics::TEXTURE_FILTER_LINEAR_MIPMAP_NEAREST;
}
else
{
return dmGraphics::TEXTURE_FILTER_NEAREST_MIPMAP_NEAREST;
}
}
dmGraphics::TextureFilter ConvertMagTextureFilter(const char* filter)
{
if (strcmp(filter, "linear") == 0)
{
return dmGraphics::TEXTURE_FILTER_LINEAR;
}
else
{
return dmGraphics::TEXTURE_FILTER_NEAREST;
}
}
static bool GetProjectFile(int argc, char *argv[], char* resources_path, char* project_file, uint32_t project_file_size)
{
if (argc > 1 && argv[argc-1][0] != '-')
{
dmStrlCpy(project_file, argv[argc-1], project_file_size);
return true;
}
else
{
char p1[DMPATH_MAX_PATH];
char p2[DMPATH_MAX_PATH];
char p3[DMPATH_MAX_PATH];
char* paths[3];
uint32_t count = 0;
const char* mountstr = "";
#if defined(__NX__)
mountstr = "data:/";
// there's no way to check for a named mount, and it will assert
// So we'll only enter here if it's set on this platform
if (dmSys::GetEnv("DM_MOUNT_HOST") != 0)
mountstr = "host:/";
#endif
dmSnPrintf(p1, sizeof(p1), "%sgame.projectc", mountstr);
dmSnPrintf(p2, sizeof(p2), "%sbuild/default/game.projectc", mountstr);
paths[count++] = p1;
paths[count++] = p2;
if (resources_path)
{
dmPath::Concat(resources_path, "game.projectc", p3, sizeof(p3));
paths[count++] = p3;
}
for (uint32_t i = 0; i < count; ++i)
{
if (dmSys::ResourceExists(paths[i]))
{
dmStrlCpy(project_file, paths[i], project_file_size);
return true;
}
}
}
return false;
}
static bool LoadAndSetSslKeys(const char* ssl_keys_path)
{
if (!dmSys::ResourceExists(ssl_keys_path))
{
return false;
}
uint32_t file_size;
if (dmSys::ResourceSize(ssl_keys_path, &file_size) != dmSys::RESULT_OK)
{
return false;
}
uint8_t* ssl_keys_buf = (uint8_t*)malloc(file_size);
uint32_t loaded_file_size = 0;
dmSys::Result load_result = dmSys::LoadResource(ssl_keys_path, ssl_keys_buf, file_size, &loaded_file_size);
if (load_result != dmSys::RESULT_OK)
{
dmLogError("Failed to read ssl_keys.pem at %s (%i)", ssl_keys_path, load_result);
free(ssl_keys_buf);
return false;
}
if (loaded_file_size != file_size)
{
dmLogError("Failed to load ssl_keys.pem: tried reading %d bytes, got %d bytes", file_size, loaded_file_size);
free(ssl_keys_buf);
return false;
}
dmSSLSocket::Result loadind_key_result = dmSSLSocket::SetSslPublicKeys(ssl_keys_buf, loaded_file_size);
free(ssl_keys_buf);
return loadind_key_result == dmSSLSocket::RESULT_OK;
}
static void SetSwapInterval(HEngine engine, int swap_interval)
{
swap_interval = dmMath::Max(0, swap_interval);
dmGraphics::SetSwapInterval(engine->m_GraphicsContext, swap_interval);
}
static void SetUpdateFrequency(HEngine engine, uint32_t frequency)
{
engine->m_UpdateFrequency = frequency;
}
struct LuaCallstackCtx
{
bool m_First;
char* m_Buffer;
uint32_t m_BufferSize;
};
static void GetLuaStackTraceCbk(lua_State* L, lua_Debug* entry, void* _ctx)
{
LuaCallstackCtx* ctx = (LuaCallstackCtx*)_ctx;
if (ctx->m_First)
{
int32_t nwritten = dmSnPrintf(ctx->m_Buffer, ctx->m_BufferSize, "Lua Callstack:\n");
if (nwritten < 0)
nwritten = 0;
ctx->m_Buffer += nwritten;
ctx->m_BufferSize -= nwritten;
ctx->m_First = false;
}
uint32_t nwritten = dmScript::WriteLuaTracebackEntry(entry, ctx->m_Buffer, ctx->m_BufferSize);
ctx->m_Buffer += nwritten;
ctx->m_BufferSize -= nwritten;
}
static void CrashHandlerCallback(void* ctx, char* buffer, uint32_t buffersize)
{
HEngine engine = (HEngine)ctx;
if (engine->m_SharedScriptContext) {
LuaCallstackCtx ctx;
ctx.m_First = true;
ctx.m_Buffer = buffer;
ctx.m_BufferSize = buffersize;
dmScript::GetLuaTraceback(dmScript::GetLuaState(engine->m_SharedScriptContext), "Sln", GetLuaStackTraceCbk, &ctx);
}
}
/*
The game.projectc is located using the following scheme:
A.
1. If an argument is specified load the game.project from specified file
B.
1. Look for game.project (relative path)
2. Look for build/default/game.projectc (relative path)
3. Look for dmSys::GetResourcePath()/game.project
4. Load first game.project-file found. If none is
found start the built-in connect application
The content-root is set to the directory name of
the project if not overridden in project-file
(resource.uri)
*/
bool Init(HEngine engine, int argc, char *argv[])
{
dmLogInfo("Defold Engine %s (%.7s)", dmEngineVersion::VERSION, dmEngineVersion::VERSION_SHA1);
dmCrash::SetExtraInfoCallback(CrashHandlerCallback, engine);
dmSys::EngineInfoParam engine_info;
engine_info.m_Platform = dmEngineVersion::PLATFORM;
engine_info.m_Version = dmEngineVersion::VERSION;
engine_info.m_VersionSHA1 = dmEngineVersion::VERSION_SHA1;
engine_info.m_IsDebug = dLib::IsDebugMode();
dmSys::SetEngineInfo(engine_info);
char* qoe_s = dmSys::GetEnv("DM_QUIT_ON_ESC");
engine->m_QuitOnEsc = ((qoe_s != 0x0) && (qoe_s[0] == '1'));
char project_file[DMPATH_MAX_PATH];
char project_file_uri[DMPATH_MAX_PATH];
char project_file_folder[DMPATH_MAX_PATH] = ".";
bool loaded_ok = false;
char resources_path[DMPATH_MAX_PATH];
dmSys::GetResourcesPath(argc, argv, resources_path, sizeof(resources_path));
if (GetProjectFile(argc, argv, resources_path, project_file, sizeof(project_file)))
{
dmConfigFile::Result cr = dmConfigFile::Load(project_file, argc, (const char**) argv, &engine->m_Config);
if (cr != dmConfigFile::RESULT_OK)
{
if (!engine->m_ConnectionAppMode)
{
dmLogFatal("Unable to load project file: '%s' (%d)", project_file, cr);
return false;
}
dmLogError("Unable to load project file: '%s' (%d)", project_file, cr);
}
else
{
loaded_ok = true;
dmPath::Dirname(project_file, project_file_folder, sizeof(project_file_folder));
dmStrlCpy(project_file_uri, project_file_folder, sizeof(project_file_uri));
char tmp[DMPATH_MAX_PATH];
dmStrlCpy(tmp, project_file_folder, sizeof(tmp));
if (project_file_folder[0])
{
dmStrlCat(tmp, "/game.dmanifest", sizeof(tmp));
}
else
{
dmStrlCat(tmp, "game.dmanifest", sizeof(tmp));
}
if (dmSys::ResourceExists(tmp))
{
dmStrlCpy(project_file_uri, "dmanif:", sizeof(project_file_uri));
dmStrlCat(project_file_uri, tmp, sizeof(project_file_uri));
}
}
}
if( !loaded_ok )
{
#if defined(DM_RELEASE)
dmLogFatal("Unable to load project");
return false;
#else
dmConfigFile::Result cr = dmConfigFile::LoadFromBuffer((const char*) GAME_PROJECT, GAME_PROJECT_SIZE, argc, (const char**) argv, &engine->m_Config);
if (cr != dmConfigFile::RESULT_OK)
{
dmLogFatal("Unable to load builtin connect project");
return false;
}
engine->m_ConnectionAppMode = true;
#endif
}
// Try loading SSL keys
char engine_ssl_keys_path[DMPATH_MAX_PATH];
dmPath::Concat(resources_path, "/ssl_keys.pem", engine_ssl_keys_path, sizeof(engine_ssl_keys_path));
char editor_ssl_keys_path[DMPATH_MAX_PATH];
dmPath::Concat(project_file_folder, dmConfigFile::GetString(engine->m_Config, "network.ssl_certificates", ""), editor_ssl_keys_path, sizeof(editor_ssl_keys_path));
const char* paths[] = {engine_ssl_keys_path, editor_ssl_keys_path};
for (uint32_t i = 0; i < DM_ARRAY_SIZE(paths); ++i)
{
if (paths[i] && LoadAndSetSslKeys(paths[i]))
{
dmLogInfo("SSL verification enabled");
break;
}
}
// Set HTML5 console banner "MadeWithDefold"
#if defined(__EMSCRIPTEN__)
if (1 == dmConfigFile::GetInt(engine->m_Config, "html5.show_console_banner", 1))
{
EM_ASM({
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
console.log("%c %c Made with Defold %c %c https://www.defold.com",
"background: #fd6623; padding:5px 0; border: 5px;",
"background: #272c31; color: #fafafa; padding:5px 0;",
"background: #39a3e4; padding:5px 0;",
"background: #ffffff; color: #000000; padding:5px 0;"
);
}
else {
console.log("Made with Defold -=[ https://www.defold.com ]=-");
}
});
}
#endif
// Catch engine specific arguments
bool verify_graphics_calls = dLib::IsDebugMode();
// The default is 1, and the only way to know if the property is manually set, is if it's 0
// since the values are always written to the project file
if (0 == dmConfigFile::GetInt(engine->m_Config, "graphics.verify_graphics_calls", 1))
verify_graphics_calls = false;
bool renderdoc_support = false;
bool use_validation_layers = false;
const char verify_graphics_calls_arg[] = "--verify-graphics-calls=";
const char renderdoc_support_arg[] = "--renderdoc";
const char validation_layers_support_arg[] = "--use-validation-layers";
const char verbose_long[] = "--verbose";
const char verbose_short[] = "-v";
for (int i = 0; i < argc; ++i)
{
const char* arg = argv[i];
if (strncmp(verify_graphics_calls_arg, arg, sizeof(verify_graphics_calls_arg)-1) == 0)
{
const char* eq = strchr(arg, '=');
if (strncmp("true", eq+1, sizeof("true")-1) == 0) {
verify_graphics_calls = true;
} else if (strncmp("false", eq+1, sizeof("false")-1) == 0) {
verify_graphics_calls = false;
} else {
dmLogWarning("Invalid value used for %s%s.", verify_graphics_calls_arg, eq);
}
}
else if (strncmp(renderdoc_support_arg, arg, sizeof(renderdoc_support_arg)-1) == 0)
{
renderdoc_support = true;
}
else if (strncmp(validation_layers_support_arg, arg, sizeof(validation_layers_support_arg)-1) == 0)
{
use_validation_layers = true;
}
else if (strncmp(verbose_long, arg, sizeof(verbose_long)-1) == 0 ||
strncmp(verbose_short, arg, sizeof(verbose_short)-1) == 0)
{
dmLog::Setlevel(dmLog::LOG_SEVERITY_DEBUG);
}
}
dmBuffer::NewContext();
dmHID::NewContextParams new_hid_params = dmHID::NewContextParams();
new_hid_params.m_GamepadConnectivityCallback = dmInput::GamepadConnectivityCallback;
// Accelerometer
int32_t use_accelerometer = dmConfigFile::GetInt(engine->m_Config, "input.use_accelerometer", 1);
if (use_accelerometer) {
dmHID::EnableAccelerometer(); // Creates and enables the accelerometer
}
new_hid_params.m_IgnoreAcceleration = use_accelerometer ? 0 : 1;
#if defined(__EMSCRIPTEN__)
// DEF-2450 Reverse scroll direction for firefox browser
dmSys::SystemInfo info;
dmSys::GetSystemInfo(&info);
if (info.m_UserAgent != 0x0)
{
const char* str_firefox = "firefox";
new_hid_params.m_FlipScrollDirection = (strcasestr(info.m_UserAgent, str_firefox) != NULL) ? 1 : 0;
}
#endif
engine->m_HidContext = dmHID::NewContext(new_hid_params);
dmEngine::ExtensionAppParams app_params;
app_params.m_ConfigFile = engine->m_Config;
app_params.m_WebServer = dmEngineService::GetWebServer(engine->m_EngineService);
app_params.m_GameObjectRegister = engine->m_Register;
app_params.m_HIDContext = engine->m_HidContext;
dmExtension::Result er = dmExtension::AppInitialize((dmExtension::AppParams*)&app_params);
if (er != dmExtension::RESULT_OK) {
dmLogFatal("Failed to initialize extensions (%d)", er);
return false;
}
int write_log = dmConfigFile::GetInt(engine->m_Config, "project.write_log", 0);
if (write_log) {
uint32_t count = 0;
char* log_paths[3];
const char* LOG_FILE_NAME = "log.txt";
const char* log_dir = dmConfigFile::GetString(engine->m_Config, "project.log_dir", NULL);
char log_config_path[DMPATH_MAX_PATH];
if (log_dir != NULL)
{
dmPath::Concat(log_dir, LOG_FILE_NAME, log_config_path, sizeof(log_config_path));
log_paths[count] = log_config_path;
count++;
}
char sys_path[DMPATH_MAX_PATH];
char main_log_path[DMPATH_MAX_PATH];
if (dmSys::GetLogPath(sys_path, sizeof(sys_path)) == dmSys::RESULT_OK)
{
dmPath::Concat(sys_path, LOG_FILE_NAME, main_log_path, sizeof(main_log_path));
log_paths[count] = main_log_path;
count++;
}
char application_support_path[DMPATH_MAX_PATH];
char application_support_log_path[DMPATH_MAX_PATH];
const char* logs_dir = dmConfigFile::GetString(engine->m_Config, "project.title_as_file_name", "defoldlogs");
if (dmSys::GetApplicationSavePath(logs_dir, application_support_path, sizeof(application_support_path)) == dmSys::RESULT_OK)
{
dmPath::Concat(application_support_path, LOG_FILE_NAME, application_support_log_path, sizeof(application_support_log_path));
log_paths[count] = application_support_log_path;
count++;
}
for (uint32_t i = 0; i < count; ++i)
{
if (dmLog::SetLogFile(log_paths[i]))
{
break;
}
}
}
const char* update_order = dmConfigFile::GetString(engine->m_Config, "gameobject.update_order", 0);
// This scope is mainly here to make sure the "Main" scope is created first
DM_PROFILE(Engine, "Init");
dmGraphics::ContextParams graphics_context_params;
graphics_context_params.m_DefaultTextureMinFilter = ConvertMinTextureFilter(dmConfigFile::GetString(engine->m_Config, "graphics.default_texture_min_filter", "linear"));
graphics_context_params.m_DefaultTextureMagFilter = ConvertMagTextureFilter(dmConfigFile::GetString(engine->m_Config, "graphics.default_texture_mag_filter", "linear"));
graphics_context_params.m_VerifyGraphicsCalls = verify_graphics_calls;
graphics_context_params.m_RenderDocSupport = renderdoc_support || dmConfigFile::GetInt(engine->m_Config, "graphics.use_renderdoc", 0) != 0;
graphics_context_params.m_UseValidationLayers = use_validation_layers || dmConfigFile::GetInt(engine->m_Config, "graphics.use_validationlayers", 0) != 0;
graphics_context_params.m_GraphicsMemorySize = dmConfigFile::GetInt(engine->m_Config, "graphics.memory_size", 0) * 1024*1024; // MB -> bytes
engine->m_GraphicsContext = dmGraphics::NewContext(graphics_context_params);
if (engine->m_GraphicsContext == 0x0)
{
dmLogFatal("Unable to create the graphics context.");
return false;
}
engine->m_Width = dmConfigFile::GetInt(engine->m_Config, "display.width", 960);
engine->m_Height = dmConfigFile::GetInt(engine->m_Config, "display.height", 640);
float clear_color_red = dmConfigFile::GetFloat(engine->m_Config, "render.clear_color_red", 0.0);
float clear_color_green = dmConfigFile::GetFloat(engine->m_Config, "render.clear_color_green", 0.0);
float clear_color_blue = dmConfigFile::GetFloat(engine->m_Config, "render.clear_color_blue", 0.0);
float clear_color_alpha = dmConfigFile::GetFloat(engine->m_Config, "render.clear_color_alpha", 0.0);
uint32_t clear_color = ((uint32_t)(clear_color_red * 255.0) & 0x000000ff)
| (((uint32_t)(clear_color_green * 255.0) & 0x000000ff) << 8)
| (((uint32_t)(clear_color_blue * 255.0) & 0x000000ff) << 16)
| (((uint32_t)(clear_color_alpha * 255.0) & 0x000000ff) << 24);
engine->m_ClearColor = clear_color;
dmGraphics::WindowParams window_params;
window_params.m_ResizeCallback = OnWindowResize;
window_params.m_ResizeCallbackUserData = engine;
window_params.m_CloseCallback = OnWindowClose;
window_params.m_CloseCallbackUserData = engine;
window_params.m_FocusCallback = OnWindowFocus;
window_params.m_FocusCallbackUserData = engine;
window_params.m_IconifyCallback = OnWindowIconify;
window_params.m_IconifyCallbackUserData = engine;
window_params.m_Width = engine->m_Width;
window_params.m_Height = engine->m_Height;
window_params.m_Samples = dmConfigFile::GetInt(engine->m_Config, "display.samples", 0);
window_params.m_Title = dmConfigFile::GetString(engine->m_Config, "project.title", "TestTitle");
window_params.m_Fullscreen = (bool) dmConfigFile::GetInt(engine->m_Config, "display.fullscreen", 0);
window_params.m_PrintDeviceInfo = dmConfigFile::GetInt(engine->m_Config, "display.display_device_info", 0);
window_params.m_HighDPI = (bool) dmConfigFile::GetInt(engine->m_Config, "display.high_dpi", 0);
window_params.m_BackgroundColor = clear_color;
dmGraphics::WindowResult window_result = dmGraphics::OpenWindow(engine->m_GraphicsContext, &window_params);
if (window_result != dmGraphics::WINDOW_RESULT_OK)
{
dmLogFatal("Could not open window (%d).", window_result);
return false;
}
uint32_t physical_dpi = dmGraphics::GetDisplayDpi(engine->m_GraphicsContext);
uint32_t physical_width = dmGraphics::GetWindowWidth(engine->m_GraphicsContext);
uint32_t physical_height = dmGraphics::GetWindowHeight(engine->m_GraphicsContext);
engine->m_InvPhysicalWidth = 1.0f / physical_width;
engine->m_InvPhysicalHeight = 1.0f / physical_height;
#if defined(__MACH__) || defined(__linux__) || defined(_WIN32)
engine->m_RunWhileIconified = dmConfigFile::GetInt(engine->m_Config, "engine.run_while_iconified", 0);
#endif
engine->m_FixedUpdateFrequency = dmConfigFile::GetInt(engine->m_Config, "engine.fixed_update_frequency", 60);
dmGameSystem::OnWindowCreated(physical_width, physical_height);
engine->m_UpdateFrequency = dmConfigFile::GetInt(engine->m_Config, "display.update_frequency", 0);
SetUpdateFrequency(engine, engine->m_UpdateFrequency);
bool setting_vsync = dmConfigFile::GetInt(engine->m_Config, "display.vsync", true); // Deprecated
uint32_t opengl_swap_interval = dmConfigFile::GetInt(engine->m_Config, "display.swap_interval", 1);
if (!setting_vsync)
{
opengl_swap_interval = 0;
}
SetSwapInterval(engine, opengl_swap_interval);
const uint32_t max_resources = dmConfigFile::GetInt(engine->m_Config, dmResource::MAX_RESOURCES_KEY, 1024);
dmResource::NewFactoryParams params;
params.m_MaxResources = max_resources;
params.m_Flags = 0;
dmResourceArchive::ClearArchiveLoaders(); // in case we've rebooted
dmResourceArchive::RegisterDefaultArchiveLoader();
if (dLib::IsDebugMode())
{
params.m_Flags = RESOURCE_FACTORY_FLAGS_RELOAD_SUPPORT;
int32_t http_cache = dmConfigFile::GetInt(engine->m_Config, "resource.http_cache", 1);
if (http_cache)
params.m_Flags |= RESOURCE_FACTORY_FLAGS_HTTP_CACHE;
}
int32_t liveupdate_enable = dmConfigFile::GetInt(engine->m_Config, "liveupdate.enabled", 1);
if (liveupdate_enable)
{
params.m_Flags |= RESOURCE_FACTORY_FLAGS_LIVE_UPDATE;
dmLiveUpdate::RegisterArchiveLoaders();
}
#if defined(DM_RELEASE)
params.m_ArchiveIndex.m_Data = (const void*) BUILTINS_RELEASE_ARCI;
params.m_ArchiveIndex.m_Size = BUILTINS_RELEASE_ARCI_SIZE;
params.m_ArchiveData.m_Data = (const void*) BUILTINS_RELEASE_ARCD;
params.m_ArchiveData.m_Size = BUILTINS_RELEASE_ARCD_SIZE;
params.m_ArchiveManifest.m_Data = (const void*) BUILTINS_RELEASE_DMANIFEST;
params.m_ArchiveManifest.m_Size = BUILTINS_RELEASE_DMANIFEST_SIZE;
#else
params.m_ArchiveIndex.m_Data = (const void*) BUILTINS_ARCI;
params.m_ArchiveIndex.m_Size = BUILTINS_ARCI_SIZE;
params.m_ArchiveData.m_Data = (const void*) BUILTINS_ARCD;
params.m_ArchiveData.m_Size = BUILTINS_ARCD_SIZE;
params.m_ArchiveManifest.m_Data = (const void*) BUILTINS_DMANIFEST;
params.m_ArchiveManifest.m_Size = BUILTINS_DMANIFEST_SIZE;
#endif
const char* resource_uri = dmConfigFile::GetString(engine->m_Config, "resource.uri", project_file_uri);
dmLogInfo("Loading data from: %s", resource_uri);
engine->m_Factory = dmResource::NewFactory(¶ms, resource_uri);
if (!engine->m_Factory)
{
return false;
}
dmScript::ClearLuaRefCount(); // Reset the debug counter to 0
dmArray<dmScript::HContext>& module_script_contexts = engine->m_ModuleContext.m_ScriptContexts;
bool shared = dmConfigFile::GetInt(engine->m_Config, "script.shared_state", 0);
if (shared) {
engine->m_SharedScriptContext = dmScript::NewContext(engine->m_Config, engine->m_Factory, true);
dmScript::Initialize(engine->m_SharedScriptContext);
engine->m_GOScriptContext = engine->m_SharedScriptContext;
engine->m_RenderScriptContext = engine->m_SharedScriptContext;
engine->m_GuiScriptContext = engine->m_SharedScriptContext;
module_script_contexts.SetCapacity(1);
module_script_contexts.Push(engine->m_SharedScriptContext);
} else {
engine->m_GOScriptContext = dmScript::NewContext(engine->m_Config, engine->m_Factory, true);
dmScript::Initialize(engine->m_GOScriptContext);
engine->m_RenderScriptContext = dmScript::NewContext(engine->m_Config, engine->m_Factory, true);
dmScript::Initialize(engine->m_RenderScriptContext);
engine->m_GuiScriptContext = dmScript::NewContext(engine->m_Config, engine->m_Factory, true);
dmScript::Initialize(engine->m_GuiScriptContext);
module_script_contexts.SetCapacity(3);
module_script_contexts.Push(engine->m_GOScriptContext);
module_script_contexts.Push(engine->m_RenderScriptContext);
module_script_contexts.Push(engine->m_GuiScriptContext);
}
dmHID::Init(engine->m_HidContext);
dmSound::InitializeParams sound_params;
sound_params.m_OutputDevice = "default";
#if defined(__EMSCRIPTEN__)
sound_params.m_UseThread = false;
#else
sound_params.m_UseThread = dmConfigFile::GetInt(engine->m_Config, "sound.use_thread", 1) != 0;
#endif
dmSound::Result soundInit = dmSound::Initialize(engine->m_Config, &sound_params);
if (dmSound::RESULT_OK == soundInit) {
dmLogInfo("Initialised sound device '%s'", sound_params.m_OutputDevice);
} else {
dmLogWarning("Failed to initialize sound system.");
}
dmGameObject::Result go_result = dmGameObject::SetCollectionDefaultCapacity(engine->m_Register, dmConfigFile::GetInt(engine->m_Config, dmGameObject::COLLECTION_MAX_INSTANCES_KEY, dmGameObject::DEFAULT_MAX_COLLECTION_CAPACITY));
if(go_result != dmGameObject::RESULT_OK)
{
dmLogFatal("Failed to set max instance count for collections (%d)", go_result);
return false;
}
dmGameObject::SetInputStackDefaultCapacity(engine->m_Register, dmConfigFile::GetInt(engine->m_Config, dmGameObject::COLLECTION_MAX_INPUT_STACK_ENTRIES_KEY, dmGameObject::DEFAULT_MAX_INPUT_STACK_CAPACITY));
dmRender::RenderContextParams render_params;
render_params.m_MaxRenderTypes = 16;
render_params.m_MaxInstances = (uint32_t) dmConfigFile::GetInt(engine->m_Config, "graphics.max_draw_calls", 1024);
render_params.m_MaxRenderTargets = 32;
render_params.m_VertexShaderDesc = ::DEBUG_VPC;
render_params.m_VertexShaderDescSize = ::DEBUG_VPC_SIZE;
render_params.m_FragmentShaderDesc = ::DEBUG_FPC;
render_params.m_FragmentShaderDescSize = ::DEBUG_FPC_SIZE;
render_params.m_MaxCharacters = (uint32_t) dmConfigFile::GetInt(engine->m_Config, "graphics.max_characters", 2048 * 4);;
render_params.m_CommandBufferSize = 1024;
render_params.m_ScriptContext = engine->m_RenderScriptContext;
render_params.m_MaxDebugVertexCount = (uint32_t) dmConfigFile::GetInt(engine->m_Config, "graphics.max_debug_vertices", 10000);
engine->m_RenderContext = dmRender::NewRenderContext(engine->m_GraphicsContext, render_params);
dmGameObject::Initialize(engine->m_Register, engine->m_GOScriptContext);
engine->m_ParticleFXContext.m_Factory = engine->m_Factory;
engine->m_ParticleFXContext.m_RenderContext = engine->m_RenderContext;
engine->m_ParticleFXContext.m_MaxParticleFXCount = dmConfigFile::GetInt(engine->m_Config, dmParticle::MAX_INSTANCE_COUNT_KEY, 64);
engine->m_ParticleFXContext.m_MaxEmitterCount = dmConfigFile::GetInt(engine->m_Config, dmParticle::MAX_EMITTER_COUNT_KEY, 64);
engine->m_ParticleFXContext.m_MaxParticleCount = dmConfigFile::GetInt(engine->m_Config, dmParticle::MAX_PARTICLE_COUNT_KEY, 1024);
engine->m_ParticleFXContext.m_Debug = false;
dmInput::NewContextParams input_params;
input_params.m_HidContext = engine->m_HidContext;
input_params.m_RepeatDelay = dmConfigFile::GetFloat(engine->m_Config, "input.repeat_delay", 0.5f);
input_params.m_RepeatInterval = dmConfigFile::GetFloat(engine->m_Config, "input.repeat_interval", 0.2f);
engine->m_InputContext = dmInput::NewContext(input_params);
dmMessage::Result mr = dmMessage::NewSocket(SYSTEM_SOCKET_NAME, &engine->m_SystemSocket);
if (mr != dmMessage::RESULT_OK)
{