-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathengine.pde
9708 lines (7883 loc) · 313 KB
/
engine.pde
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
import java.util.HashSet;
import java.io.File;
import java.net.MalformedURLException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.io.FileOutputStream;
import org.freedesktop.gstreamer.*;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.net.URL;
import java.util.zip.*;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.io.ByteArrayInputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.file.Paths;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.util.ArrayList;
import java.util.List;
import com.sun.jna.Native;
import com.sun.jna.Structure;
import processing.video.Movie;
import gifAnimation.*;
import java.net.URLClassLoader;
import java.net.URL;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.util.Iterator; // Used by the stack class at the bottom
import java.util.Arrays; // Used by the stack class at the bottom
import java.util.Collections;
// Timeway's engine code.
// TODO: add documentation lmao.
public class TWEngine {
//*****************CONSTANTS SETTINGS**************************
// Info and versioning
private static final String VERSION = "1.0.0";
public static final String VERSION_DESCRIPTION =
"";
public String getAppName() {
return "Timeway";
}
public String getVersion() {
return VERSION;
}
// ***************************
// How versioning works:
// a.b.c
// a is just gonna stay 0 most of the time unless something significant happens
// b is a super major release where the system has a complete overhaul.
// c is pretty much every release whether that's bug fixes or other things.
// a, b, and c can go well over 10, 100, it can be any positive integer.
// Paths
public final String WINDOWS_CMD = "engine/shell/mywindowscommand.bat";
public final String POCKET_PATH = "pocket/";
public final String TEMPLATES_PATH = "engine/realmtemplates/";
public final String EVERYTHING_TXT_PATH = "engine/everything.txt";
public final String DEFAULT_MUSIC_PATH = "engine/music/default.wav";
public String DEFAULT_UPDATE_PATH = ""; // Set up by setup()
public final String BOILERPLATE_PATH = "engine/plugindata/plugin_boilerplate.java";
public final String PDFTOPNG_PATH = "engine/bin/windows/pdftopng.exe";
public String CONSOLE_FONT() {
return "engine/font/SourceCodePro-Regular.ttf";
}
public String IMG_PATH() {
return "engine/img/";
}
public String FONT_PATH() {
return "engine/font/";
}
public String DEFAULT_FONT_PATH() {
return "engine/font/Typewriter.vlw";
}
public String SHADER_PATH() {
return "engine/shaders/";
}
public String SOUND_PATH() { return "engine/sounds/"; }
public String CONFIG_PATH() { return "config.json"; }
public String KEYBIND_PATH() { return "keybindings.json"; }
public String STATS_FILE() { return "stats.json"; }
public String PATH_SPRITES_ATTRIB() { return "engine/spritedata/"; }
public String CACHE_INFO() { return "cache_info.json"; }
public String[] FORCE_CACHE_MUSIC() {
String[] forceCacheMusic = {
"engine/music/pixelrealm_default_bgm.wav",
"engine/music/pixelrealm_default_bgm_legacy.wav",
};
return forceCacheMusic;
}
// Static constants
public static final float KEY_HOLD_TIME = 30.; // 30 frames
public static final int POWER_CHECK_INTERVAL = 5000;
public static final String CACHE_COMPATIBILITY_VERSION = "0.3";
public static final String CACHE_FILE_TYPE = "png";
public static final boolean CACHE_MUSIC = true;
// Dynamic constants (changes based on things like e.g. configuration file)
public PFont DEFAULT_FONT;
public String DEFAULT_DIR;
public String DEFAULT_FONT_NAME = "Typewriter";
public final String SKETCHIO_EXTENSION = "sketchio";
public final String ENTRY_EXTENSION = "timewayentry";
public final String[] SHORTCUT_EXTENSION = {"timewayshortcut"};
//*************************************************************
//**************ENGINE SETUP CODE AND VARIABLES****************
// Core stuff
public PApplet app;
public String APPPATH = sketchPath().replace('\\', '/')+"/data/";
public String CACHE_PATH = "cache/";
// Modules
public Console console;
public SharedResourcesModule sharedResources;
public SettingsModule settings;
public DisplayModule display;
public PowerModeModule power;
public AudioModule sound;
public FilemanagerModule file;
public StatsModule stats;
public ClipboardModule clipboard;
public UIModule ui;
public InputModule input;
public TWEngine.PluginModule plugins;
public IndexerModule indexer;
// Screens
public Screen currScreen;
public Screen prevScreen;
public boolean transitionScreens = false;
public float transition = 0;
public int transitionDirection = RIGHT;
public boolean initialScreen = true;
// Settings & config
public boolean devMode = false;
// Other / doesn't fit into any categories.
public boolean wireframe;
public SpriteSystemPlaceholder spriteSystemPlaceholder;
public long lastTimestamp;
public String lastTimestampName = null;
public int timestampCount = 0;
public boolean allowShowCommandPrompt = true;
public boolean playWhileUnfocused = true;
public HashMap<Long, Float> noiseCache = new HashMap<Long, Float>();
public HashSet<Float> noiseCacheConflicts = new HashSet<Float>();
public boolean focusedMode = true;
public class SharedResourcesModule {
private HashMap<String, Object> sharedResourcesMap;
public SharedResourcesModule() {
sharedResourcesMap = new HashMap<String, Object>();
}
public void set(String resourceName, Object val) {
sharedResourcesMap.put(resourceName, val);
}
public Object get(String resourceName) {
Object o = sharedResourcesMap.get(resourceName);
if (o == null) console.bugWarn("get: null object. Maybe use set or add a runnable argument to get?");
return o;
}
public Object get(String resourceName, Object addIfAbsent) {
Object o = sharedResourcesMap.get(resourceName);
if (o == null) this.set(resourceName, addIfAbsent);
o = sharedResourcesMap.get(resourceName);
// If it's still null after running, send a warning
if (o == null) console.bugWarn("get: You just passed a null object...?");
return o;
}
public Object get(String resourceName, Runnable runIfAbsent) {
Object o = sharedResourcesMap.get(resourceName);
if (o == null) runIfAbsent.run();
o = sharedResourcesMap.get(resourceName);
// If it's still null after running, send a warning
if (o == null) console.bugWarn("get: object still null after running runIfAbsent. Make sure to use set in your runnable!");
return o;
}
public void remove(String resourceName) {
sharedResourcesMap.remove(resourceName);
}
}
public class SettingsModule {
private JSONObject settings;
private JSONObject keybindings;
private HashMap<String, Object> defaultSettings = new HashMap<String, Object>();
private HashMap<String, Character> defaultKeybindings = new HashMap<String, Character>();
public SettingsModule() {
loadDefaultSettings();
if (!isAndroid()) {
// Normal you expect it.
settings = loadConfig(APPPATH+CONFIG_PATH(), defaultSettings);
keybindings = loadConfig(APPPATH+KEYBIND_PATH(), defaultKeybindings);
}
else {
// However, in android, we're not allowed to write to the usual place.
// Android gives you a specific variable dir to write to, so we must use that instead.
settings = loadConfig(getAndroidWriteableDir()+CONFIG_PATH(), defaultSettings);
keybindings = loadConfig(getAndroidWriteableDir()+KEYBIND_PATH(), defaultKeybindings);
}
}
public char getKeybinding(String keybindName) {
String s = keybindings.getString(keybindName);
char k;
if (s == null) {
if (defaultKeybindings.get(keybindName) != null) k = defaultKeybindings.get(keybindName);
else { console.bugWarnOnce("getKeybinding: unknown keyaction "+keybindName);
return 0; }
}
else k = s.charAt(0);
return k;
}
public boolean getBoolean(String setting) {
boolean b = false;
try {
b = settings.getBoolean(setting);
}
catch (NullPointerException e) {
if (defaultSettings.containsKey(setting)) {
b = (boolean)defaultSettings.get(setting);
} else {
console.warnOnce("Setting "+setting+" does not exist.");
return false;
}
}
return b;
}
public float getFloat(String setting) {
float f = 0.0;
try {
f = settings.getFloat(setting);
}
catch (RuntimeException e) {
if (defaultSettings.containsKey(setting)) {
f = (float)defaultSettings.get(setting);
} else {
console.warnOnce("Setting "+setting+" does not exist.");
return 0.;
}
}
return f;
}
public String getString(String setting) {
String s = "";
s = settings.getString(setting);
if (s == null) {
if (defaultSettings.containsKey(setting)) {
s = (String)defaultSettings.get(setting);
} else {
console.warnOnce("Setting "+setting+" does not exist.");
return "";
}
}
return s;
}
public final int LEFT_CLICK = 1;
public final int RIGHT_CLICK = 2;
// BIG TODO: we really need to isolate this into seperate screen objects rather than the engine.
public void loadDefaultSettings() {
defaultSettings = new HashMap<String, Object>();
defaultSettings.putIfAbsent("fullscreen", false);
defaultSettings.putIfAbsent("scrollSensitivity", 20.0);
defaultSettings.putIfAbsent("dynamicFramerate", true);
defaultSettings.putIfAbsent("lowBatteryPercent", 50.0);
defaultSettings.putIfAbsent("autoScaleDown", false);
defaultSettings.putIfAbsent("defaultSystemFont", "Typewriter");
if (isAndroid()) {
defaultSettings.putIfAbsent("homeDirectory", "/storage/emulated/0/");
}
else {
defaultSettings.putIfAbsent("homeDirectory", System.getProperty("user.home").replace('\\', '/'));
}
defaultSettings.putIfAbsent("forcePowerMode", "NONE");
defaultSettings.putIfAbsent("volumeNormal", 1.0);
defaultSettings.putIfAbsent("volumeQuiet", 0.0);
defaultSettings.putIfAbsent("fasterImageImport", false);
defaultSettings.putIfAbsent("waitForGStreamerStartup", true);
defaultSettings.putIfAbsent("enableExperimentalGifs", false);
defaultSettings.putIfAbsent("cache_miss_no_music", true);
defaultSettings.putIfAbsent("touch_controls", false);
defaultSettings.putIfAbsent("text_cursor_char", "_");
defaultKeybindings = new HashMap<String, Character>();
defaultKeybindings.putIfAbsent("CONFIG_VERSION", char(1));
defaultKeybindings.putIfAbsent("moveForewards", 'w');
defaultKeybindings.putIfAbsent("moveBackwards", 's');
defaultKeybindings.putIfAbsent("moveLeft", 'a');
defaultKeybindings.putIfAbsent("moveRight", 'd');
defaultKeybindings.putIfAbsent("lookLeft", 'q');
defaultKeybindings.putIfAbsent("lookRight", 'e');
defaultKeybindings.putIfAbsent("lookLeftTouch", char(253));
defaultKeybindings.putIfAbsent("lookRightTouch", char(254));
defaultKeybindings.putIfAbsent("menu", '\t');
defaultKeybindings.putIfAbsent("menuSelect", '\t');
defaultKeybindings.putIfAbsent("jump", ' ');
defaultKeybindings.putIfAbsent("playPause", ' ');
defaultKeybindings.putIfAbsent("sneak", char(0x0F));
defaultKeybindings.putIfAbsent("dash", 'r');
defaultKeybindings.putIfAbsent("scaleUp", '=');
defaultKeybindings.putIfAbsent("scaleDown", '-');
defaultKeybindings.putIfAbsent("scaleUpSlow", '+');
defaultKeybindings.putIfAbsent("scaleDownSlow", '_');
defaultKeybindings.putIfAbsent("primaryAction", 'o');
defaultKeybindings.putIfAbsent("secondaryAction", 'p');
defaultKeybindings.putIfAbsent("inventorySelectLeft", ',');
defaultKeybindings.putIfAbsent("inventorySelectRight", '.');
defaultKeybindings.putIfAbsent("scaleDownSlow", '_');
defaultKeybindings.putIfAbsent("showCommandPrompt", '/');
defaultKeybindings.putIfAbsent("prevDirectory", char(8));
defaultKeybindings.putIfAbsent("nextSubTool", ']');
defaultKeybindings.putIfAbsent("prevSubTool", '[');
defaultKeybindings.putIfAbsent("search", '\n');
for (int i = 0; i < 10; i++) defaultKeybindings.putIfAbsent("quickWarp"+str(i), str(i).charAt(0));
}
public JSONObject loadConfig(String configPath, HashMap defaultConfig) {
File f = new File(configPath);
JSONObject returnSettings = null;
boolean newConfig = false;
if (!f.exists()) {
newConfig = true;
} else {
try {
returnSettings = loadJSONObject(configPath);
}
catch (RuntimeException e) {
console.warn("There's an error in the config file. Loading default settings.");
newConfig = true;
}
}
// New config
if (newConfig) {
console.log("Config file not found, creating one.");
returnSettings = new JSONObject();
for (String k : (Iterable<String>)defaultConfig.keySet()) {
if (defaultConfig.get(k) instanceof Boolean)
returnSettings.setBoolean(k, (boolean)defaultConfig.get(k));
else if (defaultConfig.get(k) instanceof String)
returnSettings.setString(k, (String)defaultConfig.get(k));
else if (defaultConfig.get(k) instanceof Float)
returnSettings.setFloat(k, (float)defaultConfig.get(k));
else if (defaultConfig.get(k) instanceof Character) {
String s = "";
s += defaultConfig.get(k);
returnSettings.setString(k, s);
}
}
try {
saveJSONObject(returnSettings, configPath);
}
catch (RuntimeException e) {
console.warn("Failed to save config.");
}
}
return returnSettings;
}
}
public class PowerModeModule {
// Power modes
public PowerMode powerMode = PowerMode.HIGH;
private boolean noBattery = false;
private boolean sleepyMode = false;
private boolean dynamicFramerate = true;
private boolean powerSaver = false;
private int lastPowerCheck = 0;
public PowerMode getPowerMode() {
return powerMode;
}
final int MONITOR = 1;
final int RECOVERY = 2;
final int SLEEPY = 3;
final int GRACE = 4;
int fpsTrackingMode = MONITOR;
float fpsScore = 1000.;
float scoreDrain = 1.;
float recoveryScore = 1.;
PowerMode prevPowerMode = PowerMode.HIGH;
int recoveryFrameCount = 0;
int graceTimer = 0;
int recoveryPhase = 1;
float framerateBuffer[];
private boolean forcePowerModeEnabled = false;
private PowerMode forcedPowerMode = PowerMode.HIGH;
private PowerMode powerModeBefore = PowerMode.NORMAL;
public boolean allowMinimizedMode = true;
// The score that seperates the stable fps from the unstable fps.
// If you've got half a brain, it would make the most sense to keep it at 0.
final float FPS_SCORE_MIDDLE = 0.;
// Increase the score if the framerate is good but we're in the unstable zone.
private final float UNSTABLE_CONSTANT = 7.;
// Once we reach this score, we drop down to the previous frame.
private final float FPS_SCORE_DROP = -3000;
// If we gradually manage to make it to that score, we can go into RECOVERY mode to test what the framerate's like
// up a level.
private final float FPS_SCORE_RECOVERY = 500.;
// We want to recover to a higher framerate only if we're able to achieve a pretty good framerate.
// The higher you make RECOVERY_NEGLIGENCE, the more it will neglect the possibility of recovery.
// For example, trying to achieve 60fps but actual is 40fps, the system will likely recover faster if
// RECOVERY_NEGLIGENCE is set to 1 but very unlikely if it's set to something higher like 5.
private final float RECOVERY_NEGLIGENCE = 1;
private final int RECOVERY_PHASE_1_FRAMES = 20;
private final int RECOVERY_PHASE_2_FRAMES = 120; // 2 seconds
public PowerModeModule() {
setForcedPowerMode(settings.getString("forcePowerMode"));
}
public void setDynamicFramerate(boolean b) {
dynamicFramerate = b;
}
public String getPowerModeString() {
switch (powerMode) {
case HIGH:
return "HIGH";
case NORMAL:
return "NORMAL";
case SLEEPY:
return "SLEEPY";
case MINIMAL:
return "MINIMAL";
default:
console.bugWarn("getPowerModeString: Unknown power mode");
return "";
}
}
public void setForcedPowerMode(String p) {
forcePowerModeEnabled = true; // Temp set to true, if not enabled, it will reset to false.
if (p.equals("HIGH"))
forcedPowerMode = PowerMode.HIGH;
else if (p.equals("NORMAL"))
forcedPowerMode = PowerMode.NORMAL;
else if (p.equals("SLEEPY"))
forcedPowerMode = PowerMode.SLEEPY;
else if (p.equals("MINIMAL")) {
console.log("forcePowerMode set to MINIMAL, I wouldn't do that if I were you!");
forcedPowerMode = PowerMode.MINIMAL;
}
// Anything else (e.g. "NONE")
else {
forcePowerModeEnabled = false;
}
}
public void setForcedPowerMode(PowerMode p) {
forcePowerModeEnabled = true;
forcedPowerMode = p;
if (p == PowerMode.MINIMAL) {
console.log("forcePowerMode set to MINIMAL, I wouldn't do that if I were you!");
}
}
public void disableForcedPowerMode() {
forcePowerModeEnabled = false;
}
public void setPowerSaver(boolean b) {
power.powerSaver = b;
if (b)
forcePowerModeEnabled = false;
else {
setPowerMode(PowerMode.NORMAL);
forceFPSRecoveryMode();
}
}
public boolean getPowerSaver() { return powerSaver; }
public class NoBattery extends RuntimeException {
public NoBattery(String message) {
super(message);
}
}
public void updateBatteryStatus() {
//powerStatus = new Kernel32.SYSTEM_POWER_STATUS();
//Kernel32.INSTANCE.GetSystemPowerStatus(powerStatus);
}
public int batteryPercentage() throws NoBattery {
//String str = powerStatus.getBatteryLifePercent();
String str = "100";
str = str.substring(0, str.length()-1);
try {
int percent = Integer.parseInt(str);
return percent;
}
catch (NumberFormatException ex) {
throw new NoBattery("Battery not found..? ("+str+")");
}
}
public boolean isCharging() {
//return (powerStatus.getACLineStatusString().equals("Online"));
return false;
}
public void updatePowerModeNow() {
lastPowerCheck = millis();
}
public void setSleepy() {
if (dynamicFramerate) {
if (!isCharging() && !noBattery && !sleepyMode) {
sleepyMode = true;
powerModeBefore = getPowerMode();
lastPowerCheck = millis()+POWER_CHECK_INTERVAL;
}
} else {
sleepyMode = false;
}
}
// You shouldn't call this every frame
public void setAwake() {
sleepyMode = false;
if (getPowerMode() == PowerMode.SLEEPY) {
putFPSSystemIntoGraceMode();
setPowerMode(powerModeBefore);
}
}
private int powerModeSetTimeout = 0;
public void setPowerMode(PowerMode m) {
// Really just a debugging message to keep you using it appropriately.
//if (powerModeSetTimeout == 1)
// console.warnOnce("You shouldn't call setPowerMode on every frame, otherwise Timeway will seriously stutter.");
//powerModeSetTimeout = 2;
// Only update if it's not already set to prevent a whole load of bugs
if (powerMode != m) {
powerMode = m;
switch (m) {
case HIGH:
frameRate(60);
//console.log("Power mode HIGH");
break;
case NORMAL:
frameRate(30);
//console.log("Power mode NORMAL");
break;
case SLEEPY:
frameRate(10);
//console.log("Power mode SLEEPY");
break;
case MINIMAL:
frameRate(1); //idk for now
//console.log("Power mode MINIMAL");
break;
}
}
}
// basically use when you expect a significant difference in fps from that point forward.
public void forceFPSRecoveryMode() {
fpsScore = FPS_SCORE_MIDDLE;
fpsTrackingMode = RECOVERY;
recoveryFrameCount = 0;
// Record the next 5 frames.
framerateBuffer = new float[5];
recoveryPhase = 1;
}
// use before you expect a sudden delay, e.g. loading something during runtime or switching screens.
// We basically are telling the fps system to pause its score tracking as the average framerate drops.
public void putFPSSystemIntoGraceMode() {
fpsTrackingMode = GRACE;
graceTimer = 0;
}
// Similar to putFPSSystemIntoGraceMode() but reset the score.
// Use when you expect a different average fps, e.g. switching screens.
// We are telling the fps system to pause so the average framerate can fill up,
// and then reset the score so it can fairly decide what fps the new scene/screen/whatever
// should run in.
public void resetFPSSystem() {
putFPSSystemIntoGraceMode();
fpsScore = FPS_SCORE_MIDDLE;
scoreDrain = 1.;
recoveryScore = 1.;
}
public void updatePowerMode() {
// Just so we can provide a warning lol
powerModeSetTimeout = max(0, powerModeSetTimeout-1);
// Rules:
// If plugged in or no battery, have it running at POWER_MODE_HIGH by default.
// If on battery, the rules are as follows:
// - POWER_MODE_HIGH 60fps
// - POWER_MODE_NORMAL 30fps
// - POWER_MODE_SLEEPY 15 fps
// - POWER_MODE_MINIMAL loop is turned off
// - POWER_MODE_HIGH if power is above 30% and average fps over 2 seconds is over 58
// - POWER_MODE_NORMAL stays in
// - POWER_MODE_SLEEPY if 30% or below and window isn't focussed
// - POWER_MODE_MINIMAL if minimised
//
// Go into 1fps mode
// If the window is not focussed, don't even bother doing anything lol.
if (app.focused) {
if (!focusedMode) {
setPowerMode(prevPowerMode);
focusedMode = true;
putFPSSystemIntoGraceMode();
sound.setNormalVolume();
}
} else if (allowMinimizedMode) {
if (focusedMode) {
prevPowerMode = powerMode;
setPowerMode(PowerMode.MINIMAL);
focusedMode = false;
input.releaseAllInput();
if (playWhileUnfocused)
sound.setQuietVolume();
else
sound.setMasterVolume(0.); // Mute
}
return;
}
if (millis() > lastPowerCheck) {
lastPowerCheck = millis()+POWER_CHECK_INTERVAL;
// If we specifically requested slow, then go right ahead.
if (sleepyMode) {
prevPowerMode = powerMode;
fpsTrackingMode = SLEEPY;
setPowerMode(PowerMode.SLEEPY);
}
}
//if (!isCharging() && !noBattery && sleepyMode) {
// prevPowerMode = powerMode;
// fpsTrackingMode = SLEEPY;
// setPowerMode(PowerMode.SLEEPY);
// return;
//}
if (sleepyMode) return;
// If forced power mode is enabled, don't bother with the powermode selection algorithm below.
if (forcePowerModeEnabled) {
if (powerMode != forcedPowerMode) setPowerMode(forcedPowerMode);
return;
}
// How the fps algorithm works:
/*
There are 4 modes:
MONITOR:
- Use average framerate to determine framepoints.
- If the framerate is below the minimum required framerate, exponentially drain the score
until the framerate is stable or the drop zone has been reached.
- If in the unstable zone, linearly recover the score.
- If in the stable zone, increase the score by the recovery likelyhood (((30-framepoints)/30)**2)
but only if we're lower than HIGH power mode. Otherwise max out at the stable threshold.
- If we reach the drop threshold, drop the power mode down a level and take note of the recovery likelyhood (((30-framepoints)/30)**2)
and reset the score to the stable threshold.
- If we reach the recovery threshold, enter fps recovery mode and go up a power level.
RECOVERY:
- Don't keep track of score.
- Use the real-time fps to take a small average of the current frame.
- Once the average buffer is filled, use the average fps to determine whether we stay in this power mode or drop back.
- Framerate at least 58, 28 etc, stay in this mode and go back into monitor mode, and reset the score to the stable threshold.
- Otherwise, update recovery likelyhood and drop back.
SLEEPY:
- If sleepy mode is enabled, the score is paused and we don't do any operations;
Wait until sleepy mode is disabled.
GRACE:
- A grace period where the score is not changed for a certain amount of time to allow the average framerate to fill up.
- Once the grace period ends, return to MONITOR mode.
*/
float stableFPS = 30.;
int n = 1;
switch (powerMode) {
case HIGH:
stableFPS = 57.;
n = 1;
break;
case NORMAL:
stableFPS = 27;
n = 2;
break;
case SLEEPY:
stableFPS = 13.;
n = 4;
break;
// We shouldn't need to come to this but hey, this is a
// switch statement.
case MINIMAL:
stableFPS = 1.;
break;
}
if (fpsTrackingMode == MONITOR) {
// Everything in monitor will take twice or 4 times long if the framerate is lower.
for (int i = 0; i < n; i++) {
if (frameRate < stableFPS) {
//console.log("Drain");
scoreDrain += (stableFPS-frameRate)/stableFPS;
fpsScore -= scoreDrain;
//console.log(str(scoreDrain*scoreDrain));
//console.log(str(fpsScore));
} else {
scoreDrain = 0.;
// If in stable zone...
if (fpsScore > FPS_SCORE_MIDDLE) {
//console.log("stable zone");
if (powerMode != PowerMode.HIGH)
fpsScore += recoveryScore;
//console.log(str(recoveryScore));
}
// If in unstable zone...
else {
fpsScore += UNSTABLE_CONSTANT;
}
}
if (fpsScore < FPS_SCORE_DROP) {
// The lower our framerate, the less likely (or rather longer it takes) to get back to it.
recoveryScore = PApplet.pow((frameRate/stableFPS), RECOVERY_NEGLIGENCE);
// Reset the score.
fpsScore = FPS_SCORE_MIDDLE;
scoreDrain = 0.;
// Set the power mode down a level.
switch (powerMode) {
case HIGH:
setPowerMode(PowerMode.NORMAL);
break;
case NORMAL:
//setPowerMode(PowerMode.SLEEPY);
// Because sleepy is a pretty low framerate, chances are we just hit a slow
// spot and will speed up soon. Let's give ourselves a bit more recoveryScore
// so that we're not stuck slow forever.
//recoveryScore += 1;
fpsScore = FPS_SCORE_MIDDLE;
break;
case SLEEPY:
// Raise this to true to enable any other bits of the code to perform performance-saving measures.
break;
case MINIMAL:
// This is not a power level we downgrade to.
// We shouldn't downgrade here, but if for whatever reason we're glitched out
// and stuck in this mode, get ourselves out of it.
setPowerMode(PowerMode.SLEEPY);
fpsScore = FPS_SCORE_MIDDLE;
break;
}
}
if (fpsScore > FPS_SCORE_RECOVERY) {
//console.log("RECOVERY");
switch (powerMode) {
case HIGH:
// We shouldn't reach this here, but if we do, cap the
// score.
fpsScore = FPS_SCORE_RECOVERY;
n = 1;
break;
case NORMAL:
// Cap it out at 30fps when in power saver mode.
if (getPowerSaver()) {
fpsScore = FPS_SCORE_RECOVERY;
n = 2;
}
else {
setPowerMode(PowerMode.HIGH);
n = 1;
}
break;
case SLEEPY:
setPowerMode(PowerMode.NORMAL);
n = 2;
break;
case MINIMAL:
// This is not a power level we upgrade to.
// We shouldn't downgrade here, but if for whatever reason we're glitched out
// and stuck in this mode, get ourselves out of it.
setPowerMode(PowerMode.SLEEPY);
break;
}
fpsScore = FPS_SCORE_MIDDLE;
fpsTrackingMode = RECOVERY;
recoveryFrameCount = 0;
// Record the next so and so frames.
framerateBuffer = new float[RECOVERY_PHASE_1_FRAMES/n];
recoveryPhase = 1;
}
}
} else if (fpsTrackingMode == RECOVERY) {
// Record the fps, as long as we're not waiting to go back into MONITOR mode.
if (recoveryPhase != 3)
framerateBuffer[recoveryFrameCount++] = display.getLiveFPS();
// Once we're done recording...
int l = framerateBuffer.length;
if (recoveryFrameCount >= l) {
// Calculate the average framerate.
float total = 0.;
for (int j = 0; j < l; j++) {
total += framerateBuffer[j];
}
float avg = total/float(l);
//console.log("Recovery average: "+str(avg));
// If the framerate is at least 90%..
if (recoveryPhase == 1 && avg/stableFPS >= 0.9) {
//console.log("Recovery phase 1");
// Move on to phase 2 and get a little more data.
recoveryPhase = 2;
recoveryFrameCount = 0;
framerateBuffer = new float[RECOVERY_PHASE_2_FRAMES/n];
}
// If the framerate is at least the minimum stable fps.
else if (recoveryPhase == 2 && avg >= stableFPS) {
//console.log("Recovery phase 2");
// Now wait a bit before going back to monitor.
graceTimer = 0;
recoveryFrameCount = 0;
fpsTrackingMode = GRACE;
}
// Otherwise drop back to the previous power mode.
else {
switch (powerMode) {
case HIGH:
setPowerMode(PowerMode.NORMAL);
break;
case NORMAL:
// For the sake of this system what with the new delta framerate, we don't go any lower than NORMAL.
//setPowerMode(PowerMode.SLEEPY);
break;
case SLEEPY:
// Minimum power level, do nothing here.
// Hopefully framerates don't get that low.
break;
case MINIMAL:
// This is not a power level we downgrade to.
// We shouldn't downgrade here, but if for whatever reason we're glitched out
// and stuck in this mode, get ourselves out of it.
setPowerMode(PowerMode.SLEEPY);
fpsScore = FPS_SCORE_MIDDLE;
break;
}
recoveryScore = PApplet.pow((avg/stableFPS), RECOVERY_NEGLIGENCE);
fpsTrackingMode = MONITOR;
}
}
} else if (fpsTrackingMode == SLEEPY) {
} else if (fpsTrackingMode == GRACE) {
graceTimer++;
if (graceTimer > (240/n))