-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsource_bridge.py
More file actions
executable file
·3232 lines (2680 loc) · 119 KB
/
source_bridge.py
File metadata and controls
executable file
·3232 lines (2680 loc) · 119 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Universal Source Engine VScript Bridge
Connects Python to any Source game with VScript support or console
"""
import os
import json
import time
import threading
import platform
import psutil
import traceback
import random
import re
from mapbase_bridge import MapbaseBridge
if platform.system() == 'Windows':
import winreg
try:
import win32gui
import win32con
import win32api
import win32process
import win32clipboard
WINDOWS_API_AVAILABLE = True
except ImportError:
WINDOWS_API_AVAILABLE = False
print("Warning: pywin32 not available - install with: pip install pywin32")
else:
WINDOWS_API_AVAILABLE = False
print("Note: Console injection only supported on Windows")
print(" Linux users: VScript features work, but sourcemod spawning requires manual console")
class SourceBridge:
SUPPORTED_GAMES = {
'Team Fortress 2': {
'executables': ['hl2.exe', 'hl2_linux', 'tf_win64.exe', 'tf_linux64'],
'game_dir': 'tf',
'scriptdata': 'scriptdata',
'cmdline_contains': 'Team Fortress 2'
},
'Counter-Strike Source': {
'executables': ['hl2.exe', 'hl2_linux', 'cstrike.exe', 'cstrike_win64.exe', 'cstrike_linux64'],
'game_dir': 'cstrike',
'scriptdata': 'scriptdata',
'cmdline_contains': 'Counter-Strike Source'
},
'Day of Defeat Source': {
'executables': ['hl2.exe', 'hl2_linux', 'dod.exe', 'dod_win64.exe', 'dod_linux64'],
'game_dir': 'dod',
'scriptdata': 'scriptdata',
'cmdline_contains': 'Day of Defeat Source'
},
'Half-Life 2 Deathmatch': {
'executables': ['hl2.exe', 'hl2_linux', 'hl2mp.exe', 'hl2mp_win64.exe', 'hl2mp_linux64'],
'game_dir': 'hl2mp',
'scriptdata': 'scriptdata',
'cmdline_contains': 'Half-Life 2 Deathmatch'
},
'Half-Life 1 Source Deathmatch': {
'executables': ['hl2.exe', 'hl2_linux', 'hl1mp.exe', 'hl1mp_win64.exe', 'hl1mp_linux64'],
'game_dir': 'hl1mp',
'scriptdata': 'scriptdata',
'cmdline_contains': 'Half-Life 1 Source Deathmatch'
},
'Garry\'s Mod 9': {
'executables': ['hl2.exe', 'hl2_linux'],
'game_dir': 'gmod9',
'scriptdata': 'data',
'cmdline_contains': 'gmod9',
'is_gmod': True
},
'Garry\'s Mod 10': {
'executables': ['hl2.exe', 'hl2_linux'],
'game_dir': 'garrysmod10classic',
'scriptdata': 'data',
'cmdline_contains': 'garrysmod10classic',
'is_gmod': True
},
'Garry\'s Mod 11': {
'executables': ['hl2.exe', 'hl2_linux'],
'game_dir': 'garrysmod',
'scriptdata': 'data',
'cmdline_contains': 'garrysmod',
'is_gmod': True
},
'Garry\'s Mod 12': {
'executables': ['hl2.exe', 'hl2_linux'],
'game_dir': 'garrysmod12',
'scriptdata': 'data',
'cmdline_contains': 'garrysmod12',
'is_gmod': True
},
'Garry\'s Mod 13': {
'executables': ['hl2.exe', 'hl2_linux', 'gmod.exe', 'gmod', 'gmod64', 'gmod32', 'gmod_linux'],
'game_dir': 'garrysmod',
'scriptdata': 'data',
'cmdline_contains': 'garrysmod',
'is_gmod': True,
'install_type': 'standalone',
'install_dir': 'GarrysMod'
}
}
def __init__(self, verbose=False):
self.game_path = None
self.vscripts_path = None
self.command_file = None
self.response_file = None
self.running = False
self.watcher_thread = None
self.last_response_time = 0
self.detected_games = []
self.active_game = None
self.verbose = verbose
self.command_count = 0
self.session_id = int(time.time() * 1000) + random.randint(0, 9999)
self.gmod_bridge = None
self.mapbase_bridge = None
try:
self._cleanup_old_files()
self._detect_running_game()
except Exception as e:
print(f"[error] initialization failed: {e}")
if self.verbose:
traceback.print_exc()
def _log(self, message):
if self.verbose:
print(f"[trace] {message}")
def _safe_file_operation(self, operation, filepath, error_msg):
"""safely perform file operations with error handling"""
try:
return operation(filepath)
except (PermissionError, FileNotFoundError):
return False
except Exception as e:
if self.verbose:
print(f"[error] {error_msg}: {e}")
return False
def _cleanup_old_files(self):
"""remove stale command/response files from previous sessions"""
steam_install_path = self._get_steam_install_path()
if not steam_install_path:
return
steam_libraries = self._parse_library_folders_vdf(steam_install_path)
for library_path in steam_libraries:
for game_name, game_info in self.SUPPORTED_GAMES.items():
try:
if game_info.get('is_gmod'):
continue # gmod cleanup handled by gmod bridge
game_root = os.path.join(library_path, 'steamapps', 'common', game_name)
if not os.path.exists(game_root):
game_root = os.path.join(library_path, 'SteamApps', 'common', game_name)
if not os.path.exists(game_root):
continue
scriptdata_path = os.path.join(game_root, game_info['game_dir'], game_info['scriptdata'])
if os.path.exists(scriptdata_path):
for filename in ["python_command.txt", "python_response.txt"]:
filepath = os.path.join(scriptdata_path, filename)
self._safe_file_operation(
lambda p: os.remove(p) if os.path.exists(p) else None,
filepath,
f"failed to cleanup {filename}"
)
except:
continue
def _get_steam_path_from_process(self):
"""detect steam installation from running steam process"""
try:
for proc in psutil.process_iter(['name', 'exe']):
try:
proc_name = proc.info['name']
if proc_name and proc_name.lower() in ['steam.exe', 'steam']:
exe_path = proc.info.get('exe')
if exe_path and os.path.exists(exe_path):
steam_dir = os.path.dirname(exe_path)
if os.path.exists(os.path.join(steam_dir, 'steamapps')):
self._log(f"found steam from process: {steam_dir}")
return steam_dir
parent_dir = os.path.dirname(steam_dir)
if os.path.exists(os.path.join(parent_dir, 'steamapps')):
self._log(f"found steam from process: {parent_dir}")
return parent_dir
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
except Exception as e:
if self.verbose:
print(f"[warning] process detection failed: {e}")
return None
def _get_steam_install_path(self):
"""get steam installation directory using multiple detection methods"""
system = platform.system()
if system == 'Windows':
registry_paths = [
r"SOFTWARE\Wow6432Node\Valve\Steam",
r"SOFTWARE\Valve\Steam"
]
for reg_path in registry_paths:
try:
hkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, reg_path)
install_path, _ = winreg.QueryValueEx(hkey, "InstallPath")
winreg.CloseKey(hkey)
if install_path and os.path.exists(install_path):
self._log(f"found steam via registry: {install_path}")
return install_path
except (FileNotFoundError, OSError):
continue
process_path = self._get_steam_path_from_process()
if process_path:
return process_path
for path in [r"C:\Program Files (x86)\Steam", r"C:\Program Files\Steam"]:
if os.path.exists(path):
self._log(f"found steam at default location: {path}")
return path
elif system == 'Linux':
for path in ["~/.local/share/Steam", "~/.steam/steam", "~/.steam/root"]:
expanded = os.path.expanduser(path)
if os.path.islink(expanded):
expanded = os.path.realpath(expanded)
if os.path.exists(expanded):
self._log(f"found steam at: {expanded}")
return expanded
flatpak_steam = "~/.var/app/com.valvesoftware.Steam/.local/share/Steam"
expanded_flatpak = os.path.expanduser(flatpak_steam)
if os.path.exists(expanded_flatpak):
self._log(f"found flatpak steam at: {expanded_flatpak}")
return expanded_flatpak
process_path = self._get_steam_path_from_process()
if process_path:
return process_path
return None
def _get_running_game_library(self, game_name):
"""detect which steam library the running game is in"""
try:
for proc in psutil.process_iter(['name', 'exe', 'cmdline']):
try:
proc_name = proc.info['name']
exe_path = proc.info.get('exe')
cmdline = proc.info['cmdline']
if not cmdline or not exe_path:
continue
cmdline_str = ' '.join(cmdline).lower()
game_info = self.SUPPORTED_GAMES.get(game_name)
if not game_info:
continue
if proc_name.lower() in [exe.lower() for exe in game_info['executables']]:
if game_info['cmdline_contains'].lower() in cmdline_str or \
game_info['game_dir'] in cmdline_str:
exe_dir = os.path.dirname(exe_path)
current = exe_dir
for _ in range(10):
if os.path.exists(os.path.join(current, 'steamapps')):
self._log(f"detected running game library: {current}")
return current
parent = os.path.dirname(current)
if parent == current:
break
current = parent
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
except Exception as e:
if self.verbose:
print(f"[warning] running game library detection failed: {e}")
return None
def _parse_library_folders_vdf(self, steam_path):
"""parse libraryfolders.vdf to get all steam library locations"""
vdf_path = os.path.join(steam_path, 'steamapps', 'libraryfolders.vdf')
if not os.path.exists(vdf_path):
vdf_path = os.path.join(steam_path, 'SteamApps', 'libraryfolders.vdf')
if not os.path.exists(vdf_path):
self._log(f"libraryfolders.vdf not found")
return [steam_path]
libraries = [steam_path]
try:
with open(vdf_path, 'r', encoding='utf-8') as f:
content = f.read()
path_pattern = r'"path"\s+"([^"]+)"'
matches = re.findall(path_pattern, content)
for match in matches:
library_path = match.replace('\\\\', '\\')
if os.path.exists(library_path) and library_path not in libraries:
libraries.append(library_path)
self._log(f"found library: {library_path}")
return libraries
except Exception as e:
self._log(f"failed to parse libraryfolders.vdf: {e}")
return [steam_path]
def _resolve_game_path(self, game_arg, exe_path=None):
"""resolve -game argument into an absolute path if possible"""
if not game_arg:
return None
self._log(f"resolving -game argument: '{game_arg}'")
cleaned = os.path.expanduser(game_arg.strip('"'))
candidates = []
if os.path.isabs(cleaned):
candidates.append(os.path.normpath(cleaned))
self._log(f" candidate (absolute): {candidates[-1]}")
# candidates from exe directory
exe_dir = os.path.dirname(exe_path) if exe_path else None
if exe_dir:
self._log(f" exe directory: {exe_dir}")
# candidate 2: relative to exe dir
candidate = os.path.normpath(os.path.join(exe_dir, cleaned))
candidates.append(candidate)
self._log(f" candidate (exe_dir): {candidate}")
# candidate 3: relative to parent of exe dir
parent_dir = os.path.dirname(exe_dir)
if parent_dir and parent_dir != exe_dir:
candidate = os.path.normpath(os.path.join(parent_dir, cleaned))
candidates.append(candidate)
self._log(f" candidate (parent): {candidate}")
# candidate 4 & 5: try resolving against steam library root if path contains steamapps
steamapps_index = exe_dir.lower().find('steamapps')
if steamapps_index != -1:
steamapps_root = exe_dir[:steamapps_index + len('steamapps')]
self._log(f" found steamapps root: {steamapps_root}")
candidate = os.path.normpath(os.path.join(steamapps_root, 'sourcemods', cleaned))
candidates.append(candidate)
self._log(f" candidate (sourcemods): {candidate}")
candidate = os.path.normpath(os.path.join(steamapps_root, 'common', cleaned))
candidates.append(candidate)
self._log(f" candidate (common): {candidate}")
else:
self._log(" no exe_path provided, cannot resolve relative paths")
# deduplicate while preserving order
seen = set()
unique_candidates = []
for cand in candidates:
if cand not in seen:
unique_candidates.append(cand)
seen.add(cand)
# test each candidate
self._log(f" testing {len(unique_candidates)} unique candidates...")
for i, cand in enumerate(unique_candidates, 1):
exists = os.path.isdir(cand)
self._log(f" [{i}] {cand} - {'EXISTS' if exists else 'not found'}")
if exists:
self._log(f" resolved successfully: {cand}")
return cand
self._log(f" resolution failed: no valid path found")
return None
def _is_mapbase_path(self, path):
"""return True if the path looks like a mapbase-based mod"""
if not path:
return False
abs_path = os.path.abspath(path)
base_name = os.path.basename(abs_path).lower()
self._log(f"checking for mapbase in: {abs_path}")
# check if the folder itself is named mapbase
if base_name == 'mapbase':
self._log(f" folder name is 'mapbase' - detected")
return True
# check if there's a mapbase subfolder inside this mod
mapbase_subdir = os.path.join(abs_path, 'mapbase')
if os.path.isdir(mapbase_subdir):
self._log(f" found mapbase subdirectory: {mapbase_subdir}")
return True
# check if there's a mapbase folder in the parent directory
parent_dir = os.path.dirname(abs_path)
mapbase_parent = os.path.join(parent_dir, 'mapbase')
if os.path.isdir(mapbase_parent):
self._log(f" found mapbase in parent: {mapbase_parent}")
return True
self._log(f" not a mapbase mod")
return False
def _setup_mapbase_mod(self, mod_name, mod_path):
"""setup paths and files for a mapbase-based sourcemod"""
try:
bridge = MapbaseBridge(mod_path, verbose=self.verbose)
if not bridge.prepare_paths():
return False
bridge.install_scripts()
self.mapbase_bridge = bridge
self.active_game = f"Mapbase: {mod_name}"
self.game_path = bridge.scriptdata_path
self.vscripts_path = bridge.vscripts_path
self.command_file = bridge.command_file
self.response_file = bridge.response_file
print(f"\n[active] Mapbase Mod: {mod_name} (running)")
print(f" mod path: {mod_path}")
print(f" scriptdata: {self.game_path}")
print(f" vscripts: {self.vscripts_path}")
print(f" mode: VScript bridge (mapbase)")
return True
except Exception as e:
print(f"[error] failed to setup mapbase mod: {e}")
if self.verbose:
traceback.print_exc()
return False
def _setup_mapbase_path(self, mod_name, steam_libraries):
"""try to locate and setup a mapbase-based mod by name"""
for library_path in steam_libraries:
sourcemods_path = os.path.join(library_path, 'steamapps', 'sourcemods')
if not os.path.exists(sourcemods_path):
sourcemods_path = os.path.join(library_path, 'SteamApps', 'sourcemods')
candidate = os.path.join(sourcemods_path, mod_name)
if os.path.isdir(candidate) and self._is_mapbase_path(candidate):
return self._setup_mapbase_mod(mod_name, candidate)
return False
def _detect_running_game(self):
"""find which source game is currently running"""
print("\n" + "="*70)
print("SOURCE ENGINE BRIDGE")
print("="*70)
print("\n[scan] detecting steam libraries...")
steam_install_path = self._get_steam_install_path()
if not steam_install_path:
print(" [error] steam installation not found")
print("="*70 + "\n")
return
print(f" [steam] {steam_install_path}")
all_steam_libraries = self._parse_library_folders_vdf(steam_install_path)
print(f" [libraries] found {len(all_steam_libraries)} steam libraries")
print("\n[scan] detecting running games...")
running_game = None
running_mod = None
running_mod_path = None
running_mapbase = False
running_gmod_dir = None
try:
for proc in psutil.process_iter(['name', 'cmdline', 'exe']):
try:
proc_name = proc.info.get('name')
if not proc_name:
continue
cmdline = proc.info.get('cmdline')
if not cmdline:
continue
# skip gamescope wrapper processes
if proc_name in ['gamescope', 'gamescope-session', 'gamescopereaper']:
continue
cmdline_str = ' '.join(cmdline)
proc_name_lower = proc_name.lower()
# check for gmod processes first
if proc_name_lower in ['hl2.exe', 'hl2_linux', 'gmod.exe', 'gmod', 'gmod64', 'gmod32', 'gmod_linux']:
for i, arg in enumerate(cmdline):
if arg.lower() == '-game' and i + 1 < len(cmdline):
game_arg = cmdline[i + 1].strip('"').lower()
# check if it's a gmod sourcemod
if 'gmod9' in game_arg or 'garrysmod9' in game_arg:
running_gmod_dir = 'gmod9'
running_game = 'Garry\'s Mod 9'
print(f" [found] {running_game}")
if self._setup_gmod_path(running_game, self.SUPPORTED_GAMES[running_game], all_steam_libraries):
return
break
elif 'garrysmod10classic' in game_arg:
running_gmod_dir = 'garrysmod10classic'
running_game = 'Garry\'s Mod 10'
print(f" [found] {running_game}")
if self._setup_gmod_path(running_game, self.SUPPORTED_GAMES[running_game], all_steam_libraries):
return
break
elif 'garrysmod12' in game_arg:
running_gmod_dir = 'garrysmod12'
running_game = 'Garry\'s Mod 12'
print(f" [found] {running_game}")
if self._setup_gmod_path(running_game, self.SUPPORTED_GAMES[running_game], all_steam_libraries):
return
break
elif 'garrysmod' in game_arg and 'garrysmod10' not in game_arg and 'garrysmod12' not in game_arg:
# check if it's sourcemod (has 'sourcemods' in path) or retail
is_sourcemod = False
try:
exe_path = proc.info.get('exe')
if exe_path:
is_sourcemod = 'sourcemods' in exe_path.lower()
except:
pass
# also check cmdline for sourcemods path
if not is_sourcemod:
for cmd_part in cmdline:
if 'sourcemods' in cmd_part.lower():
is_sourcemod = True
break
if is_sourcemod:
# sourcemod garrysmod (11)
running_gmod_dir = 'garrysmod'
running_game = 'Garry\'s Mod 11'
print(f" [found] {running_game}")
if self._setup_gmod_path(running_game, self.SUPPORTED_GAMES[running_game], all_steam_libraries):
return
else:
# try retail gmod 13
gmod13_info = self.SUPPORTED_GAMES.get('Garry\'s Mod 13')
if gmod13_info and self._setup_gmod_path('Garry\'s Mod 13', gmod13_info, all_steam_libraries):
running_game = 'Garry\'s Mod 13'
print(f" [found] {running_game}")
return
# fallback to sourcemod if retail not found
running_gmod_dir = 'garrysmod'
running_game = 'Garry\'s Mod 11'
print(f" [found] {running_game}")
if self._setup_gmod_path(running_game, self.SUPPORTED_GAMES[running_game], all_steam_libraries):
return
break
# check for supported games
for game_name, game_info in self.SUPPORTED_GAMES.items():
if game_info.get('is_gmod'):
continue
if proc_name.lower() in [exe.lower() for exe in game_info['executables']]:
if game_info['cmdline_contains'].lower() in cmdline_str.lower() or \
game_info['game_dir'] in cmdline_str.lower():
running_game = game_name
print(f" [found] {game_name}")
self._log(f" process: {proc_name}")
break
if running_game:
break
# check for hl2.exe with -game argument (source mods and standalone games)
if proc_name_lower in ['hl2.exe', 'hl2_linux']:
game_paths = []
resolved_game_paths = []
exe_path = proc.info.get('exe')
if exe_path:
self._log(f"found hl2 process: {proc_name}")
self._log(f" exe location: {exe_path}")
else:
self._log(f"found hl2 process: {proc_name} (no exe path available)")
# extract -game arguments
for i, arg in enumerate(cmdline):
if arg.lower() == '-game' and i + 1 < len(cmdline):
game_arg = cmdline[i + 1].strip('"')
if not game_arg:
continue
self._log(f" -game argument: '{game_arg}'")
game_paths.append(game_arg)
# try to resolve the path
resolved_path = self._resolve_game_path(game_arg, exe_path)
if resolved_path:
self._log(f" resolved successfully")
resolved_game_paths.append(resolved_path)
else:
self._log(f" failed to resolve path")
# if exe_path is unavailable (gamescope/proton), search steam libraries
if not resolved_game_paths and game_paths and not exe_path:
self._log(" exe_path unavailable, searching steam libraries...")
for game_arg in game_paths:
self._log(f" searching for: {game_arg}")
# normalize the game_arg for fuzzy matching (remove spaces, lowercase)
normalized_arg = game_arg.replace(' ', '').lower()
# search in all steam libraries for standalone games
for library_path in all_steam_libraries:
self._log(f" checking library: {library_path}")
# check both common and sourcemods
search_paths = [
('common', os.path.join(library_path, 'steamapps', 'common')),
('common', os.path.join(library_path, 'SteamApps', 'common')),
('sourcemods', os.path.join(library_path, 'steamapps', 'sourcemods')),
('sourcemods', os.path.join(library_path, 'SteamApps', 'sourcemods'))
]
for search_type, search_path in search_paths:
if not os.path.exists(search_path):
continue
self._log(f" searching {search_type}: {search_path}")
try:
for folder in os.listdir(search_path):
# fuzzy match: compare with spaces removed
normalized_folder = folder.replace(' ', '').lower()
if normalized_folder == normalized_arg:
self._log(f" found matching folder: {folder}")
game_root = os.path.join(search_path, folder)
# check for nested directory with same/similar name
nested_candidates = [
os.path.join(game_root, folder), # exact match
os.path.join(game_root, game_arg), # game arg name
os.path.join(game_root, game_arg.replace(' ', '')), # no spaces
]
# also check all subdirs that might match
try:
for subdir in os.listdir(game_root):
subdir_path = os.path.join(game_root, subdir)
if os.path.isdir(subdir_path):
normalized_subdir = subdir.replace(' ', '').lower()
if normalized_subdir == normalized_arg:
nested_candidates.append(subdir_path)
except:
pass
# test nested candidates
for candidate in nested_candidates:
if os.path.isdir(candidate):
# verify it's a real game folder (has gameinfo.txt or bin folder)
if (os.path.exists(os.path.join(candidate, 'gameinfo.txt')) or
os.path.exists(os.path.join(candidate, 'bin'))):
self._log(f" valid game folder: {candidate}")
resolved_game_paths.append(candidate)
break
# if no nested folder worked, try the root itself
if not resolved_game_paths:
if (os.path.exists(os.path.join(game_root, 'gameinfo.txt')) or
os.path.exists(os.path.join(game_root, 'bin'))):
self._log(f" valid game folder (root): {game_root}")
resolved_game_paths.append(game_root)
if resolved_game_paths:
break
if resolved_game_paths:
break
except Exception as e:
self._log(f" error listing directory: {e}")
if resolved_game_paths:
break
if resolved_game_paths:
break
# if no resolved path but we have exe_path, try to find game from exe location
if not resolved_game_paths and exe_path and game_paths:
self._log(" attempting resolution from exe location...")
exe_dir = os.path.dirname(exe_path)
for game_arg in game_paths:
# try the subfolder with the game_arg name (case-insensitive)
for variant in [game_arg.lower(), game_arg]:
game_folder_path = os.path.join(exe_dir, variant)
self._log(f" checking: {game_folder_path}")
if os.path.isdir(game_folder_path):
self._log(f" found: {game_folder_path}")
resolved_game_paths.append(game_folder_path)
break
# mapbase detection using resolved paths or exe directory
mapbase_candidates = list(resolved_game_paths)
self._log(f" checking {len(mapbase_candidates)} resolved paths for mapbase...")
if exe_path:
exe_dir = os.path.dirname(exe_path)
# check if exe_dir itself has mapbase (for standalone games)
if self._is_mapbase_path(exe_dir):
self._log(f" exe_dir is mapbase location")
for game_arg in game_paths:
for variant in [game_arg.lower(), game_arg]:
game_folder = os.path.join(exe_dir, variant)
if os.path.isdir(game_folder):
self._log(f" adding mapbase candidate: {game_folder}")
mapbase_candidates.append(game_folder)
break
for candidate in mapbase_candidates:
if self._is_mapbase_path(candidate):
running_mod = os.path.basename(candidate.rstrip('/\\'))
running_mod_path = candidate
running_mapbase = True
print(f" [found] Mapbase Game: {running_mod}")
print(f" [process] {proc_name} -game {candidate}")
self._log(f" detected as mapbase mod: {running_mod}")
break
if running_mapbase:
break
if not running_mod and not running_mapbase and resolved_game_paths:
for resolved_path in resolved_game_paths:
# verify it's a valid source game with gameinfo.txt
gameinfo_path = os.path.join(resolved_path, 'gameinfo.txt')
if os.path.exists(gameinfo_path):
running_mod = os.path.basename(resolved_path.rstrip('/\\'))
running_mod_path = resolved_path
print(f" [found] Standalone Source Game: {running_mod}")
print(f" [process] {proc_name} -game {resolved_path}")
self._log(f" detected as standalone source game: {running_mod}")
# check if it has VScript support (scripts/vscripts folder)
vscripts_check = os.path.join(resolved_path, 'scripts', 'vscripts')
if os.path.exists(vscripts_check):
self._log(f" has VScript support")
else:
self._log(f" no VScript support detected")
break
if running_mod:
break
# check if it's a standalone source game (not sourcemod, not mapbase)
self._log(" checking for standalone source game...")
if not running_mod and not running_mapbase and resolved_game_paths:
for resolved_path in resolved_game_paths:
# check multiple possible locations for gameinfo.txt
gameinfo_candidates = [
resolved_path, # direct path
os.path.join(resolved_path, os.path.basename(resolved_path.rstrip('/\\'))), # nested folder with same name
]
# also check subdirectories that might contain the actual game
try:
for subdir in os.listdir(resolved_path):
subdir_path = os.path.join(resolved_path, subdir)
if os.path.isdir(subdir_path):
gameinfo_candidates.append(subdir_path)
except:
pass
# test each candidate
for candidate in gameinfo_candidates:
gameinfo_path = os.path.join(candidate, 'gameinfo.txt')
self._log(f" checking gameinfo.txt at: {gameinfo_path}")
if os.path.exists(gameinfo_path):
running_mod = os.path.basename(candidate.rstrip('/\\'))
running_mod_path = candidate
print(f" [found] Standalone Source Game: {running_mod}")
print(f" [process] {proc_name} -game {candidate}")
self._log(f" detected as standalone source game: {running_mod}")
break
if running_mod:
break
if running_mod:
break
# look for sourcemods path in resolved paths
self._log(" checking for sourcemod paths...")
for game_path in resolved_game_paths + game_paths:
if 'sourcemods' in str(game_path).lower():
self._log(f" found sourcemods in path: {game_path}")
parts = str(game_path).replace('\\', '/').split('/')
for i, part in enumerate(parts):
if part.lower() == 'sourcemods' and i + 1 < len(parts):
running_mod = parts[i + 1]
running_mod_path = self._resolve_game_path(game_path, exe_path) or game_path
print(f" [found] Source Mod: {running_mod}")
print(f" [process] {proc_name} -game {running_mod_path}")
self._log(f" detected as sourcemod: {running_mod}")
break
if running_mod:
break
if running_mod:
break
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
except Exception as e:
if self.verbose:
print(f"[warning] process check error: {e}")
continue
except Exception as e:
print(f"[warning] process enumeration error: {e}")
if running_mod:
# prefer mapbase setup when detected
if running_mapbase or (running_mod_path and self._is_mapbase_path(running_mod_path)):
if running_mod_path:
if self._setup_mapbase_mod(running_mod, running_mod_path):
return
else:
if self._setup_mapbase_path(running_mod, all_steam_libraries):
return
else:
if running_mod_path:
if self._setup_sourcemod_from_path(running_mod, running_mod_path):
return
else:
if self._setup_sourcemod_path(running_mod, all_steam_libraries):
return
print(f"[warning] found mod '{running_mod}' but couldn't setup paths")
if not running_game:
print(" [info] no running game found, scanning installed games...")
self._scan_installed_games(all_steam_libraries)
self._scan_sourcemods(all_steam_libraries)
else:
active_library = self._get_running_game_library(running_game)
if active_library:
steam_libraries = [active_library]
print(f" [active library] {active_library}")
else:
steam_libraries = all_steam_libraries
print(f" [warning] couldn't detect active library, checking all libraries")
if not self._setup_game_path(running_game, steam_libraries):
print(f"[error] failed to locate {running_game} files")
self._scan_installed_games(all_steam_libraries)
self._scan_sourcemods(all_steam_libraries)
def _setup_sourcemod_from_path(self, mod_name, mod_path):
"""setup paths for a sourcemod using direct path from process"""
try:
# check if this is actually a mapbase mod
if self._is_mapbase_path(mod_path):
return self._setup_mapbase_mod(mod_name, mod_path)
scriptdata_path = os.path.join(mod_path, 'scriptdata')
cfg_path = os.path.join(mod_path, 'cfg')
os.makedirs(scriptdata_path, exist_ok=True)
os.makedirs(cfg_path, exist_ok=True)
self.active_game = mod_name
self.game_path = scriptdata_path
self.vscripts_path = None
self.command_file = None
print(f"\n[active] Source Mod: {mod_name} (running)")
print(f" mod path: {mod_path}")
if platform.system() == 'Windows' and WINDOWS_API_AVAILABLE:
print(f" mode: legacy console injection (no VScript)")
else:
print(f" mode: no VScript support (manual spawning only)")
print("="*70 + "\n")
return True
except Exception as e:
print(f"[error] failed to setup paths: {e}")
if self.verbose:
traceback.print_exc()
return False
def _setup_sourcemod_path(self, mod_name, steam_libraries):
"""setup paths for a sourcemod"""
for library_path in steam_libraries:
sourcemod_path = os.path.join(library_path, 'steamapps', 'sourcemods', mod_name)
if not os.path.exists(sourcemod_path):
sourcemod_path = os.path.join(library_path, 'SteamApps', 'sourcemods', mod_name)
if os.path.exists(sourcemod_path):
return self._setup_sourcemod_from_path(mod_name, sourcemod_path)
return False
def _scan_sourcemods(self, steam_libraries):
"""scan for installed source mods in sourcemods folder"""
print("\n[scan] detecting Source mods...")
for library_path in steam_libraries:
sourcemods_path = os.path.join(library_path, 'steamapps', 'sourcemods')
if not os.path.exists(sourcemods_path):
sourcemods_path = os.path.join(library_path, 'SteamApps', 'sourcemods')
if not os.path.exists(sourcemods_path):
continue
try:
for mod_name in os.listdir(sourcemods_path):
mod_path = os.path.join(sourcemods_path, mod_name)
if os.path.isdir(mod_path):
gameinfo_path = os.path.join(mod_path, 'gameinfo.txt')
if os.path.exists(gameinfo_path):
if self._is_mapbase_path(mod_path):
scriptdata_path = os.path.join(mod_path, 'scriptdata')
vscripts_path = os.path.join(mod_path, 'scripts', 'vscripts')
os.makedirs(scriptdata_path, exist_ok=True)
os.makedirs(vscripts_path, exist_ok=True)
self.detected_games.append({
'name': f"Mapbase: {mod_name}",
'library': library_path,
'scriptdata_path': scriptdata_path,
'vscripts_path': vscripts_path,
'is_sourcemod': True,
'is_mapbase': True
})
print(f" [mapbase] {mod_name} (in {library_path})")
continue
scriptdata_path = os.path.join(mod_path, 'scriptdata')
os.makedirs(scriptdata_path, exist_ok=True)
self.detected_games.append({
'name': mod_name,
'library': library_path,
'scriptdata_path': scriptdata_path,
'vscripts_path': None,
'is_sourcemod': True
})
print(f" [sourcemod] {mod_name} (in {library_path})")
except Exception as e:
if self.verbose:
print(f"[warning] Error scanning sourcemods: {e}")
# if no supported games found, use first sourcemod
if not self.active_game and self.detected_games:
for game in self.detected_games:
if game.get('is_sourcemod'):
print(f"\n[active] using Source Mod: {game['name']} (not running)")
self.active_game = game['name']
self.game_path = game['scriptdata_path']
self.vscripts_path = None
self.command_file = None
print(" mode: console injection (no VScript)")
break
def _setup_game_path(self, game_name, steam_libraries):
"""setup paths for specific game using discovered libraries"""
game_info = self.SUPPORTED_GAMES.get(game_name)
if not game_info:
print(f"[error] unknown game: {game_name}")
return False
if game_info.get('is_gmod'):
return self._setup_gmod_path(game_name, game_info, steam_libraries)