-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.cpp
2199 lines (2033 loc) · 79.8 KB
/
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
/*
// ATM-Software-CPP © Radu Salagean 2015
//
// Rebuild & Port by XtremePrime 2021:
// -- In the spirit of the original, all code was kept in one .cpp file
// -- Ported from SFML 2.2 to SFML 2.5.1
// -- Increased the readability and modularity
// -- Future proofed for cross-platform
//
// Android port: March 2022 - Radu Salagean
*/
//- Platform definitions
#if defined(_WIN32) || defined(_WIN64)
#define TARGET_WIN
#elif defined(TARGET_OS_MAC)
#define TARGET_MAC
#elif defined(__ANDROID__)
#define TARGET_ANDROID
#elif defined(__linux__) || defined(__unix__)
#define TARGET_LINUX
#endif
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <ctime>
#include <cmath>
#include <SFML/System.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#ifdef TARGET_WIN
#define NOMINMAX
// #include <windows.h>
#endif //_WIN32
#ifdef TARGET_ANDROID
#include <android/asset_manager.h>
#include <android/log.h>
#include <jni.h>
#include <android/native_activity.h>
#include <SFML/System/NativeActivity.hpp>
#endif
#ifdef TARGET_ANDROID
#define SHOW_CURSOR
class AndroidGlue
{
private:
// General
ANativeActivity* nativeActivityHandle;
JavaVM* vm;
JNIEnv* env;
// Vibrate
jobject vibrateObject;
jmethodID vibrateMethod;
void init()
{
// First we'll need the native activity handle
nativeActivityHandle = sf::getNativeActivity();
// Retrieve the AssetManager so we can read resources from the APK
assetManager = nativeActivityHandle->assetManager;
// Retrieve the JVM and JNI environment
vm = nativeActivityHandle->vm;
env = nativeActivityHandle->env;
// Attach this thread to the main thread
attachToMainThread();
// Retrieve class information
jclass nativeActivity = env->FindClass("android/app/NativeActivity");
jclass context = env->FindClass("android/content/Context");
initVibration(context, nativeActivity);
// Free references
env->DeleteLocalRef(context);
env->DeleteLocalRef(nativeActivity);
}
bool attachToMainThread()
{
JavaVMAttachArgs attachargs;
attachargs.version = JNI_VERSION_1_6;
attachargs.name = "NativeThread";
attachargs.group = nullptr;
jint res = vm->AttachCurrentThread(&env, &attachargs);
if (res == JNI_ERR)
return false;
return true;
}
void initVibration(jclass context, jclass nativeActivity)
{
// Get the value of a constant
jfieldID vibratorServiceFieldId = env->GetStaticFieldID(context, "VIBRATOR_SERVICE", "Ljava/lang/String;");
jobject vibratorServiceObject = env->GetStaticObjectField(context, vibratorServiceFieldId);
// Get the method 'getSystemService' and call it
jmethodID getSystemServiceMethodId = env->GetMethodID(nativeActivity, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
vibrateObject = env->CallObjectMethod(nativeActivityHandle->clazz, getSystemServiceMethodId, vibratorServiceObject);
// Get the object's class and retrieve the member name
jclass vibrateClass = env->GetObjectClass(vibrateObject);
vibrateMethod = env->GetMethodID(vibrateClass, "vibrate", "(J)V");
// Free references
env->DeleteLocalRef(vibrateClass);
env->DeleteLocalRef(vibratorServiceObject);
}
public:
// Asset Manager
AAssetManager* assetManager;
AndroidGlue()
{
init();
}
void vibrate(int durationMillis)
{
jlong durationMillisJlong = durationMillis;
// Bzzz!
env->CallVoidMethod(vibrateObject, vibrateMethod, durationMillisJlong);
}
void release()
{
// Free references
env->DeleteLocalRef(vibrateObject);
// Detach thread again
vm->DetachCurrentThread();
}
};
#endif
struct Animation
{
virtual void update(sf::Time deltaTime) = 0;
virtual bool isEnded() = 0;
virtual ~Animation() = default;
};
template <class T>
class GenericAnimation : public Animation
{
private:
bool ended = false;
protected:
sf::Time duration;
sf::Clock runningTimeClock;
std::function<void(T animatedProperty)> onUpdateCallback;
std::function<void()> onAnimationEndCallback;
GenericAnimation(sf::Time duration,
std::function<void(T)> onUpdateCallback,
std::function<void()> onAnimationEndCallback)
{
this->duration = duration;
this->onUpdateCallback = onUpdateCallback;
this->onAnimationEndCallback = onAnimationEndCallback;
}
bool isEnded()
{
return ended;
}
virtual void onAnimationEnd()
{
ended = true;
if (onAnimationEndCallback) onAnimationEndCallback();
}
public:
virtual ~GenericAnimation() = default;
};
class AlphaAnimation : public GenericAnimation<int>
{
private:
float targetAlpha;
float currentAlpha;
float alphaDiff;
void setAlpha(float alpha)
{
float sanitizedAlpha;
if (alphaDiff > 0.f)
sanitizedAlpha = std::min(targetAlpha, alpha);
else
sanitizedAlpha = std::max(targetAlpha, alpha);
this->currentAlpha = sanitizedAlpha;
onUpdateCallback(sanitizedAlpha);
}
int getSanitizedColorComponent(int component) {
return std::max(0, std::min(255, component));
}
public:
AlphaAnimation(sf::Time duration, int startAlpha, int targetAlpha,
std::function<void(int)> onUpdateCallback,
std::function<void()> onAnimationEndCallback = {}) :
GenericAnimation(duration, onUpdateCallback, onAnimationEndCallback)
{
int startAlphaSafe = getSanitizedColorComponent(startAlpha);
int targetAlphaSafe = getSanitizedColorComponent(targetAlpha);
this->alphaDiff = targetAlphaSafe - startAlphaSafe;
this->targetAlpha = targetAlphaSafe;
setAlpha(startAlphaSafe);
}
~AlphaAnimation() = default;
void update(sf::Time deltaTime)
{
if (isEnded()) return;
if (runningTimeClock.getElapsedTime() <= duration)
{
float currentAlphaDiff = (deltaTime * (float) alphaDiff) / duration;
float newAlpha = currentAlpha + currentAlphaDiff;
setAlpha(newAlpha);
} else {
onAnimationEnd();
}
}
};
enum class OffsetAnimationUpdateType
{
SET_POSITION,
MOVE
};
struct OffsetAnimationUpdate
{
OffsetAnimationUpdateType type;
sf::Vector2f value;
};
class OffsetAnimation : public GenericAnimation<OffsetAnimationUpdate>
{
private:
sf::Vector2f getSafeIncrementalOffset(sf::Vector2f proposedOffset)
{
sf::Vector2f safeOffset;
sf::Vector2f availableSpace = targetOffset - cumulatedOffset;
if (targetOffset.x > 0.f)
safeOffset.x = std::min(availableSpace.x, proposedOffset.x);
else
safeOffset.x = std::max(availableSpace.x, proposedOffset.x);
if (targetOffset.y > 0.f)
safeOffset.y = std::min(availableSpace.y, proposedOffset.y);
else
safeOffset.y = std::max(availableSpace.y, proposedOffset.y);
return safeOffset;
}
protected:
sf::Vector2f targetOffset;
sf::Vector2f cumulatedOffset;
public:
OffsetAnimation(sf::Time duration,
std::function<void(OffsetAnimationUpdate)> onUpdateCallback,
std::function<void()> onAnimationEndCallback) :
GenericAnimation(duration, onUpdateCallback, onAnimationEndCallback) {}
OffsetAnimation(sf::Time duration,
sf::Vector2f startPosition,
sf::Vector2f targetOffset,
std::function<void(OffsetAnimationUpdate)> onUpdateCallback,
std::function<void()> onAnimationEndCallback) :
GenericAnimation(duration, onUpdateCallback, onAnimationEndCallback)
{
onUpdateCallback(OffsetAnimationUpdate {
OffsetAnimationUpdateType::SET_POSITION, startPosition
});
this->targetOffset = targetOffset;
}
virtual ~OffsetAnimation() = default;
void update(sf::Time deltaTime)
{
if (isEnded()) return;
if (runningTimeClock.getElapsedTime() <= duration)
{
float offsetX = (deltaTime * targetOffset.x) / duration;
float offsetY = (deltaTime * targetOffset.y) / duration;
sf::Vector2f safeIncrementalOffset = getSafeIncrementalOffset(sf::Vector2f(offsetX, offsetY));
this->cumulatedOffset += safeIncrementalOffset;
onUpdateCallback(OffsetAnimationUpdate {
OffsetAnimationUpdateType::MOVE, safeIncrementalOffset
});
} else {
onAnimationEnd();
}
}
};
enum VerticalOffsetAnimationType
{
TOP_TO_ORIGIN,
ORIGIN_TO_TOP
};
class VerticalOffsetAnimation : public OffsetAnimation
{
public:
VerticalOffsetAnimation(
sf::Time duration,
sf::Vector2f originPosition,
VerticalOffsetAnimationType type,
float animatedSubjectHeight,
std::function<void(OffsetAnimationUpdate)> onUpdateCallback,
std::function<void()> onAnimationEndCallback
) : OffsetAnimation(duration, onUpdateCallback, onAnimationEndCallback)
{
switch (type) {
case VerticalOffsetAnimationType::TOP_TO_ORIGIN:
onUpdateCallback({
OffsetAnimationUpdateType::SET_POSITION,
sf::Vector2f(originPosition.x, originPosition.y - animatedSubjectHeight)
});
this->targetOffset = sf::Vector2f(0, animatedSubjectHeight);
break;
case VerticalOffsetAnimationType::ORIGIN_TO_TOP:
onUpdateCallback({
OffsetAnimationUpdateType::SET_POSITION,
originPosition
});
this->targetOffset = sf::Vector2f(0, -animatedSubjectHeight);
break;
}
}
~VerticalOffsetAnimation() = default;
};
class ActionTimer
{
private:
sf::Clock clock;
sf::Time targetDuration;
std::function<void()> callback;
public:
ActionTimer(sf::Time targetDuration, std::function<void()> callback)
{
this->targetDuration = targetDuration;
this->callback = callback;
}
void update()
{
sf::Time elapsedTime = clock.getElapsedTime();
if (elapsedTime <= targetDuration) return;
callback();
}
};
void handleOffsetAnimationUpdate(sf::Sprite* sprite, OffsetAnimationUpdate* update)
{
switch (update->type)
{
case OffsetAnimationUpdateType::SET_POSITION:
sprite->setPosition(update->value);
break;
case OffsetAnimationUpdateType::MOVE:
sprite->move(update->value);
break;
}
}
class Atm
{
private:
//- Title and Version
std::string title = "ATM Software RELOADED";
std::string ver = "1.1";
//- Screen Size
const int CANVAS_WIDTH = 960, CANVAS_HEIGHT = 620;
sf::Vector2u currentWindowSize;
//- States
bool cardVisible = true, cashLargeVisible = false, cashSmallVisible = false, receiptVisible = false;
unsigned short int scrState = 1;
unsigned short int pin = 0; unsigned short int pinCount = 0; unsigned short int pinRetry = 0;
int amount = 0; unsigned short int amountCount = 0;
bool blocked = false;
bool accountSuspendedFlag = false;
bool windowHasFocus = true;
//- User Data Structure
struct User
{
std::string iban;
std::string lastName;
std::string firstName;
unsigned short int pin;
unsigned long long int balance;
};
//- General
sf::View view;
sf::VideoMode screen;
sf::RenderWindow window;
sf::Event event;
sf::Font font;
sf::Time elapsed;
//- Textures and Sprites
sf::Texture backgroundTexture; sf::Sprite backgroundSprite;
sf::Texture cardTexture; sf::Sprite cardSprite;
sf::Vector2f cardSpritePosition = sf::Vector2f(740, 198);
sf::RectangleShape cardMask;
sf::Texture cashLargeTexture; sf::Sprite cashLargeSprite;
sf::Vector2f cashLargeSpritePosition = sf::Vector2f(90, 370);
sf::RectangleShape cashLargeMask;
sf::Texture cashSmallTexture; sf::Sprite cashSmallSprite;
sf::Vector2f cashSmallSpritePosition = sf::Vector2f(695, 463);
sf::RectangleShape cashSmallMask;
sf::Texture receiptTexture; sf::Sprite receiptSprite;
sf::Vector2f receiptSpritePosition = sf::Vector2f(740, 54);
sf::RectangleShape receiptMask;
//- Sound Buffers and Sounds
sf::SoundBuffer cardSndBuf; sf::Sound cardSnd;
sf::SoundBuffer menuSndBuf; sf::Sound menuSnd;
sf::SoundBuffer clickSndBuf; sf::Sound clickSnd;
sf::SoundBuffer keySndBuf; sf::Sound keySnd;
sf::SoundBuffer cashSndBuf; sf::Sound cashSnd;
sf::SoundBuffer printReceiptSndBuf; sf::Sound printReceiptSnd;
//- Processing Time
sf::Time processingTime = sf::seconds(2);
//- Text
sf::Text scrClock;
sf::Text usernameScr;
sf::Text ibanScr;
sf::Text L1Txt;
sf::Text R1Txt;
sf::Text R3Txt;
sf::Text dialog;
sf::Text liveTxt;
//- Shapes
sf::RectangleShape pinBorderShape;
sf::RectangleShape amountBorderShape;
//- Users
std::vector<User> users;
User* user;
//- Text files
const std::string databasePath = "database/database.txt";
std::stringstream database;
std::ofstream log;
//- Out String Stream
std::ostringstream oss;
//- Screen Info Strings
std::ostringstream usernameScrStr;
std::ostringstream ibanScrStr;
std::ostringstream convert;
std::ostringstream balance;
//- Chat arrays for live text
std::string pinLiveTxt = "****"; std::string amountLiveTxt = "";
//- Outstanding Click / Touch Event
sf::Vector2i* outstandIngInteractionEvent;
//- Cursor
const int CURSOR_CIRCLE_RADIUS = 16;
sf::CircleShape cursorCircle = sf::CircleShape(CURSOR_CIRCLE_RADIUS);
sf::Color cursorCircleIdleColor = sf::Color(255, 0, 0, 0);
//- Action Timer
ActionTimer* actionTimer;
//- Animations
std::list<Animation*> runningAnimations;
Animation* cursorAnimation = nullptr;
// this is different than the card sound time because the end click is not at the end of the sound
sf::Time cardAnimationTime = sf::milliseconds(1002);
sf::Time cursorFadeOutAnimationTime = sf::seconds(1.5);
//- Frame Delta Clock
sf::Clock frameDeltaClock;
//- Routine Action Codes
enum RoutineCode {
CARD_IN = 1,
CARD_OUT = 2,
KEY_SOUND = 3,
MENU_SOUND = 4,
CASH_LARGE_OUT = 5,
CASH_SMALL_IN = 6,
RECEIPT_OUT = 7
};
//- Vibration Length
enum VibrationDuration {
SHORT = 20,
MEDIUM = 40
};
#ifdef TARGET_ANDROID
AndroidGlue androidGlue;
#endif
void initWin()
{
#ifdef TARGET_ANDROID // We support letterbox mode on Android devices
screen = sf::VideoMode(sf::VideoMode::getDesktopMode());
view.setSize(CANVAS_WIDTH, CANVAS_HEIGHT);
view.setCenter(view.getSize().x / 2, view.getSize().y / 2);
view = getLetterboxView(view, screen.width, screen.height);
window.create(screen, "");
window.setView(view);
#else
screen = sf::VideoMode(CANVAS_WIDTH, CANVAS_HEIGHT);
window.create(screen, programTitle(), sf::Style::Titlebar | sf::Style::Close);
#endif
window.setFramerateLimit(60);
window.setKeyRepeatEnabled(false);
currentWindowSize = window.getSize();
}
// https://github.com/SFML/SFML/wiki/Source:-Letterbox-effect-using-a-view
sf::View getLetterboxView(sf::View view, int windowWidth, int windowHeight) {
// Compares the aspect ratio of the window to the aspect ratio of the view,
// and sets the view's viewport accordingly in order to achieve a letterbox effect.
// A new view (with a new viewport set) is returned.
float windowRatio = windowWidth / (float) windowHeight;
float viewRatio = view.getSize().x / (float) view.getSize().y;
float sizeX = 1;
float sizeY = 1;
float posX = 0;
float posY = 0;
bool horizontalSpacing = true;
if (windowRatio < viewRatio)
horizontalSpacing = false;
// If horizontalSpacing is true, the black bars will appear on the left and right side.
// Otherwise, the black bars will appear on the top and bottom.
if (horizontalSpacing)
{
sizeX = viewRatio / windowRatio;
posX = (1 - sizeX) / 2.f;
}
else
{
sizeY = windowRatio / viewRatio;
posY = (1 - sizeY) / 2.f;
}
view.setViewport(sf::FloatRect(posX, posY, sizeX, sizeY));
return view;
}
sf::Vector2i* getScaledPointerCoordinates(int originalX, int originalY)
{
#ifdef TARGET_ANDROID
int left = view.getViewport().left * currentWindowSize.x;
int top = view.getViewport().top * currentWindowSize.y;
float scaleX = (currentWindowSize.x - 2 * left) / (float) CANVAS_WIDTH;
float scaleY = (currentWindowSize.y - 2 * top) / (float) CANVAS_HEIGHT;
int processedX = (originalX - left) / scaleX;
int processedY = (originalY - top) / scaleY;
return new sf::Vector2i(processedX, processedY);
#else
return new sf::Vector2i(originalX, originalY);
#endif
}
void loadDatabase()
{
#ifdef TARGET_ANDROID
// In order to properly read asset files in android, we use the Asset NDK Module
// Links:
// https://developer.android.com/ndk/reference/group/asset
// https://stackoverflow.com/a/33957074
if (androidGlue.assetManager != nullptr)
{
// Open your file
std::string filePath = res(databasePath);
AAsset* file = AAssetManager_open(androidGlue.assetManager, filePath.c_str(), AASSET_MODE_BUFFER);
// Get the file length
size_t fileLength = AAsset_getLength(file);
// Allocate memory to read your file
char* fileContent = new char[fileLength + 1];
// Read your file
AAsset_read(file, fileContent, fileLength);
// For safety you can add a 0 terminating character at the end of your file ...
fileContent[fileLength] = '\0';
// Do whatever you want with the content of the file
database << fileContent;
// Free the memory you allocated earlier
delete [] fileContent;
}
#else
std::ifstream fileStream(res(databasePath));
if (fileStream.is_open())
{
database << fileStream.rdbuf();
fileStream.close();
}
#endif
if (database.tellp() > std::streampos(0))
{
oss << getTimeCli() << "User database loaded"; logMsg(oss.str());
loadClients();
}
else
{
oss << getTimeCli() << "User database not found"; logMsg(oss.str());
loadPlaceholderClient();
}
}
void init()
{
//- Create new log file
#ifndef TARGET_ANDROID
log.open(getLogFileName().c_str());
#endif
//- Init States
initStates();
//- Initialize Window
initWin();
//- Initialize CLI
system("color 0A");
oss << "================================================================================"; logMsg(oss.str());
oss << "==================================ATM Software=================================="; logMsg(oss.str());
oss << "================================================================================"; logMsg(oss.str());
oss << getTimeCli() << "ATM is now powered on"; logMsg(oss.str());
//- Load database
loadDatabase();
//- Load fonts
if (font.loadFromFile(res("courier_new.ttf")))
{
oss << getTimeCli() << "Font loaded"; logMsg(oss.str());
}
else
{
oss << getTimeCli() << "Font not found"; logMsg(oss.str());
window.close();
}
//- Load textures
if (!backgroundTexture.loadFromFile(res("backgnd_texture.png")) ||
!cardTexture.loadFromFile(res("card_texture.png")) ||
!cashLargeTexture.loadFromFile(res("cash_large_texture.jpg")) ||
!cashSmallTexture.loadFromFile(res("cash_small_texture.jpg")) ||
!receiptTexture.loadFromFile(res("receipt_texture.jpg")))
{
oss << getTimeCli() << "One or more textures not found"; logMsg(oss.str());
window.close();
}
else
{
oss << getTimeCli() << "Textures loaded"; logMsg(oss.str());
}
//- Load sounds in the sound buffer
std::vector<sf::SoundBuffer*> soundPtr = { &cardSndBuf, &menuSndBuf, &clickSndBuf, &keySndBuf, &cashSndBuf, &printReceiptSndBuf };
std::vector<std::string> soundArr = {
res("card_snd.wav"),
res("menu_snd.wav"),
res("click_snd.wav"),
res("key_snd.wav"),
res("cash_snd.wav"),
res("print_receipt_snd.wav")
};
bool soundOk = true;
for (int i = 0; i < soundPtr.size(); ++i)
{
if (!soundPtr[i]->loadFromFile(soundArr[i]))
{
oss << getTimeCli() << "\"" << soundArr[i] << "\" not found"; logMsg(oss.str());
window.close();
soundOk = false;
break;
}
}
if(soundOk)
oss << getTimeCli() << "Sounds loaded"; logMsg(oss.str());
//- Ready to go
oss << getTimeCli() << "ATM is ready to use"; logMsg(oss.str());
//- Assign font to text
scrClock.setFont(font);
usernameScr.setFont(font);
ibanScr.setFont(font);
L1Txt.setFont(font);
R1Txt.setFont(font);
R3Txt.setFont(font);
dialog.setFont(font);
liveTxt.setFont(font);
//- Assign texture to sprite
backgroundSprite.setTexture(backgroundTexture);
sf::IntRect ir;
ir = sf::IntRect(716, 0, 197, 198);
cardSprite.setTexture(cardTexture); cardSprite.setPosition(cardSpritePosition);
cardMask.setSize(sf::Vector2f(ir.width, ir.height)); cardMask.setPosition(ir.left, ir.top);
cardMask.setTexture(&backgroundTexture); cardMask.setTextureRect(ir);
ir = sf::IntRect(80, 0, 484, 370);
cashLargeSprite.setTexture(cashLargeTexture); cashLargeSprite.setPosition(cashLargeSpritePosition);
cashLargeMask.setSize(sf::Vector2f(ir.width, ir.height)); cashLargeMask.setPosition(ir.left, ir.top);
cashLargeMask.setTexture(&backgroundTexture); cashLargeMask.setTextureRect(ir);
ir = sf::IntRect(688, 250, 250, 213);
cashSmallSprite.setTexture(cashSmallTexture); cashSmallSprite.setPosition(cashSmallSpritePosition);
cashSmallMask.setSize(sf::Vector2f(ir.width, ir.height)); cashSmallMask.setPosition(ir.left, ir.top);
cashSmallMask.setTexture(&backgroundTexture); cashSmallMask.setTextureRect(ir);
ir = sf::IntRect(716, 0, 197, 54);
receiptSprite.setTexture(receiptTexture); receiptSprite.setPosition(receiptSpritePosition);
receiptMask.setSize(sf::Vector2f(ir.width, ir.height)); receiptMask.setPosition(ir.left, ir.top);
receiptMask.setTexture(&backgroundTexture); receiptMask.setTextureRect(ir);
//- Assign buffer to sounds
cardSnd.setBuffer(cardSndBuf);
menuSnd.setBuffer(menuSndBuf);
clickSnd.setBuffer(clickSndBuf);
keySnd.setBuffer(keySndBuf);
cashSnd.setBuffer(cashSndBuf);
printReceiptSnd.setBuffer(printReceiptSndBuf);
// Cursor
cursorCircle.setFillColor(cursorCircleIdleColor);
}
void initStates()
{
//- Initialize States
cardVisible = true; cashLargeVisible = false; cashSmallVisible = false; receiptVisible = false;
scrState = 1;
pin = 0; pinCount = 0; pinRetry = 0;
amount = 0; amountCount = 0;
amountLiveTxt = "";
convert.str("");
balance.str("");
outstandIngInteractionEvent = nullptr;
actionTimer = nullptr;
}
void handleActionTimer()
{
if (actionTimer != nullptr)
{
actionTimer->update();
}
}
void handleEvents()
{
while (window.pollEvent(event))
{
switch (event.type)
{
#ifdef TARGET_ANDROID
// On Android MouseLeft/MouseEntered are (for now) triggered,
// whenever the app loses or gains focus.
// ^ comment taken from the official SFML Android Sample Project:
// https://github.com/SFML/SFML/blob/2e6c363e644b430fd137a7dbed9836f965796610/examples/android/app/src/main/jni/main.cpp#L137
case sf::Event::MouseLeft:
windowHasFocus = false;
break;
case sf::Event::MouseEntered:
windowHasFocus = true;
break;
case sf::Event::KeyPressed:
if (event.key.code == sf::Keyboard::Escape) // Note: This is also triggered when the back button is pressed on Android
window.close();
break;
#endif
case sf::Event::Closed:
window.close();
break;
case sf::Event::Resized:
currentWindowSize = sf::Vector2u(event.size.width, event.size.height);
#ifdef TARGET_ANDROID
view = getLetterboxView(view, event.size.width, event.size.height);
window.setView(view);
#endif
break;
case sf::Event::TouchBegan:
if (event.touch.finger == 0)
updatePointerLocation(event.touch.x, event.touch.y);
break;
case sf::Event::MouseButtonPressed:
updatePointerLocation(event.mouseButton.x, event.mouseButton.y);
break;
}
}
}
void updatePointerLocation(int rawX, int rawY)
{
sf::Vector2i* position = getScaledPointerCoordinates(rawX, rawY);
cursorCircle.setPosition(
position->x - CURSOR_CIRCLE_RADIUS / (float) 2,
position->y - CURSOR_CIRCLE_RADIUS / (float) 2
);
addCursorAnimation(
new AlphaAnimation(
cursorFadeOutAnimationTime, 127, 0,
[this](int alpha) -> void {
int currentColorInt = cursorCircle.getFillColor().toInteger();
currentColorInt = currentColorInt >> 8; // get rid of the old alpha
currentColorInt = currentColorInt << 8; // retreat
int newColor = currentColorInt | alpha;
cursorCircle.setFillColor(sf::Color(newColor));
},
[this]() -> void {
cursorCircle.setFillColor(cursorCircleIdleColor);
delete cursorAnimation;
cursorAnimation = nullptr;
}));
if (!canAcceptInput()) {
delete position;
return;
}
if (outstandIngInteractionEvent != nullptr) delete outstandIngInteractionEvent;
outstandIngInteractionEvent = position;
}
bool canAcceptInput()
{
return actionTimer == nullptr && runningAnimations.empty();
}
int getClickableObjectCode(int x, int y)
{
//===============================
//Input Codes
//===============================
//Screen Buttons:
//L1 = 1 R1 = 5
//L2 = 2 R2 = 6
//L3 = 3 R3 = 7
//L4 = 4 R4 = 8
//===============================
//Keys:
//1 = 9 2 = 12 3 = 16
//4 = 10 5 = 13 6 = 17
//7 = 11 8 = 14 9 = 18
// 0 = 15
//===============================
//Action Buttons:
//Cancel = 25
//Clear = 19
//OK = 20
//===============================
//Objects:
//card = 21
//cashLarge = 22
//cashSmall = 23
//receipt = 24
//===============================
//exit = 26
//===============================
if ((11 <= x) && (x <= 55)) //- Left Column Screen Buttons
{
if ((125 <= y) && (y <= 163)) //- Button: L1
{
return 1;
}
if ((174 <= y) && (y <= 210)) //- Button: L2
{
return 2;
}
if ((221 <= y) && (y <= 259)) //- Button: L3
{
return 3;
}
if ((269 <= y) && (y <= 305)) //- Button: L4
{
return 4;
}
}
if ((588 <= x) && (x <= 632)) //- Right Column Screen Buttons
{
if ((127 <= y) && (y <= 163)) //- Button: R1
{
return 5;
}
if ((175 <= y) && (y <= 212)) //- Button: R2
{
return 6;
}
if ((223 <= y) && (y <= 259)) //- Button: R3
{
return 7;
}
if ((270 <= y) && (y <= 308)) //- Button: R4
{
return 8;
}
}
if ((209 <= x) && (x <= 255) && !cashLargeVisible) //- Column 1 Keypad
{
if ((410 <= y) && (y <= 449)) //- Key: 1
{
return 9;
}
if ((457 <= y) && (y <= 496)) //- Key: 4
{
return 10;
}
if ((504 <= y) && (y <= 543)) //- Key: 7
{
return 11;
}
}
if ((264 <= x) && (x <= 310) && !cashLargeVisible) //- Column 2 Keypad
{
if ((410 <= y) && (y <= 449)) //- Key: 2
{
return 12;
}
if ((457 <= y) && (y <= 496)) //- Key: 5
{
return 13;
}
if ((504 <= y) && (y <= 543)) //- Key: 8
{
return 14;
}
if ((551 <= y) && (y <= 590)) //- Key 0
{
return 15;
}
}
if ((319 <= x) && (x <= 365) && !cashLargeVisible) //- Column 3 Keypad
{
if ((410 <= y) && (y <= 449)) //- Key: 3
{
return 16;
}
if ((457 <= y) && (y <= 496)) //- Key: 6
{
return 17;
}
if ((504 <= y) && (y <= 543)) //- Key: 9
{
return 18;
}
}
if ((385 <= x) && (x <= 455) && !cashLargeVisible) //- Column 4 Keypad