-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgmod_bridge.py
More file actions
1842 lines (1518 loc) · 53.2 KB
/
gmod_bridge.py
File metadata and controls
1842 lines (1518 loc) · 53.2 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
"""
Garry's Mod Bridge for SourceBox (GMod 9-13)
Automatically installs Lua addon to sourcemods and retail installs
"""
import os
import json
import time
import platform
import re
import psutil
class GModBridge:
# gmod versions as sourcemods (9-12)
GMOD_SOURCEMODS = {
'gmod9': 'GMod 9',
'garrysmod10classic': 'GMod 10 Classic',
'garrysmod': 'GMod 11',
'garrysmod12': 'GMod 12'
}
# retail gmod 13 install (steamapps/common/GarrysMod/garrysmod)
GMOD_RETAIL = {
'gmod13': {
'name': 'GMod 13',
'install_dir': 'GarrysMod',
'game_dir': 'garrysmod'
}
}
def __init__(self):
self.data_path = None
self.addon_path = None
self.command_file = None
self.response_file = None
self.session_id = int(time.time())
self.command_id = 0
self.active_gmod = None
self.gmod_version = None
self.is_gmod9 = False
self._detect_gmod()
def _get_steam_path_from_process(self):
"""detect steam from running 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')):
return steam_dir
parent_dir = os.path.dirname(steam_dir)
if os.path.exists(os.path.join(parent_dir, 'steamapps')):
return parent_dir
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
except:
pass
return None
def _get_steam_install_path(self):
"""get steam installation directory"""
system = platform.system()
if system == 'Windows':
try:
import winreg
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):
return install_path
except (FileNotFoundError, OSError):
continue
except ImportError:
pass
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):
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):
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):
return expanded_flatpak
process_path = self._get_steam_path_from_process()
if process_path:
return process_path
return None
def _parse_library_folders_vdf(self, steam_path):
"""parse libraryfolders.vdf"""
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):
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)
return libraries
except:
return [steam_path]
def _get_retail_gmod_path(self, library_path):
"""return retail gmod13 garrysmod directory if it exists"""
retail_info = self.GMOD_RETAIL['gmod13']
for steamapps_dir in ['steamapps', 'SteamApps']:
game_root = os.path.join(library_path, steamapps_dir, 'common', retail_info['install_dir'])
mod_path = os.path.join(game_root, retail_info['game_dir'])
if os.path.exists(mod_path):
return mod_path
return None
def _detect_gmod(self):
"""detect gmod installation"""
print("\n" + "="*70)
print("GARRY'S MOD BRIDGE")
print("="*70)
print("\n[scan] detecting steam libraries...")
steam_path = self._get_steam_install_path()
if not steam_path:
print(" [error] steam installation not found")
print("="*70 + "\n")
return
print(f" [steam] {steam_path}")
all_libraries = self._parse_library_folders_vdf(steam_path)
print(f" [libraries] found {len(all_libraries)} steam libraries")
print("\n[scan] detecting gmod installations...")
running_gmod = self._detect_running_gmod()
# first scan sourcemod variants (gmod 9-12)
for library_path in all_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 os.path.exists(sourcemods_path):
for mod_folder, mod_name in self.GMOD_SOURCEMODS.items():
mod_path = os.path.join(sourcemods_path, mod_folder)
if os.path.exists(mod_path):
data_path = os.path.join(mod_path, 'data')
is_gmod9 = mod_folder == 'gmod9'
if is_gmod9:
addon_path = os.path.join(mod_path, 'lua', 'init')
else:
addon_path = os.path.join(mod_path, 'addons', 'sourcebox')
os.makedirs(data_path, exist_ok=True)
if running_gmod and running_gmod == mod_folder:
self._setup_paths(data_path, addon_path, mod_name, is_gmod9, mod_folder)
self._install_lua_addon()
print(f" [found] {mod_name} (RUNNING)")
print(f" [library] {library_path}")
return
elif not self.active_gmod:
print(f" [installed] {mod_name} (in {library_path})")
# then scan retail gmod 13 install
for library_path in all_libraries:
retail_path = self._get_retail_gmod_path(library_path)
if not retail_path:
continue
data_path = os.path.join(retail_path, 'data')
addon_path = os.path.join(retail_path, 'addons', 'sourcebox')
os.makedirs(data_path, exist_ok=True)
if running_gmod in ['gmod13', 'garrysmod']:
self._setup_paths(data_path, addon_path, self.GMOD_RETAIL['gmod13']['name'], False, 'gmod13')
self._install_lua_addon()
print(f" [found] {self.GMOD_RETAIL['gmod13']['name']} (RUNNING)")
print(f" [library] {library_path}")
return
elif not self.active_gmod:
print(f" [installed] {self.GMOD_RETAIL['gmod13']['name']} (in {library_path})")
def _detect_running_gmod(self):
"""detect running gmod"""
try:
for proc in psutil.process_iter(['name', 'exe', 'cmdline']):
try:
proc_name = proc.info.get('name')
if not proc_name:
continue
cmdline = proc.info.get('cmdline')
if not cmdline:
continue
cmdline_str = ' '.join(cmdline).lower()
exe_path = proc.info.get('exe') or ''
exe_lower = exe_path.lower()
proc_lower = proc_name.lower()
# hl2 based binaries or gmod specific binaries
if proc_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()
if 'gmod9' in game_arg or 'garrysmod9' in game_arg:
return 'gmod9'
elif 'garrysmod12' in game_arg:
return 'garrysmod12'
elif 'garrysmod10classic' in game_arg:
return 'garrysmod10classic'
elif 'garrysmod' in game_arg:
# differentiate sourcemod vs retail by path hint
if 'sourcemods' in game_arg or 'sourcemods' in exe_lower:
return 'garrysmod'
return 'gmod13'
# fallback: detect retail gmod if binary path clearly in GarrysMod
if 'garrysmod' in exe_lower and 'sourcemods' not in exe_lower:
return 'gmod13'
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
except:
pass
return None
def _setup_paths(self, data_path, addon_path, gmod_name, is_gmod9=False, gmod_version=None):
"""setup paths"""
self.data_path = data_path
self.addon_path = addon_path
self.active_gmod = gmod_name
self.is_gmod9 = is_gmod9
self.gmod_version = gmod_version or ('gmod9' if is_gmod9 else None)
self.command_file = os.path.join(data_path, "sourcebox_command.txt")
self.response_file = os.path.join(data_path, "sourcebox_response.txt")
try:
if os.path.exists(self.command_file):
os.remove(self.command_file)
if os.path.exists(self.response_file):
os.remove(self.response_file)
except:
pass
def _install_lua_addon(self):
"""install lua addon automatically"""
if not self.addon_path:
return
print("\n[install] creating lua addon...")
try:
if self.is_gmod9:
# gmod 9 uses init folder structure
os.makedirs(self.addon_path, exist_ok=True)
# write picker script
picker_content = self._get_gmod9_picker_lua()
with open(os.path.join(self.addon_path, 'sv_picker_gmod9.lua'), 'w') as f:
f.write(picker_content)
# write spawner script
spawner_content = self._get_gmod9_spawner_lua()
with open(os.path.join(self.addon_path, 'sv_auto_spawner_gmod9.lua'), 'w') as f:
f.write(spawner_content)
# write bridge script
bridge_content = self._get_gmod9_bridge_lua()
with open(os.path.join(self.addon_path, 'sv_python_listener_gmod9.lua'), 'w') as f:
f.write(bridge_content)
print(f" [created] {self.addon_path}")
print(f" [files] sv_picker_gmod9.lua, sv_auto_spawner_gmod9.lua, sv_python_listener_gmod9.lua")
print(f" [gmod 9] scripts will auto-load from lua/init/")
else:
# gmod 10-12 uses addons structure
lua_path = os.path.join(self.addon_path, 'lua')
autorun_path = os.path.join(lua_path, 'autorun')
sourcebox_path = os.path.join(autorun_path, 'sourcebox')
os.makedirs(sourcebox_path, exist_ok=True)
# write addon metadata
if self.gmod_version == 'gmod13':
addon_content = '''"AddonInfo"
{
"name" "SourceBox"
"version" "1.0"
"author_name" "SourceBox Team"
"info" "Python bridge for Garry's Mod"
"override" "0"
}
'''
with open(os.path.join(self.addon_path, 'addon.txt'), 'w') as f:
f.write(addon_content)
else:
info_content = '''sourcebox
{
name "SourceBox"
version "1.0"
author "SourceBox Team"
info "Python bridge for Garry's Mod"
}
'''
with open(os.path.join(self.addon_path, 'info.txt'), 'w') as f:
f.write(info_content)
# write sourcebox_init.lua
init_content = self._get_init_lua()
with open(os.path.join(autorun_path, 'sourcebox_init.lua'), 'w') as f:
f.write(init_content)
# write sv_python_bridge.lua
bridge_content = self._get_bridge_lua()
with open(os.path.join(sourcebox_path, 'sv_python_bridge.lua'), 'w') as f:
f.write(bridge_content)
# write sv_picker.lua
picker_content = self._get_picker_lua()
with open(os.path.join(sourcebox_path, 'sv_picker.lua'), 'w') as f:
f.write(picker_content)
# write sv_auto_spawner.lua
spawner_content = self._get_spawner_lua()
with open(os.path.join(sourcebox_path, 'sv_auto_spawner.lua'), 'w') as f:
f.write(spawner_content)
print(f" [created] {self.addon_path}")
print(f" [files] info.txt, sourcebox_init.lua, sv_*.lua")
except Exception as e:
print(f" [error] failed to install addon: {e}")
def _get_gmod9_picker_lua(self):
"""get gmod 9 picker script"""
return '''-- picker (aimbot) system - gmod 9
-- smooth target switching, extensive npc support
SOURCEBOX = SOURCEBOX or {}
SOURCEBOX.Picker = SOURCEBOX.Picker or {}
local Picker = SOURCEBOX.Picker
-- state
Picker.Enabled = Picker.Enabled or {}
Picker.Target = Picker.Target or {}
Picker.Manual = Picker.Manual or {}
Picker.Targets = Picker.Targets or {}
Picker.TargetIdx = Picker.TargetIdx or {}
Picker.ManualTime = Picker.ManualTime or {}
Picker.LastAngles = Picker.LastAngles or {}
Picker.TargetSwitchTime = Picker.TargetSwitchTime or {}
-- constants
local MAX_DIST = 5000
local SMOOTH_BASE = 0.12
local SMOOTH_FAST = 0.30
local SMOOTH_SWITCH = 0.06
local SMOOTH_SNAP = 2.0
local SWITCH_SMOOTH_DURATION = 0.5
local MANUAL_TIMEOUT = 3.0
local PI = 3.14159265359
-- npc class definitions
local NPC_CLASSES = {
"npc_combine_s", "npc_combine", "npc_combine_e", "npc_combine_p",
"npc_metropolice", "npc_combinegunship", "npc_helicopter",
"npc_combinedropship", "npc_strider", "npc_apcdriver",
"npc_combine_camera", "npc_turret_floor", "npc_turret_ceiling",
"npc_turret_ground", "npc_zombie", "npc_zombie_torso",
"npc_poisonzombie", "npc_fastzombie", "npc_fastzombie_torso",
"npc_zombine", "npc_headcrab", "npc_headcrab_fast",
"npc_headcrab_black", "npc_headcrab_poison", "npc_antlion",
"npc_antlion_worker", "npc_antlionguard", "npc_antlion_grub",
"npc_vortigaunt", "npc_vortigaunt_slave", "npc_manhack",
"npc_stalker", "npc_barnacle", "npc_rollermine", "npc_cscanner",
"npc_clawscanner", "npc_hunter", "npc_sniper", "npc_citizen",
"npc_alyx", "npc_barney", "npc_monk", "npc_dog", "npc_eli",
"npc_gman", "npc_kleiner", "npc_magnusson", "npc_mossman",
"npc_breen", "npc_crow", "npc_pigeon", "npc_seagull",
"npc_ichthyosaur", "monster_alien_controller", "monster_alien_grunt",
"monster_alien_slave", "monster_babycrab", "monster_barnacle",
"monster_barney", "monster_bigmomma", "monster_bloater",
"monster_bullchicken", "monster_gargantua", "monster_generic",
"monster_gman", "monster_headcrab", "monster_houndeye",
"monster_human_assassin", "monster_human_grunt", "monster_ichthyosaur",
"monster_leech", "monster_scientist", "monster_sentry",
"monster_snark", "monster_tentacle", "monster_turret",
"monster_zombie", "boss_", "npc_", "monster_"
}
local function GetPlayerID(ply)
return ply
end
local function InitPlayer(ply)
local id = GetPlayerID(ply)
Picker.Enabled[id] = false
Picker.Target[id] = nil
Picker.Manual[id] = false
Picker.Targets[id] = {}
Picker.TargetIdx[id] = 0
Picker.ManualTime[id] = 0
Picker.LastAngles[id] = vector3(0, 0, 0)
Picker.TargetSwitchTime[id] = 0
end
local function CanSee(ply, target, tpos)
local start = _PlayerGetShootPos(ply)
local dir = vecSub(tpos, start)
local length = vecLength(dir)
if length < 0.001 then return false end
dir.x = dir.x / length
dir.y = dir.y / length
dir.z = dir.z / length
_TraceLine(start, dir, length, ply)
if not _TraceHit() then
return true
end
local hitEnt = _TraceGetEnt()
if hitEnt == target then
return true
end
local hitPos = _TraceEndPos()
if hitPos then
local d = vecLength(vecSub(hitPos, tpos))
if d < 200 then
return true
end
end
return false
end
local function IsNPC(ent)
if not ent or ent <= 0 then return false end
if IsPlayer(ent) then return false end
if not _EntExists(ent) then return false end
local class = _EntGetType(ent)
if not class then return false end
for _, npcClass in pairs(NPC_CLASSES) do
if string.find(class, npcClass) then
return true
end
end
return false
end
local function IsProp(ent)
if not ent or ent <= 0 then return false end
if IsPlayer(ent) then return false end
if not _EntExists(ent) then return false end
local class = _EntGetType(ent)
if not class then return false end
return (string.find(class, "prop_physics") ~= nil or
string.find(class, "prop_dynamic") ~= nil or
string.find(class, "prop_ragdoll") ~= nil)
end
local function GetTargetPos(ent)
if IsPlayer(ent) then
return _PlayerGetShootPos(ent)
end
local pos = _EntGetPos(ent)
if IsNPC(ent) then
return vecAdd(pos, vector3(0, 0, 36))
end
return pos
end
local function GetAllEntities()
local allEnts = {}
local found = {}
for _, npcClass in pairs(NPC_CLASSES) do
local ents = _EntitiesFindByClass(npcClass)
if ents then
for _, ent in pairs(ents) do
if _EntExists(ent) and not found[ent] then
table.insert(allEnts, ent)
found[ent] = true
end
end
end
end
local propClasses = {"prop_physics", "prop_dynamic", "prop_ragdoll"}
for _, class in pairs(propClasses) do
local props = _EntitiesFindByClass(class)
if props then
for _, prop in pairs(props) do
if _EntExists(prop) and not found[prop] then
table.insert(allEnts, prop)
found[prop] = true
end
end
end
end
return allEnts
end
local function BuildList(ply)
local list = {}
local pos = _PlayerGetShootPos(ply)
local allEnts = GetAllEntities()
for _, ent in pairs(allEnts) do
if IsNPC(ent) and _EntExists(ent) then
local tpos = GetTargetPos(ent)
local dist = vecLength(vecSub(tpos, pos))
if dist <= MAX_DIST and CanSee(ply, ent, tpos) then
table.insert(list, ent)
end
end
end
for i = 1, _MaxPlayers() do
if IsPlayerOnline(i) and i ~= ply and _PlayerInfo(i, "alive") then
local tpos = GetTargetPos(i)
local dist = vecLength(vecSub(tpos, pos))
if dist <= MAX_DIST and CanSee(ply, i, tpos) then
table.insert(list, i)
end
end
end
for _, ent in pairs(allEnts) do
if IsProp(ent) and _EntExists(ent) then
local tpos = GetTargetPos(ent)
local dist = vecLength(vecSub(tpos, pos))
if dist <= MAX_DIST and CanSee(ply, ent, tpos) then
table.insert(list, ent)
end
end
end
return list
end
local function GetBest(ply)
local pos = _PlayerGetShootPos(ply)
local bestNPC = nil
local bestPlayer = nil
local bestProp = nil
local bestNPCDist = 999999
local bestPlayerDist = 999999
local bestPropDist = 999999
local allEnts = GetAllEntities()
for _, ent in pairs(allEnts) do
if IsNPC(ent) and _EntExists(ent) then
local tpos = GetTargetPos(ent)
local dist = vecLength(vecSub(tpos, pos))
if dist <= MAX_DIST and dist < bestNPCDist and CanSee(ply, ent, tpos) then
bestNPCDist = dist
bestNPC = ent
end
end
end
if bestNPC then return bestNPC end
for i = 1, _MaxPlayers() do
if IsPlayerOnline(i) and i ~= ply and _PlayerInfo(i, "alive") then
local tpos = GetTargetPos(i)
local dist = vecLength(vecSub(tpos, pos))
if dist <= MAX_DIST and dist < bestPlayerDist and CanSee(ply, i, tpos) then
bestPlayerDist = dist
bestPlayer = i
end
end
end
if bestPlayer then return bestPlayer end
for _, ent in pairs(allEnts) do
if IsProp(ent) and _EntExists(ent) then
local tpos = GetTargetPos(ent)
local dist = vecLength(vecSub(tpos, pos))
if dist <= MAX_DIST and dist < bestPropDist and CanSee(ply, ent, tpos) then
bestPropDist = dist
bestProp = ent
end
end
end
return bestProp
end
local function CalcAngles(from, to)
local diff = vecSub(to, from)
local length = vecLength(diff)
if length < 0.001 then
return vector3(0, 0, 0)
end
diff.x = diff.x / length
diff.y = diff.y / length
diff.z = diff.z / length
local pitch = math.asin(-diff.z) * (180.0 / PI)
local yaw = math.atan2(diff.y, diff.x) * (180.0 / PI)
return vector3(pitch, yaw, 0)
end
local function NormAngle(a)
while a > 180 do a = a - 360 end
while a < -180 do a = a + 360 end
return a
end
local function LerpAngleSmooth(from, to, amt)
local d = NormAngle(to - from)
local t = 1 - amt
local eased = 1 - (t * t * t)
return from + d * eased
end
local function Aim(ply, ent)
local ppos = _PlayerGetShootPos(ply)
local tpos = GetTargetPos(ent)
local want = CalcAngles(ppos, tpos)
local cur = _EntGetAngAngle(ply)
local id = GetPlayerID(ply)
if not Picker.LastAngles[id] then
Picker.LastAngles[id] = cur
end
local dp = NormAngle(want.x - cur.x)
local dy = NormAngle(want.y - cur.y)
local td = math.sqrt(dp * dp + dy * dy)
local timeSinceSwitch = _CurTime() - (Picker.TargetSwitchTime[id] or 0)
local justSwitched = timeSinceSwitch < SWITCH_SMOOTH_DURATION
local smooth = SMOOTH_BASE
if justSwitched then
smooth = SMOOTH_SWITCH
elseif td < SMOOTH_SNAP then
smooth = 1.0
elseif td < 10 then
smooth = SMOOTH_FAST
else
local falloff = math.min(td / 60.0, 1.0)
smooth = SMOOTH_BASE * (1.0 - falloff * 0.5)
end
local np = LerpAngleSmooth(cur.x, want.x, smooth)
local ny = LerpAngleSmooth(cur.y, want.y, smooth)
if np > 89 then np = 89 end
if np < -89 then np = -89 end
ny = NormAngle(ny)
Picker.LastAngles[id] = vector3(np, ny, 0)
_EntSetAngAngle(ply, vector3(np, ny, 0))
end
local function PickerThink()
for i = 1, _MaxPlayers() do
if IsPlayerOnline(i) and _PlayerInfo(i, "alive") then
local id = GetPlayerID(i)
if not Picker.Enabled[id] then
InitPlayer(i)
end
if Picker.Enabled[id] then
if Picker.Manual[id] and _CurTime() - Picker.ManualTime[id] > MANUAL_TIMEOUT then
Picker.Manual[id] = false
Picker.Target[id] = nil
end
if not Picker.Manual[id] or not Picker.Target[id] or not _EntExists(Picker.Target[id]) then
if not Picker.Manual[id] then
local nt = GetBest(i)
if nt and nt ~= Picker.Target[id] then
Picker.TargetSwitchTime[id] = _CurTime()
Picker.Target[id] = nt
end
end
end
if Picker.Target[id] and _EntExists(Picker.Target[id]) then
Aim(i, Picker.Target[id])
end
end
end
end
end
local function Toggle(ply)
local id = GetPlayerID(ply)
if not Picker.Enabled[id] then
InitPlayer(ply)
end
Picker.Enabled[id] = not Picker.Enabled[id]
Picker.Target[id] = nil
Picker.Manual[id] = false
end
local function NextTarget(ply)
local id = GetPlayerID(ply)
if not Picker.Enabled[id] then
return
end
if not _PlayerInfo(ply, "alive") then
return
end
Picker.Manual[id] = true
Picker.ManualTime[id] = _CurTime()
Picker.Targets[id] = BuildList(ply)
if table.getn(Picker.Targets[id]) > 0 then
Picker.TargetIdx[id] = Picker.TargetIdx[id] + 1
if Picker.TargetIdx[id] > table.getn(Picker.Targets[id]) then
Picker.TargetIdx[id] = 1
end
local newTarget = Picker.Targets[id][Picker.TargetIdx[id]]
if newTarget ~= Picker.Target[id] then
Picker.TargetSwitchTime[id] = _CurTime()
end
Picker.Target[id] = newTarget
end
end
AddThinkFunction(PickerThink)
CONCOMMAND("picker_toggle", function(args)
for i = 1, _MaxPlayers() do
if IsPlayerOnline(i) then
Toggle(i)
end
end
end)
CONCOMMAND("picker_next", function(args)
for i = 1, _MaxPlayers() do
if IsPlayerOnline(i) then
NextTarget(i)
end
end
end)
'''
def _get_gmod9_spawner_lua(self):
"""get gmod 9 spawner script"""
return '''-- auto-spawner system - gmod 9
SOURCEBOX = SOURCEBOX or {}
SOURCEBOX.Spawner = SOURCEBOX.Spawner or {}
local Spawner = SOURCEBOX.Spawner
local CUBE_MODEL = "models/props/srcbox/srcbox.mdl"
local spawned_cubes = {}
local spawn_initialized = false
local spawn_attempts = 0
local function IsPositionReachable(pos)
local start = vecAdd(pos, vector3(0, 0, 10))
local endpos = vecAdd(pos, vector3(0, 0, -500))
local dir = vecSub(endpos, start)
local length = vecLength(dir)
dir.x = dir.x / length
dir.y = dir.y / length
dir.z = dir.z / length
_TraceLine(start, dir, length)
if not _TraceHit() then return false end
local groundPos = _TraceEndPos()
local heightAboveGround = pos.z - groundPos.z
if heightAboveGround > 150 or heightAboveGround < -50 then return false end
return true
end
local function FindNearPlayerSpawn()
local spawns = _EntitiesFindByClass("info_player_deathmatch")
if not spawns or table.getn(spawns) == 0 then
spawns = _EntitiesFindByClass("info_player_start")
end
if not spawns or table.getn(spawns) == 0 then
spawns = _EntitiesFindByClass("info_player_teamspawn")
end
if not spawns or table.getn(spawns) == 0 then
spawns = _EntitiesFindByClass("info_player_combine")
end
if not spawns or table.getn(spawns) == 0 then
spawns = _EntitiesFindByClass("info_player_rebel")
end
if not spawns or table.getn(spawns) == 0 then return nil end
local spawnCount = table.getn(spawns)
local spawn = spawns[math.random(1, spawnCount)]
local spawnPos = _EntGetPos(spawn)
local distances = {300, 500, 700}
local angles = {0, 45, 90, 135, 180, 225, 270, 315}
for _, dist in pairs(distances) do
for _, ang in pairs(angles) do
local rad = math.rad(ang)
local testPos = vector3(
spawnPos.x + math.cos(rad) * dist,
spawnPos.y + math.sin(rad) * dist,
spawnPos.z + 50
)
if IsPositionReachable(testPos) then return testPos end
end
end
return nil
end
local function SpawnCubeAtPosition(pos)
_EntPrecacheModel(CUBE_MODEL)
local cube = _EntCreate("prop_physics")
if not cube or not _EntExists(cube) then return nil end
_EntSetModel(cube, CUBE_MODEL)
_EntSetPos(cube, pos)
_EntSetAngAngle(cube, vector3(0, math.random(0, 360), 0))
_EntSetMoveType(cube, MOVETYPE_VPHYSICS)
_EntSetSolid(cube, SOLID_VPHYSICS)
_EntSpawn(cube)
_EntActivate(cube)
if _phys.HasPhysics(cube) then
_phys.Wake(cube)
_phys.EnableMotion(cube, true)
_phys.SetMass(cube, 50)
_phys.EnableGravity(cube, true)
_phys.EnableCollisions(cube, true)
end
_EntSetCollisionGroup(cube, COLLISION_GROUP_NONE)
return cube
end
local function InitializeSpawner()
if spawn_initialized then return end
spawn_attempts = spawn_attempts + 1
local spawnPos = FindNearPlayerSpawn()
if spawnPos then
local cube = SpawnCubeAtPosition(spawnPos)
if cube then
table.insert(spawned_cubes, cube)
spawn_initialized = true
return
end
end
if spawn_attempts >= 6 then
spawn_initialized = true
end
end
AddTimer(3, 1, InitializeSpawner)
'''
def _get_gmod9_bridge_lua(self):
"""get gmod 9 bridge script"""
return r"""-- bridge system - gmod 9
-- file-based communication for external control
SOURCEBOX = SOURCEBOX or {}
SOURCEBOX.Bridge = SOURCEBOX.Bridge or {}
local Bridge = SOURCEBOX.Bridge
Bridge.CommandFile = "data/sourcebox_command.txt"
Bridge.ResponseFile = "data/sourcebox_response.txt"
Bridge.SessionID = 0
Bridge.LastCommandID = 0
Bridge.CheckInterval = 0.1
Bridge.LastCheckTime = 0
local function InitializeBridge()
_file.Write(Bridge.CommandFile, "")
_file.Write(Bridge.ResponseFile, "")
end
local function SendResponse(status, message)
local response = '{"status":"' .. status .. '","message":"' .. message .. '"}'
_file.Write(Bridge.ResponseFile, response)
end
local function ParseJSON(str)
local data = {}
local s, e = string.find(str, '"session"%s*:%s*')
if s then
local numStart = e + 1
local numEnd = numStart
while numEnd <= string.len(str) do
local char = string.sub(str, numEnd, numEnd)
if char >= "0" and char <= "9" then
numEnd = numEnd + 1
else
break
end
end
data.session = tonumber(string.sub(str, numStart, numEnd - 1))
end
s, e = string.find(str, '"id"%s*:%s*')
if s then
local numStart = e + 1
local numEnd = numStart
while numEnd <= string.len(str) do
local char = string.sub(str, numEnd, numEnd)
if char >= "0" and char <= "9" then
numEnd = numEnd + 1
else