Cycles: Make BVH wider prior to packing
[blender.git] / intern / cycles / bvh / bvh.cpp
1 /*
2  * Adapted from code copyright 2009-2010 NVIDIA Corporation
3  * Modifications Copyright 2011, Blender Foundation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include "bvh/bvh.h"
19
20 #include "render/mesh.h"
21 #include "render/object.h"
22
23 #include "bvh/bvh2.h"
24 #include "bvh/bvh4.h"
25 #include "bvh/bvh8.h"
26 #include "bvh/bvh_build.h"
27 #include "bvh/bvh_node.h"
28
29 #ifdef WITH_EMBREE
30 #include "bvh/bvh_embree.h"
31 #endif
32
33 #include "util/util_foreach.h"
34 #include "util/util_logging.h"
35 #include "util/util_progress.h"
36
37 CCL_NAMESPACE_BEGIN
38
39 /* BVH Parameters. */
40
41 const char *bvh_layout_name(BVHLayout layout)
42 {
43         switch(layout) {
44                 case BVH_LAYOUT_BVH2: return "BVH2";
45                 case BVH_LAYOUT_BVH4: return "BVH4";
46                 case BVH_LAYOUT_BVH8: return "BVH8";
47                 case BVH_LAYOUT_NONE: return "NONE";
48                 case BVH_LAYOUT_EMBREE: return "EMBREE";
49                 case BVH_LAYOUT_ALL:  return "ALL";
50         }
51         LOG(DFATAL) << "Unsupported BVH layout was passed.";
52         return "";
53 }
54
55 BVHLayout BVHParams::best_bvh_layout(BVHLayout requested_layout,
56                                      BVHLayoutMask supported_layouts)
57 {
58         const BVHLayoutMask requested_layout_mask = (BVHLayoutMask)requested_layout;
59         /* Check whether requested layout is supported, if so -- no need to do
60          * any extra computation.
61          */
62         if(supported_layouts & requested_layout_mask) {
63                 return requested_layout;
64         }
65         /* Some bit magic to get widest supported BVH layout. */
66         /* This is a mask of supported BVH layouts which are narrower than the
67          * requested one.
68          */
69         const BVHLayoutMask allowed_layouts_mask =
70                 (supported_layouts & (requested_layout_mask - 1));
71         /* We get widest from allowed ones and convert mask to actual layout. */
72         const BVHLayoutMask widest_allowed_layout_mask = __bsr(allowed_layouts_mask);
73         return (BVHLayout)(1 << widest_allowed_layout_mask);
74 }
75
76 /* Pack Utility */
77
78 BVHStackEntry::BVHStackEntry(const BVHNode *n, int i)
79     : node(n), idx(i)
80 {
81 }
82
83 int BVHStackEntry::encodeIdx() const
84 {
85         return (node->is_leaf())? ~idx: idx;
86 }
87
88 /* BVH */
89
90 BVH::BVH(const BVHParams& params_, const vector<Object*>& objects_)
91 : params(params_), objects(objects_)
92 {
93 }
94
95 BVH *BVH::create(const BVHParams& params, const vector<Object*>& objects)
96 {
97         switch(params.bvh_layout) {
98                 case BVH_LAYOUT_BVH2:
99                         return new BVH2(params, objects);
100                 case BVH_LAYOUT_BVH4:
101                         return new BVH4(params, objects);
102                 case BVH_LAYOUT_BVH8:
103                         return new BVH8(params, objects);
104                 case BVH_LAYOUT_EMBREE:
105 #ifdef WITH_EMBREE
106                         return new BVHEmbree(params, objects);
107 #endif
108                 case BVH_LAYOUT_NONE:
109                 case BVH_LAYOUT_ALL:
110                         break;
111         }
112         LOG(DFATAL) << "Requested unsupported BVH layout.";
113         return NULL;
114 }
115
116 /* Building */
117
118 void BVH::build(Progress& progress, Stats*)
119 {
120         progress.set_substatus("Building BVH");
121
122         /* build nodes */
123         BVHBuild bvh_build(objects,
124                            pack.prim_type,
125                            pack.prim_index,
126                            pack.prim_object,
127                            pack.prim_time,
128                            params,
129                            progress);
130         BVHNode *bvh2_root = bvh_build.run();
131
132         if(progress.get_cancel()) {
133                 if(bvh2_root != NULL) {
134                         bvh2_root->deleteSubtree();
135                 }
136                 return;
137         }
138
139         /* BVH builder returns tree in a binary mode (with two children per inner
140          * node. Need to adopt that for a wider BVH implementations. */
141         BVHNode *root = widen_children_nodes(bvh2_root);
142         if(root != bvh2_root) {
143                 bvh2_root->deleteSubtree();
144         }
145
146         if(progress.get_cancel()) {
147                 if(root != NULL) {
148                         root->deleteSubtree();
149                 }
150                 return;
151         }
152
153         /* pack triangles */
154         progress.set_substatus("Packing BVH triangles and strands");
155         pack_primitives();
156
157         if(progress.get_cancel()) {
158                 root->deleteSubtree();
159                 return;
160         }
161
162         /* pack nodes */
163         progress.set_substatus("Packing BVH nodes");
164         pack_nodes(root);
165
166         /* free build nodes */
167         root->deleteSubtree();
168 }
169
170 /* Refitting */
171
172 void BVH::refit(Progress& progress)
173 {
174         progress.set_substatus("Packing BVH primitives");
175         pack_primitives();
176
177         if(progress.get_cancel()) return;
178
179         progress.set_substatus("Refitting BVH nodes");
180         refit_nodes();
181 }
182
183 void BVH::refit_primitives(int start, int end, BoundBox& bbox, uint& visibility)
184 {
185         /* Refit range of primitives. */
186         for(int prim = start; prim < end; prim++) {
187                 int pidx = pack.prim_index[prim];
188                 int tob = pack.prim_object[prim];
189                 Object *ob = objects[tob];
190
191                 if(pidx == -1) {
192                         /* Object instance. */
193                         bbox.grow(ob->bounds);
194                 }
195                 else {
196                         /* Primitives. */
197                         const Mesh *mesh = ob->mesh;
198
199                         if(pack.prim_type[prim] & PRIMITIVE_ALL_CURVE) {
200                                 /* Curves. */
201                                 int str_offset = (params.top_level)? mesh->curve_offset: 0;
202                                 Mesh::Curve curve = mesh->get_curve(pidx - str_offset);
203                                 int k = PRIMITIVE_UNPACK_SEGMENT(pack.prim_type[prim]);
204
205                                 curve.bounds_grow(k, &mesh->curve_keys[0], &mesh->curve_radius[0], bbox);
206
207                                 visibility |= PATH_RAY_CURVE;
208
209                                 /* Motion curves. */
210                                 if(mesh->use_motion_blur) {
211                                         Attribute *attr = mesh->curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
212
213                                         if(attr) {
214                                                 size_t mesh_size = mesh->curve_keys.size();
215                                                 size_t steps = mesh->motion_steps - 1;
216                                                 float3 *key_steps = attr->data_float3();
217
218                                                 for(size_t i = 0; i < steps; i++)
219                                                         curve.bounds_grow(k, key_steps + i*mesh_size, &mesh->curve_radius[0], bbox);
220                                         }
221                                 }
222                         }
223                         else {
224                                 /* Triangles. */
225                                 int tri_offset = (params.top_level)? mesh->tri_offset: 0;
226                                 Mesh::Triangle triangle = mesh->get_triangle(pidx - tri_offset);
227                                 const float3 *vpos = &mesh->verts[0];
228
229                                 triangle.bounds_grow(vpos, bbox);
230
231                                 /* Motion triangles. */
232                                 if(mesh->use_motion_blur) {
233                                         Attribute *attr = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
234
235                                         if(attr) {
236                                                 size_t mesh_size = mesh->verts.size();
237                                                 size_t steps = mesh->motion_steps - 1;
238                                                 float3 *vert_steps = attr->data_float3();
239
240                                                 for(size_t i = 0; i < steps; i++)
241                                                         triangle.bounds_grow(vert_steps + i*mesh_size, bbox);
242                                         }
243                                 }
244                         }
245                 }
246                 visibility |= ob->visibility_for_tracing();
247
248         }
249 }
250
251 /* Triangles */
252
253 void BVH::pack_triangle(int idx, float4 tri_verts[3])
254 {
255         int tob = pack.prim_object[idx];
256         assert(tob >= 0 && tob < objects.size());
257         const Mesh *mesh = objects[tob]->mesh;
258
259         int tidx = pack.prim_index[idx];
260         Mesh::Triangle t = mesh->get_triangle(tidx);
261         const float3 *vpos = &mesh->verts[0];
262         float3 v0 = vpos[t.v[0]];
263         float3 v1 = vpos[t.v[1]];
264         float3 v2 = vpos[t.v[2]];
265
266         tri_verts[0] = float3_to_float4(v0);
267         tri_verts[1] = float3_to_float4(v1);
268         tri_verts[2] = float3_to_float4(v2);
269 }
270
271 void BVH::pack_primitives()
272 {
273         const size_t tidx_size = pack.prim_index.size();
274         size_t num_prim_triangles = 0;
275         /* Count number of triangles primitives in BVH. */
276         for(unsigned int i = 0; i < tidx_size; i++) {
277                 if((pack.prim_index[i] != -1)) {
278                         if((pack.prim_type[i] & PRIMITIVE_ALL_TRIANGLE) != 0) {
279                                 ++num_prim_triangles;
280                         }
281                 }
282         }
283         /* Reserve size for arrays. */
284         pack.prim_tri_index.clear();
285         pack.prim_tri_index.resize(tidx_size);
286         pack.prim_tri_verts.clear();
287         pack.prim_tri_verts.resize(num_prim_triangles * 3);
288         pack.prim_visibility.clear();
289         pack.prim_visibility.resize(tidx_size);
290         /* Fill in all the arrays. */
291         size_t prim_triangle_index = 0;
292         for(unsigned int i = 0; i < tidx_size; i++) {
293                 if(pack.prim_index[i] != -1) {
294                         int tob = pack.prim_object[i];
295                         Object *ob = objects[tob];
296                         if((pack.prim_type[i] & PRIMITIVE_ALL_TRIANGLE) != 0) {
297                                 pack_triangle(i, (float4*)&pack.prim_tri_verts[3 * prim_triangle_index]);
298                                 pack.prim_tri_index[i] = 3 * prim_triangle_index;
299                                 ++prim_triangle_index;
300                         }
301                         else {
302                                 pack.prim_tri_index[i] = -1;
303                         }
304                         pack.prim_visibility[i] = ob->visibility_for_tracing();
305                         if(pack.prim_type[i] & PRIMITIVE_ALL_CURVE) {
306                                 pack.prim_visibility[i] |= PATH_RAY_CURVE;
307                         }
308                 }
309                 else {
310                         pack.prim_tri_index[i] = -1;
311                         pack.prim_visibility[i] = 0;
312                 }
313         }
314 }
315
316 /* Pack Instances */
317
318 void BVH::pack_instances(size_t nodes_size, size_t leaf_nodes_size)
319 {
320         /* The BVH's for instances are built separately, but for traversal all
321          * BVH's are stored in global arrays. This function merges them into the
322          * top level BVH, adjusting indexes and offsets where appropriate.
323          */
324         const bool use_qbvh = (params.bvh_layout == BVH_LAYOUT_BVH4);
325         const bool use_obvh = (params.bvh_layout == BVH_LAYOUT_BVH8);
326
327         /* Adjust primitive index to point to the triangle in the global array, for
328          * meshes with transform applied and already in the top level BVH.
329          */
330         for(size_t i = 0; i < pack.prim_index.size(); i++)
331                 if(pack.prim_index[i] != -1) {
332                         if(pack.prim_type[i] & PRIMITIVE_ALL_CURVE)
333                                 pack.prim_index[i] += objects[pack.prim_object[i]]->mesh->curve_offset;
334                         else
335                                 pack.prim_index[i] += objects[pack.prim_object[i]]->mesh->tri_offset;
336                 }
337
338         /* track offsets of instanced BVH data in global array */
339         size_t prim_offset = pack.prim_index.size();
340         size_t nodes_offset = nodes_size;
341         size_t nodes_leaf_offset = leaf_nodes_size;
342
343         /* clear array that gives the node indexes for instanced objects */
344         pack.object_node.clear();
345
346         /* reserve */
347         size_t prim_index_size = pack.prim_index.size();
348         size_t prim_tri_verts_size = pack.prim_tri_verts.size();
349
350         size_t pack_prim_index_offset = prim_index_size;
351         size_t pack_prim_tri_verts_offset = prim_tri_verts_size;
352         size_t pack_nodes_offset = nodes_size;
353         size_t pack_leaf_nodes_offset = leaf_nodes_size;
354         size_t object_offset = 0;
355
356         map<Mesh*, int> mesh_map;
357
358         foreach(Object *ob, objects) {
359                 Mesh *mesh = ob->mesh;
360                 BVH *bvh = mesh->bvh;
361
362                 if(mesh->need_build_bvh()) {
363                         if(mesh_map.find(mesh) == mesh_map.end()) {
364                                 prim_index_size += bvh->pack.prim_index.size();
365                                 prim_tri_verts_size += bvh->pack.prim_tri_verts.size();
366                                 nodes_size += bvh->pack.nodes.size();
367                                 leaf_nodes_size += bvh->pack.leaf_nodes.size();
368
369                                 mesh_map[mesh] = 1;
370                         }
371                 }
372         }
373
374         mesh_map.clear();
375
376         pack.prim_index.resize(prim_index_size);
377         pack.prim_type.resize(prim_index_size);
378         pack.prim_object.resize(prim_index_size);
379         pack.prim_visibility.resize(prim_index_size);
380         pack.prim_tri_verts.resize(prim_tri_verts_size);
381         pack.prim_tri_index.resize(prim_index_size);
382         pack.nodes.resize(nodes_size);
383         pack.leaf_nodes.resize(leaf_nodes_size);
384         pack.object_node.resize(objects.size());
385
386         if(params.num_motion_curve_steps > 0 || params.num_motion_triangle_steps > 0) {
387                 pack.prim_time.resize(prim_index_size);
388         }
389
390         int *pack_prim_index = (pack.prim_index.size())? &pack.prim_index[0]: NULL;
391         int *pack_prim_type = (pack.prim_type.size())? &pack.prim_type[0]: NULL;
392         int *pack_prim_object = (pack.prim_object.size())? &pack.prim_object[0]: NULL;
393         uint *pack_prim_visibility = (pack.prim_visibility.size())? &pack.prim_visibility[0]: NULL;
394         float4 *pack_prim_tri_verts = (pack.prim_tri_verts.size())? &pack.prim_tri_verts[0]: NULL;
395         uint *pack_prim_tri_index = (pack.prim_tri_index.size())? &pack.prim_tri_index[0]: NULL;
396         int4 *pack_nodes = (pack.nodes.size())? &pack.nodes[0]: NULL;
397         int4 *pack_leaf_nodes = (pack.leaf_nodes.size())? &pack.leaf_nodes[0]: NULL;
398         float2 *pack_prim_time = (pack.prim_time.size())? &pack.prim_time[0]: NULL;
399
400         /* merge */
401         foreach(Object *ob, objects) {
402                 Mesh *mesh = ob->mesh;
403
404                 /* We assume that if mesh doesn't need own BVH it was already included
405                  * into a top-level BVH and no packing here is needed.
406                  */
407                 if(!mesh->need_build_bvh()) {
408                         pack.object_node[object_offset++] = 0;
409                         continue;
410                 }
411
412                 /* if mesh already added once, don't add it again, but used set
413                  * node offset for this object */
414                 map<Mesh*, int>::iterator it = mesh_map.find(mesh);
415
416                 if(mesh_map.find(mesh) != mesh_map.end()) {
417                         int noffset = it->second;
418                         pack.object_node[object_offset++] = noffset;
419                         continue;
420                 }
421
422                 BVH *bvh = mesh->bvh;
423
424                 int noffset = nodes_offset;
425                 int noffset_leaf = nodes_leaf_offset;
426                 int mesh_tri_offset = mesh->tri_offset;
427                 int mesh_curve_offset = mesh->curve_offset;
428
429                 /* fill in node indexes for instances */
430                 if(bvh->pack.root_index == -1)
431                         pack.object_node[object_offset++] = -noffset_leaf-1;
432                 else
433                         pack.object_node[object_offset++] = noffset;
434
435                 mesh_map[mesh] = pack.object_node[object_offset-1];
436
437                 /* merge primitive, object and triangle indexes */
438                 if(bvh->pack.prim_index.size()) {
439                         size_t bvh_prim_index_size = bvh->pack.prim_index.size();
440                         int *bvh_prim_index = &bvh->pack.prim_index[0];
441                         int *bvh_prim_type = &bvh->pack.prim_type[0];
442                         uint *bvh_prim_visibility = &bvh->pack.prim_visibility[0];
443                         uint *bvh_prim_tri_index = &bvh->pack.prim_tri_index[0];
444                         float2 *bvh_prim_time = bvh->pack.prim_time.size()? &bvh->pack.prim_time[0]: NULL;
445
446                         for(size_t i = 0; i < bvh_prim_index_size; i++) {
447                                 if(bvh->pack.prim_type[i] & PRIMITIVE_ALL_CURVE) {
448                                         pack_prim_index[pack_prim_index_offset] = bvh_prim_index[i] + mesh_curve_offset;
449                                         pack_prim_tri_index[pack_prim_index_offset] = -1;
450                                 }
451                                 else {
452                                         pack_prim_index[pack_prim_index_offset] = bvh_prim_index[i] + mesh_tri_offset;
453                                         pack_prim_tri_index[pack_prim_index_offset] =
454                                                 bvh_prim_tri_index[i] + pack_prim_tri_verts_offset;
455                                 }
456
457                                 pack_prim_type[pack_prim_index_offset] = bvh_prim_type[i];
458                                 pack_prim_visibility[pack_prim_index_offset] = bvh_prim_visibility[i];
459                                 pack_prim_object[pack_prim_index_offset] = 0;  // unused for instances
460                                 if(bvh_prim_time != NULL) {
461                                         pack_prim_time[pack_prim_index_offset] = bvh_prim_time[i];
462                                 }
463                                 pack_prim_index_offset++;
464                         }
465                 }
466
467                 /* Merge triangle vertices data. */
468                 if(bvh->pack.prim_tri_verts.size()) {
469                         const size_t prim_tri_size = bvh->pack.prim_tri_verts.size();
470                         memcpy(pack_prim_tri_verts + pack_prim_tri_verts_offset,
471                                &bvh->pack.prim_tri_verts[0],
472                                prim_tri_size*sizeof(float4));
473                         pack_prim_tri_verts_offset += prim_tri_size;
474                 }
475
476                 /* merge nodes */
477                 if(bvh->pack.leaf_nodes.size()) {
478                         int4 *leaf_nodes_offset = &bvh->pack.leaf_nodes[0];
479                         size_t leaf_nodes_offset_size = bvh->pack.leaf_nodes.size();
480                         for(size_t i = 0, j = 0;
481                             i < leaf_nodes_offset_size;
482                             i += BVH_NODE_LEAF_SIZE, j++)
483                         {
484                                 int4 data = leaf_nodes_offset[i];
485                                 data.x += prim_offset;
486                                 data.y += prim_offset;
487                                 pack_leaf_nodes[pack_leaf_nodes_offset] = data;
488                                 for(int j = 1; j < BVH_NODE_LEAF_SIZE; ++j) {
489                                         pack_leaf_nodes[pack_leaf_nodes_offset + j] = leaf_nodes_offset[i + j];
490                                 }
491                                 pack_leaf_nodes_offset += BVH_NODE_LEAF_SIZE;
492                         }
493                 }
494
495                 if(bvh->pack.nodes.size()) {
496                         int4 *bvh_nodes = &bvh->pack.nodes[0];
497                         size_t bvh_nodes_size = bvh->pack.nodes.size();
498
499                         for(size_t i = 0, j = 0; i < bvh_nodes_size; j++) {
500                                 size_t nsize, nsize_bbox;
501                                 if(bvh_nodes[i].x & PATH_RAY_NODE_UNALIGNED) {
502                                         if(use_obvh) {
503                                                 nsize = BVH_UNALIGNED_ONODE_SIZE;
504                                                 nsize_bbox = BVH_UNALIGNED_ONODE_SIZE-1;
505                                         }
506                                         else {
507                                                 nsize = use_qbvh
508                                                         ? BVH_UNALIGNED_QNODE_SIZE
509                                                         : BVH_UNALIGNED_NODE_SIZE;
510                                                 nsize_bbox = (use_qbvh) ? BVH_UNALIGNED_QNODE_SIZE-1 : 0;
511                                         }
512                                 }
513                                 else {
514                                         if(use_obvh) {
515                                                 nsize = BVH_ONODE_SIZE;
516                                                 nsize_bbox = BVH_ONODE_SIZE-1;
517                                         }
518                                         else {
519                                                 nsize = (use_qbvh)? BVH_QNODE_SIZE: BVH_NODE_SIZE;
520                                                 nsize_bbox = (use_qbvh)? BVH_QNODE_SIZE-1 : 0;
521                                         }
522                                 }
523
524                                 memcpy(pack_nodes + pack_nodes_offset,
525                                        bvh_nodes + i,
526                                        nsize_bbox*sizeof(int4));
527
528                                 /* Modify offsets into arrays */
529                                 int4 data = bvh_nodes[i + nsize_bbox];
530                                 int4 data1 = bvh_nodes[i + nsize_bbox-1];
531                                 if(use_obvh) {
532                                         data.z += (data.z < 0) ? -noffset_leaf : noffset;
533                                         data.w += (data.w < 0) ? -noffset_leaf : noffset;
534                                         data.x += (data.x < 0) ? -noffset_leaf : noffset;
535                                         data.y += (data.y < 0) ? -noffset_leaf : noffset;
536                                         data1.z += (data1.z < 0) ? -noffset_leaf : noffset;
537                                         data1.w += (data1.w < 0) ? -noffset_leaf : noffset;
538                                         data1.x += (data1.x < 0) ? -noffset_leaf : noffset;
539                                         data1.y += (data1.y < 0) ? -noffset_leaf : noffset;
540                                 }
541                                 else {
542                                         data.z += (data.z < 0) ? -noffset_leaf : noffset;
543                                         data.w += (data.w < 0) ? -noffset_leaf : noffset;
544                                         if(use_qbvh) {
545                                                 data.x += (data.x < 0)? -noffset_leaf: noffset;
546                                                 data.y += (data.y < 0)? -noffset_leaf: noffset;
547                                         }
548                                 }
549                                 pack_nodes[pack_nodes_offset + nsize_bbox] = data;
550                                 if(use_obvh) {
551                                         pack_nodes[pack_nodes_offset + nsize_bbox - 1] = data1;
552                                 }
553
554                                 /* Usually this copies nothing, but we better
555                                  * be prepared for possible node size extension.
556                                  */
557                                 memcpy(&pack_nodes[pack_nodes_offset + nsize_bbox+1],
558                                        &bvh_nodes[i + nsize_bbox+1],
559                                        sizeof(int4) * (nsize - (nsize_bbox+1)));
560
561                                 pack_nodes_offset += nsize;
562                                 i += nsize;
563                         }
564                 }
565
566                 nodes_offset += bvh->pack.nodes.size();
567                 nodes_leaf_offset += bvh->pack.leaf_nodes.size();
568                 prim_offset += bvh->pack.prim_index.size();
569         }
570 }
571
572 CCL_NAMESPACE_END