-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
234 lines (203 loc) · 9.57 KB
/
main.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
import pygame
from pygame.math import Vector3, Vector2
from vnoise import vnoise
import math
import time
import numpy as np
from render import drawTerrainCollored, renderPipeline, point3
def rotatePoint(p: Vector3, rot: Vector3):
return p.rotate_z_rad(rot.z).rotate_y_rad(rot.y).rotate_x_rad(rot.x)
# TODO: migrate from pygame.Vector to numpy everywhere
def getCameraPlanes(cameraPos: point3, cameraRotation: Vector3, farPlaneDistance: float, closePlaneDistance: float):
screenRect3d = [Vector3(closePlaneDistance, -1, 1), Vector3(closePlaneDistance, 1, 1), Vector3(closePlaneDistance, 1, -1), Vector3(closePlaneDistance, -1, -1)]
closePlanePoints = [rotatePoint(p, cameraRotation) for p in screenRect3d]
farPlanePoints = [p * (farPlaneDistance / closePlaneDistance) + cameraPos for p in closePlanePoints]
closePlanePoints = [p + cameraPos for p in closePlanePoints]
return closePlanePoints, farPlanePoints
# TODO: remove the slow vnoise - implementation at https://github.com/plottertools/vnoise/blob/main/vnoise/vnoise.py
vnoiseObj = vnoise.Noise()
def terrainGenerator(minX, minY, maxX, maxY, tilesize=8.40, scale=8):
heights = vnoiseObj.noise2(np.arange(minY, maxY)/tilesize, np.arange(minX, maxX)/tilesize)
heights += 0.75
heights *= scale / 1.5
return heights
def getPointsArr(minX, maxX, minY, maxY):
points = np.ndarray(( maxY-minY, maxX-minX, 3))
points[:, :, 0] = np.reshape( np.tile( np.arange(minX, maxX), maxY-minY), points.shape[:2])
points[:, :, 1] = np.reshape( np.repeat( np.arange(minY, maxY), maxX-minX), points.shape[:2])
points[:, :, 2] = terrainGenerator(minX, minY, maxX, maxY)
return points
def chopPointsIntoTris(points):
tris = np.ndarray((points.shape[0]-1, points.shape[1]-1, 2, 3, 3))
x = np.repeat(points[:-1, :-1], 2, axis=1)
tris[:, :, :, 0, :] = x.reshape((x.shape[0], x.shape[1]//2, 2, 3))
tris[:, :, 0, 1, :] = points[:-1, 1:, :]
tris[:, :, 0, 2, :] = points[1:, 1:, :]
tris[:, :, 1, 1, :] = points[1:, 1:, :]
tris[:, :, 1, 2, :] = points[1:, :-1, :]
return tris.reshape(tris.shape[0] * tris.shape[1] * 2, 3, 3)
def getVisibleMapSquare(cameraPos, cameraRotation, farPlaneDistance, closePlaneDistance):
closePlane, farPlane = getCameraPlanes(cameraPos, cameraRotation, farPlaneDistance, closePlaneDistance)
minX, maxX = min(closePlane+farPlane, key=lambda p: p.x).x, max(closePlane+farPlane, key=lambda p: p.x).x
minY, maxY = min(closePlane+farPlane, key=lambda p: p.y).y, max(closePlane+farPlane, key=lambda p: p.y).y
minX = int(min(minX, cameraPos.x)) - 1
maxX = int(max(maxX, cameraPos.x)) + 1
minY = int(min(minY, cameraPos.y)) - 1
maxY = int(max(maxY, cameraPos.y)) + 1
return (minX, maxX, minY, maxY)
def generateColor(tris, baseColor=(0, 90, 30), scale=20):
heights = tris['points'][:, 0, 2]
tris['color'] = baseColor
tris['color'][:, 1] += (heights * scale).astype('u1')
return tris
def constructTriangles(points):
triangles = chopPointsIntoTris(points)
tris = np.ndarray(triangles.shape[0], dtype=[('color', 'u1', 3), ('points', 'f4', (3, 3))])
tris['points'] = triangles
generateColor(tris)
return tris
def colorClouds(tris, baseColor=(255, 255, 255), scale=40):
heights = tris['points'][:, 1, 2] - 10
tris['color'] = baseColor
tris['color'] -= (heights * scale).astype('u1')[:, np.newaxis]
return tris
def constructClouds(points):
triangles = chopPointsIntoTris(points)
triangles = triangles[triangles[:, 0, 2] < 12]
tris = np.ndarray(triangles.shape[0], dtype=[('color', 'u1', 3), ('points', 'f4', (3, 3))])
tris['points'] = triangles
colorClouds(tris)
return tris
def cloudGenerator(minX, minY, maxX, maxY, tilesize=6, scale=4, base=10., offset=50):
heights = vnoiseObj.noise2(np.arange(minY+offset, maxY+offset)/tilesize, np.arange(minX+offset, maxX+offset)/tilesize)
heights += 0.75
heights *= scale / 1.5
# heights **= 2
heights += base
return heights
def getCloudsArr(minX, maxX, minY, maxY):
points = np.ndarray(( maxY-minY, maxX-minX, 3))
points[:, :, 0] = np.reshape( np.tile( np.arange(minX, maxX), maxY-minY), points.shape[:2])
points[:, :, 1] = np.reshape( np.repeat( np.arange(minY, maxY), maxX-minX), points.shape[:2])
points[:, :, 2] = cloudGenerator(minX, minY, maxX, maxY)
return points
def getTriangles(cameraPos, cameraRotation, farPlaneDistance, closePlaneDistance):
boundaries = getVisibleMapSquare(cameraPos, cameraRotation, farPlaneDistance, closePlaneDistance)
points = getPointsArr(*boundaries)
clouds = getCloudsArr(*boundaries)
clouds = constructClouds(clouds)
return np.concatenate((constructTriangles(points), clouds))
# TODO: merge this into the rendering so we don't have to call vnoise twice
def getSurfaceHeight(cameraPos, playerHeight=1.5):
adjacentSquares = getPointsArr(int(cameraPos.x), int(cameraPos.x)+2, int(cameraPos.y), int(cameraPos.y)+2)
cameraFractX = cameraPos.x % 1
cameraFractY = cameraPos.y % 1
a = adjacentSquares[0, :, 2]
b = adjacentSquares[1, :, 2]
newA, newB = cameraFractY * (b - a) + a
height = cameraFractX * (newB - newA) + newA
return height + playerHeight
def main():
# pygame
screenSize = 700
display = pygame.display.set_mode((screenSize, screenSize), pygame.DOUBLEBUF)
pygame.event.set_blocked(None)
pygame.event.set_allowed([pygame.QUIT, pygame.KEYDOWN, pygame.KEYUP, pygame.MOUSEMOTION])
frameClock = pygame.time.Clock()
# mouse
crossPos = pygame.Vector2((screenSize/2, screenSize/2))
crossRects = [(crossPos.x, crossPos.y-4, 2, 10), (crossPos.x-4, crossPos.y, 10, 2)]
lastMouseRel = (0, 0)
pygame.mouse.set_visible(False)
pygame.mouse.set_pos(crossPos)
# TODO: use the fogSurface
fogSurface = pygame.Surface((screenSize, screenSize))
fogSurface.fill((2,204,254))
fogSurface.set_alpha(15)
# camera
cameraPos = Vector3(0, 0, 0)
cameraPos.z = getSurfaceHeight(cameraPos)
cameraRotation = Vector3(0, 0, 0)
cameraSpeed = Vector3(0., 0., 0.)
airTime = True
# rendering
farPlaneDistance = 20
closePlaneDistance = 1.
# controls per second
cameraMovementSpeed = 5.
cameraRotationSpeed = 3. # radians
cameraJumpStartVelocity = 2.5
gravity = Vector3(0, 0, -2.)
keysDown = {x: False for x in [pygame.K_w, pygame.K_s, pygame.K_a, pygame.K_d, pygame.K_SPACE]}
# inner vars
startFrameTime = time.time()
running = True
while running:
temp = startFrameTime
startFrameTime = time.time()
numSecsPassed = startFrameTime - temp
mouseMotions = pygame.Vector2((0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key in [pygame.K_w, pygame.K_s, pygame.K_a, pygame.K_d, pygame.K_SPACE]:
keysDown[event.key] = True
elif event.key == pygame.K_p: # debug
print('camera pos:', cameraPos, '\ncamera rot:', cameraRotation)
elif event.key == pygame.K_ESCAPE:
running = False
elif event.type == pygame.KEYUP:
if event.key in [pygame.K_w, pygame.K_s, pygame.K_a, pygame.K_d, pygame.K_SPACE]:
keysDown[event.key] = False
elif event.type == pygame.MOUSEMOTION:
mouseMotions += event.rel
mouseMotions -= lastMouseRel
lastMouseRel = crossPos - pygame.Vector2( pygame.mouse.get_pos() )
pygame.mouse.set_pos(crossPos)
# cam rotations
cameraRotation.y += mouseMotions.y / 100
cameraRotation.y = max(min(cameraRotation.y, 1), -1)
cameraRotation.z += mouseMotions.x / 100
# controls
speedScalingFactor = cameraMovementSpeed * numSecsPassed
moveVectorForward = Vector2(math.cos(cameraRotation.z), math.sin(cameraRotation.z)) * speedScalingFactor
moveVectorSideways = Vector2(-math.sin(cameraRotation.z), math.cos(cameraRotation.z)) * speedScalingFactor
if keysDown[pygame.K_w]:
cameraPos.xy += moveVectorForward
if keysDown[pygame.K_s]:
cameraPos.xy -= moveVectorForward
if keysDown[pygame.K_a]:
cameraPos.xy -= moveVectorSideways
if keysDown[pygame.K_d]:
cameraPos.xy += moveVectorSideways
if keysDown[pygame.K_SPACE]:
if not airTime:
cameraSpeed.z = cameraJumpStartVelocity
airTime = True
# camera movement
surfaceHeight = getSurfaceHeight(cameraPos)
cameraPos += numSecsPassed * (cameraSpeed + gravity * numSecsPassed/2)
cameraSpeed += gravity * numSecsPassed
if not airTime and cameraPos.z <= surfaceHeight + .5:
cameraPos.z = surfaceHeight
cameraSpeed += gravity * 6
elif cameraPos.z < surfaceHeight:
cameraPos.z = surfaceHeight
cameraSpeed.z = 0.
airTime = False
# rendering
tris = getTriangles(cameraPos, cameraRotation, farPlaneDistance, closePlaneDistance)
tris2D = renderPipeline(tris, cameraPos, cameraRotation, screenSize, closePlaneDistance)
# drawing
display.fill((2,204,254))
drawTerrainCollored(tris2D, display)
pygame.draw.rect(display, (128, 128, 128), crossRects[0])
pygame.draw.rect(display, (128, 128, 128), crossRects[1])
pygame.display.update()
frameClock.tick(30)
# print(f'{frameClock.get_fps():.1f}')
if __name__ == '__main__':
pygame.init()
main()
pygame.quit()