forked from edennz/artoolkit6-calibration
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcalib_camera.cpp
More file actions
1501 lines (1344 loc) · 56.8 KB
/
calib_camera.cpp
File metadata and controls
1501 lines (1344 loc) · 56.8 KB
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
/*
* calib_camera.cpp
* artoolkitX
*
* Camera calibration utility.
*
* Run with "--help" parameter to see usage.
*
* This file is part of artoolkitX.
*
* artoolkitX is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* artoolkitX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with artoolkitX. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules, and to
* copy and distribute the resulting executable under terms of your choice,
* provided that you also meet, for each linked independent module, the terms and
* conditions of the license of that module. An independent module is a module
* which is neither derived from nor based on this library. If you modify this
* library, you may extend this exception to your version of the library, but you
* are not obligated to do so. If you do not wish to do so, delete this exception
* statement from your version.
*
* Copyright 2019-2023 Philip Lamb
* Copyright 2018 Realmax, Inc.
* Copyright 2015-2016 Daqri, LLC.
* Copyright 2002-2015 ARToolworks, Inc.
*
* Author(s): Hirokazu Kato, Philip Lamb
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#ifdef _WIN32
# include <windows.h>
# define MAXPATHLEN MAX_PATH
# include <direct.h> // getcwd
#else
# include <sys/param.h> // MAXPATHLEN
# include <unistd.h> // getcwd
#endif
#include <ARX/AR/ar.h>
//#include <ARX/ARVideo/video.h>
#include <ARX/ARVideoSource.h>
#include <ARX/ARVideoView.h>
#include <ARX/ARUtil/system.h>
#include <ARX/ARUtil/thread_sub.h>
#include <ARX/ARUtil/time.h>
#include <ARX/ARUtil/file_utils.h>
#include <ARX/ARG/arg.h>
#include <ARX/ARG/mtx.h>
#include <ARX/ARG/shader_gl.h>
#include <ARX/ARG/glStateCache2.h>
#include "fileUploader.h"
#include "Calibration.hpp"
#include "flow.hpp"
#include "Eden/EdenMessage.h"
#include "Eden/EdenGLFont.h"
#include "prefs.hpp"
#include "loc_strings.hpp"
#include "calib_camera.h"
#ifdef __APPLE__
# if (HAVE_GL || HAVE_GL3)
# include <SDL2/SDL_opengl.h>
# elif HAVE_GLES2
# include <SDL2/SDL_opengles2.h>
# endif
#elif defined(ANDROID)
# include <SDL3/SDL_main.h>
# include <SDL3/SDL_opengles2.h>
# define HAVE_SDL3
#else
# if (HAVE_GL || HAVE_GL3)
# include "SDL2/SDL_opengl.h"
# elif HAVE_GLES2
# include "SDL2/SDL_opengles2.h"
# endif
#endif
// ============================================================================
// Types
// ============================================================================
// ============================================================================
// Constants
// ============================================================================
#if HAVE_GLES2
// Indices of GL ES program uniforms.
enum {
UNIFORM_MODELVIEW_PROJECTION_MATRIX,
UNIFORM_COLOR,
UNIFORM_COUNT
};
// Indices of of GL ES program attributes.
enum {
ATTRIBUTE_VERTEX,
ATTRIBUTE_COUNT
};
#endif // HAVE_GLES2
#define CHESSBOARD_CORNER_NUM_X 7
#define CHESSBOARD_CORNER_NUM_Y 5
#define CHESSBOARD_PATTERN_WIDTH 30.0
#define CALIB_IMAGE_NUM 10
#define SAVE_FILENAME "camera_para.dat"
// Data upload.
#define QUEUE_DIR "queue"
#define QUEUE_INDEX_FILE_EXTENSION "upload"
#ifdef __APPLE__
# include <CommonCrypto/CommonDigest.h>
# define MD5 CC_MD5
# define MD5_DIGEST_LENGTH CC_MD5_DIGEST_LENGTH
# define MD5_COUNT_t CC_LONG
#else
//#include <openssl/md5.h>
// Rather than including full OpenSSL header tree, just provide prototype for MD5().
// Usage is here: https://www.openssl.org/docs/manmaster/man3/MD5.html .
# define MD5_DIGEST_LENGTH 16
# define MD5_COUNT_t size_t
# ifdef __cplusplus
extern "C" {
# endif
unsigned char *MD5(const unsigned char *d, size_t n, unsigned char *md);
# ifdef __cplusplus
}
# endif
#endif
#define FONT_SIZE 18.0f
#define UPLOAD_STATUS_HIDE_AFTER_SECONDS 9.0f
// ============================================================================
// Global variables.
// ============================================================================
// Prefs.
static void *gPreferences = NULL;
Uint32 gSDLEventPreferencesChanged = 0;
static char *gPreferenceCameraOpenToken = NULL;
static char *gPreferenceCameraResolutionToken = NULL;
static bool gCalibrationSave = false;
static char *gCalibrationSaveDir = NULL;
static char *gCalibrationServerUploadURL = NULL;
static char *gCalibrationServerAuthenticationToken = NULL;
static int gPreferencesCalibImageCountMax = CALIB_IMAGE_NUM;
static Calibration::CalibrationPatternType gCalibrationPatternType;
static cv::Size gCalibrationPatternSize;
static float gCalibrationPatternSpacing;
//
// Calibration.
//
static Calibration *gCalibration = nullptr;
//
// Data upload.
//
static char *gFileUploadQueuePath = NULL;
FILE_UPLOAD_HANDLE_t *fileUploadHandle = NULL;
// Video acquisition and rendering.
static ARVideoSource *vs = nullptr;
static ARVideoView *vv = nullptr;
static bool gPostVideoSetupDone = false;
static bool gCameraIsFrontFacing = false;
static long gFrameCount = 0;
// Window and GL context.
static ARG_API drawAPI = ARG_API_None;
static SDL_GLContext gSDLContext = NULL;
static int contextWidth = 0;
static int contextHeight = 0;
static bool contextWasUpdated = false;
static SDL_Window* gSDLWindow = NULL;
static int32_t gViewport[4] = {0, 0, 0, 0}; // {x, y, width, height}
static int gDisplayOrientation =
#ifndef ANDROID
1; // range [0-3]. 1=landscape.
#else
0; // range [0-3]. 0=portrait.
#endif
static float gDisplayDPI = 72.0f;
#if HAVE_GLES2
static GLint uniforms[UNIFORM_COUNT] = {0};
static GLuint program = 0;
#endif // HAVE_GLES2
// Main state.
static struct timeval gStartTime;
// Corner finder results copy, for display to user.
static ARGL_CONTEXT_SETTINGS_REF gArglSettingsCornerFinderImage = NULL;
// ============================================================================
// Function prototypes
// ============================================================================
static void quit(int rc);
static void reshape(int w, int h);
static void drawView(void);
static void init(int argc, char *argv[]);
static void usage(char *com);
static void saveParam(const ARParam *param, ARdouble err_min, ARdouble err_avg, ARdouble err_max, void *userdata);
static void startVideo(void)
{
#ifdef ANDROID
if (SDL_AndroidRequestPermission("android.permission.CAMERA") != SDL_TRUE) {
ARLOGe("Error: Unable to open video source.\n");
EdenMessageShow((const unsigned char *)LOC_STRING(loc_string::VideoOpenErrorTouchscreen));
return;
}
#endif
char *buf = NULL;
if (asprintf(&buf, "%s%s%s",
(gPreferenceCameraOpenToken ? gPreferenceCameraOpenToken : ""),
(gPreferenceCameraOpenToken && gPreferenceCameraResolutionToken ? " " : ""),
(gPreferenceCameraResolutionToken ? gPreferenceCameraResolutionToken : "")) < 0) {
ARLOGe("Error: out of memory!!!.\n");
}
vs = new ARVideoSource;
if (!vs) {
ARLOGe("Error: Unable to create video source.\n");
quit(-1);
} else {
vs->configure(buf, true, NULL, NULL, 0);
if (!vs->open()) {
ARLOGe("Error: Unable to open video source.\n");
#ifdef ANDROID
EdenMessageShow((const unsigned char *)LOC_STRING(loc_string::VideoOpenErrorTouchscreen));
#else
EdenMessageShow((const unsigned char *)LOC_STRING(loc_string::VideoOpenError));
#endif
}
}
gPostVideoSetupDone = false;
free(buf);
}
static void stopVideo(void)
{
// Stop calibration flow.
flowStopAndFinal();
if (gCalibration) {
delete gCalibration;
gCalibration = nullptr;
}
if (gArglSettingsCornerFinderImage) {
arglCleanup(gArglSettingsCornerFinderImage); // Clean up any left-over ARGL data.
gArglSettingsCornerFinderImage = NULL;
}
delete vv;
vv = nullptr;
delete vs;
vs = nullptr;
}
static void rereadPreferences(void)
{
// Re-read preferences.
gCalibrationSave = getPreferenceCalibrationSave(gPreferences);
char *csd = getPreferenceCalibSaveDir(gPreferences);
if (csd && gCalibrationSaveDir && strcmp(gCalibrationSaveDir, csd) == 0) {
free(csd);
} else {
free(gCalibrationSaveDir);
gCalibrationSaveDir = csd;
}
char *csuu = getPreferenceCalibrationServerUploadURL(gPreferences);
if (csuu && gCalibrationServerUploadURL && strcmp(gCalibrationServerUploadURL, csuu) == 0) {
free(csuu);
} else {
free(gCalibrationServerUploadURL);
gCalibrationServerUploadURL = csuu;
fileUploaderFinal(&fileUploadHandle);
if (csuu) {
fileUploadHandle = fileUploaderInit(gFileUploadQueuePath, QUEUE_INDEX_FILE_EXTENSION, gCalibrationServerUploadURL, UPLOAD_STATUS_HIDE_AFTER_SECONDS);
if (!fileUploadHandle) {
ARLOGe("Error: Could not initialise fileUploadHandle.\n");
}
}
}
char *csat = getPreferenceCalibrationServerAuthenticationToken(gPreferences);
if (csat && gCalibrationServerAuthenticationToken && strcmp(gCalibrationServerAuthenticationToken, csat) == 0) {
free(csat);
} else {
free(gCalibrationServerAuthenticationToken);
gCalibrationServerAuthenticationToken = csat;
}
bool changedCameraSettings = false;
char *crt = getPreferenceCameraResolutionToken(gPreferences);
if (crt && gPreferenceCameraResolutionToken && strcmp(gPreferenceCameraResolutionToken, crt) == 0) {
free(crt);
} else {
free(gPreferenceCameraResolutionToken);
gPreferenceCameraResolutionToken = crt;
changedCameraSettings = true;
}
char *cot = getPreferenceCameraOpenToken(gPreferences);
if (cot && gPreferenceCameraOpenToken && strcmp(gPreferenceCameraOpenToken, cot) == 0) {
free(cot);
} else {
free(gPreferenceCameraOpenToken);
gPreferenceCameraOpenToken = cot;
changedCameraSettings = true;
}
Calibration::CalibrationPatternType patternType = getPreferencesCalibrationPatternType(gPreferences);
cv::Size patternSize = getPreferencesCalibrationPatternSize(gPreferences);
float patternSpacing = getPreferencesCalibrationPatternSpacing(gPreferences);
if (patternType != gCalibrationPatternType || patternSize != gCalibrationPatternSize || patternSpacing != gCalibrationPatternSpacing) {
gCalibrationPatternType = patternType;
gCalibrationPatternSize = patternSize;
gCalibrationPatternSpacing = patternSpacing;
changedCameraSettings = true;
}
if (changedCameraSettings) {
// Changing camera settings requires complete cancelation of calibration flow,
// closing of video source, and re-init.
stopVideo();
startVideo();
}
}
int main(int argc, char *argv[])
{
#ifdef DEBUG
arLogLevel = AR_LOG_LEVEL_DEBUG;
#endif
// For mobile platforms, lock to portrait.
SDL_SetHint(SDL_HINT_ORIENTATIONS, "Portrait");
// Initialize SDL.
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
ARLOGe("Error: SDL initialisation failed. SDL error: '%s'.\n", SDL_GetError());
return -1;
}
// Preferences.
gPreferences = initPreferences();
gPreferenceCameraOpenToken = getPreferenceCameraOpenToken(gPreferences);
gPreferenceCameraResolutionToken = getPreferenceCameraResolutionToken(gPreferences);
gCalibrationSave = getPreferenceCalibrationSave(gPreferences);
gCalibrationSaveDir = getPreferenceCalibSaveDir(gPreferences);
gCalibrationServerUploadURL = getPreferenceCalibrationServerUploadURL(gPreferences);
gCalibrationServerAuthenticationToken = getPreferenceCalibrationServerAuthenticationToken(gPreferences);
gCalibrationPatternType = getPreferencesCalibrationPatternType(gPreferences);
gCalibrationPatternSize = getPreferencesCalibrationPatternSize(gPreferences);
gCalibrationPatternSpacing = getPreferencesCalibrationPatternSpacing(gPreferences);
// Allow command-line to override preferences.
init(argc, argv);
gSDLEventPreferencesChanged = SDL_RegisterEvents(1);
// Create a window.
gSDLWindow = SDL_CreateWindow("artoolkitX Camera Calibration Utility",
#ifndef HAVE_SDL3
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
#endif
1280, 720,
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE
#ifndef HAVE_SDL3
| SDL_WINDOW_ALLOW_HIGHDPI
#endif
);
if (!gSDLWindow) {
ARLOGe("Error creating window: %s.\n", SDL_GetError());
quit(-1);
}
// Create an OpenGL context to draw into. If OpenGL 3.2 not available, attempt to fall back to OpenGL 1.5, then OpenGL ES 2.0
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); // This is the default.
SDL_GL_SetSwapInterval(1);
#if HAVE_GL3
// SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
// SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
// SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
// gSDLContext = SDL_GL_CreateContext(gSDLWindow);
// if (gSDLContext) {
// drawAPI = ARG_API_GL3;
// ARLOGi("Created OpenGL 3.2+ context.\n");
// } else {
// ARLOGi("Unable to create OpenGL 3.2 context: %s. Will try OpenGL 1.5.\n", SDL_GetError());
#endif // HAVE_GL3
#if HAVE_GL
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 5);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, 0);
gSDLContext = SDL_GL_CreateContext(gSDLWindow);
if (gSDLContext) {
drawAPI = ARG_API_GL;
ARLOGi("Created OpenGL 1.5+ context.\n");
} else {
ARLOGi("Unable to create OpenGL 1.5 context: %s. Will try OpenGL ES 2.0\n", SDL_GetError());
#endif // HAVE_GL
#if HAVE_GLES2
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
gSDLContext = SDL_GL_CreateContext(gSDLWindow);
if (gSDLContext) {
drawAPI = ARG_API_GLES2;
ARLOGi("Created OpenGL ES 2.0+ context.\n");
} else {
ARLOGi("Unable to create OpenGL ES 2.0 context: %s.\n", SDL_GetError());
}
#endif // HAVE_GLES2
#if HAVE_GL
}
#endif
#if HAVE_GL3
// }
#endif
if (drawAPI == ARG_API_None) {
ARLOGe("No OpenGL context available. Giving up.\n", SDL_GetError());
quit(-1);
}
int w, h;
SDL_Window *window = SDL_GL_GetCurrentWindow();
#ifndef HAVE_SDL3
SDL_GL_GetDrawableSize(window, &w, &h);
#else
SDL_GetWindowSizeInPixels(window, &w, &h);
#endif
reshape(w, h);
#ifndef ANDROID
char *cachePath = arUtilGetResourcesDirectoryPath(AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_USE_APP_CACHE_DIR);
#else
char *cachePath = arUtilGetResourcesDirectoryPath(AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_USE_APP_CACHE_DIR, NULL);
arUtilChangeToResourcesDirectory(AR_UTIL_RESOURCES_DIRECTORY_BEHAVIOR_USE_SUPPLIED_PATH, cachePath, NULL);
#endif
asprintf(&gFileUploadQueuePath, "%s/%s", cachePath, QUEUE_DIR);
free(cachePath);
// Check for QUEUE_DIR and create if not already existing.
if (!fileUploaderCreateQueueDir(gFileUploadQueuePath)) {
ARLOGe("Error: Could not create queue directory.\n");
exit(-1);
}
if (gCalibrationServerUploadURL) {
fileUploadHandle = fileUploaderInit(gFileUploadQueuePath, QUEUE_INDEX_FILE_EXTENSION, gCalibrationServerUploadURL, UPLOAD_STATUS_HIDE_AFTER_SECONDS);
if (!fileUploadHandle) {
ARLOGe("Error: Could not initialise fileUploadHandle.\n");
}
fileUploaderTickle(fileUploadHandle);
}
// Calibration prefs.
ARLOGi("Calbration pattern size X = %d\n", gCalibrationPatternSize.width);
ARLOGi("Calbration pattern size Y = %d\n", gCalibrationPatternSize.height);
ARLOGi("Calbration pattern spacing = %f\n", gCalibrationPatternSpacing);
ARLOGi("Calibration image count maximum = %d\n", gPreferencesCalibImageCountMax);
// Library setup.
int contextsActiveCount = 1;
EdenMessageInit(contextsActiveCount);
EdenGLFontInit(contextsActiveCount);
EdenGLFontSetFont(EDEN_GL_FONT_ID_Stroke_Roman);
EdenGLFontSetupFontForContext(0, EDEN_GL_FONT_ID_Stroke_Roman);
EdenGLFontSetSize(FONT_SIZE);
// Get start time.
gettimeofday(&gStartTime, NULL);
#if HAVE_GLES2
if (drawAPI == ARG_API_GLES2 && !program) {
GLuint vertShader = 0, fragShader = 0;
// A simple shader pair which accepts just a vertex position. Fixed color, no lighting.
const char vertShaderString[] =
"attribute vec4 position;\n"
"uniform vec4 color;\n"
"uniform mat4 modelViewProjectionMatrix;\n"
"varying vec4 colorVarying;\n"
"void main()\n"
"{\n"
"gl_Position = modelViewProjectionMatrix * position;\n"
"colorVarying = color;\n"
"}\n";
const char fragShaderString[] =
"#ifdef GL_ES\n"
"precision mediump float;\n"
"#endif\n"
"varying vec4 colorVarying;\n"
"void main()\n"
"{\n"
"gl_FragColor = colorVarying;\n"
"}\n";
if (program) arglGLDestroyShaders(0, 0, program);
program = glCreateProgram();
if (!program) {
ARLOGe("draw: Error creating shader program.\n");
quit(-1);
}
if (!arglGLCompileShaderFromString(&vertShader, GL_VERTEX_SHADER, vertShaderString)) {
ARLOGe("draw: Error compiling vertex shader.\n");
arglGLDestroyShaders(vertShader, fragShader, program);
program = 0;
quit(-1);
}
if (!arglGLCompileShaderFromString(&fragShader, GL_FRAGMENT_SHADER, fragShaderString)) {
ARLOGe("draw: Error compiling fragment shader.\n");
arglGLDestroyShaders(vertShader, fragShader, program);
program = 0;
quit(-1);
}
glAttachShader(program, vertShader);
glAttachShader(program, fragShader);
glBindAttribLocation(program, ATTRIBUTE_VERTEX, "position");
if (!arglGLLinkProgram(program)) {
ARLOGe("draw: Error linking shader program.\n");
arglGLDestroyShaders(vertShader, fragShader, program);
program = 0;
quit(-1);
}
arglGLDestroyShaders(vertShader, fragShader, 0); // After linking, shader objects can be deleted.
// Retrieve linked uniform locations.
uniforms[UNIFORM_MODELVIEW_PROJECTION_MATRIX] = glGetUniformLocation(program, "modelViewProjectionMatrix");
uniforms[UNIFORM_COLOR] = glGetUniformLocation(program, "color");
}
#endif // HAVE_GLES2
startVideo();
// Main loop.
bool done = false;
while (!done) {
SDL_Event ev;
while (SDL_PollEvent(&ev)) {
if (ev.type ==
#ifndef HAVE_SDL3
SDL_QUIT
#else
SDL_EVENT_QUIT
#endif
/*|| (ev.type == SDL_KEYDOWN && ev.key.keysym.sym == SDLK_ESCAPE)*/) {
done = true;
break;
#ifndef HAVE_SDL3
} else if (ev.type == SDL_WINDOWEVENT) {
//ARLOGd("Window event %d.\n", ev.window.event);
if (ev.window.event == SDL_WINDOWEVENT_RESIZED && ev.window.windowID == SDL_GetWindowID(gSDLWindow)) {
//int32_t w = ev.window.data1;
//int32_t h = ev.window.data2;
int w, h;
SDL_GL_GetDrawableSize(gSDLWindow, &w, &h);
reshape(w, h);
}
#else
} else if (ev.type == SDL_EVENT_WINDOW_RESIZED) {
//ARLOGd("Window resized event %d.\n", ev.window.event);
if (ev.window.windowID == SDL_GetWindowID(gSDLWindow)) {
//int32_t w = ev.window.data1;
//int32_t h = ev.window.data2;
int w, h;
SDL_GetWindowSizeInPixels(gSDLWindow, &w, &h);
reshape(w, h);
}
#endif
} else if (ev.type ==
#ifndef HAVE_SDL3
SDL_KEYDOWN
#else
SDL_EVENT_KEY_DOWN
#endif
) {
if (EdenMessageKeyboardRequired()) {
EdenMessageInputKeyboard(ev.key.keysym.sym);
} else if (ev.key.keysym.sym == SDLK_ESCAPE) {
flowHandleEvent(EVENT_BACK_BUTTON);
} else if (ev.key.keysym.sym == SDLK_SPACE) {
flowHandleEvent(EVENT_TOUCH);
} else if ((ev.key.keysym.sym == SDLK_COMMA && (ev.key.keysym.mod &
#ifndef HAVE_SDL3
KMOD_LGUI
#else
SDL_KMOD_LGUI
#endif
)) || ev.key.keysym.sym == SDLK_p) {
showPreferences(gPreferences);
}
} else if (gSDLEventPreferencesChanged != 0 && ev.type == gSDLEventPreferencesChanged) {
rereadPreferences();
}
}
if (vs->isOpen()) {
if (vs->captureFrame()) {
gFrameCount++; // Increment ARToolKit FPS counter.
#ifdef DEBUG
if (gFrameCount % 150 == 0) {
ARLOGi("*** Camera - %f (frame/sec)\n", (double)gFrameCount/arUtilTimer());
gFrameCount = 0;
arUtilTimerReset();
}
#endif
if (!gPostVideoSetupDone) {
#ifdef ANDROID
char *toast;
if (asprintf(&toast, "Camera: %dx%d", vs->getVideoWidth(), vs->getVideoHeight()) < 0) {
ARLOGe("asprintf");
} else {
SDL_AndroidShowToast(toast, 1, -1, 0, 0); // int duration = 1 = long, int gravity = -1 = don't care, int xoffset, int yoffset
free(toast);
}
#endif
gCameraIsFrontFacing = false;
AR2VideoParamT *vid = vs->getAR2VideoParam();
if (vid->module == AR_VIDEO_MODULE_AVFOUNDATION) {
int frontCamera;
if (ar2VideoGetParami(vid, AR_VIDEO_PARAM_AVFOUNDATION_CAMERA_POSITION, &frontCamera) >= 0) {
gCameraIsFrontFacing = (frontCamera == AR_VIDEO_AVFOUNDATION_CAMERA_POSITION_FRONT);
ARLOGi("Camera is %sfront-facing.\n", gCameraIsFrontFacing ? "" : "not ");
}
} else if (vid->module == AR_VIDEO_MODULE_ANDROID) {
int frontCamera;
if (ar2VideoGetParami(vid, AR_VIDEO_PARAM_ANDROID_CAMERA_FACE, &frontCamera) >= 0) {
gCameraIsFrontFacing = (frontCamera == AR_VIDEO_ANDROID_CAMERA_FACE_FRONT);
ARLOGi("Camera is %sfront-facing.\n", gCameraIsFrontFacing ? "" : "not ");
}
}
bool contentRotate90, contentFlipV, contentFlipH;
if (gDisplayOrientation == 1) { // Landscape with top of device at left.
contentRotate90 = false;
contentFlipV = gCameraIsFrontFacing;
contentFlipH = gCameraIsFrontFacing;
} else if (gDisplayOrientation == 2) { // Portrait upside-down.
contentRotate90 = true;
contentFlipV = !gCameraIsFrontFacing;
contentFlipH = true;
} else if (gDisplayOrientation == 3) { // Landscape with top of device at right.
contentRotate90 = false;
contentFlipV = !gCameraIsFrontFacing;
contentFlipH = (!gCameraIsFrontFacing);
} else /*(gDisplayOrientation == 0)*/ { // Portait
contentRotate90 = true;
contentFlipV = false;
contentFlipH = gCameraIsFrontFacing;
}
// Setup a route for rendering the colour background image.
vv = new ARVideoView;
if (!vv) {
ARLOGe("Error: unable to create video view.\n");
quit(-1);
}
vv->setRotate90(contentRotate90);
vv->setFlipH(contentFlipH);
vv->setFlipV(contentFlipV);
vv->setScalingMode(ARVideoView::ScalingMode::SCALE_MODE_FIT);
vv->initWithVideoSource(*vs, contextWidth, contextHeight);
ARLOGi("Content %dx%d (wxh) will display in GL context %dx%d%s.\n", vs->getVideoWidth(), vs->getVideoHeight(), contextWidth, contextHeight, (contentRotate90 ? " rotated" : ""));
vv->getViewport(gViewport);
// Setup a route for rendering the mono background image.
ARParam idealParam;
arParamClear(&idealParam, vs->getVideoWidth(), vs->getVideoHeight(), AR_DIST_FUNCTION_VERSION_DEFAULT);
if ((gArglSettingsCornerFinderImage = arglSetupForCurrentContext(&idealParam, AR_PIXEL_FORMAT_MONO)) == NULL) {
ARLOGe("Unable to setup argl.\n");
quit(-1);
}
if (!arglDistortionCompensationSet(gArglSettingsCornerFinderImage, FALSE)) {
ARLOGe("Unable to setup argl.\n");
quit(-1);
}
arglSetRotate90(gArglSettingsCornerFinderImage, contentRotate90);
arglSetFlipV(gArglSettingsCornerFinderImage, contentFlipV);
arglSetFlipH(gArglSettingsCornerFinderImage, contentFlipH);
//
// Calibration init.
//
gCalibration = new Calibration(gCalibrationPatternType, gPreferencesCalibImageCountMax, gCalibrationPatternSize, gCalibrationPatternSpacing, vs->getVideoWidth(), vs->getVideoHeight());
if (!gCalibration) {
ARLOGe("Error initialising calibration.\n");
quit(-1);
}
if (!flowInitAndStart(gCalibration, saveParam, NULL)) {
ARLOGe("Error: Could not initialise and start flow.\n");
quit(-1);
}
// For FPS statistics.
arUtilTimerReset();
gFrameCount = 0;
gPostVideoSetupDone = true;
} // !gPostVideoSetupDone
if (contextWasUpdated) {
vv->setContextSize({contextWidth, contextHeight});
vv->getViewport(gViewport);
}
FLOW_STATE state = flowStateGet();
if (state == FLOW_STATE_WELCOME || state == FLOW_STATE_DONE || state == FLOW_STATE_CALIBRATING) {
// Upload the frame to OpenGL.
// Now done as part of the draw call.
} else if (state == FLOW_STATE_CAPTURING) {
gCalibration->frame(vs);
}
}
} // vs->isOpen()
// The display has changed.
drawView();
arUtilSleep(1); // 1 millisecond.
}
stopVideo();
quit(0);
}
void reshape(int w, int h)
{
contextWidth = w;
contextHeight = h;
ARLOGd("Resized to %dx%d.\n", w, h);
contextWasUpdated = true;
}
static void quit(int rc)
{
fileUploaderFinal(&fileUploadHandle);
SDL_Quit();
free(gPreferenceCameraOpenToken);
free(gPreferenceCameraResolutionToken);
free(gCalibrationServerUploadURL);
free(gCalibrationServerAuthenticationToken);
preferencesFinal(&gPreferences);
exit(rc);
}
static void usage(char *com)
{
ARPRINT("Usage: %s [options]\n", com);
ARPRINT("Options:\n");
ARPRINT(" --vconf <video parameter for the camera>\n");
ARPRINT(" -cornerx=n: specify the number of corners on chessboard in X direction.\n");
ARPRINT(" -cornery=n: specify the number of corners on chessboard in Y direction.\n");
ARPRINT(" -imagenum=n: specify the number of images captured for calibration.\n");
ARPRINT(" -pattwidth=n: specify the square width in the chessbaord.\n");
ARPRINT(" -h -help --help: show this message\n");
exit(0);
}
static void init(int argc, char *argv[])
{
int i;
int gotTwoPartOption;
char *vconf = NULL;
int cornerNumX = 0;
int cornerNumY = 0;
int calibImageNum = 0;
float patternWidth = 0.0f;
char *cwd = NULL;
arMalloc(cwd, char, MAXPATHLEN);
if (!getcwd(cwd, MAXPATHLEN)) ARLOGe("Unable to read current working directory.\n");
else ARPRINT("Current working directory is '%s'\n", cwd);
free(cwd);
i = 1; // argv[0] is name of app, so start at 1.
while (i < argc) {
gotTwoPartOption = FALSE;
// Look for two-part options first.
if ((i + 1) < argc) {
if (strcmp(argv[i], "--vconf") == 0) {
i++;
vconf = argv[i];
gotTwoPartOption = TRUE;
}
}
if (!gotTwoPartOption) {
// Look for single-part options.
if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "-h") == 0) {
usage(argv[0]);
} else if (strcmp(argv[i], "--version") == 0 || strcmp(argv[i], "-version") == 0 || strcmp(argv[i], "-v") == 0) {
ARPRINT("%s version %s\n", argv[0], AR_HEADER_VERSION_STRING);
exit(0);
} else if( strncmp(argv[i], "-cornerx=", 9) == 0 ) {
if( sscanf(&(argv[i][9]), "%d", &cornerNumX) != 1 ) usage(argv[0]);
if( cornerNumX <= 0 ) usage(argv[0]);
} else if( strncmp(argv[i], "-cornery=", 9) == 0 ) {
if( sscanf(&(argv[i][9]), "%d", &cornerNumY) != 1 ) usage(argv[0]);
if( cornerNumY <= 0 ) usage(argv[0]);
} else if( strncmp(argv[i], "-imagenum=", 10) == 0 ) {
if( sscanf(&(argv[i][10]), "%d", &calibImageNum) != 1 ) usage(argv[0]);
if( calibImageNum <= 0 ) usage(argv[0]);
} else if( strncmp(argv[i], "-pattwidth=", 11) == 0 ) {
if( sscanf(&(argv[i][11]), "%f", &patternWidth) != 1 ) usage(argv[0]);
if( patternWidth <= 0.0 ) usage(argv[0]);
} else {
ARLOGe("Error: invalid command line argument '%s'.\n", argv[i]);
usage(argv[0]);
}
}
i++;
}
if (cornerNumX != 0) {
ARPRINT("gCalibrationPatternSize.width = %d\n", cornerNumX);
gCalibrationPatternSize.width = cornerNumX;
}
if (cornerNumY != 0) {
ARPRINT("gCalibrationPatternSize.height = %d\n", cornerNumY);
gCalibrationPatternSize.height = cornerNumY;
}
if (patternWidth != 0.0f) {
ARPRINT("gCalibrationPatternSpacing = %f\n", patternWidth);
gCalibrationPatternSpacing = patternWidth;
}
if (calibImageNum != 0) {
ARPRINT("gPreferencesCalibImageCountMax = %d\n", calibImageNum);
gPreferencesCalibImageCountMax = calibImageNum;
}
if (vconf != NULL) {
ARPRINT("gPreferenceCameraOpenToken = '%s'\n", vconf);
free(gPreferenceCameraOpenToken);
gPreferenceCameraOpenToken = strdup(vconf);
free(gPreferenceCameraResolutionToken);
gPreferenceCameraResolutionToken = NULL;
}
}
static void drawBackground(const float width, const float height, const float x, const float y, const bool drawBorder, const GLfloat p[16])
{
GLfloat vertices[4][2];
#if HAVE_GLES2
GLfloat colorBlack50[4] = {0.0f, 0.0f, 0.0f, 0.5f}; // 50% transparent black.
GLfloat colorWhite[4] = {1.0f, 1.0f, 1.0f, 1.0f}; // Opaque white.
#endif // HAVE_GLES2
vertices[0][0] = x; vertices[0][1] = y;
vertices[1][0] = width + x; vertices[1][1] = y;
vertices[2][0] = width + x; vertices[2][1] = height + y;
vertices[3][0] = x; vertices[3][1] = height + y;
#if !HAVE_GLES2
glLoadIdentity(); // Reset to ortho origin. Assumes MODELVIEW mode.
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
glVertexPointer(2, GL_FLOAT, 0, vertices);
glEnableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glClientActiveTexture(GL_TEXTURE0);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glColor4f(0.0f, 0.0f, 0.0f, 0.5f); // 50% transparent black.
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
if (drawBorder) {
glColor4f(1.0f, 1.0f, 1.0f, 1.0f); // Opaque white.
glLineWidth(1.0f);
glDrawArrays(GL_LINE_LOOP, 0, 4);
}
#else
glUseProgram(program);
glUniformMatrix4fv(uniforms[UNIFORM_MODELVIEW_PROJECTION_MATRIX], 1, GL_FALSE, p);
glStateCacheDisableDepthTest();
glStateCacheBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glStateCacheEnableBlend();
glVertexAttribPointer(ATTRIBUTE_VERTEX, 2, GL_FLOAT, GL_FALSE, 0, vertices);
glEnableVertexAttribArray(ATTRIBUTE_VERTEX);
glUniform4fv(uniforms[UNIFORM_COLOR], 1, colorBlack50);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
if (drawBorder) {
glUniform4fv(uniforms[UNIFORM_COLOR], 1, colorWhite);
glLineWidth(1.0f);
glDrawArrays(GL_LINE_LOOP, 0, 4);
}
#endif // !HAVE_GLES2
}
// An animation while we're waiting.
// Designed to be drawn on background of at least 3xsquareSize wide and tall.
static void drawBusyIndicator(int positionX, int positionY, int squareSize, struct timeval *tp, const GLfloat p[16])
{
const GLfloat square_vertices [4][2] = { {0.5f, 0.5f}, {squareSize - 0.5f, 0.5f}, {squareSize - 0.5f, squareSize - 0.5f}, {0.5f, squareSize - 0.5f} };
int i;
int hundredthSeconds = (int)tp->tv_usec / 1E4;
int secDiv255 = (int)tp->tv_usec / 3921;
int secMod6 = tp->tv_sec % 6;
// Set up drawing.
#if !HAVE_GLES2
glPushMatrix();
glLoadIdentity();
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
glVertexPointer(2, GL_FLOAT, 0, square_vertices);
glEnableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glClientActiveTexture(GL_TEXTURE0);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
#else
GLfloat mvp[16];
glStateCacheDisableDepthTest();
glStateCacheDisableBlend();
glVertexAttribPointer(ATTRIBUTE_VERTEX, 2, GL_FLOAT, GL_FALSE, 0, square_vertices);
glEnableVertexAttribArray(ATTRIBUTE_VERTEX);
#endif
for (i = 0; i < 4; i++) {
float tx = (float)(positionX + ((i + 1)/2 != 1 ? -squareSize : 0.0f));
float ty = (float)(positionY + (i / 2 == 0 ? 0.0f : -squareSize));
#if !HAVE_GLES2
glLoadIdentity();
glTranslatef(tx, ty , 0.0f); // Order: UL, UR, LR, LL.
#else
mtxLoadMatrixf(mvp, p);
mtxTranslatef(mvp, tx, ty, 0.0f);
glUseProgram(program);
glUniformMatrix4fv(uniforms[UNIFORM_MODELVIEW_PROJECTION_MATRIX], 1, GL_FALSE, mvp);
#endif
if (i == hundredthSeconds / 25) {
unsigned char r, g, b;
if (secMod6 == 0) {
r = 255; g = secDiv255; b = 0;
} else if (secMod6 == 1) {
r = secDiv255; g = 255; b = 0;
} else if (secMod6 == 2) {
r = 0; g = 255; b = secDiv255;
} else if (secMod6 == 3) {
r = 0; g = secDiv255; b = 255;
} else if (secMod6 == 4) {
r = secDiv255; g = 0; b = 255;
} else {
r = 255; g = 0; b = secDiv255;
}
#if !HAVE_GLES2
glColor4ub(r, g, b, 255);
#else
const float color[4] = {(float)r/255.0f, (float)g/255.0f, (float)b/255.0f, 1.0f};
glUniform4fv(uniforms[UNIFORM_COLOR], 1, color);
#endif
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}
#if !HAVE_GLES2