-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathDynamicFPSMod.java
More file actions
359 lines (285 loc) · 10 KB
/
DynamicFPSMod.java
File metadata and controls
359 lines (285 loc) · 10 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
package dynamic_fps.impl;
import dynamic_fps.impl.compat.ClothConfig;
import dynamic_fps.impl.compat.GLFW;
import dynamic_fps.impl.config.BatteryTrackerConfig;
import dynamic_fps.impl.config.Config;
import dynamic_fps.impl.config.DynamicFPSConfig;
import dynamic_fps.impl.config.option.GraphicsState;
import dynamic_fps.impl.feature.state.ClickIgnoreHandler;
import dynamic_fps.impl.service.ModCompat;
import dynamic_fps.impl.feature.battery.BatteryToast;
import dynamic_fps.impl.feature.battery.BatteryTracker;
import dynamic_fps.impl.feature.state.IdleHandler;
import dynamic_fps.impl.util.BatteryUtil;
import dynamic_fps.impl.util.Components;
import dynamic_fps.impl.util.FallbackConfigScreen;
import dynamic_fps.impl.util.Logging;
import dynamic_fps.impl.feature.state.OptionHolder;
import dynamic_fps.impl.util.ResourceLocations;
import dynamic_fps.impl.util.Threads;
import dynamic_fps.impl.util.Version;
import dynamic_fps.impl.feature.volume.SmoothVolumeHandler;
import dynamic_fps.impl.util.duck.DuckLoadingOverlay;
import dynamic_fps.impl.feature.state.WindowObserver;
import dynamic_fps.impl.service.Platform;
import net.lostluma.battery.api.State;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.LoadingOverlay;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.Identifier;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.Util;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public class DynamicFPSMod {
private static Config config = Config.ACTIVE;
private static PowerState state = PowerState.FOCUSED;
private static boolean isForcingLowFPS = false;
private static boolean isKeybindDisabled = false;
private static @Nullable WindowObserver window;
private static @Nullable ClickIgnoreHandler clickHandler;
private static long lastRender;
// we always render one last frame before actually reducing FPS, so the hud text
// shows up instantly when forcing low fps.
// additionally, this would enable mods which render differently while mc is
// inactive.
private static boolean hasRenderedLastFrame = false;
private static final boolean OVERLAY_OPTIMIZATION_ACTIVE = !ModCompat.getInstance().disableOverlayOptimization();
// Internal "API" for Dynamic FPS itself
public static void init() {
doInit();
}
public static boolean disabledByUser() {
return isKeybindDisabled;
}
public static @Nullable WindowObserver getWindow() {
return window;
}
public static boolean isDisabled() {
return isKeybindDisabled || !DynamicFPSConfig.INSTANCE.enabled() || ModCompat.getInstance().isDisabled();
}
public static String whyIsTheModNotWorking() {
List<String> results = new ArrayList<>();
if (isKeybindDisabled) {
results.add("keybinding");
}
if (!DynamicFPSConfig.INSTANCE.enabled()) {
results.add("mod config");
}
if (ModCompat.getInstance().isDisabled()) {
results.add("another mod");
}
return String.join(", ", results);
}
public static void toggleDisabled() {
isKeybindDisabled = !isKeybindDisabled;
onStatusChanged(true);
}
public static void onConfigChanged() {
doInit();
DynamicFPSConfig.INSTANCE.save();
checkForStateChanges(); // The unplugged state may now be enabled or disabled
}
public static Screen getConfigScreen(Screen parent) {
if (!Platform.getInstance().isModLoaded(Constants.CLOTH_CONFIG_ID)) {
return new FallbackConfigScreen(parent);
} else {
return ClothConfig.genConfigScreen(parent);
}
}
public static void onStatusChanged(boolean userInitiated) {
// Ensure game runs at full speed when
// Returning without giving any other input
if (userInitiated) {
IdleHandler.onActivity();
}
checkForStateChanges();
}
public static PowerState powerState() {
return state;
}
public static boolean isForcingLowFPS() {
return isForcingLowFPS;
}
public static void toggleForceLowFPS() {
isForcingLowFPS = !isForcingLowFPS;
onStatusChanged(true);
}
public static void setWindow(long address) {
IdleHandler.setWindow(address);
window = new WindowObserver(address);
initClickHandler();
checkForStateChanges();
}
static boolean renderedCurrentFrame = true;
public static boolean checkForRender() {
long currentTime = Util.getEpochMillis();
long timeSinceLastRender = currentTime - lastRender;
if (!checkForRender(timeSinceLastRender)) {
renderedCurrentFrame = false;
return false;
}
lastRender = currentTime;
renderedCurrentFrame = true;
return true;
}
public static boolean renderedCurrentFrame() {
return renderedCurrentFrame;
}
public static int targetFrameRate() {
return config.frameRateTarget();
}
public static boolean enableVsync() {
return config.enableVsync();
}
public static float volumeMultiplier(SoundSource source) {
return config.volumeMultiplier(source);
}
public static boolean shouldShowToasts() {
return config.showToasts();
}
public static GraphicsState graphicsState() {
return config.graphicsState();
}
public static boolean shouldShowLevels() {
return isDisabled() || !isLevelCoveredByOverlay();
}
public static void onBatteryChargeChanged(int before, int after) {
int percentage = DynamicFPSConfig.INSTANCE.batteryTracker().criticalLevel();
if (before > percentage && after <= percentage) {
showNotification("battery_critical", "reminder");
}
}
public static void onBatteryStatusChanged(State before, State after) {
if (before == State.DISCHARGING && BatteryUtil.isCharging(after)) {
showNotification("battery_charging", "charging");
} else if (BatteryUtil.isCharging(before) && after == State.DISCHARGING) {
showNotification("battery_draining", "draining");
}
}
// Internal logic
private static void doInit() {
initClickHandler();
SmoothVolumeHandler.init();
if (!BatteryTracker.isFeatureEnabled()) {
IdleHandler.init();
} else {
// Run battery tracker init on its own thread to ensure
// The initial library download doesn't block rendering
Threads.create("init", () -> {
BatteryTracker.init();
// The idle handler must be initialized later,
// Since it queries whether there are batteries available
Threads.runOnMainThread(IdleHandler::init);
});
}
}
private static void initClickHandler() {
if (window == null || clickHandler != null) {
return;
}
if (ClickIgnoreHandler.isFeatureActive()) {
clickHandler = new ClickIgnoreHandler(window.address());
}
}
private static void showNotification(String titleTranslationKey, String iconPath) {
if (!DynamicFPSConfig.INSTANCE.batteryTracker().notifications()) {
return;
}
Component title = Components.translatable("toast", titleTranslationKey);
Identifier icon = ResourceLocations.of("dynamic_fps", "textures/battery/toast/" + iconPath + ".png");
BatteryToast.queueToast(title, icon);
}
private static boolean isLevelCoveredByOverlay() {
Minecraft minecraft = Minecraft.getInstance();
return OVERLAY_OPTIMIZATION_ACTIVE && minecraft.getOverlay() instanceof LoadingOverlay && !((DuckLoadingOverlay)minecraft.getOverlay()).dynamic_fps$isReloadComplete();
}
@SuppressWarnings("squid:S1215") // Garbage collector call
public static void handleStateChange(PowerState previous, PowerState current) {
Minecraft minecraft = Minecraft.getInstance();
if (Constants.DEBUG) {
Logging.getLogger().info("State changed from {} to {}.", previous, current);
}
Config before = config;
config = DynamicFPSConfig.INSTANCE.get(current);
GLFW.applyWorkaround(); // Apply mouse hover fix if required
hasRenderedLastFrame = false; // Render next frame w/o delay
if (config.runGarbageCollector()) {
System.gc();
}
SmoothVolumeHandler.onStateChange();
if (before.graphicsState() != config.graphicsState()) {
if (before.graphicsState() == GraphicsState.DEFAULT) {
OptionHolder.copyOptions(minecraft.options);
}
OptionHolder.applyOptions(minecraft.options, config.graphicsState());
}
// The FOCUSED config doesn't have the user's actual vsync preference sadly ...
boolean enableVsync = current != PowerState.FOCUSED ? config.enableVsync() : minecraft.options.enableVsync().get();
if (enableVsync != before.enableVsync()) {
minecraft.getWindow().updateVsync(enableVsync);
}
}
private static void checkForStateChanges() {
Minecraft minecraft = Minecraft.getInstance();
if (window == null) {
return;
}
if (minecraft.isSameThread()) {
checkForStateChanges0();
} else {
// Schedule check for the beginning of the next frame
Threads.runOnMainThread(DynamicFPSMod::checkForStateChanges0);
}
}
private static void checkForStateChanges0() {
PowerState current;
BatteryTrackerConfig batteryTracking = DynamicFPSConfig.INSTANCE.batteryTracker();
if (isDisabled()) {
current = PowerState.FOCUSED;
} else if (isForcingLowFPS) {
current = PowerState.UNFOCUSED;
} else if (window.isFocused()) {
if (IdleHandler.isIdle()) {
current = PowerState.ABANDONED;
} else if (batteryTracking.enabled() && batteryTracking.switchStates() && BatteryTracker.status() == State.DISCHARGING) {
current = PowerState.UNPLUGGED;
} else {
current = PowerState.FOCUSED; // Default
}
} else if (window.isHovered()) {
current = PowerState.HOVERED;
} else if (!window.isIconified()) {
current = PowerState.UNFOCUSED;
} else {
current = PowerState.INVISIBLE;
}
if (state != current) {
PowerState previous = state;
state = current;
handleStateChange(previous, current);
}
}
private static boolean checkForRender(long timeSinceLastRender) {
int frameRateTarget = targetFrameRate();
// Disable all rendering
if (frameRateTarget == 0) {
return false;
}
// Disable mod-side frame rate limiting
if (frameRateTarget >= Constants.MIN_FRAME_RATE_LIMIT) {
return true;
}
// Render one more frame before
// Applying the custom frame rate
// So changes show up immediately
if (!hasRenderedLastFrame) {
hasRenderedLastFrame = true;
return true;
}
long frameTime = 1000 / frameRateTarget;
return timeSinceLastRender >= frameTime;
}
}