-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcgI_engine.py
More file actions
1056 lines (857 loc) · 36.2 KB
/
Copy pathcgI_engine.py
File metadata and controls
1056 lines (857 loc) · 36.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
"""
cgI_engine.py
--------------
Simple CPU rasterization engine based on the moderm OpenGL programmable pipeline.
This engine design:
Input Assembly -> Vertex Shader
-> Clip Space
-> Perspective Divide (NDC)
-> Viewport Transform
-> Triangle Assembly
-> Rasterization
-> Fragment Shader
-> Depth Test + Framebuffer Write
Author: Zhen Lai (zl6098@rit.edu)
Date: Dec 16, 2025
"""
# ------------------------------------------------------------
# Import
# ------------------------------------------------------------
from vertex import *
from pyglm import glm
import math
from transforms import T2
# ------------------------------------------------------------
# Texture2D — wrapper for texture sampling
# ------------------------------------------------------------
class Texture2D:
"""
CPU-side 2D texture abstraction.
This class does:
1. normalized UV coordinates
2. wrap mode: repeat
3. filtering: nearest or bilinear
NOTE:
- No mipmaps
- No anisotropic filtering
- All sampling is done in software per-fragment
"""
def __init__(self, pil_image):
self.img = pil_image
self.width, self.height = pil_image.size
self.pixels = pil_image.load()
def sample_nearest(self, uv):
"""
uv : glm.vec2, values wrapped into [0,1)
"""
u = uv.x - math.floor(uv.x)
v = uv.y - math.floor(uv.y)
x = int(u * (self.width - 1))
y = int(v * (self.height - 1))
r, g, b = self.pixels[x, y][0:3]
return (r/255.0, g/255.0, b/255.0)
def sample_bilinear(self, uv):
"""
Bilinear sample of the texture at uv.
"""
u = uv.x - math.floor(uv.x)
v = uv.y - math.floor(uv.y)
fx = u * (self.width - 1)
fy = v * (self.height - 1)
x0 = int(math.floor(fx))
y0 = int(math.floor(fy))
x1 = min(x0 + 1, self.width - 1)
y1 = min(y0 + 1, self.height - 1)
tx = fx - x0
ty = fy - y0
c00 = self.pixels[x0, y0]
c10 = self.pixels[x1, y0]
c01 = self.pixels[x0, y1]
c11 = self.pixels[x1, y1]
def lerp(a, b, t): return (1 - t) * a + t * b
r_top = lerp(c00[0], c10[0], tx)
r_bot = lerp(c01[0], c11[0], tx)
r = lerp(r_top, r_bot, ty)
g_top = lerp(c00[1], c10[1], tx)
g_bot = lerp(c01[1], c11[1], tx)
g = lerp(g_top, g_bot, ty)
b_top = lerp(c00[2], c10[2], tx)
b_bot = lerp(c01[2], c11[2], tx)
b = lerp(b_top, b_bot, ty)
return (r/255.0, g/255.0, b/255.0)
# ------------------------------------------------------------
# Vertex Attribute Buffers
# ------------------------------------------------------------
class VertexAttributeBuffer:
"""
Stores one named per-vertex attribute array.
Example:
VertexAttributeBuffer("normal", [glm.vec3, glm.vec3, ...])
VertexAttributeBuffer("uv", [glm.vec2, glm.vec2, ...])
"""
def __init__(self, name, data_list):
self.name = name
self.data = data_list
self.length = len(data_list)
# ------------------------------------------------------------
# Vertex Array Object (VAO)
# ------------------------------------------------------------
class VertexArrayObject:
"""
CPU analogue of an OpenGL Vertex Array Object (VAO).
Stores a collection of named vertex attribute buffers that are accessed by the vertex shader.
Example:
vao = VertexArrayObject()
vao.add_attribute(VertexAttributeBuffer("position", positions))
vao.add_attribute(VertexAttributeBuffer("normal", normals))
vao.add_attribute(VertexAttributeBuffer("uv", uvs))
"""
def __init__(self):
self.attributes = {} # name -> VertexAttributeBuffer
def add_attribute(self, attrib_buffer):
self.attributes[attrib_buffer.name] = attrib_buffer
def get_attribute(self, name):
return self.attributes.get(name, None)
def get_vertex_count(self):
# All attribute buffers must have matching lengths
any_attr = next(iter(self.attributes.values()))
return any_attr.length
# ------------------------------------------------------------
# Helpers for barycentric / edge tests — will be used by engine
# ------------------------------------------------------------
def edge_function(a, b, c):
"""
Signed double area for triangle edges.
Returns:
> 0 : point C is on the left side of edge AB
< 0 : point C is on the right side
= 0 : collinear
"""
return (c.x - a.x) * (b.y - a.y) - (c.y - a.y) * (b.x - a.x)
def is_top_left(a, b):
"""
Determines whether edge (a → b) is a "top-left" edge.
This is used by the top-left rasterization rule to ensure watertight triangle coverage when adjacent triangles share edges.
Assumes:
• Screen-space coordinates
• +x right, +y down
"""
if (a.y == b.y):
return a.x < b.x
return a.y < b.y
# ================================================================
# Engine Core (Unified drawTriangles Pipeline)
# ================================================================
class CGIengine:
"""
CPU-based rasterization engine with an OpenGL-style pipeline.
- Manage depth buffer
- Perform viewport transform
- Execute programmable draw calls
- Rasterize triangles
- Invoke fragment shaders
- Write pixels to the framebuffer
"""
# ------------------------------------------------------------
# Constructor
# ------------------------------------------------------------
def __init__(self, width=800, height=800):
self.zbuffer_width = width
self.zbuffer_height = height
self.allocate_zbuffer(width, height)
self.viewportT = glm.mat3(
width / 2.0, 0.0, 0.0,
0.0, -height/2.0, 0.0,
width / 2.0, height/2.0, 1.0
)
def allocate_zbuffer(self, w, h):
"""
Allocate and initialize the depth buffer.
Depth convention:
- Stored depth is in [0,1]
- Smaller values are closer to the camera
- Initialized to a very large value (far plane)
"""
self.zbuffer = [[1e9 for _ in range(w)] for _ in range(h)]
print(f"[CGIengine] Allocated Z-buffer: {w} by {h}")
def clear_color(self, win, color=(0, 0, 0)):
"""
Fill framebuffer with a color.
"""
w, h = self.zbuffer_width, self.zbuffer_height
r, g, b = color
for y in range(h):
for x in range(w):
self._draw(win, x, y, (r,g,b))
def clearZBuffer(self):
"""
Reset depth buffer for next frame.
"""
w, h = self.zbuffer_width, self.zbuffer_height
for y in range(h):
for x in range(w):
self.zbuffer[y][x] = 1e9
# ------------------------------------------------------------
# Low-level pixel write
# ------------------------------------------------------------
def _draw(self, win, x, y, color):
"""
color is a tuple (r, g, b) in [0,1].
RitWindow expects set_pixel(x, y, r, g, b)
"""
if 0 <= x < self.zbuffer_width and 0 <= y < self.zbuffer_height:
r, g, b = color
win.set_pixel(x, y, r, g, b)
def defineViewWindow(self, top: int, bottom: int, right: int, left: int) -> None:
"""
Configure the screen-space viewport and store the matrix internally.
--------
t: int -- Top boundary of view window
b: int -- Bottomr
r: int -- Left
l: int -- Right
"""
# Compute viewport transform (NDC → screen coordinates)
self.viewportT = T2.viewport(left, right, bottom, top)
# Define clipping window boundaries in normalized coordinates
self.clip_top = 1.0
self.clip_bottom = -1.0
self.clip_right = 1.0
self.clip_left = -1.0
# ============================================================
# UNIFIED DRAW CALL — OpenGL-style
# ============================================================
def drawTriangles(
self,
win,
vao, # VertexArrayObject
index_buffer, # list[int]
vertex_shader, # function(V, uniforms)
fragment_shader, # function(p0,p1,p2,alpha,beta,gamma,uniforms)
uniforms):
"""
The heart of the pipeline.
Accepts:
- win : framebuffer
- vao : VertexArrayObject with named vertex attributes
- index_buffer : triangles (triplets)
- vertex_shader : programmable vertex shader
- fragment_shader: programmable fragment shader
- uniforms : dict of uniforms used by both shaders
Pipeline mirrors OpenGL:
1.Input Assembly - Fetch vertex attributes from VAO
2.Vertex Shader - Transform object-space -> clip-space; Emit varyings
3. Perspective Divide - Clip-space -> Normalized Device Coordinates (NDC)
4. Viewport Transform - NDC -> screen-space pixels
5. Primitive Assembly - Build triangles using index buffer
6. Rasterization
- Convert triangles -> fragments
- Perform depth testing
- Interpolate varyings
7. Fragment Shader - Compute final color per fragment
No 3D clipping implemented at this point.
"""
# ----------------------------------------------------------
# 1. INPUT ASSEMBLY + VERTEX PROCESSING
# — Run vertex shader per vertex
# ----------------------------------------------------------
# Query how many vertices exist in the VAO.
# All attribute buffers must have the same length.
num_vertices = vao.get_vertex_count()
# This list will store all vertices after vertex processing, perspective divide, and viewport transform
processed_vertices = []
# Iterate over each vertex ID
for vertex_id in range(num_vertices):
# Create a fresh Vertex object for the shader to operate on.
V = Vertex()
V.space = VertexSpace.OBJECT
# ------------------------------------------------------
# Load vertex attributes from VAO
# ------------------------------------------------------
for name, attrib_buf in vao.attributes.items():
# Fetch the attribute value for this vertex ID
value = attrib_buf.data[vertex_id]
if name == "position":
# By convention, position is written directly
# into V.x, V.y, V.z (object-space position).
V.x = value.x
V.y = value.y
V.z = value.z
else:
# All other attributes are treated as varyings
# and stored in the vertex attribute dictionary
V.attach_varying(name, value)
if __debug__:
assert V.space == VertexSpace.OBJECT
# ------------------------------------------------------
# 2. VERTEX SHADER EXECUTION
# ------------------------------------------------------
# Call the user-supplied vertex shader
# The shader is expected to
# Read object-space position
# Write clip-space position back into V position attribute
# Attach any varyings needed for interpolation
vertex_shader(V, uniforms)
# After vertex shader, vertex MUST be in clip space
V.space = VertexSpace.CLIP
if __debug__:
assert V.space == VertexSpace.CLIP
# ------------------------------------------------------
# 3. PERSPECTIVE DIVIDE (CLIP → NDC)
# ------------------------------------------------------
# Guard against w == 0 to avoid to crash
clip_w = V.w if V.w != 0.0 else 1.0
# Convert clip-space coordinates to Normalized Device Coordinates
ndc_x = V.x / clip_w
ndc_y = V.y / clip_w
ndc_z = V.z / clip_w
# Map NDC z from [-1, 1] to depth range [0, 1]
depth01 = 0.5 * (ndc_z + 1.0)
# Create a new vertex for NDC space
V_ndc = V.copy()
V_ndc.x = ndc_x
V_ndc.y = ndc_y
V_ndc.z = ndc_z
V_ndc.space = VertexSpace.NDC
if __debug__:
assert V_ndc.space == VertexSpace.NDC
# ------------------------------------------------------
# 4. VIEWPORT TRANSFORM (NDC → SCREEN SPACE)
# ------------------------------------------------------
ndc_vec = glm.vec3(V_ndc.x, V_ndc.y, 1.0)
# Apply viewport transformation: NDC -> pixel coordinates
scr = self.viewportT * ndc_vec
screen_x = int(round(scr.x))
screen_y = int(round(scr.y))
# ------------------------------------------------------
# 5. BUILD FINAL SCREEN-SPACE VERTEX
# ------------------------------------------------------
# Create a new Vertex representing this vertex in SCREEN SPACE.
# Create final screen-space vertex
V_screen = V_ndc.copy()
V_screen.x = screen_x
V_screen.y = screen_y
V_screen.z = depth01 # depth buffer value
V_screen.w = clip_w # preserve clip-space w
V_screen.space = VertexSpace.SCREEN
if __debug__:
assert V_screen.space == VertexSpace.SCREEN
# Store the processed vertex
processed_vertices.append(V_screen)
# ----------------------------------------------------------
# 6. TRIANGLE ASSEMBLY & RASTERIZATION
# ----------------------------------------------------------
# Iterate through index buffer in groups of three.
# Each triple defines on triangle
for i in range(0, len(index_buffer), 3):
p0 = processed_vertices[index_buffer[i + 0]]
p1 = processed_vertices[index_buffer[i + 1]]
p2 = processed_vertices[index_buffer[i + 2]]
if __debug__:
assert p0.space == VertexSpace.SCREEN
assert p1.space == VertexSpace.SCREEN
assert p2.space == VertexSpace.SCREEN
# Rasterize the triangle.
self.rasterizeTriangle(win, p0, p1, p2, fragment_shader, uniforms)
# ============================================================
# Unified Rasterizer
# ============================================================
def rasterizeTriangle(self, win, p0, p1, p2, fragment_shader, uniforms):
"""
Rasterize a single triangle in screen space.
- Primitive Rasterization
- Fragment Generation
- Depth Test
- Fragment Shader Execution
- Framebuffer Write
p0, p1, p2 : Vertex
Screen-space vertices with:
- x, y : pixel coordinates
- z : depth in [0,1]
- w : clip-space w (for perspective correction)
- varyings : dict of per-vertex attributes (glm floats/vecs)
fragment_shader(p0, p1, p2, alpha, beta, gamma, uniforms, varyings)
Returns (r,g,b) in [0,1] or None to discard fragment.
NOTE:
No clipping
Single sample per pixel
"""
# ------------------------------------------------------
# 1. PREPARE SCREEN-SPACE GEOMETRY
# ------------------------------------------------------
# Convert vertex positions to 2D vectors for edge testing
a = glm.vec2(p0.x, p0.y)
b = glm.vec2(p1.x, p1.y)
c = glm.vec2(p2.x, p2.y)
# Compute signed area of the triangle
# This value is proportional to twice the triangle area.
area = edge_function(a, b, c)
# If area is zero, the triangle is degenerate
# (all points lie on a line).
if area == 0:
return
# ------------------------------------------------------
# 2. HANDLE ORIENTATION (WINDING)
# ------------------------------------------------------
# We want all edge tests to treat "inside" as >= 0.
# If the triangle is clockwise, flip the sign.
sign = 1.0
if area < 0:
sign = -1.0
area = -area
# Precompute reciprocal of area for barycentric normalizaton
inv_area = 1.0 / area
# Determine top-left edges
edge0_top_left = is_top_left(b, c)
edge1_top_left = is_top_left(c, a)
edge2_top_left = is_top_left(a, b)
# ------------------------------------------------------
# 3. COMPUTE SCREEN_SPACE BOUDNING BOX
# ------------------------------------------------------
# Clamp counding box to framebuffer dimensions to avoid out-of-bounds memory access
min_x = max(int(min(p0.x, p1.x, p2.x)), 0)
max_x = min(int(max(p0.x, p1.x, p2.x)), self.zbuffer_width - 1)
min_y = max(int(min(p0.y, p1.y, p2.y)), 0)
max_y = min(int(max(p0.y, p1.y, p2.y)), self.zbuffer_height - 1)
# ------------------------------------------------------
# 4. RASTERIZATION LOOP (PIXEL GRID)
# ------------------------------------------------------
# Iterate over every pixel covered by the bounding box.
for py in range(min_y, max_y + 1):
for px in range(min_x, max_x + 1):
# Pixel center sampling
P = glm.vec2(px + 0.5, py + 0.5)
# --------------------------------------------------
# 5. EDGE FUNCTION TESTS (INSIDE TRIANGLE)
# --------------------------------------------------
# Evaluate edge functions for barycentric weights.
w0 = edge_function(b, c, P) * sign
w1 = edge_function(c, a, P) * sign
w2 = edge_function(a, b, P) * sign
if (
(w0 < 0) or (w0 == 0 and not edge0_top_left) or
(w1 < 0) or (w1 == 0 and not edge1_top_left) or
(w2 < 0) or (w2 == 0 and not edge2_top_left)
):
continue
# --------------------------------------------------
# 6. BARYCENTRIC COORDINATES
# --------------------------------------------------
alpha = w0 * inv_area
beta = w1 * inv_area
gamma = w2 * inv_area
# --------------------------------------------------
# 7. DEPTH INTERPOLATION + Z-TEST
# ---------------------------------------------------
# Linearly interpolate depth in screen space.
depth = (alpha * p0.z +
beta * p1.z +
gamma * p2.z)
# Depth test: reject fragment if it is farther than the currently stored depth.
if depth >= self.zbuffer[py][px]:
continue
# --------------------------------------------------
# 8. PERSPECTIVE-CORRECT INTERPOLATION
# --------------------------------------------------
final_varyings = {}
# Precompute reciprocal w for each vertex.
inv_w0 = 1.0 / p0.w if p0.w != 0.0 else 0.0
inv_w1 = 1.0 / p1.w if p1.w != 0.0 else 0.0
inv_w2 = 1.0 / p2.w if p2.w != 0.0 else 0.0
# Interpolated 1/w
inv_w = (alpha * inv_w0 +
beta * inv_w1 +
gamma * inv_w2)
# Guard against division by zero.
if inv_w == 0.0:
continue
# Interpolate each varying.
for name in p0.varyings.keys():
v0 = p0.varyings[name]
v1 = p1.varyings[name]
v2 = p2.varyings[name]
# v_over_w at each vertex
v0_over_w = v0 * inv_w0
v1_over_w = v1 * inv_w1
v2_over_w = v2 * inv_w2
# Linearly interpolate v / w
v_over_w = (alpha * v0_over_w +
beta * v1_over_w +
gamma * v2_over_w)
# Recover perspective-correct varying
final_varyings[name] = v_over_w / inv_w
# --------------------------------------------------
# 9. FRAGMENT SHADER EXECUTION
# --------------------------------------------------
# Call fragment shader.
out_color = fragment_shader(
p0, p1, p2,
alpha, beta, gamma,
uniforms,
final_varyings
)
# Fragment shader can discard by returning None.
if out_color is None:
continue
# --------------------------------------------------
# 10. FRAMEBUFFER WRITE
# --------------------------------------------------
# Update depth buffer.
self.zbuffer[py][px] = depth
# Write color to framebuffer.
self._draw(win, px, py, out_color)
# ================================================================
# Shader Pipeline Utilities
# ================================================================
# ------------------------------------------------------------
# Basic arithmetic helpers
# ------------------------------------------------------------
@staticmethod
def saturate(x):
"""Clamp a float to [0,1]."""
return max(0.0, min(1.0, float(x)))
@staticmethod
def clamp(x, lo, hi):
"""Clamp x to [lo,hi]."""
return max(lo, min(hi, x))
@staticmethod
def lerp(a, b, t):
"""Linear interpolation."""
return (1 - t) * a + t * b
@staticmethod
def reflect(I, N):
"""
Reflection vector (same as GLSL reflect):
R = I - 2 * dot(N,I) * N
"""
return I - 2.0 * glm.dot(N, I) * N
@staticmethod
def safe_normalize(v):
"""
Normalize vector v, returning zero if length is 0.
Works for glm.vec2/vec3/vec4.
"""
length = glm.length(v)
if length < 1e-8:
return glm.normalize(glm.vec3(0, 0, 0)) if hasattr(v, "z") else v
return glm.normalize(v)
# ------------------------------------------------------------
# Color helpers
# ------------------------------------------------------------
@staticmethod
def rgb(r, g, b):
"""Convenience helper to convert 0–255 ints to [0,1] floats."""
return (r / 255.0, g / 255.0, b / 255.0)
@staticmethod
def color_mul(c, s):
"""Multiply color tuple by scalar."""
return (c[0]*s, c[1]*s, c[2]*s)
@staticmethod
def color_add(a, b):
"""Add two RGB colors."""
return (a[0]+b[0], a[1]+b[1], a[2]+b[2])
@staticmethod
def color_clamp(c):
"""Clamp RGB values to [0,1]."""
return (CGIengine.saturate(c[0]), CGIengine.saturate(c[1]), CGIengine.saturate(c[2]))
# ------------------------------------------------------------
# Shader varyings helper — convert Python/scalar/GLM types
# ------------------------------------------------------------
@staticmethod
def to_vec2(x):
if isinstance(x, glm.vec2):
return x
return glm.vec2(float(x[0]), float(x[1]))
@staticmethod
def to_vec3(x):
if isinstance(x, glm.vec3):
return x
return glm.vec3(float(x[0]), float(x[1]), float(x[2]))
# ------------------------------------------------------------
# Lighting utilities (Lambert + Blinn-Phong components)
# ------------------------------------------------------------
@staticmethod
def lambert(normal, light_dir):
"""
Basic diffuse = max(N · L, 0).
normal, light_dir: glm.vec3 (assumed normalized)
"""
return CGIengine.saturate(glm.dot(normal, light_dir))
@staticmethod
def blinn_phong(normal, light_dir, view_dir, shininess):
"""
Blinn-Phong specular highlight.
normal, light_dir, view_dir: glm.vec3 (normalized)
shininess: float
"""
half_vec = CGIengine.safe_normalize(light_dir + view_dir)
spec_angle = max(0.0, glm.dot(normal, half_vec))
return pow(spec_angle, shininess)
@staticmethod
def phong_specular(normal, light_dir, view_dir, shininess):
"""
Classic Phong reflection model:
R = reflect(-L, N)
specular = max(dot(R, V), 0)^shininess
"""
R = CGIengine.reflect(-light_dir, normal)
spec = max(glm.dot(R, view_dir), 0.0)
return pow(spec, shininess)
# ================================================================
# Shader Library
#
# Conventions:
# Vertex shader:
# • Input:
# - V.x, V.y, V.z : object-space position
# - V.attrs : per-vertex attribuets (normals, UVs, etc.)
# • Output:
# - V.x, V.y, V.z, V.w : clip-space position
# - Attached varyings via V.attach_varying()
#
# Fragment shader:
# • Input:
# - Barycentric weights (alpha, beta, gamma)
# - Perspective-correct varyings
# • Output:
# - (r, g, b) color in [0,1], or None to discard
# ================================================================
# ------------------------------------------------------------
# BASIC (UNLIT) SHADERS
# ------------------------------------------------------------
@staticmethod
def vs_basic(vertex, uniforms):
"""
Basic vertex shader.
Transforms object-space vertex position into clip space using:
clip_pos = Projection * View * Model * position
"""
# Object-space position (homogeneous)
position_object = glm.vec4(vertex.x, vertex.y, vertex.z, 1.0)
# Standard transformation matrices
model_matrix = uniforms["modelT"]
view_matrix = uniforms["viewT"]
projection_matrix = uniforms["projectionT"]
# Transform to clip space
position_clip = projection_matrix * (view_matrix * (model_matrix * position_object))
# Write clip-space position back to vertex
vertex.x = position_clip.x
vertex.y = position_clip.y
vertex.z = position_clip.z
vertex.w = position_clip.w
@staticmethod
def fs_basic_color(p0, p1, p2, alpha, beta, gamma, uniforms, varyings):
"""
Fragment shader returning a constant color.
"""
return uniforms.get("color", (1.0, 1.0, 1.0))
# ------------------------------------------------------------
# 2. TEXTURE MAPPING SHADERS
# ------------------------------------------------------------
@staticmethod
def vs_texture(vertex, uniforms):
"""
Vertex shader for texture mapping.
- Transform position to clip space
- Pass UV coordinates as varyings for interpolation
"""
position_object = glm.vec4(vertex.x, vertex.y, vertex.z, 1.0)
model_matrix = uniforms["modelT"]
view_matrix = uniforms["viewT"]
projection_matrix = uniforms["projectionT"]
position_clip = projection_matrix * (view_matrix * (model_matrix * position_object))
# Write clip-space
vertex.x = position_clip.x
vertex.y = position_clip.y
vertex.z = position_clip.z
vertex.w = position_clip.w if position_clip.w != 0 else 1.0
# Pass UVs through as varyings
uv = vertex.get_varying("uv") # glm.vec2
vertex.attach_varying("uv", uv)
@staticmethod
def fs_texture(p0, p1, p2, alpha, beta, gamma, uniforms, varyings):
"""
Fragment shader performing texture lookup.
- Perspective-correct UV interpolation
- Texture sampling (nearest or bilinear)
"""
texture = uniforms.get("sampler2D", None)
if texture is None:
# Bright magenta signals missing texture
return (1, 0, 1) # magenta error color
uv = varyings["uv"] # already perspective-correct
# Select filtering mode
if uniforms.get("filter", "nearest") == "bilinear":
return texture.sample_bilinear(uv)
else:
return texture.sample_nearest(uv)
# ------------------------------------------------------------
# 3. PROCEDURAL CHECKERBOARD SHADERS
# ------------------------------------------------------------
@staticmethod
def vs_checkerboard(vertex, uniforms):
"""
Vertex shader for procedural checkerboard texturing.
Outputs:
• uv_over_w
• inv_w
These are later recombined in the fragment shader to
recover perspective-correct UVs.
"""
position_object = glm.vec4(vertex.x, vertex.y, vertex.z, 1.0)
model_matrix = uniforms["modelT"]
view_matrix = uniforms["viewT"]
projection_matrix = uniforms["projectionT"]
position_clip = projection_matrix * (view_matrix * (model_matrix * position_object))
vertex.x = position_clip.x
vertex.y = position_clip.y
vertex.z = position_clip.z
vertex.w = position_clip.w if position_clip.w != 0.0 else 1.0
uv = vertex.get_varying("uv")
inv_w = 1.0 / vertex.w
# Store components needed for perspective-correct interpolation
vertex.attach_varying("uv_over_w", uv * inv_w)
vertex.attach_varying("inv_w", inv_w)
@staticmethod
def fs_checkerboard(p0, p1, p2, alpha, beta, gamma, uniforms, varyings):
"""
Fragment shader that generates a crisp checkerboard pattern
in UV space.
"""
cell_size = uniforms.get("checksize", 0.1)
color_a = uniforms.get("color1", (1.0, 1.0, 1.0))
color_b = uniforms.get("color2", (0.0, 0.0, 0.0))
# Recover perspective-correct UV
uv = varyings["uv_over_w"] / varyings["inv_w"]
# Wrap UVs to [0,1)
u = uv.x - math.floor(uv.x)
v = uv.y - math.floor(uv.y)
# Determine checker cell
cell_u = int(math.floor(u / cell_size))
cell_v = int(math.floor(v / cell_size))
return color_a if (cell_u % 2) == (cell_v % 2) else color_b
# ------------------------------------------------------------
# 4. PHONG SHADING SHADERS
# ------------------------------------------------------------
@staticmethod
def vs_phong(vertex, uniforms):
"""
Vertex shader for Phong / Blinn-Phong lighting.
Outputs:
• pos_view : position in view (camera) space
• normal_view : normal in view space
"""
position_object = glm.vec4(vertex.x, vertex.y, vertex.z, 1.0)
normal_object = vertex.get_varying("normal")
model_matrix = uniforms["modelT"]
view_matrix = uniforms["viewT"]
projection_matrix = uniforms["projectionT"]
# Transform position
position_world = model_matrix * position_object
position_view = view_matrix * position_world
# Final clip-space position
position_clip = projection_matrix * position_view
vertex.x = position_clip.x
vertex.y = position_clip.y
vertex.z = position_clip.z
vertex.w = position_clip.w
# Transform normal correctly (inverse-transpose of model)
normal_world = CGIengine.safe_normalize(
glm.vec3(glm.transpose(glm.inverse(model_matrix)) * glm.vec4(normal_object, 0.0))
)
normal_view = CGIengine.safe_normalize(
glm.vec3(view_matrix * glm.vec4(normal_world, 0.0))
)
# Pass varyings to fragment shader
vertex.attach_varying("pos_view", glm.vec3(position_view))
vertex.attach_varying("normal_view", normal_view)
@staticmethod
def fs_phong(p0, p1, p2, alpha, beta, gamma, uniforms, varyings):
"""
Fragment shader implementing Blinn-Phong lighting model.
"""
position_view = varyings["pos_view"]
normal_view = CGIengine.safe_normalize(varyings["normal_view"])
# Lighting parameters
light_position = uniforms.get("light_pos", glm.vec3(0, 0, 1))
light_color = uniforms.get("light_color", (1.0, 1.0, 1.0))
diffuse_strength = uniforms.get("kd", 1.0)
specular_strength = uniforms.get("ks", 0.5)
shininess = uniforms.get("shininess", 32)
ambient_strength = uniforms.get("ambient", 0.1)
# Direction vectors (view space)
light_dir = CGIengine.safe_normalize(light_position - position_view)
view_dir = CGIengine.safe_normalize(-position_view)
# Diffuse (Lambert)
diffuse_term = diffuse_strength * max(0.0, glm.dot(normal_view, light_dir))
# Specular (Blinn-Phong)
specular_term = specular_strength * CGIengine.blinn_phong(
normal_view, light_dir, view_dir, shininess
)
r = ambient_strength + (diffuse_term + specular_term) * light_color[0]
g = ambient_strength + (diffuse_term + specular_term) * light_color[1]
b = ambient_strength + (diffuse_term + specular_term) * light_color[2]
return CGIengine.color_clamp((r, g, b))
# ------------------------------------------------------------
# 5. WIREFRAME RENDERING SHADERS
# ------------------------------------------------------------
@staticmethod
def vs_wireframe(vertex, uniforms):
"""
Vertex shader for wireframe rendering.
Outputs only clip-space position.
Edge detection is performed in the fragment shader
using barycentric coordinates.
"""
position_object = glm.vec4(vertex.x, vertex.y, vertex.z, 1.0)
model_matrix = uniforms["modelT"]
view_matrix = uniforms["viewT"]
projection_matrix = uniforms["projectionT"]
position_clip = projection_matrix * (view_matrix * (model_matrix * position_object))
vertex.x = position_clip.x
vertex.y = position_clip.y
vertex.z = position_clip.z