forked from Rexxt/cambridge
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.lua
930 lines (837 loc) · 30 KB
/
main.lua
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
-- Pre-load aliases
random = love.math.random
math.random = love.math.random
math.randomseed = love.math.setRandomSeed
-- This translates and scales the screen into specified dimensions.
---@type function
local scaleToResolution
function love.load()
love.graphics.setDefaultFilter("linear", "nearest")
require "load.fonts"
love.graphics.setFont(font_3x5_4)
love.graphics.printf("Please wait...\nLoading...", 160, 160, 320, "center")
love.graphics.present()
love.graphics.clear()
math.randomseed(os.time())
highscores = {}
require "load.filesystem"
require "load.rpc"
require "load.graphics"
require "load.sounds"
require "load.bgm"
require "load.save"
require "load.bigint"
require "load.modules"
require "load.replays"
require "load.version"
loadSave()
require "funcs"
require "scene"
--config["side_next"] = false
--config["reverse_rotate"] = true
--config["das_last_key"] = false
--config["fullscreen"] = false
-- used for screenshots
GLOBAL_CANVAS = love.graphics.newCanvas()
-- init config
initConfig()
love.window.setFullscreen(config["fullscreen"])
-- loads game graphics and sounds.
loadResources()
-- import custom modules
initModules()
-- this is executed after the sound table is generated. why is that is unknown.
if config.secret then playSE("welcome") end
end
function scaleToResolution(width, height)
local screen_width, screen_height = love.graphics.getDimensions()
local scale_factor = math.min(screen_width / width, screen_height / height)
love.graphics.translate(
(screen_width - scale_factor * width) / 2,
(screen_height - scale_factor * height) / 2
)
love.graphics.scale(scale_factor)
end
mouse_idle = 0
TAS_mode = false
local system_cursor_type = "arrow"
local screenshot_images = {}
---@param type love.CursorType
function setSystemCursorType(type)
system_cursor_type = type
end
---@param x number
---@param y number
---@param a number
function drawT48Cursor(x, y, a)
if a <= 0 then return end
love.graphics.setColor(1,1,1,a)
love.graphics.polygon("fill", x + 5, y + 0, x + 0, y + 10, x + 5, y + 8, x + 8, y + 20, x + 12, y + 18, x + 10, y + 7, x + 15, y + 5)
love.graphics.setColor(0,0,0,a)
love.graphics.polygon("line", x + 5, y + 0, x + 0, y + 10, x + 5, y + 8, x + 8, y + 20, x + 12, y + 18, x + 10, y + 7, x + 15, y + 5)
love.graphics.setColor(1,1,1,a)
end
---@param image love.ImageData
local function screenshotFunction(image)
playSE("screenshot")
screenshot_images[#screenshot_images+1] = {image = love.graphics.newImage(image), time = 0, y_position = #screenshot_images * 260}
end
local last_time = 0
local function getDeltaTime()
local time = love.timer.getTime()
local dt = time - last_time
last_time = time
return dt
end
local time_table = {}
local last_fps = 0
local function getAvgDelta()
if #time_table > 24 then
table.remove(time_table, 1)
end
local dt = getDeltaTime()
table.insert(time_table, dt)
local acc = 0
for i = 1, #time_table do
acc = acc + time_table[i]
end
if math.floor(love.timer.getTime()) + dt > love.timer.getTime() then
last_fps = acc / #time_table
end
return last_fps
end
--What a mess trying to do something with it
local function drawScreenshotPreviews()
local accumulated_y = 0
for idx, value in ipairs(screenshot_images) do
local image_x, image_y = value.image:getDimensions()
local local_scale_factor = math.min(image_x / 640, image_y / 480)
value.time = value.time + math.max(value.time < 300 and 4 or 1, value.time / 10 - 30)
value.y_position = interpolateNumber(value.y_position, accumulated_y)
local scaled_width, scaled_zero = getScaledDimensions(love.graphics.getWidth(), 0)
local x = (scaled_width) - ((image_x / 4) / local_scale_factor) + math.max(0, value.time - 300)
local rect_x, rect_y, rect_w, rect_h = x - 1, scaled_zero + value.y_position - 1, ((image_x / 4) / local_scale_factor) + 2, ((image_y / 4) / local_scale_factor) + 2
love.graphics.setColor(0, 0, 0)
love.graphics.rectangle("fill", rect_x, rect_y, rect_w, rect_h)
love.graphics.setColor(1, 1, 1)
love.graphics.draw(value.image, x, scaled_zero + value.y_position, 0, 0.25 / local_scale_factor, 0.25 / local_scale_factor)
love.graphics.setColor(1, 1, 1, math.max(0, 1 - (value.time / 60)))
love.graphics.rectangle("fill", rect_x, rect_y, rect_w, rect_h)
if value.time > (image_x / local_scale_factor) + 100 then
value.image:release()
table.remove(screenshot_images, idx)
end
accumulated_y = accumulated_y + (image_y / local_scale_factor / 4) + 5
end
end
--#region Error Handler
local utf8 = require("utf8")
local function error_printer(msg, layer)
print((debug.traceback("Error: " .. tostring(msg), 1+(layer or 1)):gsub("\n[^\n]+$", "")))
end
function love.errorhandler(msg)
msg = tostring(msg)
local errored_filename = msg:sub(1, msg:find(':') -1)
local substring = msg:sub(msg:find(':') +1)
local line_error = tonumber(substring:sub(1, substring:find(':') - 1), 10)
if love.filesystem.isFused() then
local source_dir = love.filesystem.getSourceBaseDirectory()
love.filesystem.mount(source_dir, "")
end
local lua_file_content = {}
if love.filesystem.getInfo(errored_filename, "file") then
local str_data = love.filesystem.read("string", errored_filename)
for v in string.gmatch(str_data, "([^\r\n]*)\r\n?") do
lua_file_content[#lua_file_content+1] = v
end
end
error_printer(msg, 2)
if not love.window or not love.graphics or not love.event then
return
end
if not love.graphics.isCreated() or not love.window.isOpen() then
local success, status = pcall(love.window.setMode, 800, 600)
if not success or not status then
return
end
end
-- Reset state.
if love.mouse then
love.mouse.setVisible(true)
love.mouse.setGrabbed(false)
love.mouse.setRelativeMode(false)
if love.mouse.isCursorSupported() then
love.mouse.setCursor()
end
end
if love.joystick then
-- Stop all joystick vibrations.
for i,v in ipairs(love.joystick.getJoysticks()) do
v:setVibration()
end
end
if love.audio then love.audio.stop() end
love.graphics.reset()
local font = love.graphics.newFont(14)
love.graphics.setFont(font)
love.graphics.setColor(1, 1, 1)
local trace = debug.traceback()
love.graphics.origin()
local sanitizedmsg = {}
for char in msg:gmatch(utf8.charpattern) do
table.insert(sanitizedmsg, char)
end
sanitizedmsg = table.concat(sanitizedmsg)
local err = {}
table.insert(err, "Error\n")
table.insert(err, sanitizedmsg)
if #sanitizedmsg ~= #msg then
table.insert(err, "Invalid UTF-8 string in error message.")
end
table.insert(err, "\n")
for l in trace:gmatch("(.-)\n") do
if not l:match("boot.lua") then
l = l:gsub("stack traceback:", "Traceback\n")
table.insert(err, l)
end
end
local p = table.concat(err, "\n")
p = p:gsub("\t", "")
p = p:gsub("%[string \"(.-)\"%]", "%1")
local function draw()
if not love.graphics.isActive() then return end
local pos = 70
love.graphics.clear(89/255, 157/255, 220/255)
love.graphics.printf("Cambridge Crashed!", pos, pos-40, love.graphics.getWidth() - pos, "center")
for i = 1, 7 do
local local_line = line_error-4+i
if local_line > 0 and local_line <= #lua_file_content then
love.graphics.print(local_line.. ": " .. lua_file_content[local_line] .. (local_line == line_error and " <---" or "") , pos, pos + (i * 15) - 5)
end
end
if #lua_file_content == 0 then
love.graphics.print("Couldn't find a lua file! Is it missing in some way?", pos, pos + 30)
end
love.graphics.printf(p, pos, pos + 120, love.graphics.getWidth() - pos)
love.graphics.present()
end
local fullErrorText = p
local function copyToClipboard()
if not love.system then return end
love.system.setClipboardText(fullErrorText)
p = p .. "\nCopied to clipboard!"
end
if love.system then
p = p .. "\n\nPress Ctrl+C or tap to copy this error"
end
return function()
love.event.pump()
for e, a, b, c in love.event.poll() do
if e == "quit" then
return 1
elseif e == "keypressed" and a == "escape" then
return 1
elseif e == "keypressed" and a == "c" and love.keyboard.isDown("lctrl", "rctrl") then
copyToClipboard()
elseif e == "touchpressed" then
local name = love.window.getTitle()
if #name == 0 or name == "Untitled" then name = "Game" end
local buttons = {"OK", "Cancel"}
if love.system then
buttons[3] = "Copy to clipboard"
end
local pressed = love.window.showMessageBox("Quit "..name.."?", "", buttons)
if pressed == 1 then
return 1
elseif pressed == 3 then
copyToClipboard()
end
end
end
draw()
if love.timer then
love.timer.sleep(0.1)
end
end
end
--#endregion
function love.draw()
local avg_delta = getAvgDelta()
love.graphics.setCanvas(GLOBAL_CANVAS)
love.graphics.clear()
love.graphics.push()
-- get offset matrix
scaleToResolution(640, 480)
scene:render()
if TAS_mode then
love.graphics.setColor(1, 1, 1, love.timer.getTime() % 2 < 1 and 1 or 0)
love.graphics.setFont(font_3x5_3)
love.graphics.printf(
"TAS MODE ON", 240, 0, 160, "center"
)
end
local bottom_right_corner_y_offset = 0
love.graphics.setFont(font_3x5_2)
love.graphics.setColor(1, 1, 1, 1)
if config.visualsettings.display_gamemode == 1 or scene.title == "Title" then
bottom_right_corner_y_offset = bottom_right_corner_y_offset + 20
love.graphics.printf(
string.format("(%g) %.2f fps - %s", getTargetFPS(), 1.0 / avg_delta, version),
0, 480 - bottom_right_corner_y_offset, 635, "right"
)
end
if config.visualsettings.debug_level > 1 then
bottom_right_corner_y_offset = bottom_right_corner_y_offset + 18
love.graphics.printf(
string.format("Lua memory use: %.1fMB", collectgarbage("count")/1000),
0, 480 - bottom_right_corner_y_offset, 635, "right"
)
end
if scene.title == "Game" or scene.title == "Replay" then
else
love.mouse.setVisible(config.visualsettings.cursor_type == 1)
if config.visualsettings.cursor_type ~= 1 then
local lx, ly = getScaledDimensions(love.mouse.getPosition())
drawT48Cursor(lx, ly, 9 - mouse_idle * 4)
end
end
love.graphics.pop()
love.graphics.setCanvas()
love.graphics.setColor(1,1,1,1)
love.graphics.draw(GLOBAL_CANVAS)
scaleToResolution(640, 480)
drawScreenshotPreviews()
love.graphics.setColor(1, 1, 1, 1)
if config.visualsettings.debug_level > 2 then
bottom_right_corner_y_offset = bottom_right_corner_y_offset + 113
local stats = love.graphics.getStats()
love.graphics.printf(
string.format("GPU stats:\nDraw calls: %d\nTexture Memory: %dKB\n"..(stats.textures and "Textures" or "Images").." loaded: %d\nFonts loaded: %d\nBatched draw calls: %d", stats.drawcalls + 1, stats.texturememory / 1024, (stats.images or stats.textures), stats.fonts, stats.drawcallsbatched),
0, 480 - bottom_right_corner_y_offset, 635, "right"
)
end
end
local function onInputPress(e)
if scene.title == "Key Config" then
scene:onInputPress(e)
elseif e.input == "fullscreen" then
config["fullscreen"] = not config["fullscreen"]
saveConfig()
love.window.setFullscreen(config["fullscreen"])
elseif e.input == "tas_mode" then
TAS_mode = not TAS_mode
return
elseif e.input == "configure_inputs" and scene.title ~= "Input Config" and scene.title ~= "Game" and scene.title ~= "Replay" then
scene = InputConfigScene()
switchBGM(nil)
loadSave()
-- load state tool
elseif e.input == "save_state" and TAS_mode and (scene.title == "Replay") then
scene:onInputPress({input="save_state"})
elseif e.input == "load_state" and TAS_mode and (scene.title == "Replay") then
scene:onInputPress({input="load_state"})
-- secret sound playing :eyes:
elseif e.input == "secret" and scene.title == "Title" then
config.secret = not config.secret
saveConfig()
scene.restart_message = true
if config.secret then playSE("mode_decide")
else playSE("erase", "single") end
elseif e.input == "screenshot" then
local ss_name = os.date("ss/%Y-%m-%d_%H-%M-%S.png")
local info = love.filesystem.getInfo("ss", "directory")
if not info then
love.filesystem.remove("ss")
love.filesystem.createDirectory("ss")
end
print("Saving screenshot as "..love.filesystem.getSaveDirectory().."/"..ss_name)
local image = GLOBAL_CANVAS:newImageData()
image:encode("png", ss_name)
screenshotFunction(image)
image:release()
else
scene:onInputPress(e)
end
end
local function onInputRelease(e)
scene:onInputRelease(e)
end
local function multipleInputs(input_table, input)
local result_inputs = {}
for input_type, value in pairs(input_table) do
if input == value then
table.insert(result_inputs, input_type)
end
end
return result_inputs
end
---@param file love.File
function love.filedropped(file)
file:open("r")
local data = file:read()
file:close()
local raw_file_directory = file:getFilename()
local char_pos = raw_file_directory:gsub("\\", "/"):reverse():find("/")
local filename = raw_file_directory:sub(-char_pos+1)
local final_directory
local msgbox_choice = 0
local binser = require "libs.binser"
local confirmation_buttons = {"No", "Yes", enterbutton = 2}
if raw_file_directory:sub(-4) == ".lua" then
msgbox_choice = love.window.showMessageBox(love.window.getTitle(), "Where do you put "..filename.."?", { "Cancel", "Rulesets", "Modes"}, "info")
if msgbox_choice == 0 or msgbox_choice == 1 then
return
end
local directory_string = "rulesets/"
if msgbox_choice == 3 then
directory_string = "modes/"
end
final_directory = "tetris/"..directory_string
elseif raw_file_directory:sub(-4) == ".crp" then
msgbox_choice = love.window.showMessageBox(love.window.getTitle(), "What option do you select for "..filename.."?", {"Insert", "View", escapebutton = 0}, "info")
if msgbox_choice == 0 then
return
end
if msgbox_choice == 1 then
final_directory = "replays/"
elseif msgbox_choice == 2 then
local replay_data = binser.d(data)[1]
local info_string = "Replay file view:\n"
info_string = info_string .. "Mode: " .. replay_data["mode"] .. " (" .. (replay_data["mode_hash"] or "???") .. ")\n"
info_string = info_string .. "Ruleset: " .. replay_data["ruleset"] .. " (" .. (replay_data["ruleset_hash"] or "???") .. ")\n"
info_string = info_string .. os.date("Timestamp: %c\n", replay_data["timestamp"])
if replay_data.cambridge_version then
if replay_data.cambridge_version ~= version then
info_string = info_string .. "Warning! The versions don't match!\nStuff may break, so, start at your own risk.\n"
end
info_string = info_string .. "Cambridge version for this replay: "..replay_data.cambridge_version.."\n"
end
if replay_data.pause_count and replay_data.pause_time then
info_string = info_string .. ("Pause count: %d\nTime Paused: %s\n"):format(replay_data.pause_count, formatTime(replay_data.pause_time))
end
if replay_data.sha256_table then
info_string = info_string .. ("SHA256 replay hashes:\nMode: %s\nRuleset: %s\n"):format(replay_data.sha256_table.mode, replay_data.sha256_table.ruleset)
end
if replay_data.highscore_data then
info_string = info_string .. "In-replay highscore data:\n\n"
for key, value in pairs(replay_data["highscore_data"]) do
info_string = info_string .. stringWrapByLength((key..": ".. toFormattedValue(value)), 75) .. "\n"
end
else
info_string = info_string .. "Legacy replay\nLevel: "..replay_data["level"]
end
love.window.showMessageBox(love.window.getTitle(), info_string, "info")
return
end
else
love.window.showMessageBox(love.window.getTitle(), "This file ("..filename..") is not a Lua nor replay file.", "warning")
return
end
local do_write = 2
if love.filesystem.getInfo(final_directory..filename) then
do_write = love.window.showMessageBox(love.window.getTitle(), "This file ("..filename..") already exists! Do you want to override it?", confirmation_buttons, "warning")
end
if do_write == 2 then
love.filesystem.createDirectory(final_directory)
love.filesystem.write(final_directory..filename, data)
if final_directory ~= "replays/" then
loaded_replays = false
elseif loaded_replays then
local replay = binser.deserialize(data)[1]
insertReplay(replay)
sortReplays()
end
end
end
---@param dir string
function love.directorydropped(dir)
local msgbox_choice = love.window.showMessageBox(love.window.getTitle(), "Do you want to insert a directory ("..dir..") as a mod pack?", {"No", "Yes"}, "info")
if msgbox_choice <= 1 then
return
end
local success = love.filesystem.mount(dir, "directory_dropped")
if not success then
error("Unsuccessful mount on "..dir.."!")
end
copyDirectoryRecursively("directory_dropped", "", true)
love.filesystem.unmount(dir)
end
---@param key string|nil
---@param scancode string|nil
function love.keypressed(key, scancode)
local result_inputs = {}
if config.input and config.input.keys then
result_inputs = multipleInputs(config.input.keys, scancode)
for _, input in pairs(result_inputs) do
onInputPress({input=input, type="key", key=key, scancode=scancode})
key = nil
scancode = nil
end
end
if #result_inputs == 0 then
onInputPress({type="key", key=key, scancode=scancode})
end
end
---@param key string|nil
---@param scancode string|nil
function love.keyreleased(key, scancode)
local result_inputs = {}
if config.input and config.input.keys then
result_inputs = multipleInputs(config.input.keys, scancode)
for _, input in pairs(result_inputs) do
onInputRelease({input=input, type="key", key=key, scancode=scancode})
key = nil
scancode = nil
end
end
if #result_inputs == 0 then
onInputRelease({type="key", key=key, scancode=scancode})
end
end
---@param joystick love.Joystick
---@param button integer
function love.joystickpressed(joystick, button)
local result_inputs = {}
if config.input and config.input.joysticks then
if config.input.joysticks[joystick:getName()] then
result_inputs = multipleInputs(config.input.joysticks[joystick:getName()], "buttons-"..button)
end
for _, input in pairs(result_inputs) do
scene:onInputPress({input=input, type="joybutton", name=joystick:getName(), button=button})
end
end
if #result_inputs == 0 then
scene:onInputPress({type="joybutton", name=joystick:getName(), button=button})
end
-- scene:onInputPress({input=input_pressed, type="joybutton", name=joystick:getName(), button=button})
end
---@param joystick love.Joystick
---@param button integer
function love.joystickreleased(joystick, button)
local result_inputs = {}
if config.input and config.input.joysticks then
if config.input.joysticks[joystick:getName()] then
result_inputs = multipleInputs(config.input.joysticks[joystick:getName()], "buttons-"..button)
end
for _, input in pairs(result_inputs) do
scene:onInputRelease({input=input, type="joybutton", name=joystick:getName(), button=button})
end
end
if #result_inputs == 0 then
scene:onInputRelease({type="joybutton", name=joystick:getName(), button=button})
end
end
---@param joystick love.Joystick
---@param axis number
---@param value number
function love.joystickaxis(joystick, axis, value)
local result_inputs = {}
local joystick_input_table = nil
local joystick_name = joystick:getName()
if config.input and config.input.joysticks and config.input.joysticks[joystick_name] then
joystick_input_table = config.input.joysticks[joystick_name]
end
if math.abs(value) >= 1 then
if type(joystick_input_table) == "table" then
result_inputs = multipleInputs(joystick_input_table, "axes-"..axis.."-"..(value >= 1 and "positive" or "negative"))
for _, input in pairs(result_inputs) do
scene:onInputPress({input=input, type="joyaxis", name=joystick:getName(), axis=axis, value=value})
end
local opposite_direction_inputs = multipleInputs(joystick_input_table, "axes-"..axis.."-"..(value <= -1 and "positive" or "negative"))
for _, input in pairs(opposite_direction_inputs) do
scene:onInputRelease({input=input, type="joyaxis", name=joystick:getName(), axis=axis, value=value})
end
-- scene:onInputPress({input=input_pressed, type="joyaxis", name=joystick:getName(), axis=axis, value=value})
end
if #result_inputs == 0 then
scene:onInputPress({type="joyaxis", name=joystick:getName(), axis=axis, value=value})
end
else
if type(joystick_input_table) == "table" then
for input_type, v in pairs(joystick_input_table) do
if "axes-"..axis.."-".."negative" == v then
table.insert(result_inputs, input_type)
end
if "axes-"..axis.."-".."positive" == v then
table.insert(result_inputs, input_type)
end
end
for _, input in pairs(result_inputs) do
scene:onInputRelease({input=input, type="joyaxis", name=joystick_name, axis=axis, value=value})
end
end
if #result_inputs == 0 then
scene:onInputRelease({type="joyaxis", name=joystick_name, axis=axis, value=value})
end
end
end
local last_hat_direction = ""
local directions = {
["u"] = "up",
["d"] = "down",
["l"] = "left",
["r"] = "right",
}
--wtf
---@param joystick love.Joystick
---@param hat number
---@param direction string
function love.joystickhat(joystick, hat, direction)
local input_pressed = nil
local has_hat = false
if
config.input and
config.input.joysticks and
config.input.joysticks[joystick:getName()]
then
input_pressed = direction ~= "c"
has_hat = true
end
if input_pressed then
for i = 1, #direction do
local char = direction:sub(i, i)
local _, count = last_hat_direction:gsub(char, char)
if count == 0 then
local result_inputs = {}
for input_type, value in pairs(config.input.joysticks[joystick:getName()]) do
if "hat-"..hat.."-"..directions[char] == value then
table.insert(result_inputs, input_type)
end
end
for _, input in pairs(result_inputs) do
scene:onInputPress({input=input, type="joyhat", name=joystick:getName(), hat=hat, direction=char})
end
if #result_inputs == 0 then
scene:onInputPress({input=directions[char], type="joyhat", name=joystick:getName(), hat=hat, direction=char})
end
--scene:onInputPress({input=config.input.joysticks[joystick:getName()].hats[hat][char], type="joyhat", name=joystick:getName(), hat=hat, direction=char})
end
end
for i = 1, #last_hat_direction do
local char = last_hat_direction:sub(i, i)
local _, count = direction:gsub(char, char)
if count == 0 then
local result_inputs = {}
for input_type, value in pairs(config.input.joysticks[joystick:getName()]) do
if "hat-"..hat.."-"..directions[char] == value then
table.insert(result_inputs, input_type)
end
end
for _, input in pairs(result_inputs) do
scene:onInputRelease({input=input, type="joyhat", name=joystick:getName(), hat=hat, direction=char})
end
if #result_inputs == 0 then
scene:onInputRelease({input=directions[char], type="joyhat", name=joystick:getName(), hat=hat, direction=char})
end
-- scene:onInputRelease({input=config.input.joysticks[joystick:getName()].hats[hat][char], type="joyhat", name=joystick:getName(), hat=hat, direction=char})
end
end
last_hat_direction = direction
elseif has_hat then
--why redefine the local variable?
for i, fdirection in ipairs{"d", "l", "ld", "lu", "r", "rd", "ru", "u"} do
local result_inputs = multipleInputs(config.input.joysticks[joystick:getName()], "hat-"..hat.."-"..(directions[fdirection] or "nil"))
for _, input in pairs(result_inputs) do
scene:onInputRelease({input=input, type="joyhat", name=joystick:getName(), hat=hat, direction=fdirection})
end
if #result_inputs == 0 then
scene:onInputRelease({input=directions[fdirection] or nil, type="joyhat", name=joystick:getName(), hat=hat, direction=fdirection})
end
-- scene:onInputRelease({input=config.input.joysticks[joystick:getName()].hats[hat][direction], type="joyhat", name=joystick:getName(), hat=hat, direction=direction})
end
last_hat_direction = ""
elseif direction ~= "c" then
for i = 1, #direction do
local char = direction:sub(i, i)
local _, count = last_hat_direction:gsub(char, char)
if count == 0 then
scene:onInputPress({input=directions[char], type="joyhat", name=joystick:getName(), hat=hat, direction=char})
end
end
for i = 1, #last_hat_direction do
local char = last_hat_direction:sub(i, i)
local _, count = direction:gsub(char, char)
if count == 0 then
scene:onInputRelease({input=directions[char], type="joyhat", name=joystick:getName(), hat=hat, direction=char})
end
end
last_hat_direction = direction
else
for i, fdirection in ipairs{"d", "l", "ld", "lu", "r", "rd", "ru", "u"} do
scene:onInputRelease({input=directions[fdirection], type="joyhat", name=joystick:getName(), hat=hat, direction=fdirection})
end
last_hat_direction = ""
end
end
local mouse_buttons_pressed = {}
---@param x number
---@param y number
---@param button integer
---@param istouch boolean
---@param presses integer
function love.mousepressed(x, y, button, istouch, presses)
if mouse_idle > 2 then return end
mouse_buttons_pressed[button] = true
local local_x, local_y = getScaledDimensions(x, y)
scene:onInputPress({type="mouse", x=local_x, y=local_y, button=button, istouch=istouch, presses=presses})
end
---@param x number
---@param y number
---@param button integer
---@param istouch boolean
---@param presses integer
function love.mousereleased(x, y, button, istouch, presses)
if mouse_idle > 2 and not mouse_buttons_pressed[button] then return end
mouse_buttons_pressed[button] = false
local local_x, local_y = getScaledDimensions(x, y)
scene:onInputRelease({type="mouse", x=local_x, y=local_y, button=button, istouch=istouch, presses=presses})
end
---@param x number
---@param y number
---@param dx number
---@param dy number
---@param istouch boolean
function love.mousemoved(x, y, dx, dy, istouch)
mouse_idle = 0
local local_x, local_y = getScaledDimensions(x, y)
local local_dx, local_dy = getScaledDimensions(dx, dy)
scene:onInputMove({type="mouse", x=local_x, y=local_y, dx=local_dx, dy=local_dy, istouch=istouch})
end
---@param id lightuserdata
---@param x number
---@param y number
---@param dx number
---@param dy number
---@param pressure number
function love.touchpressed(id, x, y, dx, dy, pressure)
local local_x, local_y = getScaledDimensions(x, y)
local local_dx, local_dy = getScaledDimensions(dx, dy)
scene:onInputPress({type="touch", id=id, x=local_x, y=local_y, dx=local_dx, dy=local_dy, pressure=pressure})
end
---@param id lightuserdata
---@param x number
---@param y number
---@param dx number
---@param dy number
---@param pressure number
function love.touchmoved(id, x, y, dx, dy, pressure)
local local_x, local_y = getScaledDimensions(x, y)
local local_dx, local_dy = getScaledDimensions(dx, dy)
scene:onInputMove({type="touch", id=id, x=local_x, y=local_y, dx=local_dx, dy=local_dy, pressure=pressure})
end
---@param id lightuserdata
---@param x number
---@param y number
---@param dx number
---@param dy number
---@param pressure number
function love.touchreleased(id, x, y, dx, dy, pressure)
local local_x, local_y = getScaledDimensions(x, y)
local local_dx, local_dy = getScaledDimensions(dx, dy)
scene:onInputRelease({type="touch", id=id, x=local_x, y=local_y, dx=local_dx, dy=local_dy, pressure=pressure})
end
function love.focus(f)
if f then
love.audio.setVolume(config.audiosettings.master_volume / 100)
else
love.audio.setVolume(config.audiosettings.master_volume / 1000)
end
end
---@param x number
---@param y number
function love.wheelmoved(x, y)
scene:onInputPress({input=nil, type="wheel", x=x, y=y})
end
---@param w integer
---@param h integer
function love.resize(w, h)
GLOBAL_CANVAS:release()
GLOBAL_CANVAS = love.graphics.newCanvas(w, h)
end
-- higher values of TARGET_FPS will make the game run "faster"
-- since the game is mostly designed for 60 FPS
local TARGET_FPS = 60
local FRAME_DURATION = 1.0 / TARGET_FPS
---@param fps number
function setTargetFPS(fps)
if fps <= 0 or fps == math.huge then
TARGET_FPS = math.huge
return
end
TARGET_FPS = fps
FRAME_DURATION = 1.0 / TARGET_FPS
end
function getTargetFPS()
return TARGET_FPS
end
-- custom run function; optimizes game by syncing draw/update calls
function love.run()
if love.load then love.load(love.arg.parseGameArguments(arg), arg) end
if love.timer then love.timer.step() end
local dt = 0
local last_time = love.timer.getTime()
local time_accumulator = 0.0
return function()
if love.event then
love.event.pump()
for name, a,b,c,d,e,f in love.event.poll() do
if name == "quit" then
if not love.quit or not love.quit() then
if disposeReplayThread then disposeReplayThread() end
return a or 0
end
end
love.handlers[name](a,b,c,d,e,f)
end
end
if love.timer then
processBGMFadeout(love.timer.step())
end
if scene and scene.update and love.timer then
scene:update()
if time_accumulator < FRAME_DURATION or TARGET_FPS == math.huge then
if love.graphics and love.graphics.isActive() and love.draw then
love.graphics.origin()
love.graphics.clear(love.graphics.getBackgroundColor())
love.draw()
love.graphics.present()
end
if love.mouse then
mouse_idle = mouse_idle + love.timer.getDelta()
love.mouse.setCursor(love.mouse.getSystemCursor(system_cursor_type))
if system_cursor_type ~= "arrow" then
system_cursor_type = "arrow"
end
end
if TARGET_FPS ~= math.huge then
-- request 1ms delays first but stop short of overshooting, then do "0ms" delays without overshooting (0ms requests generally do a delay of some nonzero amount of time, but maybe less than 1ms)
for milliseconds=0.001,0.000,-0.001 do
local max_delay = 0.0
while max_delay < FRAME_DURATION do
local delay_start_time = love.timer.getTime()
if delay_start_time - last_time < FRAME_DURATION - max_delay then
love.timer.sleep(milliseconds)
local last_delay = love.timer.getTime() - delay_start_time
if last_delay > max_delay then
max_delay = last_delay
end
else
break
end
end
end
while love.timer.getTime() - last_time < FRAME_DURATION do
-- busy loop, do nothing here until delay is finished; delays above stop short of finishing, so this part can finish it off precisely
end
end
end
local finish_delay_time = love.timer.getTime()
local real_frame_duration = finish_delay_time - last_time
time_accumulator = time_accumulator + real_frame_duration - FRAME_DURATION
last_time = finish_delay_time
if time_accumulator > 0.2 + FRAME_DURATION then
time_accumulator = 0
end
end
end
end