-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSourcebox.py
More file actions
executable file
·1616 lines (1357 loc) · 60.5 KB
/
Sourcebox.py
File metadata and controls
executable file
·1616 lines (1357 loc) · 60.5 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
import pygame
import math
import os
import sys
import time
import random
from pathlib import Path
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
import platform
from cone_scene import ConeScene
from rendering_helpers import PIL_AVAILABLE, pil_load_image_rgba, pil_render_text_rgba
# platform detection
PLATFORM = platform.system()
# hide console window on windows
if PLATFORM == 'Windows':
try:
import ctypes
ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0)
except:
pass
# conditional glut import
try:
from OpenGL.GLUT import *
GLUT_AVAILABLE = True
except ImportError:
GLUT_AVAILABLE = False
print("Warning: GLUT not available, some features may be limited")
# import source_bridge conditionally
try:
from source_bridge import SourceBridge
BRIDGE_AVAILABLE = True
except ImportError:
BRIDGE_AVAILABLE = False
print("Warning: source_bridge not available")
try:
from gmod_bridge import GModBridge
GMOD_BRIDGE_AVAILABLE = True
except ImportError:
GMOD_BRIDGE_AVAILABLE = False
print("Warning: gmod_bridge not available")
def get_resource_path(filename):
"""get absolute path to resource file, works for dev and pyinstaller"""
if hasattr(sys, '_MEIPASS'):
base_path = Path(sys._MEIPASS)
else:
base_path = Path(__file__).parent if '__file__' in globals() else Path.cwd()
return str(base_path / filename)
def find_resource(filenames):
"""find first existing resource from list of filenames"""
if isinstance(filenames, str):
filenames = [filenames]
for filename in filenames:
path = get_resource_path(filename)
if os.path.exists(path):
return path
return None
def _pygame_font_available() -> bool:
try:
import pygame.font
pygame.font.init()
pygame.font.Font(None, 12)
return True
except Exception:
return False
class Object3D:
def __init__(self, obj_type, position=(0, 0, 0), rotation=(0, 0, 0), scale=1.0, scale_xyz=[1.0, 1.0, 1.0], brightness=0.6):
self.type = obj_type
self.position = list(position)
self.rotation = list(rotation)
self.base_rotation = list(rotation)
self.base_scale = max(0.01, abs(scale))
self.scale = self.base_scale
self.target_scale = self.base_scale
self.scale_xyz = [max(0.01, abs(s)) for s in scale_xyz]
self.brightness = max(0.0, min(1.0, brightness))
self.base_brightness = self.brightness
self.is_hovered = False
self.is_rotating = False
self.rotation_angle = 0.0
self.hover_timer = 0.0
self.hover_animation_duration = 0.1
self.hover_scale_amount = 0.05
self.was_hovered = False
self.display_list = None
# precalculate bounding sphere radius
if self.type == "sphere":
self.bounding_radius = 0.5 * self.scale * max(self.scale_xyz)
elif self.type == "cube":
self.bounding_radius = 0.866 * self.scale * max(self.scale_xyz)
elif self.type == "cone":
self.bounding_radius = 0.6 * self.scale * max(self.scale_xyz)
else:
self.bounding_radius = 0.5 * self.scale * max(self.scale_xyz)
def create_display_list(self):
if self.display_list is not None:
return
try:
self.display_list = glGenLists(1)
if self.display_list == 0:
return
glNewList(self.display_list, GL_COMPILE)
if self.type == "cube":
self._draw_cube_geometry()
elif self.type == "sphere":
quadric = gluNewQuadric()
if quadric:
gluQuadricNormals(quadric, GLU_SMOOTH)
gluSphere(quadric, 0.5, 32, 32)
gluDeleteQuadric(quadric)
elif self.type == "cone":
quadric = gluNewQuadric()
if quadric:
gluQuadricNormals(quadric, GLU_SMOOTH)
gluCylinder(quadric, 0.5, 0.0, 1.0, 32, 4)
gluDeleteQuadric(quadric)
glBegin(GL_TRIANGLE_FAN)
glNormal3f(0, 0, -1)
glVertex3f(0, 0, 0)
for i in range(33):
angle = (i / 32.0) * 2.0 * math.pi
x = 0.5 * math.cos(angle)
y = 0.5 * math.sin(angle)
glVertex3f(x, y, 0)
glEnd()
glEndList()
except Exception as e:
print(f"Error creating display list for {self.type}: {e}")
if self.display_list:
try:
glDeleteLists(self.display_list, 1)
except:
pass
self.display_list = None
def _draw_cube_geometry(self):
glBegin(GL_QUADS)
# top
glNormal3f(0, 1, 0)
glVertex3f(0.5, 0.5, -0.5)
glVertex3f(-0.5, 0.5, -0.5)
glVertex3f(-0.5, 0.5, 0.5)
glVertex3f(0.5, 0.5, 0.5)
# bottom
glNormal3f(0, -1, 0)
glVertex3f(0.5, -0.5, -0.5)
glVertex3f(-0.5, -0.5, -0.5)
glVertex3f(-0.5, -0.5, 0.5)
glVertex3f(0.5, -0.5, 0.5)
# right
glNormal3f(1, 0, 0)
glVertex3f(0.5, 0.5, -0.5)
glVertex3f(0.5, 0.5, 0.5)
glVertex3f(0.5, -0.5, 0.5)
glVertex3f(0.5, -0.5, -0.5)
# left
glNormal3f(-1, 0, 0)
glVertex3f(-0.5, 0.5, -0.5)
glVertex3f(-0.5, 0.5, 0.5)
glVertex3f(-0.5, -0.5, 0.5)
glVertex3f(-0.5, -0.5, -0.5)
# front
glNormal3f(0, 0, -1)
glVertex3f(0.5, 0.5, -0.5)
glVertex3f(-0.5, 0.5, -0.5)
glVertex3f(-0.5, -0.5, -0.5)
glVertex3f(0.5, -0.5, -0.5)
# back
glNormal3f(0, 0, 1)
glVertex3f(-0.5, 0.5, 0.5)
glVertex3f(0.5, 0.5, 0.5)
glVertex3f(0.5, -0.5, 0.5)
glVertex3f(-0.5, -0.5, 0.5)
glEnd()
def cleanup(self):
if self.display_list:
try:
glDeleteLists(self.display_list, 1)
except:
pass
self.display_list = None
class Camera:
def __init__(self):
self.position = [0.0, -1.0, -10.0]
self.rotation = [92.97, -9.00, -10.38]
self.fov = max(1.0, min(179.0, 53.25))
self.matrices_dirty = True
def apply(self):
glLoadIdentity()
glTranslatef(*self.position)
glRotatef(self.rotation[0], 1, 0, 0)
glRotatef(self.rotation[1], 0, 1, 0)
glRotatef(self.rotation[2], 0, 0, 1)
class Light:
def __init__(self):
self.position = [107.10, 2.85, -185.15, 1.0]
self.ambient = [0.1, 0.1, 0.1, 1.0]
self.diffuse = [1.0, 1.0, 1.0, 1.0]
self.specular = [1.0, 1.0, 1.0, 1.0]
self.setup_done = False
def apply(self):
if not self.setup_done:
glLightfv(GL_LIGHT0, GL_AMBIENT, self.ambient)
glLightfv(GL_LIGHT0, GL_DIFFUSE, self.diffuse)
glLightfv(GL_LIGHT0, GL_SPECULAR, self.specular)
self.setup_done = True
glLightfv(GL_LIGHT0, GL_POSITION, self.position)
class Checkerboard:
def __init__(self):
self.size = 30
self.position = [-25.87, 0.53, 6.68]
self.rotation = [0, 0, 0]
self.scale = [1.55, 0.63, 1.22]
self.dark_color = [0.2, 0.2, 0.2]
self.light_color = [0.0, 0.0, 0.0]
self.brightness = 2
self.display_list = None
self.texture = None
def create_display_list(self):
if self.display_list is not None:
return
self._create_blurred_texture()
try:
self.display_list = glGenLists(1)
if self.display_list == 0:
return
glNewList(self.display_list, GL_COMPILE)
size = self.size
if self.texture:
glEnable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, self.texture)
glNormal3f(0, 1, 0)
glColor3f(1, 1, 1)
glBegin(GL_QUADS)
glTexCoord2f(0, 0); glVertex3f(-size, 0, -size)
glTexCoord2f(1, 0); glVertex3f(size, 0, -size)
glTexCoord2f(1, 1); glVertex3f(size, 0, size)
glTexCoord2f(0, 1); glVertex3f(-size, 0, size)
glEnd()
glDisable(GL_TEXTURE_2D)
else:
dark_r = self.dark_color[0] * self.brightness
dark_g = self.dark_color[1] * self.brightness
dark_b = self.dark_color[2] * self.brightness
light_r = self.light_color[0] * self.brightness
light_g = self.light_color[1] * self.brightness
light_b = self.light_color[2] * self.brightness
glNormal3f(0, 1, 0)
glBegin(GL_QUADS)
for x in range(-size, size):
for z in range(-size, size):
if (x + z) & 1:
glColor3f(light_r, light_g, light_b)
else:
glColor3f(dark_r, dark_g, dark_b)
glVertex3f(x, 0, z)
glVertex3f(x, 0, z+1)
glVertex3f(x+1, 0, z+1)
glVertex3f(x+1, 0, z)
glEnd()
glEndList()
except Exception as e:
print(f"Error creating checkerboard display list: {e}")
if self.display_list:
try:
glDeleteLists(self.display_list, 1)
except:
pass
self.display_list = None
def _create_blurred_texture(self):
"""generate a pre-blurred checkerboard texture"""
try:
tex_size = 1024
tile_count = self.size * 2
pixels_per_tile = tex_size / tile_count
dark_val = int(self.dark_color[0] * self.brightness * 255)
light_val = int(self.light_color[0] * self.brightness * 255)
# generate sharp checkerboard
data = bytearray(tex_size * tex_size * 3)
for y in range(tex_size):
for x in range(tex_size):
tx = int(x / pixels_per_tile)
ty = int(y / pixels_per_tile)
val = light_val if (tx + ty) & 1 else dark_val
idx = (y * tex_size + x) * 3
data[idx] = val
data[idx + 1] = val
data[idx + 2] = val
# gentle blur: blend 20% blurred with 80% sharp
sharp = bytes(data)
blurred = bytearray(tex_size * tex_size * 3)
radius = 1
for y in range(tex_size):
for x in range(tex_size):
r_sum = 0
count = 0
for dy in range(-radius, radius + 1):
for dx in range(-radius, radius + 1):
nx = min(max(x + dx, 0), tex_size - 1)
ny = min(max(y + dy, 0), tex_size - 1)
r_sum += sharp[(ny * tex_size + nx) * 3]
count += 1
idx = (y * tex_size + x) * 3
blur_val = r_sum // count
sharp_val = sharp[idx]
val = int(sharp_val * 0.9 + blur_val * 0.1)
blurred[idx] = val
blurred[idx + 1] = val
blurred[idx + 2] = val
data = blurred
self.texture = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, self.texture)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tex_size, tex_size, 0,
GL_RGB, GL_UNSIGNED_BYTE, bytes(data))
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
glBindTexture(GL_TEXTURE_2D, 0)
except Exception as e:
print(f"Blur texture creation failed ({e}), using sharp checkerboard")
self.texture = None
def draw(self, display_width=None, display_height=None):
if self.display_list is None:
return
glPushMatrix()
glTranslatef(*self.position)
if self.rotation[0] or self.rotation[1] or self.rotation[2]:
glRotatef(self.rotation[0], 1, 0, 0)
glRotatef(self.rotation[1], 0, 1, 0)
glRotatef(self.rotation[2], 0, 0, 1)
glScalef(self.scale[0], self.scale[1], self.scale[2])
glCallList(self.display_list)
glPopMatrix()
def cleanup(self):
if self.display_list:
try:
glDeleteLists(self.display_list, 1)
except:
pass
self.display_list = None
if self.texture:
try:
glDeleteTextures([self.texture])
except:
pass
self.texture = None
class MissingTextureScene:
def __init__(self, sound_manager=None, display_scale=1.0):
self.display_list = None
self.text = "WARNING: NO GRAPHICS DRIVER DETECTED. PLEASE ENABLE A VALID GRAPHICS DRIVER."
self.text_visible = True
self.flash_timer = 0.0
self.next_flash_interval = random.choice([0.1, 0.3, 0.5])
self.text_texture = None
self.text_width = 0
self.text_height = 0
self.sound_manager = sound_manager
self.display_scale = display_scale
self.create_text_texture()
def create_text_texture(self):
font_size = 36
char_spacing = 2
# Pygame path (fastest when available)
if _pygame_font_available():
try:
if PLATFORM == "Windows":
font_candidates = ["Trebuchet MS", "Arial", "Verdana"]
else:
font_candidates = ["DejaVu Sans", "Liberation Sans", "FreeSans", "Arial"]
font = None
for font_candidate in font_candidates:
try:
font = pygame.font.SysFont(font_candidate, font_size)
break
except Exception:
continue
if font is None:
font = pygame.font.Font(None, font_size)
total_width = 0
char_surfaces = []
for char in self.text:
char_surf = font.render(char, True, (255, 0, 0))
char_surfaces.append(char_surf)
total_width += char_surf.get_width() + char_spacing
total_width = max(1, total_width - char_spacing)
max_height = max(1, max(surf.get_height() for surf in char_surfaces))
text_surface = pygame.Surface((total_width, max_height), pygame.SRCALPHA)
text_surface.fill((0, 0, 0, 0))
x_offset = 0
for char_surf in char_surfaces:
text_surface.blit(char_surf, (x_offset, 0))
x_offset += char_surf.get_width() + char_spacing
text_data = pygame.image.tostring(text_surface, "RGBA", True)
self.text_width = text_surface.get_width()
self.text_height = text_surface.get_height()
self.text_texture = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, self.text_texture)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA,
self.text_width,
self.text_height,
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
text_data,
)
return
except Exception:
pass
# Pillow path (works when pygame.font is not built)
if PIL_AVAILABLE:
cabin_font_path = find_resource(
[
"assets/fonts/Cabin-Regular.ttf",
"fonts/Cabin-Regular.ttf",
"Cabin-Regular.ttf",
]
)
rendered = pil_render_text_rgba(
self.text,
font_path=cabin_font_path,
font_size=font_size,
color=(255, 0, 0, 255),
letter_spacing=char_spacing,
bold=False,
flip_y=True,
)
if rendered:
text_data, self.text_width, self.text_height = rendered
self.text_texture = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, self.text_texture)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA,
self.text_width,
self.text_height,
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
text_data,
)
return
self.text_texture = None
def create_display_list(self):
if self.display_list is not None:
return
try:
self.display_list = glGenLists(1)
if self.display_list == 0:
return
glNewList(self.display_list, GL_COMPILE)
size = 50
block_width = 0.7
block_height = 0.5
glBegin(GL_QUADS)
for x in range(-size, size):
for z in range(-size, size):
if (x + z) & 1:
glColor3f(1.0, 0.0, 1.0)
else:
glColor3f(0.0, 0.0, 0.0)
center_x = 0
center_z = 0
corners = [
(x, z),
(x, z+1),
(x+1, z+1),
(x+1, z)
]
vertices = []
for cx, cz in corners:
dx = cx - center_x
dz = cz - center_z
dist = math.sqrt(dx*dx + dz*dz)
push_amount = dist * 0.03
if dist > 0:
push_x = (dx / dist) * push_amount
push_z = (dz / dist) * push_amount
else:
push_x = 0
push_z = 0
x_pos = cx * block_width + push_x
z_pos = cz * block_height + push_z
vertices.append((x_pos, z_pos))
glVertex3f(vertices[0][0], vertices[0][1], 0)
glVertex3f(vertices[1][0], vertices[1][1], 0)
glVertex3f(vertices[2][0], vertices[2][1], 0)
glVertex3f(vertices[3][0], vertices[3][1], 0)
glEnd()
glEndList()
except Exception as e:
print(f"Error creating missing texture display list: {e}")
if self.display_list:
try:
glDeleteLists(self.display_list, 1)
except:
pass
self.display_list = None
def update(self, dt):
self.flash_timer += dt
if self.flash_timer >= self.next_flash_interval:
self.text_visible = not self.text_visible
self.flash_timer = 0.0
self.next_flash_interval = random.choice([0.01, 0.05, 0.09])
def draw(self, display_width, display_height):
glDisable(GL_LIGHTING)
glDisable(GL_DEPTH_TEST)
glMatrixMode(GL_PROJECTION)
glPushMatrix()
glLoadIdentity()
glOrtho(-display_width/200.0, display_width/200.0, -display_height/200.0, display_height/200.0, -1, 1)
glMatrixMode(GL_MODELVIEW)
glPushMatrix()
glLoadIdentity()
if self.display_list:
glCallList(self.display_list)
if self.text_visible and self.text_texture:
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, self.text_texture)
glColor4f(1.0, 1.0, 1.0, 1.0)
target_width_percentage = 0.8
ortho_width = display_width / 100.0
target_width = ortho_width * target_width_percentage
scale_factor = target_width / self.text_width
w = self.text_width * scale_factor
h = self.text_height * scale_factor
x = -w / 2.0
y = -h / 24.0
glBegin(GL_QUADS)
glTexCoord2f(0, 0); glVertex2f(x, y)
glTexCoord2f(1, 0); glVertex2f(x + w, y)
glTexCoord2f(1, 1); glVertex2f(x + w, y + h)
glTexCoord2f(0, 1); glVertex2f(x, y + h)
glEnd()
glDisable(GL_TEXTURE_2D)
glDisable(GL_BLEND)
glPopMatrix()
glMatrixMode(GL_PROJECTION)
glPopMatrix()
glMatrixMode(GL_MODELVIEW)
glEnable(GL_DEPTH_TEST)
glEnable(GL_LIGHTING)
def cleanup(self):
if self.display_list:
try:
glDeleteLists(self.display_list, 1)
except:
pass
self.display_list = None
if self.text_texture:
try:
glDeleteTextures([self.text_texture])
except:
pass
self.text_texture = None
class CursorRenderer:
def __init__(self, cursor_file):
self.texture_id = None
self.width = 0
self.height = 0
self.enabled = False
self.scale = 1.0
self.load_cursor(cursor_file)
def load_cursor(self, cursor_file):
try:
cursor_candidates = [
'assets/images/cursor.png',
cursor_file,
'cursor.png'
]
cursor_path = find_resource(cursor_candidates)
if cursor_path:
try:
cursor_img = pygame.image.load(cursor_path).convert_alpha()
cursor_img = pygame.transform.flip(cursor_img, False, True)
self._create_texture(cursor_img)
self.enabled = True
print(f"Cursor loaded: {cursor_path}")
return True
except Exception as e:
if PIL_AVAILABLE:
pil_result = pil_load_image_rgba(cursor_path, flip_y=False)
if pil_result:
cursor_data, width, height = pil_result
self._create_texture_rgba(cursor_data, width, height)
if self.texture_id:
self.enabled = True
print(f"Cursor loaded: {cursor_path}")
return True
print(f"Error loading cursor from {cursor_path}: {e}")
print("No cursor loaded, using system cursor")
return False
except Exception as e:
print(f"Cursor loading error: {e}")
return False
def _create_texture(self, cursor_img):
try:
cursor_data = pygame.image.tostring(cursor_img, "RGBA", True)
self.width = cursor_img.get_width()
self.height = cursor_img.get_height()
self.texture_id = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, self.texture_id)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self.width, self.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, cursor_data)
except Exception as e:
print(f"Error creating cursor texture: {e}")
self.texture_id = None
def _create_texture_rgba(self, rgba_data: bytes, width: int, height: int):
try:
self.width = int(width)
self.height = int(height)
self.texture_id = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, self.texture_id)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA,
self.width,
self.height,
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
rgba_data,
)
except Exception as e:
print(f"Error creating cursor texture: {e}")
self.texture_id = None
def set_scale(self, scale):
"""set cursor scale factor"""
self.scale = max(1.0, min(2.0, scale))
def draw(self, mouse_pos, display_width, display_height):
if not self.enabled or self.texture_id is None:
return
glDisable(GL_DEPTH_TEST)
glDisable(GL_LIGHTING)
glMatrixMode(GL_PROJECTION)
glPushMatrix()
glLoadIdentity()
glOrtho(0, display_width, display_height, 0, -1, 1)
glMatrixMode(GL_MODELVIEW)
glPushMatrix()
glLoadIdentity()
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, self.texture_id)
glColor4f(1.0, 1.0, 1.0, 1.0)
x, y = mouse_pos
w = self.width * self.scale
h = self.height * self.scale
glBegin(GL_QUADS)
glTexCoord2f(0, 0); glVertex2f(x, y)
glTexCoord2f(1, 0); glVertex2f(x + w, y)
glTexCoord2f(1, 1); glVertex2f(x + w, y + h)
glTexCoord2f(0, 1); glVertex2f(x, y + h)
glEnd()
glDisable(GL_TEXTURE_2D)
glDisable(GL_BLEND)
glPopMatrix()
glMatrixMode(GL_PROJECTION)
glPopMatrix()
glMatrixMode(GL_MODELVIEW)
glEnable(GL_DEPTH_TEST)
glEnable(GL_LIGHTING)
def cleanup(self):
if self.texture_id:
try:
glDeleteTextures([self.texture_id])
except:
pass
self.texture_id = None
class SoundManager:
def __init__(self):
self.sounds = {}
self.music_loaded = False
self.initialized = False
self._mixer = None
try:
import pygame.mixer as mixer
mixer.init(frequency=44100, size=-16, channels=2, buffer=512)
self._mixer = mixer
self.initialized = True
except Exception as e:
print(f"Failed to initialize audio: {e}")
def load_sound(self, name, filepath):
if not self.initialized or not self._mixer:
return False
try:
sound_path = find_resource(filepath)
if sound_path:
self.sounds[name] = self._mixer.Sound(sound_path)
return True
return False
except Exception as e:
print(f"Error loading sound {name}: {e}")
return False
def stop_sound(self, name):
if self.initialized and name in self.sounds:
try:
self.sounds[name].stop()
except:
pass
def get_sound_duration(self, name):
if self.initialized and name in self.sounds:
try:
return self.sounds[name].get_length()
except:
return 0.0
return 0.0
def load_music(self, filepath):
if not self.initialized or not self._mixer:
return False
try:
music_path = find_resource(filepath)
if music_path:
self._mixer.music.load(music_path)
self.music_loaded = True
return True
return False
except Exception as e:
print(f"Error loading music: {e}")
return False
def play_sound(self, name):
if self.initialized and name in self.sounds:
try:
self.sounds[name].play()
except:
pass
def play_music(self, loops=-1, volume=0.5, start=0.0):
if self.initialized and self.music_loaded and self._mixer:
try:
self._mixer.music.set_volume(max(0.0, min(1.0, volume)))
self._mixer.music.play(loops, start=start)
except:
pass
def stop_music(self):
if self.initialized and self.music_loaded and self._mixer:
try:
self._mixer.music.stop()
except:
pass
class RayCaster:
def __init__(self):
self.viewport = None
self.modelview = None
self.projection = None
self.last_mouse_pos = None
self.cached_ray = (None, None)
def update_matrices(self):
self.viewport = glGetIntegerv(GL_VIEWPORT)
self.modelview = glGetDoublev(GL_MODELVIEW_MATRIX)
self.projection = glGetDoublev(GL_PROJECTION_MATRIX)
def get_ray_from_mouse(self, mouse_x, mouse_y):
if self.last_mouse_pos == (mouse_x, mouse_y) and self.cached_ray[0] is not None:
return self.cached_ray
self.last_mouse_pos = (mouse_x, mouse_y)
if self.viewport is None:
self.cached_ray = (None, None)
return self.cached_ray
try:
y = self.viewport[3] - mouse_y
near_point = gluUnProject(mouse_x, y, 0.0, self.modelview, self.projection, self.viewport)
far_point = gluUnProject(mouse_x, y, 1.0, self.modelview, self.projection, self.viewport)
dx = far_point[0] - near_point[0]
dy = far_point[1] - near_point[1]
dz = far_point[2] - near_point[2]
length = math.sqrt(dx*dx + dy*dy + dz*dz)
if length < 0.0001:
self.cached_ray = (None, None)
return self.cached_ray
inv_length = 1.0 / length
ray_dir = [dx * inv_length, dy * inv_length, dz * inv_length]
self.cached_ray = (list(near_point), ray_dir)
return self.cached_ray
except:
self.cached_ray = (None, None)
return self.cached_ray
@staticmethod
def ray_sphere_intersection(ray_origin, ray_dir, sphere_pos, sphere_radius):
if not ray_origin or not ray_dir or sphere_radius <= 0:
return False
oc_x = ray_origin[0] - sphere_pos[0]
oc_y = ray_origin[1] - sphere_pos[1]
oc_z = ray_origin[2] - sphere_pos[2]
a = ray_dir[0]*ray_dir[0] + ray_dir[1]*ray_dir[1] + ray_dir[2]*ray_dir[2]
if a < 0.0001:
return False
b = 2.0 * (oc_x * ray_dir[0] + oc_y * ray_dir[1] + oc_z * ray_dir[2])
c = oc_x*oc_x + oc_y*oc_y + oc_z*oc_z - sphere_radius * sphere_radius
discriminant = b*b - 4*a*c
return discriminant >= 0
def get_display_scale(display_width, display_height):
"""calculate scale factor based on display resolution, base: 1920x1080"""
base_width = 1920.0
base_height = 1080.0
width_scale = display_width / base_width
height_scale = display_height / base_height
scale = min(width_scale, height_scale)
return scale
def init_pygame():
try:
pygame.init()
if GLUT_AVAILABLE:
try:
glutInit()
except:
print("GLUT initialization failed, continuing without it")
# get_desktop_sizes() is more reliable than display.Info() on Linux/Wayland,
# especially after screen lock/unlock where display.Info() can return wrong values
if hasattr(pygame.display, 'get_desktop_sizes'):
desktop_sizes = pygame.display.get_desktop_sizes()
if desktop_sizes:
screen_width, screen_height = desktop_sizes[0]
else:
display_info = pygame.display.Info()
screen_width = display_info.current_w
screen_height = display_info.current_h
else:
display_info = pygame.display.Info()
screen_width = display_info.current_w
screen_height = display_info.current_h
print(f"Detected screen resolution: {screen_width}x{screen_height}")
if screen_width <= 1366 or screen_height <= 768:
display = (int(screen_width * 0.8), int(screen_height * 0.8))
elif screen_width <= 1920 or screen_height <= 1080:
display = (1280, 720)
else:
display = (1600, 900)
print(f"Using display resolution: {display[0]}x{display[1]}")
icon_candidates = [
'assets/images/sourcebox.png',
'assets/images/icon.png',
'assets/images/icon.ico',
'sourcebox.png',
'icon.png'
]