-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathandroid_main.cpp
1677 lines (1353 loc) · 55.6 KB
/
android_main.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
#pragma clang diagnostic ignored "-Wmissing-braces"
//
// Includes
//
#include "common.h"
#include "android_platform.h"
#include "android_opengl.h"
#include "opengl.h"
#include "math.h"
//
// Defines
//
#define MAX_VERTICES_COUNT 2048
#define TEXTURE_SIZE 2048
#define TAB_MENU_COUNT 3
#define TAB_MENU_HEIGHT 100.0f
// For solid color quads
#define TEXPOS_SOLID v2{\
(TEXTURE_SIZE - 1.0f + 0.5f) / TEXTURE_SIZE, \
(TEXTURE_SIZE - 1.0f + 0.5f) / TEXTURE_SIZE \
}
#define PERMANENT_ARENA_SIZE MB(1)
#define TRANSIENT_ARENA_SIZE MB(10)
#define ACTIVE_RESUME (1 << 0)
#define ACTIVE_FOCUS (1 << 1)
#define ACTIVE_SURFACE (1 << 2)
#define ACTIVE_INTERACTIVE (ACTIVE_RESUME | ACTIVE_FOCUS | ACTIVE_SURFACE)
struct render_context
{
// EGL Stuff
EGLint Width; // In Pixels
EGLint Height; // In Pixels
EGLDisplay Display;
EGLConfig Config;
EGLSurface Surface;
EGLContext Context;
ANativeWindow *Window;
EGLint Format; // Format of the native window
// Shader stuff GL 2.0
GLuint MainShader;
GLint MetersToNDCLocation;
};
struct loaded_glyph
{
u8 Width;
u8 Height;
s8 OffsetX;
s8 OffsetY;
u8 Advance; // Advance X when drawing next glyph
};
struct font // TTF Parsed
{
memory_arena Arena;
u8 *FileData;
s32 FileSize;
u16 FontSize;
u16 GlyphCount;
f32 ScaleFactor; // Design units to Pixels
//
// We are storing the valeus of the CMAP table parsed
// so we can skip the conversion from BigEndian to LittleEndian
//
u16 HMetricCount;
u16 CMAP_SegmentCount;
u16 *CMAP_EndCodes;
u16 *CMAP_StartCodes;
s16 *CMAP_IDDeltas;
u16 *CMAP_IDRangeOffsets;
s32 IndexToLocFormat;
s32 GlyfOffset;
s32 HmtxOffset;
s32 LocaOffset;
//
// Glyph Used Atlas
//
u8 LoadedGlyphMask; // Used to map from index to X pos
u8 LoadedGlyphShift; // Used to map from index to Y pos
u16 ReservedGlyphCount;
u16 LoadedGlyphCount;
u16 MaxLoadedGlyphCount;
u32 *LoadedGlyphsCodepoint; // Used for simple lookup, @Todo Switch to custom Hash table
u16 *LoadedGlyphsUsedFrame;
loaded_glyph *LoadedGlyphsData;
};
struct main_state
{
render_context RenderContext;
f32 PixelsToMeters;
f32 MetersToPixels;
f32 Width; // In Meters
f32 Height; // In Meters
f32 StatusBarHeight; // In Meters
s32 TabIndex;
memory_arena PermanentArena;
memory_arena TransientArena;
font Font;
timespec BeginClockTime;
f32 SecondsPerFrame;
f32 FramesPerSecond;
s32 Frame;
s32 VertexCount;
vertex VertexBuffer[MAX_VERTICES_COUNT];
};
//
// Globals
//
global ANativeActivity *GLOBAL_Activity;
global main_state *GLOBAL_MainState;
// @Note These are written to by the Android thread
global ANativeWindow *GLOBAL_PendingWindow;
global AInputQueue *GLOBAL_InputQueue;
global s32 GLOBAL_ActiveFlags;
global s32 GLOBAL_GestureType;
global s32 GLOBAL_GestureStartTime;
global bmm GLOBAL_GestureCanScroll;
global v2 GLOBAL_GestureStart;
global v2 GLOBAL_GestureFocus;
global f32 GLOBAL_GestureMovedSq;
global f32 GLOBAL_ScrollYSpeed;
global f32 GLOBAL_ScrollPrevAmount;
global s32 GLOBAL_ScrollDir; // 0 is X, 1 is Y
global v2 GLOBAL_Scroll;
enum gesture
{
GESTURE_NONE,
GESTURE_TOUCH,
GESTURE_SCROLL,
GESTURE_UNKNOWN,
};
// Month daycount lookup INTERNAL, Use GetDaysInMonth() function
global u8 DaysInMonthInternal[] = // 0-11
{
/* January */ 31,
/* February */ 28, // 29 in every leap year, handled specially
/* March */ 31,
/* April */ 30,
/* May */ 31,
/* June */ 30,
/* July */ 31,
/* August */ 31,
/* September */ 30,
/* October */ 31,
/* November */ 30,
/* December */ 31
};
// Month name lookup
global string MonthNames[] = // 0-11
{
string{ StringAndLength("January") },
string{ StringAndLength("February") },
string{ StringAndLength("March") },
string{ StringAndLength("April") },
string{ StringAndLength("May") },
string{ StringAndLength("June") },
string{ StringAndLength("July") },
string{ StringAndLength("August") },
string{ StringAndLength("September")},
string{ StringAndLength("October") },
string{ StringAndLength("November") },
string{ StringAndLength("December") }
};
//
// Functions
//
#if DEBUG
#define Assert(Expression) if (!(Expression)) { Print("ASSERT Line %d", __LINE__); __builtin_trap(); }
#define Print(Message, ...) PrintInternal(Message, ##__VA_ARGS__)
internal void PrintInternal(char *Message, ...)
{
//
// Print the debug message
//
va_list List;
va_start(List, Message);
__android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, Message, List);
va_end(List);
}
#define Error(Message, ...) ErrorInternal(Message, ##__VA_ARGS__)
internal void ErrorInternal(char *Message, ...)
{
//
// Print the error message
//
va_list List;
va_start(List, Message);
__android_log_vprint(ANDROID_LOG_ERROR, LOG_TAG, Message, List);
Print("ERROR: errno %d", errno);
va_end(List);
// End the activity
ANativeActivity_finish(GLOBAL_Activity);
}
#else
#define Assert(Expression)
#define Print(Message ...)
#define Error(Message ...)
#endif
internal inline u8 *ArenaAllocEx(memory_arena *Arena, smm Count, smm ElementSize)
{
Assert(Arena != nullptr);
Assert(Count >= 1);
Assert(ElementSize >= 1);
// Allocation
smm Size = Count * ElementSize;
u8 *Result = Arena->Data + Arena->Taken;
Arena->Taken += Size;
// Because stores/loads across cache lines are very slow we need to align
// aligned 1 cycle VS unaligned 12 cycles, this isn't always like this
smm Alignment = Min(ElementSize, 64);
Assert((Alignment % ElementSize) == 0); // Do not allow elements crossing cache line boundary
// Alignment
smm Address = (smm)Result; // Cannout RoundUp pointer* types
smm Padding = RoundUp(Address, Alignment) - Address;
Result += Padding;
Arena->Taken += Padding;
// Range check
Assert(Arena->Taken <= Arena->Size);
return Result;
}
internal inline memory_arena ArenaCreate(memory_arena *Arena, smm Size)
{
memory_arena Result;
Result.Data = ArenaAllocEx(Arena, Size, sizeof(u8));
Result.Size = Size;
Result.Taken = 0;
return Result;
}
#define ArenaAlloc(Arena, Type, Count)\
((Type *)ArenaAllocEx((Arena), (Count), sizeof(Type)))
internal inline smm GetDaysInMonth(smm Month, smm IsLeapYear)
{
smm Result = DaysInMonthInternal[Month];
// Handle February leap year, month is 0-11, so 1 means February
Result += (Month == 1) * IsLeapYear;
return Result;
}
internal inline void MiliSleep(smm Miliseconds)
{
Assert(Miliseconds < 1000);
timespec Time;
Time.tv_sec = 0;
Time.tv_nsec = Miliseconds * 1000000;
if (nanosleep(&Time, nullptr) == -1)
{
Print("WARN: ------ nanosleep failed");
}
}
internal inline void SecSleep(smm Seconds)
{
timespec Time;
Time.tv_sec = Seconds;
Time.tv_nsec = 0;
if (nanosleep(&Time, nullptr) == -1)
{
Print("WARN: ------ nanosleep failed");
}
}
internal inline smm GetNanosecondsElapsed(timespec BeginClockTime, timespec *EndClockTime)
{
if (clock_gettime(CLOCK_MONOTONIC_RAW, EndClockTime) == -1)
{
Error("clock_gettime failed");
}
smm Result = ((EndClockTime->tv_sec - BeginClockTime.tv_sec) * SECONDS_TO_NANOSECONDS +
(EndClockTime->tv_nsec - BeginClockTime.tv_nsec));
return Result;
}
//
// JNI Functions
//
internal f32 JNIGetXDPI()
{
JNIEnv *Env = GLOBAL_Activity->env;
(*GLOBAL_Activity->vm)->AttachCurrentThread(GLOBAL_Activity->vm, &Env, nullptr);
jclass ActivityClass = (*Env)->FindClass(Env, "android/app/NativeActivity");
JNIAssert(ActivityClass);
jmethodID GetWindowManager = (*Env)->GetMethodID(Env, ActivityClass, "getWindowManager", "()Landroid/view/WindowManager;");
JNIAssert(GetWindowManager);
jobject WindowManager = (*Env)->CallObjectMethod(Env, GLOBAL_Activity->clazz, GetWindowManager);
JNIAssert(WindowManager);
jclass WindowManagerClass = (*Env)->FindClass(Env, "android/view/WindowManager");
JNIAssert(WindowManagerClass);
jmethodID GetDefaultDisplay = (*Env)->GetMethodID(Env, WindowManagerClass, "getDefaultDisplay", "()Landroid/view/Display;");
JNIAssert(GetDefaultDisplay);
jobject Display = (*Env)->CallObjectMethod(Env, WindowManager, GetDefaultDisplay);
JNIAssert(Display);
jclass DisplayClass = (*Env)->FindClass(Env, "android/view/Display");
JNIAssert(DisplayClass);
jclass DisplayMetricsClass = (*Env)->FindClass(Env, "android/util/DisplayMetrics");
JNIAssert(DisplayMetricsClass);
jmethodID DisplayMetricsConstructor = (*Env)->GetMethodID(Env, DisplayMetricsClass, "<init>", "()V");
JNIAssert(DisplayMetricsConstructor);
jobject DisplayMetrics = (*Env)->NewObject(Env, DisplayMetricsClass, DisplayMetricsConstructor);
JNIAssert(DisplayMetrics);
jmethodID GetMetrics = (*Env)->GetMethodID(Env, DisplayClass, "getMetrics", "(Landroid/util/DisplayMetrics;)V");
JNIAssert(GetMetrics);
(*Env)->CallVoidMethod(Env, Display, GetMetrics, DisplayMetrics);
jfieldID FieldXDPI = (*Env)->GetFieldID(Env, DisplayMetricsClass, "xdpi", "F");
JNIAssert(FieldXDPI);
// This is measured in Pixels Per Inch
f32 XDPI = (*Env)->GetFloatField(Env, DisplayMetrics, FieldXDPI);
Print("XDPI: %f", XDPI);
(*GLOBAL_Activity->vm)->DetachCurrentThread(GLOBAL_Activity->vm);
return XDPI;
}
//
// Utility
//
internal inline smm BitScanForwardU32(smm Value)
{
#if defined(__clang__)
smm Result = __builtin_clz(__builtin_arm_rbit(Value));
#else
#error BitScanForwardU32
#endif
return Result;
}
internal inline smm GetNLZ(smm X) // Number Of Leading Zeroes
{
smm Y, M, N;
Y = -(X >> 16); // If left half of X is 0,
M = (Y >> 16) & 16; // set N = 16. If left half
N = 16 - M; // is nonzero, set N = 0 and
X = X >> M; // shift X right 16.
// Now X Is of the form 0000xxxx.
Y = X - 0x100; // If positions 8-15 are 0,
M = (Y >> 16) & 8; // add 8 to N and shift X left 8.
N = N + M;
X = X << M;
Y = X - 0x1000; // If positions 12-15 are 0,
M = (Y >> 16) & 4; // add 4 to N and shift X left 4.
N = N + M;
X = X << M;
Y = X - 0x4000; // If positions 14-15 are 0,
M = (Y >> 16) & 2; // add 2 to N and shift X left 2.
N = N + M;
X = X << M;
Y = X >> 14; // Set Y = 0, 1, 2, or 3.
M = Y & ~(Y >> 1); // Set M = 0, 1, 2, or 2 resp.
smm Result = N + 2 - M;
return Result;
}
internal inline s32 RoundUpToPowerOfTwo(s32 Value)
{
return 1 << (32 - GetNLZ(Value - 1));
}
internal inline s32 RoundDownToPowerOfTwo(s32 Value)
{
return 1 << (31 - GetNLZ(Value));
}
//
// Glyph Rasterization & TTF parsing
//
#include "truetype.h"
//
// OpenGL stuff
//
internal GLuint OGLCompileShader(GLenum ShaderType, char *ShaderSource, GLint ShaderSize)
{
GLuint Shader = glCreateShader(ShaderType);
if (Shader == 0)
{
Error("glCreateShader failed");
}
glShaderSource(Shader, 1, (GLchar **)&ShaderSource, &ShaderSize);
GLAssert();
glCompileShader(Shader);
GLint CompileStatus;
glGetShaderiv(Shader, GL_COMPILE_STATUS, &CompileStatus);
if (CompileStatus == GL_FALSE)
{
GLsizei ErrorLength;
glGetShaderiv(Shader, GL_INFO_LOG_LENGTH, &ErrorLength);
// ErrorLength is 0 if there is no shader log
if (ErrorLength > 0)
{
char ErrorBuffer[4 * 1024];
Assert(ErrorLength < sizeof(ErrorBuffer));
glGetShaderInfoLog(Shader, ErrorLength, &ErrorLength, (GLchar *)ErrorBuffer); GLAssert();
Print("%.*s", ErrorLength, ErrorBuffer);
}
Error("glCompileShader failed");
}
return Shader;
}
internal void CommonInitOpenGL()
{
//
// Texture
//
glBindTexture(GL_TEXTURE_2D, TEXNAME_MAIN); GLAssert();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); GLAssert();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); GLAssert();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); GLAssert();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); GLAssert();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); GLAssert();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); GLAssert();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8,
TEXTURE_SIZE, TEXTURE_SIZE, 0,
PLATFORM_OPENGL_UPLOAD_FORMAT, GL_UNSIGNED_BYTE, nullptr
); GLAssert();
// White pixel for solid Color texturing
u32 WhitePixel = 0xFFFFFFFF;
glTexSubImage2D(
GL_TEXTURE_2D, 0,
TEXTURE_SIZE - 1, TEXTURE_SIZE - 1, 1, 1,
PLATFORM_OPENGL_UPLOAD_FORMAT, GL_UNSIGNED_BYTE, &WhitePixel
);
//
// Compile the main vertex and fragment shaders
//
GLuint MainVertexShader = OGLCompileShader(GL_VERTEX_SHADER, StringAndLength(
R"RAWSTR(#version 100
precision mediump float;
attribute vec2 vPosition;
attribute vec2 vTexture;
attribute vec4 vColor;
varying vec2 Texture;
varying vec4 Color;
uniform vec2 MetersToNDC;
void main()
{
gl_Position = vec4(vPosition * MetersToNDC - 1.0, 0.0, 1.0);
Texture = vTexture;
Color = vColor;
}
)RAWSTR"));
GLuint MainFragmentShader = OGLCompileShader(GL_FRAGMENT_SHADER, StringAndLength(
R"RAWSTR(#version 100
precision mediump float;
varying vec2 Texture;
varying vec4 Color;
uniform sampler2D Sampler;
void main()
{
gl_FragColor = texture2D(Sampler, Texture.st);
gl_FragColor *= Color;
}
)RAWSTR"));
GLuint MainShader = glCreateProgram(); GLAssert();
glAttachShader(MainShader, MainVertexShader); GLAssert();
glAttachShader(MainShader, MainFragmentShader); GLAssert();
glBindAttribLocation(MainShader, 0, "vPosition"); GLAssert();
glBindAttribLocation(MainShader, 1, "vTexture"); GLAssert();
glBindAttribLocation(MainShader, 2, "vColor"); GLAssert();
glLinkProgram(MainShader); GLAssert();
GLint LinkStatus;
glGetProgramiv(MainShader, GL_LINK_STATUS, &LinkStatus);
if (LinkStatus == GL_FALSE)
{
Error("glLinkProgram");
}
glValidateProgram(MainShader);
GLint ValidationStatus;
glGetProgramiv(MainShader, GL_VALIDATE_STATUS, &ValidationStatus);
if (ValidationStatus == GL_FALSE)
{
Error("glValidateProgram");
}
glUseProgram(MainShader); GLAssert();
GLint MetersToNDCLocation = glGetUniformLocation(MainShader, "MetersToNDC");
if (MetersToNDCLocation == -1)
{
Error("glGetUniformLocation(MetersToNDC)");
}
// The sampler will not be changed, always 0
GLint SamplerLocation = glGetUniformLocation(MainShader, "Sampler");
if (SamplerLocation == -1)
{
Error("glGetUniformLocation(Sampler)");
}
glUniform1i(SamplerLocation, 0);
render_context *RenderContext = &GLOBAL_MainState->RenderContext;
f32 MetersToPixels = 1.0f;
v2 MetersToNDC = MetersToPixels * 2.0f / v2{ (f32)RenderContext->Width, (f32)RenderContext->Height };
glUniform2f(MetersToNDCLocation, MetersToNDC.X, MetersToNDC.Y);
// Store the shader information for later
RenderContext->MainShader = MainShader;
RenderContext->MetersToNDCLocation = MetersToNDCLocation;
Print("MainShader %d", GLOBAL_MainState->RenderContext.MainShader);
Print("Location %d", GLOBAL_MainState->RenderContext.MetersToNDCLocation);
//
// Vertex buffer
//
glBindBuffer(GL_ARRAY_BUFFER, BUFNAME_VERTEX); GLAssert();
glBufferData(GL_ARRAY_BUFFER, MAX_VERTICES_COUNT * sizeof(vertex), nullptr, GL_DYNAMIC_DRAW); GLAssert();
glVertexAttribPointer(0, floatsof(vertex, Position), GL_FLOAT, GL_FALSE, sizeof(vertex), (void *)offsetof(vertex, Position)); GLAssert();
glVertexAttribPointer(1, floatsof(vertex, Texture), GL_FLOAT, GL_FALSE, sizeof(vertex), (void *)offsetof(vertex, Texture)); GLAssert();
glVertexAttribPointer(2, floatsof(vertex, Color), GL_FLOAT, GL_FALSE, sizeof(vertex), (void *)offsetof(vertex, Color)); GLAssert();
glEnableVertexAttribArray(0); GLAssert();
glEnableVertexAttribArray(1); GLAssert();
glEnableVertexAttribArray(2); GLAssert();
//
// Index buffer
//
u16 Indices[(MAX_VERTICES_COUNT / 4) * 6];
u16 IndexBase = 0;
for (size_t Index = 0; Index < GetArrayCount(Indices); Index += 6)
{
Indices[Index + 0] = IndexBase + 0;
Indices[Index + 1] = IndexBase + 1;
Indices[Index + 2] = IndexBase + 2;
Indices[Index + 3] = IndexBase + 3;
Indices[Index + 4] = IndexBase + 2;
Indices[Index + 5] = IndexBase + 1;
IndexBase += 4;
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, BUFNAME_INDEX); GLAssert();
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Indices), Indices, GL_STATIC_DRAW); GLAssert();
//
// Blend
//
glEnable(GL_BLEND); GLAssert();
// @Note Premultiplied alpha
glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); GLAssert();
// Clear
v4 ClearColor = COL_BACK;
glClearColor(ClearColor.Red, ClearColor.Green, ClearColor.Blue, ClearColor.Alpha); GLAssert();
}
internal void AndroidUpdateWindowSurface()
{
render_context *RenderContext = &GLOBAL_MainState->RenderContext;
if (ANativeWindow_setBuffersGeometry(RenderContext->Window, 0, 0, RenderContext->Format) < 0)
{
Error("ANativeWindow_setBuffersGeometry failed");
}
// Surface
Print("Creating surface!\n");
RenderContext->Surface = eglCreateWindowSurface(RenderContext->Display, RenderContext->Config, RenderContext->Window, nullptr);
if (RenderContext->Surface == EGL_NO_SURFACE)
{
Error("eglCreateWindowSurface failed");
}
if (eglQuerySurface(RenderContext->Display, RenderContext->Surface, EGL_WIDTH, &RenderContext->Width) == EGL_FALSE)
{
Error("eglQuerySurface Width failed");
}
if (eglQuerySurface(RenderContext->Display, RenderContext->Surface, EGL_HEIGHT, &RenderContext->Height) == EGL_FALSE)
{
Error("eglQuerySurface Height failed");
}
Print("Width %d, Height %d", RenderContext->Width, RenderContext->Height);
//
// Make current
//
if (eglMakeCurrent(RenderContext->Display,
RenderContext->Surface, RenderContext->Surface,
RenderContext->Context) == EGL_FALSE)
{
s32 ErrorNumber = eglGetError();
Print("eglMakeCurrent failed %d", ErrorNumber);
}
//
// Set the viewport to the new dimensions
//
glViewport(0, 0, RenderContext->Width, RenderContext->Height); GLAssert();
//
// Set values
//
GLOBAL_MainState->MetersToPixels = 1.0f;
GLOBAL_MainState->PixelsToMeters = 1.0f;
GLOBAL_MainState->Width = GLOBAL_MainState->PixelsToMeters * RenderContext->Width;
GLOBAL_MainState->Height = GLOBAL_MainState->PixelsToMeters * RenderContext->Height;
}
internal void AndroidInitOpenGL()
{
Print("Initializing EGL state...\n");
render_context *RenderContext = &GLOBAL_MainState->RenderContext;
//
// Display
//
RenderContext->Display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (RenderContext->Display == EGL_NO_DISPLAY)
{
Error("eglGetDisplay failed");
}
if (eglInitialize(RenderContext->Display, 0, 0) == EGL_FALSE)
{
Error("eglInitialize failed");
}
//
// Config
//
EGLint Attributes[] =
{
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_ALPHA_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_RED_SIZE, 8,
EGL_NONE,
};
EGLint ConfigCount;
if (eglChooseConfig(RenderContext->Display, Attributes, &RenderContext->Config, 1, &ConfigCount) == EGL_FALSE)
{
Error("eglChooseConfig failed");
}
//
// Context
//
EGLint ContextAttributes[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };
RenderContext->Context = eglCreateContext(RenderContext->Display, RenderContext->Config, nullptr, ContextAttributes);
if (RenderContext->Context == EGL_FALSE)
{
Error("eglCreateContext failed");
}
//
// Set format of window buffer
//
if (eglGetConfigAttrib(RenderContext->Display, RenderContext->Config,
EGL_NATIVE_VISUAL_ID, &RenderContext->Format) == EGL_FALSE)
{
Error("eglGetConfigAttrib failed");
}
// Wait for us to Android to give us the Window
while (GLOBAL_PendingWindow == nullptr)
{
Print("Waiting for window!");
MiliSleep(5);
}
Print("Got window %d, previously was %d", GLOBAL_PendingWindow, RenderContext->Window);
RenderContext->Window = GLOBAL_PendingWindow;
// Initialize the window surface
AndroidUpdateWindowSurface();
}
internal inline void AndroidReadFontFile()
{
Print("opening Roboto-Regular.ttf");
// Open the file
smm FontFile = open("/system/fonts/Roboto-Regular.ttf", O_RDONLY);
if (FontFile == -1)
{
Print("open font file failed, error %d", errno);
}
// Get the file size
stat FontStat;
if (fstat(FontFile, &FontStat) == -1)
{
Print("fstat font file failed, error %d", errno);
}
Print("File size is %lld KB", FontStat.st_size / 1024);
font *Font = &GLOBAL_MainState->Font;
Font->FileSize = FontStat.st_size;
// Allocate the memory for the file
Font->FileData = ArenaAlloc(&Font->Arena, u8, Font->FileSize);
// Read the entire file
ssize_t BytesRead = read(FontFile, Font->FileData, Font->FileSize);
if (BytesRead == -1)
{
Print("read font file failed, error %d", errno);
Error("read failed");
}
if (BytesRead != Font->FileSize)
{
Print("WARN: read font file missing bytes, %d / %d", BytesRead, Font->FileSize);
}
}
internal inline void DrawQuad(v2 PosMin, v2 PosMax, v2 TexMin, v2 TexMax, v4 Color)
{
vertex *VertexBuffer = GLOBAL_MainState->VertexBuffer;
smm VertexCount = GLOBAL_MainState->VertexCount;
Assert(VertexCount + 4 <= MAX_VERTICES_COUNT);
// Top Left
VertexBuffer[VertexCount + 0] =
vertex{ v2{ PosMin.X, PosMin.Y }, v2{ TexMin.X, TexMax.Y }, Color };
// Bottom Left
VertexBuffer[VertexCount + 1] =
vertex{ v2{ PosMin.X, PosMax.Y }, v2{ TexMin.X, TexMin.Y }, Color };
// Top Right
VertexBuffer[VertexCount + 2] =
vertex{ v2{ PosMax.X, PosMin.Y }, v2{ TexMax.X, TexMax.Y }, Color };
// Bottom Right
VertexBuffer[VertexCount + 3] =
vertex{ v2{ PosMax.X, PosMax.Y }, v2{ TexMax.X, TexMin.Y }, Color };
GLOBAL_MainState->VertexCount += 4;
}
internal inline void DrawGlyph(v2 Position, smm LoadedIndex, v4 Color)
{
font *Font = &GLOBAL_MainState->Font;
f32 TextureScale = (1.0f / TEXTURE_SIZE);
v2 TexMin = v2{
((f32)((LoadedIndex & Font->LoadedGlyphMask) * FONT_CELL_WIDTH) + 0.5f) * TextureScale,
((f32)((LoadedIndex >> Font->LoadedGlyphShift) * FONT_CELL_HEIGHT) + 0.5f) * TextureScale,
};
v2 Dimensions = v2{
(f32)Font->LoadedGlyphsData[LoadedIndex].Width,
(f32)Font->LoadedGlyphsData[LoadedIndex].Height,
};
v2 PosMin = v2{
Position.X + (f32)Font->LoadedGlyphsData[LoadedIndex].OffsetX,
Position.Y + (f32)Font->LoadedGlyphsData[LoadedIndex].OffsetY,
};
DrawQuad(
PosMin, PosMin + (GLOBAL_MainState->PixelsToMeters * Dimensions),
TexMin, TexMin + (TextureScale * (Dimensions - v2{ 1.0f, 1.0f })),
Color
);
}
internal v2 DrawText(v2 Position, char *Text, smm Size, v4 Color)
{
font *Font = &GLOBAL_MainState->Font;
f32 LineStartX = Position.X;
for (smm ByteIndex = 0; ByteIndex < Size;)
{
smm LoadedIndex = 0; // Default to null glyph
umm CharacterUTF32 = UTF8ToCodepoint((u8 *)Text, &ByteIndex);
if (CharacterUTF32 == '\n')
{
Position.X = LineStartX;
Position.Y += Font->FontSize * GLOBAL_MainState->PixelsToMeters;
continue;
}
if (CharacterUTF32 != ' ')
{
smm GlyphID = UnicodeToGlyphID(CharacterUTF32);
// Print("U+%04X, GlyphID: %d", (u32)CharacterUTF32, (u32)GlyphID);
LoadedIndex = RasterizeGlyph(GlyphID);
DrawGlyph(Position, LoadedIndex, Color);
}
Position.X += Font->LoadedGlyphsData[LoadedIndex].Advance * GLOBAL_MainState->PixelsToMeters;
}
return Position;
}
internal void *AndroidMain(void *Param)
{
Print("Thread start Param %d", Param);
#if DEBUG
SecSleep(2);
#endif
//
// Arena creation
//
memory_arena *PermanentArena = &GLOBAL_MainState->PermanentArena;
PermanentArena->Data = (u8 *)GLOBAL_MainState + sizeof(main_state);
PermanentArena->Size = PERMANENT_ARENA_SIZE;
PermanentArena->Taken = 0;
memory_arena *TransientArena = &GLOBAL_MainState->TransientArena;
TransientArena->Data = PermanentArena->Data + PermanentArena->Size;
TransientArena->Size = TRANSIENT_ARENA_SIZE;
TransientArena->Taken = 0;
GLOBAL_MainState->Font.Arena = ArenaCreate(PermanentArena, MB(1));
//
// Read the font file
//
AndroidReadFontFile();
ParseTTF();
font *Font = &GLOBAL_MainState->Font;
//
// XDPI
//
f32 XDPI = JNIGetXDPI();
f32 PixelsPerInch = XDPI;
f32 PixelsPerMm = PixelsPerInch * 25.4f;
f32 MmPerPixel = (1.0f / PixelsPerInch) * 25.4f;
//
// Get the day and month
//
tm LocalTime = {};
time_t Time = time(nullptr);
if (localtime_r(&Time, &LocalTime) == nullptr)
{
Print("localtime_r failed");
}
// @Todo Update this when changing years
smm IsLeapYear = !((LocalTime.tm_year % 100) ? (LocalTime.tm_year % 4) : (LocalTime.tm_year % 16));
//
// OpenGL
//
AndroidInitOpenGL();
CommonInitOpenGL();
GLOBAL_MainState->MetersToPixels = 1.0f;
GLOBAL_MainState->PixelsToMeters = 1.0f;
GLOBAL_MainState->Width = GLOBAL_MainState->RenderContext.Width * GLOBAL_MainState->PixelsToMeters;
GLOBAL_MainState->Height = GLOBAL_MainState->RenderContext.Height * GLOBAL_MainState->PixelsToMeters;
GLOBAL_MainState->FramesPerSecond = 60.0f; // @Todo Calculate the FPS Target
GLOBAL_MainState->SecondsPerFrame = 1.0f / GLOBAL_MainState->FramesPerSecond;
// Status bar and navigation bar
GLOBAL_MainState->StatusBarHeight = 48.0f * GLOBAL_MainState->PixelsToMeters;
// @Todo One big glTexImage2D call to update all the initial state
//
// Maybe keep a local copy on the CPU in case a big chunk needs to be updated
// and in that case the whole texture can be uploaded instead of subregion for a
// unknown/unmeasured performance gain. this is probably a microoptimization
//
// This would also allow RasterizeGlyph to be called before OpenGL initialization
// In that case it could be API agnostic, because texture upload can be deffered
RasterizeGlyph(0); // ntdef glyph
RasterizeGlyph(UnicodeToGlyphID('0'));
RasterizeGlyph(UnicodeToGlyphID('1'));
RasterizeGlyph(UnicodeToGlyphID('2'));
RasterizeGlyph(UnicodeToGlyphID('3'));
RasterizeGlyph(UnicodeToGlyphID('4'));
RasterizeGlyph(UnicodeToGlyphID('5'));
RasterizeGlyph(UnicodeToGlyphID('6'));
RasterizeGlyph(UnicodeToGlyphID('7'));
RasterizeGlyph(UnicodeToGlyphID('8'));
RasterizeGlyph(UnicodeToGlyphID('9'));