-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathraycaster.py
299 lines (239 loc) · 9.66 KB
/
raycaster.py
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
# A simple pygame raycaster started on 19/07/2022 by James Czekaj
# I enjoyed making this. I used my previous experience from the lodev tutorial,
# and now a more simple tutorial here:
# https://github.com/vinibiavatti1/RayCastingTutorial
# I simplified some things in that tutorial, and now I believe I finally fully
# understand how a raycaster works.
import random
import sys
import math
import opensimplex
import pygame as pg
from pygame import Vector2
from player import Player
import utils
from utils import clamp
# from pygame.math import clamp # waiting for next pygame release (hopefully)
# Colour constants
WALL_UNBREAKABLE_COLOR = (100, 100, 100)
WALL_BREAKABLE_COLORS = []
for i in range(1000):
WALL_BREAKABLE_COLORS.append(
(random.randrange(0, 255), random.randrange(0, 255),
random.randrange(0, 255))
)
SKY_COLOR = (107, 191, 255)
GROUND_COLOR = (71, 201, 92)
# Size of the raycaster surface
RAYCAST_WIDTH = 320
RAYCAST_HEIGHT = 240
RAYCAST_HALF_WIDTH = int(RAYCAST_WIDTH/2)
RAYCAST_HALF_HEIGHT = int(RAYCAST_HEIGHT/2)
MINIMAP_SIZE = 200
# 0 = empty, 1 = unbreakable, >1 = breakable
map = []
ray_angle_increment = Player.FOV / RAYCAST_WIDTH
ray_precision = 0.08 # ray increment amount
def generate_map(map_size, noise_scale):
"""Generates a 2d list of map_size width and height using simplex noise.
Also makes sure map boundaries are always walls.
Arguments:
map_size -- The width and height of the list
noise_scale -- the scale of the simplex noise \
(smaller values mean bigger noise)"""
opensimplex.seed(random.randrange(999999999))
for x in range(map_size):
map.append([])
for y in range(map_size):
if (y == 0 or y == map_size-1) or (x == 0 or x == map_size-1):
map[x].append(1)
else:
noise = opensimplex.noise2(x*noise_scale, y*noise_scale)
if noise > 0:
grid_val = 2 + random.randrange(len(WALL_BREAKABLE_COLORS))
else:
grid_val = 0
map[x].append(grid_val)
def render_floor_or_ceiling(*, which, light_color: pg.Color,
dark_color: pg.Color):
"""Renders the floor or ceiling
Arguments:
which -- Either 'ceiling' or 'floor'
light_color -- the lightest color of the ceiling or floor
dark_color -- the darkest color of the ceiling or floor"""
which = which.lower()
if which == 'ceiling':
for y in range(0, RAYCAST_HALF_HEIGHT):
color = light_color.lerp(dark_color, y/RAYCAST_HALF_HEIGHT)
pg.draw.line(raycast_surface, color, (0, y), (RAYCAST_WIDTH, y))
elif which == 'floor':
for y in range(RAYCAST_HALF_HEIGHT, RAYCAST_HEIGHT):
color = dark_color.lerp(
light_color,
(y-RAYCAST_HALF_HEIGHT)/RAYCAST_HALF_HEIGHT
)
pg.draw.line(raycast_surface, color, (0, y), (RAYCAST_WIDTH, y))
else:
raise Exception('Error: invalid option for which. '
'Has to be \'ceiling\' or \'floor\'')
def raycast(brightness=0.6):
"""Raycast rendering
Arguments:
brightness -- the intensity of the lighting (smaller values make \
light brighter.)"""
ray_angle = player.angle - Player.HALF_FOV
for x in range(0, RAYCAST_WIDTH):
ray_pos = player.pos.copy()
ray_dir = Vector2(math.cos(math.radians(ray_angle)),
math.sin(math.radians(ray_angle))).normalize()
map_pos = Vector2(
int(ray_pos.x),
int(ray_pos.y)
)
xlength = abs(1 / math.cos(math.radians(ray_angle)))
ylength = abs(1 / math.sin(math.radians(ray_angle)))
if ray_dir.x < 0:
xdir = -1
xdist = (ray_pos.x - map_pos.x) * xlength
else:
xdir = 1
# TODO: Figure out why it needs to be map_pos + 1 - ray_pos
xdist = (map_pos.x + 1.0 - ray_pos.x) * xlength
if ray_dir.y < 0:
ydir = -1
ydist = (ray_pos.y - map_pos.y) * ylength
else:
ydir = 1
ydist = (map_pos.y + 1.0 - ray_pos.y) * ylength
wall = 0
side = 0
while(wall == 0):
if xdist < ydist:
xdist += xlength
side = 0
map_pos.x += xdir
else:
ydist += ylength
side = 1
map_pos.y += ydir
wall = map[int(map_pos.x)][int(map_pos.y)]
if side == 0:
# TODO: Figure out on paper why you need to subtract xlength
distance = xdist - xlength
else:
distance = ydist - ylength
# solve fisheye effect (rays near to edge of fov need to go further, so
# you scale them by cos(rayangle/playerangle) to scale them to the same
# length that they would be, had they been cast from the playerangle.
distance *= math.cos(
math.radians(ray_angle)-math.radians(player.angle)
)
wall_height = math.floor(RAYCAST_HEIGHT / distance) * 0.5
if wall == 1:
base_color = WALL_UNBREAKABLE_COLOR
elif wall >= 2:
base_color = WALL_BREAKABLE_COLORS[wall-2]
if side == 1:
base_color = tuple(n/1.5 for n in base_color)
lit_color = tuple(n/(distance*brightness) for n in base_color)
# clamp between 0 and the corrosponding base_color value
color = tuple(
clamp(v, 0, base_color[i]) for i, v in enumerate(lit_color)
)
pg.draw.line(raycast_surface, color,
(x, RAYCAST_HALF_HEIGHT - wall_height),
(x, RAYCAST_HALF_HEIGHT + wall_height))
ray_angle += ray_angle_increment
def render_minimap(surface):
# Draw minimap background
pg.draw.rect(surface, tuple(clamp(v/2, 0, 255) for v in GROUND_COLOR),
pg.Rect(0, 0, len(map), len(map)))
# Draw minimap tiles
for x in range(len(map)):
for y in range(len(map)):
if map[x][y] == 1:
pg.draw.line(surface, WALL_UNBREAKABLE_COLOR,
(x, y), (x, y))
elif map[x][y] >= 2:
pg.draw.line(surface, WALL_BREAKABLE_COLORS[map[x][y]-2],
(x, y), (x, y))
# Draw player position as circle
pg.draw.circle(surface, (255, 255, 255), player.pos, 2)
# Draw player FOV lines
ray_angle = utils.degrees_to_vec2(player.angle - Player.HALF_FOV) * 50
pg.draw.line(surface, (255, 255, 255), player.pos, player.pos+ray_angle)
ray_angle = ray_angle.rotate(Player.FOV)
pg.draw.line(surface, (255, 255, 255), player.pos, player.pos+ray_angle)
def break_wall():
"""Casts a ray forward from the player until it hits a wall. Breaks the \
wall if it's breakable."""
ray = player.pos.copy()
wall = 0
while wall == 0:
ray += player.angle_xy() * ray_precision
wall = map[int(ray.x)][int(ray.y)]
if wall > 1:
map[int(ray.x)][int(ray.y)] = 0
def render():
render_floor_or_ceiling(which='ceiling', light_color=pg.Color(SKY_COLOR),
dark_color=pg.Color(0, 0, 0))
render_floor_or_ceiling(which='floor', light_color=pg.Color(GROUND_COLOR),
dark_color=pg.Color(0, 0, 0))
raycast()
screen.blit(pg.transform.scale(raycast_surface, (screen.get_width(),
screen.get_height())), (0, 0))
if show_minimap:
# Render minimap
minimap_surf = pg.Surface((100, 100))
render_minimap(minimap_surf)
screen.blit(pg.transform.scale(minimap_surf,
(MINIMAP_SIZE, MINIMAP_SIZE)), (0, 0))
# Also render FPS
fps_text = font.render(f'FPS: {int(1/delta_time)}', False,
(255, 255, 255))
screen.blit(fps_text, (0, MINIMAP_SIZE))
angle_text = font.render(
f'Angle: x{player.angle_xy().x:0.2} y{player.angle_xy().y:0.2}',
False, (255, 255, 255)
)
screen.blit(angle_text, (0, MINIMAP_SIZE+20))
# Render crosshair
crosshair_surf = pg.Surface((screen.get_width(), screen.get_height()),
pg.SRCALPHA)
pg.draw.circle(crosshair_surf, pg.Color(255, 255, 255, 70),
(screen.get_width()/2, screen.get_height()/2), 5, )
screen.blit(crosshair_surf, (0, 0))
# TODO: Refactor code (make functions less coupled to global vars)
# Make functions take color values/find a better way to deal with
# colours. Also, just generally polish the code a bit.
# Enable a max raycast distance to save performance (try to make it look
# nicer than walls just popping in)
# Initialization
pg.init()
raycast_surface = pg.surface.Surface((RAYCAST_WIDTH, RAYCAST_HEIGHT))
screen = pg.display.set_mode((960, 720))
generate_map(100, 0.2)
show_minimap = True
# Find empty map spot and spawn player there.
for x in range(1, len(map)):
for y in range(1, len(map[0])):
if map[x][y] == 0:
player = Player(Vector2(x, y))
delta_time = 1/60
font = pg.font.Font(None, 32)
brick_sprite = pg.image.load('textures/texture.jpeg')
# Main loop
while True:
loop_start_time = pg.time.get_ticks()/1000
for event in pg.event.get():
if event.type == pg.QUIT:
sys.exit()
if event.type == pg.KEYDOWN:
if event.key == pg.K_m:
show_minimap = not show_minimap
elif event.key == pg.K_SPACE:
break_wall()
player.update(delta_time, map)
render()
pg.display.flip()
delta_time = pg.time.get_ticks() / 1000 - loop_start_time