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
|
import numpy as np
import numpy.ma as ma
import pycuda.driver as cuda
from pycuda import gpuarray
from mesh import Mesh
from materials import wavelengths
def interleave(arr, bits):
"""
Interleave the bits of quantized three-dimensional points in space.
Example
>>> interleave(np.identity(3, dtype=np.int))
array([4, 2, 1], dtype=uint64)
"""
if len(arr.shape) != 2 or arr.shape[1] != 3:
raise Exception('shape mismatch')
z = np.zeros(arr.shape[0], dtype=np.uint32)
for i in range(bits):
z |= (arr[:,2] & 1 << i) << (2*i) | \
(arr[:,1] & 1 << i) << (2*i+1) | \
(arr[:,0] & 1 << i) << (2*i+2)
return z
def morton_order(mesh, bits):
"""
Return a list of zvalues for triangles in `mesh` by interleaving the
bits of the quantized center coordinates of each triangle. Each coordinate
axis is quantized into 2**bits bins.
"""
lower_bound = np.array([np.min(mesh[:,:,0]),
np.min(mesh[:,:,1]),
np.min(mesh[:,:,2])])
upper_bound = np.array([np.max(mesh[:,:,0]),
np.max(mesh[:,:,1]),
np.max(mesh[:,:,2])])
if bits <= 0 or bits > 12:
raise Exception('number of bits must be in the range (0,12].')
max_value = 2**bits - 1
def quantize(x):
return np.uint32((x-lower_bound)*max_value/(upper_bound-lower_bound))
mean_positions = quantize(np.mean(mesh, axis=1))
return interleave(mean_positions, bits)
class Geometry(object):
def __init__(self, solids=[]):
self.solids = solids
def add_solid(self, solid):
self.solids.append(solid)
def build(self, bits=8):
offsets = [ (0,0) ]
for solid in self.solids:
offsets.append( (offsets[-1][0] + len(solid.mesh.vertices),
offsets[-1][1] + len(solid.mesh.triangles)) )
vertices = np.zeros(shape=(offsets[-1][0], 3), dtype=np.float32)
triangles = np.zeros(shape=(offsets[-1][1],3), dtype=np.int32)
for solid, (vertex_offset, triangle_offset) in zip(self.solids, offsets[:-1]):
triangles[triangle_offset:triangle_offset+len(solid.mesh.triangles),:] = \
solid.mesh.triangles + vertex_offset
vertices[vertex_offset:vertex_offset + len(solid.mesh.vertices),:] = \
np.inner(solid.mesh.vertices, solid.rotation) + solid.displacement
self.mesh = Mesh(vertices, triangles)
del vertices
del triangles
zvalues_mesh = morton_order(self.mesh[:], bits)
reorder = np.argsort(zvalues_mesh)
zvalues_mesh = zvalues_mesh[reorder]
if (np.diff(zvalues_mesh) < 0).any():
raise Exception('zvalues_mesh out of order.')
self.mesh.triangles = self.mesh.triangles[reorder]
material1 = np.concatenate([solid.material1 for solid in self.solids])
material2 = np.concatenate([solid.material2 for solid in self.solids])
self.materials = \
list(np.unique(np.concatenate([material1, material2])))
self.material1_index = np.empty(len(self.mesh), dtype=np.int32)
self.material2_index = np.empty(len(self.mesh), dtype=np.int32)
for i, material in enumerate(material1[reorder]):
if material is not None:
self.material1_index[i] = self.materials.index(material)
else:
self.material1_index[i] = -1
for i, material in enumerate(material2[reorder]):
if material is not None:
self.material2_index[i] = self.materials.index(material)
else:
self.material2_index[i] = -1
surface = np.concatenate([solid.surface for solid in self.solids])
self.surfaces = list(np.unique(surface))
self.surface_index = np.empty(len(self.mesh), dtype=np.int32)
for i, surface in enumerate(surface[reorder]):
if surface is not None:
self.surface_index[i] = self.surfaces.index(surface)
else:
self.surface_index[i] = -1
self.colors = np.concatenate([solid.color for solid in self.solids])
self.solid_id = np.concatenate([np.tile(solid.id, len(solid.mesh)) \
for solid in self.solids])[reorder]
unique_zvalues = np.unique(zvalues_mesh)
zvalues = np.empty(unique_zvalues.size, dtype=np.uint64)
self.lower_bounds = np.empty((unique_zvalues.size,3), dtype=np.float32)
self.upper_bounds = np.empty((unique_zvalues.size,3), dtype=np.float32)
self.node_map = np.empty(unique_zvalues.size, dtype=np.uint32)
self.node_length = np.empty(unique_zvalues.size, dtype=np.uint32)
for i, z in enumerate(unique_zvalues):
i1 = np.searchsorted(zvalues_mesh, z)
i2 = np.searchsorted(zvalues_mesh, z, side='right')
self.lower_bounds[i] = [np.min(self.mesh[i1:i2][:,:,0]),
np.min(self.mesh[i1:i2][:,:,1]),
np.min(self.mesh[i1:i2][:,:,2])]
self.upper_bounds[i] = [np.max(self.mesh[i1:i2][:,:,0]),
np.max(self.mesh[i1:i2][:,:,1]),
np.max(self.mesh[i1:i2][:,:,2])]
self.node_map[i] = i1
self.node_length[i] = i2-i1
zvalues[i] = z
self.first_node = unique_zvalues.size
begin_last_layer = 0
while True:
bit_shifted_zvalues = zvalues >> 1
unique_bit_shifted_zvalues = np.unique(bit_shifted_zvalues)
zvalues = np.empty(unique_bit_shifted_zvalues.size, dtype=np.uint64)
self.lower_bounds.resize(\
(self.lower_bounds.shape[0]+unique_bit_shifted_zvalues.size,3))
self.upper_bounds.resize(\
(self.upper_bounds.shape[0]+unique_bit_shifted_zvalues.size,3))
self.node_map.resize(\
self.node_map.size+unique_bit_shifted_zvalues.size)
self.node_length.resize(\
self.node_length.size+unique_bit_shifted_zvalues.size)
for i, z in enumerate(unique_bit_shifted_zvalues):
i1 = np.searchsorted(bit_shifted_zvalues, z) + \
begin_last_layer
i2 = np.searchsorted(bit_shifted_zvalues, z, side='right') + \
begin_last_layer
zvalues[i] = z
i += begin_last_layer + bit_shifted_zvalues.size
self.lower_bounds[i] = \
[np.min(self.lower_bounds[i1:i2,0]),
np.min(self.lower_bounds[i1:i2,1]),
np.min(self.lower_bounds[i1:i2,2])]
self.upper_bounds[i] = \
[np.max(self.upper_bounds[i1:i2,0]),
np.max(self.upper_bounds[i1:i2,1]),
np.max(self.upper_bounds[i1:i2,2])]
self.node_map[i] = i1
self.node_length[i] = i2-i1
begin_last_layer += bit_shifted_zvalues.size
if unique_bit_shifted_zvalues.size == 1:
break
def load(self, module, color=False):
"""
Load the bounding volume hierarchy onto the GPU module,
bind it to the appropriate textures, and return a list
of the texture references.
"""
set_wavelength_range = module.get_function('set_wavelength_range')
set_wavelength_range(wavelengths[0], wavelengths[-1], wavelengths[1]-wavelengths[0], block=(1,1,1), grid=(1,1))
set_material = module.get_function('set_material')
for i, material in enumerate(self.materials):
if material is None:
continue
refractive_index = np.interp(wavelengths, material.refractive_index[:,0], material.refractive_index[:,1]).astype(np.float32)
absorption_length = np.interp(wavelengths, material.absorption_length[:,0], material.absorption_length[:,1]).astype(np.float32)
scattering_length = np.interp(wavelengths, material.scattering_length[:,0], material.scattering_length[:,1]).astype(np.float32)
material.refractive_index_gpu = cuda.to_device(refractive_index)
material.absorption_length_gpu = cuda.to_device(absorption_length)
material.scattering_length_gpu = cuda.to_device(scattering_length)
set_material(np.int32(i), material.refractive_index_gpu, material.absorption_length_gpu, material.scattering_length_gpu, block=(1,1,1), grid=(1,1))
set_surface = module.get_function('set_surface')
for i, surface in enumerate(self.surfaces):
if surface is None:
continue
absorption = np.interp(wavelengths, surface.absorption[:,0], surface.absorption[:,1]).astype(np.float32)
reflection_diffuse = np.interp(wavelengths, surface.reflection_diffuse[:,0], surface.reflection_diffuse[:,1]).astype(np.float32)
reflection_specular = np.interp(wavelengths, surface.reflection_specular[:,0], surface.reflection_specular[:,1]).astype(np.float32)
surface.absorption_gpu = cuda.to_device(absorption)
surface.reflection_diffuse_gpu = cuda.to_device(reflection_diffuse)
surface.reflection_specular_gpu = cuda.to_device(reflection_specular)
set_surface(np.int32(i), surface.absorption_gpu, surface.reflection_diffuse_gpu, surface.reflection_specular_gpu, block=(1,1,1), grid=(1,1))
material1_index_tex = module.get_texref('material1_lookup')
material2_index_tex = module.get_texref('material2_lookup')
surface_index_tex = module.get_texref('surface_lookup')
material1_index_gpu = cuda.to_device(self.material1_index)
material2_index_gpu = cuda.to_device(self.material2_index)
surface_index_gpu = cuda.to_device(self.surface_index)
material1_index_tex.set_address(material1_index_gpu, self.material1_index.nbytes)
material2_index_tex.set_address(material2_index_gpu, self.material2_index.nbytes)
surface_index_tex.set_address(surface_index_gpu, self.surface_index.nbytes)
material1_index_tex.set_format(cuda.array_format.SIGNED_INT32, 1)
material2_index_tex.set_format(cuda.array_format.SIGNED_INT32, 1)
surface_index_tex.set_format(cuda.array_format.SIGNED_INT32, 1)
vertices = np.empty(len(self.mesh.vertices), dtype=gpuarray.vec.float4)
vertices['x'] = self.mesh.vertices[:,0]
vertices['y'] = self.mesh.vertices[:,1]
vertices['z'] = self.mesh.vertices[:,2]
triangles = \
np.empty(len(self.mesh.triangles), dtype=gpuarray.vec.uint4)
triangles['x'] = self.mesh.triangles[:,0]
triangles['y'] = self.mesh.triangles[:,1]
triangles['z'] = self.mesh.triangles[:,2]
if color:
triangles['w'] = self.colors
else:
triangles['w'] = (self.material1_index << 24) | (self.material2_index << 16) | (self.surface_index << 8)
lower_bounds = np.empty(self.lower_bounds.shape[0], dtype=gpuarray.vec.float4)
lower_bounds['x'] = self.lower_bounds[:,0]
lower_bounds['y'] = self.lower_bounds[:,1]
lower_bounds['z'] = self.lower_bounds[:,2]
upper_bounds = np.empty(self.upper_bounds.shape[0], dtype=gpuarray.vec.float4)
upper_bounds['x'] = self.upper_bounds[:,0]
upper_bounds['y'] = self.upper_bounds[:,1]
upper_bounds['z'] = self.upper_bounds[:,2]
self.vertices_gpu = cuda.to_device(vertices)
self.triangles_gpu = cuda.to_device(triangles)
self.lower_bounds_gpu = cuda.to_device(lower_bounds)
self.upper_bounds_gpu = cuda.to_device(upper_bounds)
self.node_map_gpu = cuda.to_device(self.node_map)
self.node_length_gpu = cuda.to_device(self.node_length)
set_pointer = module.get_function('set_pointer')
set_pointer(self.triangles_gpu, block=(1,1,1), grid=(1,1))
vertices_tex = module.get_texref('vertices')
lower_bounds_tex = module.get_texref('lower_bounds')
upper_bounds_tex = module.get_texref('upper_bounds')
node_map_tex = module.get_texref('node_map')
node_length_tex = module.get_texref('node_length')
vertices_tex.set_address(self.vertices_gpu, vertices.nbytes)
lower_bounds_tex.set_address(self.lower_bounds_gpu, lower_bounds.nbytes)
upper_bounds_tex.set_address(self.upper_bounds_gpu, upper_bounds.nbytes)
node_map_tex.set_address(self.node_map_gpu, self.node_map.nbytes)
node_length_tex.set_address(self.node_length_gpu, self.node_length.nbytes)
vertices_tex.set_format(cuda.array_format.FLOAT, 4)
lower_bounds_tex.set_format(cuda.array_format.FLOAT, 4)
upper_bounds_tex.set_format(cuda.array_format.FLOAT, 4)
node_map_tex.set_format(cuda.array_format.UNSIGNED_INT32, 1)
node_length_tex.set_format(cuda.array_format.UNSIGNED_INT32, 1)
return [vertices_tex, lower_bounds_tex, upper_bounds_tex, node_map_tex, node_length_tex]
|