Code cleanup: fix compiler warning.
[blender-staging.git] / intern / cycles / render / mesh.cpp
1 /*
2  * Copyright 2011-2013 Blender Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "bvh/bvh.h"
18 #include "bvh/bvh_build.h"
19
20 #include "render/camera.h"
21 #include "render/curves.h"
22 #include "device/device.h"
23 #include "render/graph.h"
24 #include "render/shader.h"
25 #include "render/light.h"
26 #include "render/mesh.h"
27 #include "render/nodes.h"
28 #include "render/object.h"
29 #include "render/scene.h"
30
31 #include "kernel/osl/osl_globals.h"
32
33 #include "subd/subd_split.h"
34 #include "subd/subd_patch_table.h"
35
36 #include "util/util_foreach.h"
37 #include "util/util_logging.h"
38 #include "util/util_progress.h"
39 #include "util/util_set.h"
40
41 CCL_NAMESPACE_BEGIN
42
43 /* Triangle */
44
45 void Mesh::Triangle::bounds_grow(const float3 *verts, BoundBox& bounds) const
46 {
47         bounds.grow(verts[v[0]]);
48         bounds.grow(verts[v[1]]);
49         bounds.grow(verts[v[2]]);
50 }
51
52 void Mesh::Triangle::motion_verts(const float3 *verts,
53                                   const float3 *vert_steps,
54                                   size_t num_verts,
55                                   size_t num_steps,
56                                   float time,
57                                   float3 r_verts[3]) const
58 {
59         /* Figure out which steps we need to fetch and their interpolation factor. */
60         const size_t max_step = num_steps - 1;
61         const size_t step = min((int)(time * max_step), max_step - 1);
62         const float t = time*max_step - step;
63         /* Fetch vertex coordinates. */
64         float3 curr_verts[3];
65         float3 next_verts[3];
66         verts_for_step(verts,
67                        vert_steps,
68                        num_verts,
69                        num_steps,
70                        step,
71                        curr_verts);
72         verts_for_step(verts,
73                        vert_steps,
74                        num_verts,
75                        num_steps,
76                        step + 1,
77                        next_verts);
78         /* Interpolate between steps. */
79         r_verts[0] = (1.0f - t)*curr_verts[0] + t*next_verts[0];
80         r_verts[1] = (1.0f - t)*curr_verts[1] + t*next_verts[1];
81         r_verts[2] = (1.0f - t)*curr_verts[2] + t*next_verts[2];
82 }
83
84 void Mesh::Triangle::verts_for_step(const float3 *verts,
85                                     const float3 *vert_steps,
86                                     size_t num_verts,
87                                     size_t num_steps,
88                                     size_t step,
89                                     float3 r_verts[3]) const
90 {
91         const size_t center_step = ((num_steps - 1) / 2);
92         if(step == center_step) {
93                 /* Center step: regular vertex location. */
94                 r_verts[0] = verts[v[0]];
95                 r_verts[1] = verts[v[1]];
96                 r_verts[2] = verts[v[2]];
97         }
98         else {
99                 /* Center step not stored in the attribute array array. */
100                 if(step > center_step) {
101                         step--;
102                 }
103                 size_t offset = step * num_verts;
104                 r_verts[0] = vert_steps[offset + v[0]];
105                 r_verts[1] = vert_steps[offset + v[1]];
106                 r_verts[2] = vert_steps[offset + v[2]];
107         }
108 }
109
110 float3 Mesh::Triangle::compute_normal(const float3 *verts) const
111 {
112         const float3& v0 = verts[v[0]];
113         const float3& v1 = verts[v[1]];
114         const float3& v2 = verts[v[2]];
115         const float3 norm = cross(v1 - v0, v2 - v0);
116         const float normlen = len(norm);
117         if(normlen == 0.0f) {
118                 return make_float3(1.0f, 0.0f, 0.0f);
119         }
120         return norm / normlen;
121 }
122
123 bool Mesh::Triangle::valid(const float3 *verts) const
124 {
125         return isfinite3_safe(verts[v[0]]) &&
126                isfinite3_safe(verts[v[1]]) &&
127                isfinite3_safe(verts[v[2]]);
128 }
129
130 /* Curve */
131
132 void Mesh::Curve::bounds_grow(const int k, const float3 *curve_keys, const float *curve_radius, BoundBox& bounds) const
133 {
134         float3 P[4];
135
136         P[0] = curve_keys[max(first_key + k - 1,first_key)];
137         P[1] = curve_keys[first_key + k];
138         P[2] = curve_keys[first_key + k + 1];
139         P[3] = curve_keys[min(first_key + k + 2, first_key + num_keys - 1)];
140
141         float3 lower;
142         float3 upper;
143
144         curvebounds(&lower.x, &upper.x, P, 0);
145         curvebounds(&lower.y, &upper.y, P, 1);
146         curvebounds(&lower.z, &upper.z, P, 2);
147
148         float mr = max(curve_radius[first_key + k], curve_radius[first_key + k + 1]);
149
150         bounds.grow(lower, mr);
151         bounds.grow(upper, mr);
152 }
153
154 void Mesh::Curve::bounds_grow(const int k,
155                               const float3 *curve_keys,
156                               const float *curve_radius,
157                               const Transform& aligned_space,
158                               BoundBox& bounds) const
159 {
160         float3 P[4];
161
162         P[0] = curve_keys[max(first_key + k - 1,first_key)];
163         P[1] = curve_keys[first_key + k];
164         P[2] = curve_keys[first_key + k + 1];
165         P[3] = curve_keys[min(first_key + k + 2, first_key + num_keys - 1)];
166
167         P[0] = transform_point(&aligned_space, P[0]);
168         P[1] = transform_point(&aligned_space, P[1]);
169         P[2] = transform_point(&aligned_space, P[2]);
170         P[3] = transform_point(&aligned_space, P[3]);
171
172         float3 lower;
173         float3 upper;
174
175         curvebounds(&lower.x, &upper.x, P, 0);
176         curvebounds(&lower.y, &upper.y, P, 1);
177         curvebounds(&lower.z, &upper.z, P, 2);
178
179         float mr = max(curve_radius[first_key + k], curve_radius[first_key + k + 1]);
180
181         bounds.grow(lower, mr);
182         bounds.grow(upper, mr);
183 }
184
185 void Mesh::Curve::bounds_grow(float4 keys[4], BoundBox& bounds) const
186 {
187         float3 P[4] = {
188                 float4_to_float3(keys[0]),
189                 float4_to_float3(keys[1]),
190                 float4_to_float3(keys[2]),
191                 float4_to_float3(keys[3]),
192         };
193
194         float3 lower;
195         float3 upper;
196
197         curvebounds(&lower.x, &upper.x, P, 0);
198         curvebounds(&lower.y, &upper.y, P, 1);
199         curvebounds(&lower.z, &upper.z, P, 2);
200
201         float mr = max(keys[1].w, keys[2].w);
202
203         bounds.grow(lower, mr);
204         bounds.grow(upper, mr);
205 }
206
207 void Mesh::Curve::motion_keys(const float3 *curve_keys,
208                               const float *curve_radius,
209                               const float3 *key_steps,
210                               size_t num_curve_keys,
211                               size_t num_steps,
212                               float time,
213                               size_t k0, size_t k1,
214                               float4 r_keys[2]) const
215 {
216         /* Figure out which steps we need to fetch and their interpolation factor. */
217         const size_t max_step = num_steps - 1;
218         const size_t step = min((int)(time * max_step), max_step - 1);
219         const float t = time*max_step - step;
220         /* Fetch vertex coordinates. */
221         float4 curr_keys[2];
222         float4 next_keys[2];
223         keys_for_step(curve_keys,
224                       curve_radius,
225                       key_steps,
226                       num_curve_keys,
227                       num_steps,
228                       step,
229                       k0, k1,
230                       curr_keys);
231         keys_for_step(curve_keys,
232                       curve_radius,
233                       key_steps,
234                       num_curve_keys,
235                       num_steps,
236                       step + 1,
237                       k0, k1,
238                       next_keys);
239         /* Interpolate between steps. */
240         r_keys[0] = (1.0f - t)*curr_keys[0] + t*next_keys[0];
241         r_keys[1] = (1.0f - t)*curr_keys[1] + t*next_keys[1];
242 }
243
244 void Mesh::Curve::cardinal_motion_keys(const float3 *curve_keys,
245                                        const float *curve_radius,
246                                        const float3 *key_steps,
247                                        size_t num_curve_keys,
248                                        size_t num_steps,
249                                        float time,
250                                        size_t k0, size_t k1,
251                                        size_t k2, size_t k3,
252                                        float4 r_keys[4]) const
253 {
254         /* Figure out which steps we need to fetch and their interpolation factor. */
255         const size_t max_step = num_steps - 1;
256         const size_t step = min((int)(time * max_step), max_step - 1);
257         const float t = time*max_step - step;
258         /* Fetch vertex coordinates. */
259         float4 curr_keys[4];
260         float4 next_keys[4];
261         cardinal_keys_for_step(curve_keys,
262                                curve_radius,
263                                key_steps,
264                                num_curve_keys,
265                                num_steps,
266                                step,
267                                k0, k1, k2, k3,
268                                curr_keys);
269         cardinal_keys_for_step(curve_keys,
270                                curve_radius,
271                                key_steps,
272                                num_curve_keys,
273                                num_steps,
274                                step + 1,
275                                k0, k1, k2, k3,
276                                next_keys);
277         /* Interpolate between steps. */
278         r_keys[0] = (1.0f - t)*curr_keys[0] + t*next_keys[0];
279         r_keys[1] = (1.0f - t)*curr_keys[1] + t*next_keys[1];
280         r_keys[2] = (1.0f - t)*curr_keys[2] + t*next_keys[2];
281         r_keys[3] = (1.0f - t)*curr_keys[3] + t*next_keys[3];
282 }
283
284 void Mesh::Curve::keys_for_step(const float3 *curve_keys,
285                                 const float *curve_radius,
286                                 const float3 *key_steps,
287                                 size_t num_curve_keys,
288                                 size_t num_steps,
289                                 size_t step,
290                                 size_t k0, size_t k1,
291                                 float4 r_keys[2]) const
292 {
293         k0 = max(k0, 0);
294         k1 = min(k1, num_keys - 1);
295         const size_t center_step = ((num_steps - 1) / 2);
296         if(step == center_step) {
297                 /* Center step: regular key location. */
298                 /* TODO(sergey): Consider adding make_float4(float3, float)
299                  * function.
300                  */
301                 r_keys[0] = make_float4(curve_keys[first_key + k0].x,
302                                         curve_keys[first_key + k0].y,
303                                         curve_keys[first_key + k0].z,
304                                         curve_radius[first_key + k0]);
305                 r_keys[1] = make_float4(curve_keys[first_key + k1].x,
306                                         curve_keys[first_key + k1].y,
307                                         curve_keys[first_key + k1].z,
308                                         curve_radius[first_key + k1]);
309         }
310         else {
311                 /* Center step is not stored in this array. */
312                 if(step > center_step) {
313                         step--;
314                 }
315                 const size_t offset = first_key + step * num_curve_keys;
316                 r_keys[0] = make_float4(key_steps[offset + k0].x,
317                                         key_steps[offset + k0].y,
318                                         key_steps[offset + k0].z,
319                                         curve_radius[first_key + k0]);
320                 r_keys[1] = make_float4(key_steps[offset + k1].x,
321                                         key_steps[offset + k1].y,
322                                         key_steps[offset + k1].z,
323                                         curve_radius[first_key + k1]);
324         }
325 }
326
327 void Mesh::Curve::cardinal_keys_for_step(const float3 *curve_keys,
328                                          const float *curve_radius,
329                                          const float3 *key_steps,
330                                          size_t num_curve_keys,
331                                          size_t num_steps,
332                                          size_t step,
333                                          size_t k0, size_t k1,
334                                          size_t k2, size_t k3,
335                                          float4 r_keys[4]) const
336 {
337         k0 = max(k0, 0);
338         k3 = min(k3, num_keys - 1);
339         const size_t center_step = ((num_steps - 1) / 2);
340         if(step == center_step) {
341                 /* Center step: regular key location. */
342                 r_keys[0] = make_float4(curve_keys[first_key + k0].x,
343                                         curve_keys[first_key + k0].y,
344                                         curve_keys[first_key + k0].z,
345                                         curve_radius[first_key + k0]);
346                 r_keys[1] = make_float4(curve_keys[first_key + k1].x,
347                                         curve_keys[first_key + k1].y,
348                                         curve_keys[first_key + k1].z,
349                                         curve_radius[first_key + k1]);
350                 r_keys[2] = make_float4(curve_keys[first_key + k2].x,
351                                         curve_keys[first_key + k2].y,
352                                         curve_keys[first_key + k2].z,
353                                         curve_radius[first_key + k2]);
354                 r_keys[3] = make_float4(curve_keys[first_key + k3].x,
355                                         curve_keys[first_key + k3].y,
356                                         curve_keys[first_key + k3].z,
357                                         curve_radius[first_key + k3]);
358         }
359         else {
360                 /* Center step is not stored in this array. */
361                 if(step > center_step) {
362                         step--;
363                 }
364                 const size_t offset = first_key + step * num_curve_keys;
365                 r_keys[0] = make_float4(key_steps[offset + k0].x,
366                                         key_steps[offset + k0].y,
367                                         key_steps[offset + k0].z,
368                                         curve_radius[first_key + k0]);
369                 r_keys[1] = make_float4(key_steps[offset + k1].x,
370                                         key_steps[offset + k1].y,
371                                         key_steps[offset + k1].z,
372                                         curve_radius[first_key + k1]);
373                 r_keys[2] = make_float4(key_steps[offset + k2].x,
374                                         key_steps[offset + k2].y,
375                                         key_steps[offset + k2].z,
376                                         curve_radius[first_key + k2]);
377                 r_keys[3] = make_float4(key_steps[offset + k3].x,
378                                         key_steps[offset + k3].y,
379                                         key_steps[offset + k3].z,
380                                         curve_radius[first_key + k3]);
381         }
382 }
383
384 /* SubdFace */
385
386 float3 Mesh::SubdFace::normal(const Mesh *mesh) const
387 {
388         float3 v0 = mesh->verts[mesh->subd_face_corners[start_corner+0]];
389         float3 v1 = mesh->verts[mesh->subd_face_corners[start_corner+1]];
390         float3 v2 = mesh->verts[mesh->subd_face_corners[start_corner+2]];
391
392         return safe_normalize(cross(v1 - v0, v2 - v0));
393 }
394
395 /* Mesh */
396
397 NODE_DEFINE(Mesh)
398 {
399         NodeType* type = NodeType::add("mesh", create);
400
401         SOCKET_UINT(motion_steps, "Motion Steps", 3);
402         SOCKET_BOOLEAN(use_motion_blur, "Use Motion Blur", false);
403
404         SOCKET_INT_ARRAY(triangles, "Triangles", array<int>());
405         SOCKET_POINT_ARRAY(verts, "Vertices", array<float3>());
406         SOCKET_INT_ARRAY(shader, "Shader", array<int>());
407         SOCKET_BOOLEAN_ARRAY(smooth, "Smooth", array<bool>());
408
409         SOCKET_POINT_ARRAY(curve_keys, "Curve Keys", array<float3>());
410         SOCKET_FLOAT_ARRAY(curve_radius, "Curve Radius", array<float>());
411         SOCKET_INT_ARRAY(curve_first_key, "Curve First Key", array<int>());
412         SOCKET_INT_ARRAY(curve_shader, "Curve Shader", array<int>());
413
414         return type;
415 }
416
417 Mesh::Mesh()
418 : Node(node_type)
419 {
420         need_update = true;
421         need_update_rebuild = false;
422         transform_applied = false;
423         transform_negative_scaled = false;
424         transform_normal = transform_identity();
425         bounds = BoundBox::empty;
426
427         bvh = NULL;
428
429         tri_offset = 0;
430         vert_offset = 0;
431
432         curve_offset = 0;
433         curvekey_offset = 0;
434
435         patch_offset = 0;
436         face_offset = 0;
437         corner_offset = 0;
438
439         attr_map_offset = 0;
440
441         num_subd_verts = 0;
442
443         attributes.triangle_mesh = this;
444         curve_attributes.curve_mesh = this;
445         subd_attributes.subd_mesh = this;
446
447         geometry_flags = GEOMETRY_NONE;
448
449         volume_isovalue = 0.001f;
450         has_volume = false;
451         has_surface_bssrdf = false;
452
453         num_ngons = 0;
454
455         subdivision_type = SUBDIVISION_NONE;
456         subd_params = NULL;
457
458         patch_table = NULL;
459 }
460
461 Mesh::~Mesh()
462 {
463         delete bvh;
464         delete patch_table;
465         delete subd_params;
466 }
467
468 void Mesh::resize_mesh(int numverts, int numtris)
469 {
470         verts.resize(numverts);
471         triangles.resize(numtris * 3);
472         shader.resize(numtris);
473         smooth.resize(numtris);
474
475         if(subd_faces.size()) {
476                 triangle_patch.resize(numtris);
477                 vert_patch_uv.resize(numverts);
478         }
479
480         attributes.resize();
481 }
482
483 void Mesh::reserve_mesh(int numverts, int numtris)
484 {
485         /* reserve space to add verts and triangles later */
486         verts.reserve(numverts);
487         triangles.reserve(numtris * 3);
488         shader.reserve(numtris);
489         smooth.reserve(numtris);
490
491         if(subd_faces.size()) {
492                 triangle_patch.reserve(numtris);
493                 vert_patch_uv.reserve(numverts);
494         }
495
496         attributes.resize(true);
497 }
498
499 void Mesh::resize_curves(int numcurves, int numkeys)
500 {
501         curve_keys.resize(numkeys);
502         curve_radius.resize(numkeys);
503         curve_first_key.resize(numcurves);
504         curve_shader.resize(numcurves);
505
506         curve_attributes.resize();
507 }
508
509 void Mesh::reserve_curves(int numcurves, int numkeys)
510 {
511         curve_keys.reserve(numkeys);
512         curve_radius.reserve(numkeys);
513         curve_first_key.reserve(numcurves);
514         curve_shader.reserve(numcurves);
515
516         curve_attributes.resize(true);
517 }
518
519 void Mesh::resize_subd_faces(int numfaces, int num_ngons_, int numcorners)
520 {
521         subd_faces.resize(numfaces);
522         subd_face_corners.resize(numcorners);
523         num_ngons = num_ngons_;
524
525         subd_attributes.resize();
526 }
527
528 void Mesh::reserve_subd_faces(int numfaces, int num_ngons_, int numcorners)
529 {
530         subd_faces.reserve(numfaces);
531         subd_face_corners.reserve(numcorners);
532         num_ngons = num_ngons_;
533
534         subd_attributes.resize(true);
535 }
536
537 void Mesh::clear(bool preserve_voxel_data)
538 {
539         /* clear all verts and triangles */
540         verts.clear();
541         triangles.clear();
542         shader.clear();
543         smooth.clear();
544
545         triangle_patch.clear();
546         vert_patch_uv.clear();
547
548         curve_keys.clear();
549         curve_radius.clear();
550         curve_first_key.clear();
551         curve_shader.clear();
552
553         subd_faces.clear();
554         subd_face_corners.clear();
555
556         num_subd_verts = 0;
557
558         subd_creases.clear();
559
560         curve_attributes.clear();
561         subd_attributes.clear();
562         attributes.clear(preserve_voxel_data);
563
564         used_shaders.clear();
565
566         if(!preserve_voxel_data) {
567                 geometry_flags = GEOMETRY_NONE;
568         }
569
570         transform_applied = false;
571         transform_negative_scaled = false;
572         transform_normal = transform_identity();
573
574         delete patch_table;
575         patch_table = NULL;
576 }
577
578 int Mesh::split_vertex(int vertex)
579 {
580         /* copy vertex location and vertex attributes */
581         add_vertex_slow(verts[vertex]);
582
583         foreach(Attribute& attr, attributes.attributes) {
584                 if(attr.element == ATTR_ELEMENT_VERTEX) {
585                         array<char> tmp(attr.data_sizeof());
586                         memcpy(tmp.data(), attr.data() + tmp.size()*vertex, tmp.size());
587                         attr.add(tmp.data());
588                 }
589         }
590
591         foreach(Attribute& attr, subd_attributes.attributes) {
592                 if(attr.element == ATTR_ELEMENT_VERTEX) {
593                         array<char> tmp(attr.data_sizeof());
594                         memcpy(tmp.data(), attr.data() + tmp.size()*vertex, tmp.size());
595                         attr.add(tmp.data());
596                 }
597         }
598
599         return verts.size() - 1;
600 }
601
602 void Mesh::add_vertex(float3 P)
603 {
604         verts.push_back_reserved(P);
605
606         if(subd_faces.size()) {
607                 vert_patch_uv.push_back_reserved(make_float2(0.0f, 0.0f));
608         }
609 }
610
611 void Mesh::add_vertex_slow(float3 P)
612 {
613         verts.push_back_slow(P);
614
615         if(subd_faces.size()) {
616                 vert_patch_uv.push_back_slow(make_float2(0.0f, 0.0f));
617         }
618 }
619
620 void Mesh::add_triangle(int v0, int v1, int v2, int shader_, bool smooth_)
621 {
622         triangles.push_back_reserved(v0);
623         triangles.push_back_reserved(v1);
624         triangles.push_back_reserved(v2);
625         shader.push_back_reserved(shader_);
626         smooth.push_back_reserved(smooth_);
627
628         if(subd_faces.size()) {
629                 triangle_patch.push_back_reserved(-1);
630         }
631 }
632
633 void Mesh::add_curve_key(float3 co, float radius)
634 {
635         curve_keys.push_back_reserved(co);
636         curve_radius.push_back_reserved(radius);
637 }
638
639 void Mesh::add_curve(int first_key, int shader)
640 {
641         curve_first_key.push_back_reserved(first_key);
642         curve_shader.push_back_reserved(shader);
643 }
644
645 void Mesh::add_subd_face(int* corners, int num_corners, int shader_, bool smooth_)
646 {
647         int start_corner = subd_face_corners.size();
648
649         for(int i = 0; i < num_corners; i++) {
650                 subd_face_corners.push_back_reserved(corners[i]);
651         }
652
653         int ptex_offset = 0;
654
655         if(subd_faces.size()) {
656                 SubdFace& s = subd_faces[subd_faces.size()-1];
657                 ptex_offset = s.ptex_offset + s.num_ptex_faces();
658         }
659
660         SubdFace face = {start_corner, num_corners, shader_, smooth_, ptex_offset};
661         subd_faces.push_back_reserved(face);
662 }
663
664 void Mesh::compute_bounds()
665 {
666         BoundBox bnds = BoundBox::empty;
667         size_t verts_size = verts.size();
668         size_t curve_keys_size = curve_keys.size();
669
670         if(verts_size + curve_keys_size > 0) {
671                 for(size_t i = 0; i < verts_size; i++)
672                         bnds.grow(verts[i]);
673
674                 for(size_t i = 0; i < curve_keys_size; i++)
675                         bnds.grow(curve_keys[i], curve_radius[i]);
676
677                 Attribute *attr = attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
678                 if(use_motion_blur && attr) {
679                         size_t steps_size = verts.size() * (motion_steps - 1);
680                         float3 *vert_steps = attr->data_float3();
681
682                         for(size_t i = 0; i < steps_size; i++)
683                                 bnds.grow(vert_steps[i]);
684                 }
685
686                 Attribute *curve_attr = curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
687                 if(use_motion_blur && curve_attr) {
688                         size_t steps_size = curve_keys.size() * (motion_steps - 1);
689                         float3 *key_steps = curve_attr->data_float3();
690
691                         for(size_t i = 0; i < steps_size; i++)
692                                 bnds.grow(key_steps[i]);
693                 }
694
695                 if(!bnds.valid()) {
696                         bnds = BoundBox::empty;
697
698                         /* skip nan or inf coordinates */
699                         for(size_t i = 0; i < verts_size; i++)
700                                 bnds.grow_safe(verts[i]);
701
702                         for(size_t i = 0; i < curve_keys_size; i++)
703                                 bnds.grow_safe(curve_keys[i], curve_radius[i]);
704
705                         if(use_motion_blur && attr) {
706                                 size_t steps_size = verts.size() * (motion_steps - 1);
707                                 float3 *vert_steps = attr->data_float3();
708
709                                 for(size_t i = 0; i < steps_size; i++)
710                                         bnds.grow_safe(vert_steps[i]);
711                         }
712
713                         if(use_motion_blur && curve_attr) {
714                                 size_t steps_size = curve_keys.size() * (motion_steps - 1);
715                                 float3 *key_steps = curve_attr->data_float3();
716
717                                 for(size_t i = 0; i < steps_size; i++)
718                                         bnds.grow_safe(key_steps[i]);
719                         }
720                 }
721         }
722
723         if(!bnds.valid()) {
724                 /* empty mesh */
725                 bnds.grow(make_float3(0.0f, 0.0f, 0.0f));
726         }
727
728         bounds = bnds;
729 }
730
731 void Mesh::add_face_normals()
732 {
733         /* don't compute if already there */
734         if(attributes.find(ATTR_STD_FACE_NORMAL))
735                 return;
736
737         /* get attributes */
738         Attribute *attr_fN = attributes.add(ATTR_STD_FACE_NORMAL);
739         float3 *fN = attr_fN->data_float3();
740
741         /* compute face normals */
742         size_t triangles_size = num_triangles();
743
744         if(triangles_size) {
745                 float3 *verts_ptr = verts.data();
746
747                 for(size_t i = 0; i < triangles_size; i++) {
748                         fN[i] = get_triangle(i).compute_normal(verts_ptr);
749                 }
750         }
751
752         /* expected to be in local space */
753         if(transform_applied) {
754                 Transform ntfm = transform_inverse(transform_normal);
755
756                 for(size_t i = 0; i < triangles_size; i++)
757                         fN[i] = normalize(transform_direction(&ntfm, fN[i]));
758         }
759 }
760
761 void Mesh::add_vertex_normals()
762 {
763         bool flip = transform_negative_scaled;
764         size_t verts_size = verts.size();
765         size_t triangles_size = num_triangles();
766
767         /* static vertex normals */
768         if(!attributes.find(ATTR_STD_VERTEX_NORMAL) && triangles_size) {
769                 /* get attributes */
770                 Attribute *attr_fN = attributes.find(ATTR_STD_FACE_NORMAL);
771                 Attribute *attr_vN = attributes.add(ATTR_STD_VERTEX_NORMAL);
772
773                 float3 *fN = attr_fN->data_float3();
774                 float3 *vN = attr_vN->data_float3();
775
776                 /* compute vertex normals */
777                 memset(vN, 0, verts.size()*sizeof(float3));
778
779                 for(size_t i = 0; i < triangles_size; i++) {
780                         for(size_t j = 0; j < 3; j++) {
781                                 vN[get_triangle(i).v[j]] += fN[i];
782                         }
783                 }
784
785                 for(size_t i = 0; i < verts_size; i++) {
786                         vN[i] = normalize(vN[i]);
787                         if(flip) {
788                                 vN[i] = -vN[i];
789                         }
790                 }
791         }
792
793         /* motion vertex normals */
794         Attribute *attr_mP = attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
795         Attribute *attr_mN = attributes.find(ATTR_STD_MOTION_VERTEX_NORMAL);
796
797         if(has_motion_blur() && attr_mP && !attr_mN && triangles_size) {
798                 /* create attribute */
799                 attr_mN = attributes.add(ATTR_STD_MOTION_VERTEX_NORMAL);
800
801                 for(int step = 0; step < motion_steps - 1; step++) {
802                         float3 *mP = attr_mP->data_float3() + step*verts.size();
803                         float3 *mN = attr_mN->data_float3() + step*verts.size();
804
805                         /* compute */
806                         memset(mN, 0, verts.size()*sizeof(float3));
807
808                         for(size_t i = 0; i < triangles_size; i++) {
809                                 for(size_t j = 0; j < 3; j++) {
810                                         float3 fN = get_triangle(i).compute_normal(mP);
811                                         mN[get_triangle(i).v[j]] += fN;
812                                 }
813                         }
814
815                         for(size_t i = 0; i < verts_size; i++) {
816                                 mN[i] = normalize(mN[i]);
817                                 if(flip) {
818                                         mN[i] = -mN[i];
819                                 }
820                         }
821                 }
822         }
823
824         /* subd vertex normals */
825         if(!subd_attributes.find(ATTR_STD_VERTEX_NORMAL) && subd_faces.size()) {
826                 /* get attributes */
827                 Attribute *attr_vN = subd_attributes.add(ATTR_STD_VERTEX_NORMAL);
828                 float3 *vN = attr_vN->data_float3();
829
830                 /* compute vertex normals */
831                 memset(vN, 0, verts.size()*sizeof(float3));
832
833                 for(size_t i = 0; i < subd_faces.size(); i++) {
834                         SubdFace& face = subd_faces[i];
835                         float3 fN = face.normal(this);
836
837                         for(size_t j = 0; j < face.num_corners; j++) {
838                                 size_t corner = subd_face_corners[face.start_corner+j];
839                                 vN[corner] += fN;
840                         }
841                 }
842
843                 for(size_t i = 0; i < verts_size; i++) {
844                         vN[i] = normalize(vN[i]);
845                         if(flip) {
846                                 vN[i] = -vN[i];
847                         }
848                 }
849         }
850 }
851
852 void Mesh::add_undisplaced()
853 {
854         AttributeSet& attrs = (subdivision_type == SUBDIVISION_NONE) ? attributes : subd_attributes;
855
856         /* don't compute if already there */
857         if(attrs.find(ATTR_STD_POSITION_UNDISPLACED)) {
858                 return;
859         }
860
861         /* get attribute */
862         Attribute *attr = attrs.add(ATTR_STD_POSITION_UNDISPLACED);
863         attr->flags |= ATTR_SUBDIVIDED;
864
865         float3 *data = attr->data_float3();
866
867         /* copy verts */
868         size_t size = attr->buffer_size(this, (subdivision_type == SUBDIVISION_NONE) ? ATTR_PRIM_TRIANGLE : ATTR_PRIM_SUBD);
869
870         /* Center points for ngons aren't stored in Mesh::verts but are included in size since they will be
871          * calculated later, we subtract them from size here so we don't have an overflow while copying.
872          */
873         size -= num_ngons * attr->data_sizeof();
874
875         if(size) {
876                 memcpy(data, verts.data(), size);
877         }
878 }
879
880 void Mesh::pack_shaders(Scene *scene, uint *tri_shader)
881 {
882         uint shader_id = 0;
883         uint last_shader = -1;
884         bool last_smooth = false;
885
886         size_t triangles_size = num_triangles();
887         int *shader_ptr = shader.data();
888
889         for(size_t i = 0; i < triangles_size; i++) {
890                 if(shader_ptr[i] != last_shader || last_smooth != smooth[i]) {
891                         last_shader = shader_ptr[i];
892                         last_smooth = smooth[i];
893                         Shader *shader = (last_shader < used_shaders.size()) ?
894                                 used_shaders[last_shader] : scene->default_surface;
895                         shader_id = scene->shader_manager->get_shader_id(shader, last_smooth);
896                 }
897
898                 tri_shader[i] = shader_id;
899         }
900 }
901
902 void Mesh::pack_normals(float4 *vnormal)
903 {
904         Attribute *attr_vN = attributes.find(ATTR_STD_VERTEX_NORMAL);
905         if(attr_vN == NULL) {
906                 /* Happens on objects with just hair. */
907                 return;
908         }
909
910         bool do_transform = transform_applied;
911         Transform ntfm = transform_normal;
912
913         float3 *vN = attr_vN->data_float3();
914         size_t verts_size = verts.size();
915
916         for(size_t i = 0; i < verts_size; i++) {
917                 float3 vNi = vN[i];
918
919                 if(do_transform)
920                         vNi = safe_normalize(transform_direction(&ntfm, vNi));
921
922                 vnormal[i] = make_float4(vNi.x, vNi.y, vNi.z, 0.0f);
923         }
924 }
925
926 void Mesh::pack_verts(const vector<uint>& tri_prim_index,
927                       uint4 *tri_vindex,
928                       uint *tri_patch,
929                       float2 *tri_patch_uv,
930                       size_t vert_offset,
931                       size_t tri_offset)
932 {
933         size_t verts_size = verts.size();
934
935         if(verts_size && subd_faces.size()) {
936                 float2 *vert_patch_uv_ptr = vert_patch_uv.data();
937
938                 for(size_t i = 0; i < verts_size; i++) {
939                         tri_patch_uv[i] = vert_patch_uv_ptr[i];
940                 }
941         }
942
943         size_t triangles_size = num_triangles();
944
945         for(size_t i = 0; i < triangles_size; i++) {
946                 Triangle t = get_triangle(i);
947                 tri_vindex[i] = make_uint4(t.v[0] + vert_offset,
948                                            t.v[1] + vert_offset,
949                                            t.v[2] + vert_offset,
950                                            tri_prim_index[i + tri_offset]);
951
952                 tri_patch[i] = (!subd_faces.size()) ? -1 : (triangle_patch[i]*8 + patch_offset);
953         }
954 }
955
956 void Mesh::pack_curves(Scene *scene, float4 *curve_key_co, float4 *curve_data, size_t curvekey_offset)
957 {
958         size_t curve_keys_size = curve_keys.size();
959
960         /* pack curve keys */
961         if(curve_keys_size) {
962                 float3 *keys_ptr = curve_keys.data();
963                 float *radius_ptr = curve_radius.data();
964
965                 for(size_t i = 0; i < curve_keys_size; i++)
966                         curve_key_co[i] = make_float4(keys_ptr[i].x, keys_ptr[i].y, keys_ptr[i].z, radius_ptr[i]);
967         }
968
969         /* pack curve segments */
970         size_t curve_num = num_curves();
971
972         for(size_t i = 0; i < curve_num; i++) {
973                 Curve curve = get_curve(i);
974                 int shader_id = curve_shader[i];
975                 Shader *shader = (shader_id < used_shaders.size()) ?
976                         used_shaders[shader_id] : scene->default_surface;
977                 shader_id = scene->shader_manager->get_shader_id(shader, false);
978
979                 curve_data[i] = make_float4(
980                         __int_as_float(curve.first_key + curvekey_offset),
981                         __int_as_float(curve.num_keys),
982                         __int_as_float(shader_id),
983                         0.0f);
984         }
985 }
986
987 void Mesh::pack_patches(uint *patch_data, uint vert_offset, uint face_offset, uint corner_offset)
988 {
989         size_t num_faces = subd_faces.size();
990         int ngons = 0;
991
992         for(size_t f = 0; f < num_faces; f++) {
993                 SubdFace face = subd_faces[f];
994
995                 if(face.is_quad()) {
996                         int c[4];
997                         memcpy(c, &subd_face_corners[face.start_corner], sizeof(int)*4);
998
999                         *(patch_data++) = c[0] + vert_offset;
1000                         *(patch_data++) = c[1] + vert_offset;
1001                         *(patch_data++) = c[2] + vert_offset;
1002                         *(patch_data++) = c[3] + vert_offset;
1003
1004                         *(patch_data++) = f+face_offset;
1005                         *(patch_data++) = face.num_corners;
1006                         *(patch_data++) = face.start_corner + corner_offset;
1007                         *(patch_data++) = 0;
1008                 }
1009                 else {
1010                         for(int i = 0; i < face.num_corners; i++) {
1011                                 int c[4];
1012                                 c[0] = subd_face_corners[face.start_corner + mod(i + 0, face.num_corners)];
1013                                 c[1] = subd_face_corners[face.start_corner + mod(i + 1, face.num_corners)];
1014                                 c[2] = verts.size() - num_subd_verts + ngons;
1015                                 c[3] = subd_face_corners[face.start_corner + mod(i - 1, face.num_corners)];
1016
1017                                 *(patch_data++) = c[0] + vert_offset;
1018                                 *(patch_data++) = c[1] + vert_offset;
1019                                 *(patch_data++) = c[2] + vert_offset;
1020                                 *(patch_data++) = c[3] + vert_offset;
1021
1022                                 *(patch_data++) = f+face_offset;
1023                                 *(patch_data++) = face.num_corners | (i << 16);
1024                                 *(patch_data++) = face.start_corner + corner_offset;
1025                                 *(patch_data++) = subd_face_corners.size() + ngons + corner_offset;
1026                         }
1027
1028                         ngons++;
1029                 }
1030         }
1031 }
1032
1033 void Mesh::compute_bvh(Device *device,
1034                        DeviceScene *dscene,
1035                        SceneParams *params,
1036                        Progress *progress,
1037                        int n,
1038                        int total)
1039 {
1040         if(progress->get_cancel())
1041                 return;
1042
1043         compute_bounds();
1044
1045         if(need_build_bvh()) {
1046                 string msg = "Updating Mesh BVH ";
1047                 if(name == "")
1048                         msg += string_printf("%u/%u", (uint)(n+1), (uint)total);
1049                 else
1050                         msg += string_printf("%s %u/%u", name.c_str(), (uint)(n+1), (uint)total);
1051
1052                 Object object;
1053                 object.mesh = this;
1054
1055                 vector<Object*> objects;
1056                 objects.push_back(&object);
1057
1058                 if(bvh && !need_update_rebuild) {
1059                         progress->set_status(msg, "Refitting BVH");
1060                         bvh->objects = objects;
1061                         bvh->refit(*progress);
1062                 }
1063                 else {
1064                         progress->set_status(msg, "Building BVH");
1065
1066                         BVHParams bparams;
1067                         bparams.use_spatial_split = params->use_bvh_spatial_split;
1068                         bparams.bvh_layout = BVHParams::best_bvh_layout(
1069                                 params->bvh_layout,
1070                                 device->info.bvh_layout_mask);
1071                         bparams.use_unaligned_nodes = dscene->data.bvh.have_curves &&
1072                                                       params->use_bvh_unaligned_nodes;
1073                         bparams.num_motion_triangle_steps = params->num_bvh_time_steps;
1074                         bparams.num_motion_curve_steps = params->num_bvh_time_steps;
1075
1076                         delete bvh;
1077                         bvh = BVH::create(bparams, objects);
1078                         MEM_GUARDED_CALL(progress, bvh->build, *progress);
1079                 }
1080         }
1081
1082         need_update = false;
1083         need_update_rebuild = false;
1084 }
1085
1086 void Mesh::tag_update(Scene *scene, bool rebuild)
1087 {
1088         need_update = true;
1089
1090         if(rebuild) {
1091                 need_update_rebuild = true;
1092                 scene->light_manager->need_update = true;
1093         }
1094         else {
1095                 foreach(Shader *shader, used_shaders)
1096                         if(shader->has_surface_emission)
1097                                 scene->light_manager->need_update = true;
1098         }
1099
1100         scene->mesh_manager->need_update = true;
1101         scene->object_manager->need_update = true;
1102 }
1103
1104 bool Mesh::has_motion_blur() const
1105 {
1106         return (use_motion_blur &&
1107                 (attributes.find(ATTR_STD_MOTION_VERTEX_POSITION) ||
1108                  curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION)));
1109 }
1110
1111 bool Mesh::has_true_displacement() const
1112 {
1113         foreach(Shader *shader, used_shaders) {
1114                 if(shader->has_displacement && shader->displacement_method != DISPLACE_BUMP) {
1115                         return true;
1116                 }
1117         }
1118
1119         return false;
1120 }
1121
1122 float Mesh::motion_time(int step) const
1123 {
1124         return (motion_steps > 1) ? 2.0f * step / (motion_steps - 1) - 1.0f : 0.0f;
1125 }
1126
1127 int Mesh::motion_step(float time) const
1128 {
1129         if(motion_steps > 1) {
1130                 int attr_step = 0;
1131
1132                 for(int step = 0; step < motion_steps; step++) {
1133                         float step_time = motion_time(step);
1134                         if(step_time == time) {
1135                                 return attr_step;
1136                         }
1137
1138                         /* Center step is stored in a separate attribute. */
1139                         if(step != motion_steps / 2) {
1140                                 attr_step++;
1141                         }
1142                 }
1143         }
1144
1145         return -1;
1146 }
1147
1148 bool Mesh::need_build_bvh() const
1149 {
1150         return !transform_applied || has_surface_bssrdf;
1151 }
1152
1153 bool Mesh::is_instanced() const
1154 {
1155         /* Currently we treat subsurface objects as instanced.
1156          *
1157          * While it might be not very optimal for ray traversal, it avoids having
1158          * duplicated BVH in the memory, saving quite some space.
1159          */
1160         return !transform_applied || has_surface_bssrdf;
1161 }
1162
1163 /* Mesh Manager */
1164
1165 MeshManager::MeshManager()
1166 {
1167         need_update = true;
1168         need_flags_update = true;
1169 }
1170
1171 MeshManager::~MeshManager()
1172 {
1173 }
1174
1175 void MeshManager::update_osl_attributes(Device *device, Scene *scene, vector<AttributeRequestSet>& mesh_attributes)
1176 {
1177 #ifdef WITH_OSL
1178         /* for OSL, a hash map is used to lookup the attribute by name. */
1179         OSLGlobals *og = (OSLGlobals*)device->osl_memory();
1180
1181         og->object_name_map.clear();
1182         og->attribute_map.clear();
1183         og->object_names.clear();
1184
1185         og->attribute_map.resize(scene->objects.size()*ATTR_PRIM_TYPES);
1186
1187         for(size_t i = 0; i < scene->objects.size(); i++) {
1188                 /* set object name to object index map */
1189                 Object *object = scene->objects[i];
1190                 og->object_name_map[object->name] = i;
1191                 og->object_names.push_back(object->name);
1192
1193                 /* set object attributes */
1194                 foreach(ParamValue& attr, object->attributes) {
1195                         OSLGlobals::Attribute osl_attr;
1196
1197                         osl_attr.type = attr.type();
1198                         osl_attr.desc.element = ATTR_ELEMENT_OBJECT;
1199                         osl_attr.value = attr;
1200                         osl_attr.desc.offset = 0;
1201                         osl_attr.desc.flags = 0;
1202
1203                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_TRIANGLE][attr.name()] = osl_attr;
1204                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][attr.name()] = osl_attr;
1205                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_SUBD][attr.name()] = osl_attr;
1206                 }
1207
1208                 /* find mesh attributes */
1209                 size_t j;
1210
1211                 for(j = 0; j < scene->meshes.size(); j++)
1212                         if(scene->meshes[j] == object->mesh)
1213                                 break;
1214
1215                 AttributeRequestSet& attributes = mesh_attributes[j];
1216
1217                 /* set object attributes */
1218                 foreach(AttributeRequest& req, attributes.requests) {
1219                         OSLGlobals::Attribute osl_attr;
1220
1221                         if(req.triangle_desc.element != ATTR_ELEMENT_NONE) {
1222                                 osl_attr.desc = req.triangle_desc;
1223
1224                                 if(req.triangle_type == TypeDesc::TypeFloat)
1225                                         osl_attr.type = TypeDesc::TypeFloat;
1226                                 else if(req.triangle_type == TypeDesc::TypeMatrix)
1227                                         osl_attr.type = TypeDesc::TypeMatrix;
1228                                 else
1229                                         osl_attr.type = TypeDesc::TypeColor;
1230
1231                                 if(req.std != ATTR_STD_NONE) {
1232                                         /* if standard attribute, add lookup by geom: name convention */
1233                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
1234                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_TRIANGLE][stdname] = osl_attr;
1235                                 }
1236                                 else if(req.name != ustring()) {
1237                                         /* add lookup by mesh attribute name */
1238                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_TRIANGLE][req.name] = osl_attr;
1239                                 }
1240                         }
1241
1242                         if(req.curve_desc.element != ATTR_ELEMENT_NONE) {
1243                                 osl_attr.desc = req.curve_desc;
1244
1245                                 if(req.curve_type == TypeDesc::TypeFloat)
1246                                         osl_attr.type = TypeDesc::TypeFloat;
1247                                 else if(req.curve_type == TypeDesc::TypeMatrix)
1248                                         osl_attr.type = TypeDesc::TypeMatrix;
1249                                 else
1250                                         osl_attr.type = TypeDesc::TypeColor;
1251
1252                                 if(req.std != ATTR_STD_NONE) {
1253                                         /* if standard attribute, add lookup by geom: name convention */
1254                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
1255                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][stdname] = osl_attr;
1256                                 }
1257                                 else if(req.name != ustring()) {
1258                                         /* add lookup by mesh attribute name */
1259                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][req.name] = osl_attr;
1260                                 }
1261                         }
1262
1263                         if(req.subd_desc.element != ATTR_ELEMENT_NONE) {
1264                                 osl_attr.desc = req.subd_desc;
1265
1266                                 if(req.subd_type == TypeDesc::TypeFloat)
1267                                         osl_attr.type = TypeDesc::TypeFloat;
1268                                 else if(req.subd_type == TypeDesc::TypeMatrix)
1269                                         osl_attr.type = TypeDesc::TypeMatrix;
1270                                 else
1271                                         osl_attr.type = TypeDesc::TypeColor;
1272
1273                                 if(req.std != ATTR_STD_NONE) {
1274                                         /* if standard attribute, add lookup by geom: name convention */
1275                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
1276                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_SUBD][stdname] = osl_attr;
1277                                 }
1278                                 else if(req.name != ustring()) {
1279                                         /* add lookup by mesh attribute name */
1280                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_SUBD][req.name] = osl_attr;
1281                                 }
1282                         }
1283                 }
1284         }
1285 #else
1286         (void)device;
1287         (void)scene;
1288         (void)mesh_attributes;
1289 #endif
1290 }
1291
1292 void MeshManager::update_svm_attributes(Device *, DeviceScene *dscene, Scene *scene, vector<AttributeRequestSet>& mesh_attributes)
1293 {
1294         /* for SVM, the attributes_map table is used to lookup the offset of an
1295          * attribute, based on a unique shader attribute id. */
1296
1297         /* compute array stride */
1298         int attr_map_size = 0;
1299
1300         for(size_t i = 0; i < scene->meshes.size(); i++) {
1301                 Mesh *mesh = scene->meshes[i];
1302                 mesh->attr_map_offset = attr_map_size;
1303                 attr_map_size += (mesh_attributes[i].size() + 1)*ATTR_PRIM_TYPES;
1304         }
1305
1306         if(attr_map_size == 0)
1307                 return;
1308
1309         /* create attribute map */
1310         uint4 *attr_map = dscene->attributes_map.alloc(attr_map_size*scene->meshes.size());
1311         memset(attr_map, 0, dscene->attributes_map.size()*sizeof(uint));
1312
1313         for(size_t i = 0; i < scene->meshes.size(); i++) {
1314                 Mesh *mesh = scene->meshes[i];
1315                 AttributeRequestSet& attributes = mesh_attributes[i];
1316
1317                 /* set object attributes */
1318                 int index = mesh->attr_map_offset;
1319
1320                 foreach(AttributeRequest& req, attributes.requests) {
1321                         uint id;
1322
1323                         if(req.std == ATTR_STD_NONE)
1324                                 id = scene->shader_manager->get_attribute_id(req.name);
1325                         else
1326                                 id = scene->shader_manager->get_attribute_id(req.std);
1327
1328                         if(mesh->num_triangles()) {
1329                                 attr_map[index].x = id;
1330                                 attr_map[index].y = req.triangle_desc.element;
1331                                 attr_map[index].z = as_uint(req.triangle_desc.offset);
1332
1333                                 if(req.triangle_type == TypeDesc::TypeFloat)
1334                                         attr_map[index].w = NODE_ATTR_FLOAT;
1335                                 else if(req.triangle_type == TypeDesc::TypeMatrix)
1336                                         attr_map[index].w = NODE_ATTR_MATRIX;
1337                                 else
1338                                         attr_map[index].w = NODE_ATTR_FLOAT3;
1339
1340                                 attr_map[index].w |= req.triangle_desc.flags << 8;
1341                         }
1342
1343                         index++;
1344
1345                         if(mesh->num_curves()) {
1346                                 attr_map[index].x = id;
1347                                 attr_map[index].y = req.curve_desc.element;
1348                                 attr_map[index].z = as_uint(req.curve_desc.offset);
1349
1350                                 if(req.curve_type == TypeDesc::TypeFloat)
1351                                         attr_map[index].w = NODE_ATTR_FLOAT;
1352                                 else if(req.curve_type == TypeDesc::TypeMatrix)
1353                                         attr_map[index].w = NODE_ATTR_MATRIX;
1354                                 else
1355                                         attr_map[index].w = NODE_ATTR_FLOAT3;
1356
1357                                 attr_map[index].w |= req.curve_desc.flags << 8;
1358                         }
1359
1360                         index++;
1361
1362                         if(mesh->subd_faces.size()) {
1363                                 attr_map[index].x = id;
1364                                 attr_map[index].y = req.subd_desc.element;
1365                                 attr_map[index].z = as_uint(req.subd_desc.offset);
1366
1367                                 if(req.subd_type == TypeDesc::TypeFloat)
1368                                         attr_map[index].w = NODE_ATTR_FLOAT;
1369                                 else if(req.subd_type == TypeDesc::TypeMatrix)
1370                                         attr_map[index].w = NODE_ATTR_MATRIX;
1371                                 else
1372                                         attr_map[index].w = NODE_ATTR_FLOAT3;
1373
1374                                 attr_map[index].w |= req.subd_desc.flags << 8;
1375                         }
1376
1377                         index++;
1378                 }
1379
1380                 /* terminator */
1381                 for(int j = 0; j < ATTR_PRIM_TYPES; j++) {
1382                         attr_map[index].x = ATTR_STD_NONE;
1383                         attr_map[index].y = 0;
1384                         attr_map[index].z = 0;
1385                         attr_map[index].w = 0;
1386
1387                         index++;
1388                 }
1389         }
1390
1391         /* copy to device */
1392         dscene->attributes_map.copy_to_device();
1393 }
1394
1395 static void update_attribute_element_size(Mesh *mesh,
1396                                           Attribute *mattr,
1397                                           AttributePrimitive prim,
1398                                           size_t *attr_float_size,
1399                                           size_t *attr_float3_size,
1400                                           size_t *attr_uchar4_size)
1401 {
1402         if(mattr) {
1403                 size_t size = mattr->element_size(mesh, prim);
1404
1405                 if(mattr->element == ATTR_ELEMENT_VOXEL) {
1406                         /* pass */
1407                 }
1408                 else if(mattr->element == ATTR_ELEMENT_CORNER_BYTE) {
1409                         *attr_uchar4_size += size;
1410                 }
1411                 else if(mattr->type == TypeDesc::TypeFloat) {
1412                         *attr_float_size += size;
1413                 }
1414                 else if(mattr->type == TypeDesc::TypeMatrix) {
1415                         *attr_float3_size += size * 4;
1416                 }
1417                 else {
1418                         *attr_float3_size += size;
1419                 }
1420         }
1421 }
1422
1423 static void update_attribute_element_offset(Mesh *mesh,
1424                                             device_vector<float>& attr_float,
1425                                             size_t& attr_float_offset,
1426                                             device_vector<float4>& attr_float3,
1427                                             size_t& attr_float3_offset,
1428                                             device_vector<uchar4>& attr_uchar4,
1429                                             size_t& attr_uchar4_offset,
1430                                             Attribute *mattr,
1431                                             AttributePrimitive prim,
1432                                             TypeDesc& type,
1433                                             AttributeDescriptor& desc)
1434 {
1435         if(mattr) {
1436                 /* store element and type */
1437                 desc.element = mattr->element;
1438                 desc.flags = mattr->flags;
1439                 type = mattr->type;
1440
1441                 /* store attribute data in arrays */
1442                 size_t size = mattr->element_size(mesh, prim);
1443
1444                 AttributeElement& element = desc.element;
1445                 int& offset = desc.offset;
1446
1447                 if(mattr->element == ATTR_ELEMENT_VOXEL) {
1448                         /* store slot in offset value */
1449                         VoxelAttribute *voxel_data = mattr->data_voxel();
1450                         offset = voxel_data->slot;
1451                 }
1452                 else if(mattr->element == ATTR_ELEMENT_CORNER_BYTE) {
1453                         uchar4 *data = mattr->data_uchar4();
1454                         offset = attr_uchar4_offset;
1455
1456                         assert(attr_uchar4.size() >= offset + size);
1457                         for(size_t k = 0; k < size; k++) {
1458                                 attr_uchar4[offset+k] = data[k];
1459                         }
1460                         attr_uchar4_offset += size;
1461                 }
1462                 else if(mattr->type == TypeDesc::TypeFloat) {
1463                         float *data = mattr->data_float();
1464                         offset = attr_float_offset;
1465
1466                         assert(attr_float.size() >= offset + size);
1467                         for(size_t k = 0; k < size; k++) {
1468                                 attr_float[offset+k] = data[k];
1469                         }
1470                         attr_float_offset += size;
1471                 }
1472                 else if(mattr->type == TypeDesc::TypeMatrix) {
1473                         Transform *tfm = mattr->data_transform();
1474                         offset = attr_float3_offset;
1475
1476                         assert(attr_float3.size() >= offset + size * 3);
1477                         for(size_t k = 0; k < size*3; k++) {
1478                                 attr_float3[offset+k] = (&tfm->x)[k];
1479                         }
1480                         attr_float3_offset += size * 3;
1481                 }
1482                 else {
1483                         float4 *data = mattr->data_float4();
1484                         offset = attr_float3_offset;
1485
1486                         assert(attr_float3.size() >= offset + size);
1487                         for(size_t k = 0; k < size; k++) {
1488                                 attr_float3[offset+k] = data[k];
1489                         }
1490                         attr_float3_offset += size;
1491                 }
1492
1493                 /* mesh vertex/curve index is global, not per object, so we sneak
1494                  * a correction for that in here */
1495                 if(mesh->subdivision_type == Mesh::SUBDIVISION_CATMULL_CLARK && desc.flags & ATTR_SUBDIVIDED) {
1496                         /* indices for subdivided attributes are retrieved
1497                          * from patch table so no need for correction here*/
1498                 }
1499                 else if(element == ATTR_ELEMENT_VERTEX)
1500                         offset -= mesh->vert_offset;
1501                 else if(element == ATTR_ELEMENT_VERTEX_MOTION)
1502                         offset -= mesh->vert_offset;
1503                 else if(element == ATTR_ELEMENT_FACE) {
1504                         if(prim == ATTR_PRIM_TRIANGLE)
1505                                 offset -= mesh->tri_offset;
1506                         else
1507                                 offset -= mesh->face_offset;
1508                 }
1509                 else if(element == ATTR_ELEMENT_CORNER || element == ATTR_ELEMENT_CORNER_BYTE) {
1510                         if(prim == ATTR_PRIM_TRIANGLE)
1511                                 offset -= 3*mesh->tri_offset;
1512                         else
1513                                 offset -= mesh->corner_offset;
1514                 }
1515                 else if(element == ATTR_ELEMENT_CURVE)
1516                         offset -= mesh->curve_offset;
1517                 else if(element == ATTR_ELEMENT_CURVE_KEY)
1518                         offset -= mesh->curvekey_offset;
1519                 else if(element == ATTR_ELEMENT_CURVE_KEY_MOTION)
1520                         offset -= mesh->curvekey_offset;
1521         }
1522         else {
1523                 /* attribute not found */
1524                 desc.element = ATTR_ELEMENT_NONE;
1525                 desc.offset = 0;
1526         }
1527 }
1528
1529 void MeshManager::device_update_attributes(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
1530 {
1531         progress.set_status("Updating Mesh", "Computing attributes");
1532
1533         /* gather per mesh requested attributes. as meshes may have multiple
1534          * shaders assigned, this merges the requested attributes that have
1535          * been set per shader by the shader manager */
1536         vector<AttributeRequestSet> mesh_attributes(scene->meshes.size());
1537
1538         for(size_t i = 0; i < scene->meshes.size(); i++) {
1539                 Mesh *mesh = scene->meshes[i];
1540
1541                 scene->need_global_attributes(mesh_attributes[i]);
1542
1543                 foreach(Shader *shader, mesh->used_shaders) {
1544                         mesh_attributes[i].add(shader->attributes);
1545                 }
1546         }
1547
1548         /* mesh attribute are stored in a single array per data type. here we fill
1549          * those arrays, and set the offset and element type to create attribute
1550          * maps next */
1551
1552         /* Pre-allocate attributes to avoid arrays re-allocation which would
1553          * take 2x of overall attribute memory usage.
1554          */
1555         size_t attr_float_size = 0;
1556         size_t attr_float3_size = 0;
1557         size_t attr_uchar4_size = 0;
1558         for(size_t i = 0; i < scene->meshes.size(); i++) {
1559                 Mesh *mesh = scene->meshes[i];
1560                 AttributeRequestSet& attributes = mesh_attributes[i];
1561                 foreach(AttributeRequest& req, attributes.requests) {
1562                         Attribute *triangle_mattr = mesh->attributes.find(req);
1563                         Attribute *curve_mattr = mesh->curve_attributes.find(req);
1564                         Attribute *subd_mattr = mesh->subd_attributes.find(req);
1565
1566                         update_attribute_element_size(mesh,
1567                                                       triangle_mattr,
1568                                                       ATTR_PRIM_TRIANGLE,
1569                                                       &attr_float_size,
1570                                                       &attr_float3_size,
1571                                                       &attr_uchar4_size);
1572                         update_attribute_element_size(mesh,
1573                                                       curve_mattr,
1574                                                       ATTR_PRIM_CURVE,
1575                                                       &attr_float_size,
1576                                                       &attr_float3_size,
1577                                                       &attr_uchar4_size);
1578                         update_attribute_element_size(mesh,
1579                                                       subd_mattr,
1580                                                       ATTR_PRIM_SUBD,
1581                                                       &attr_float_size,
1582                                                       &attr_float3_size,
1583                                                       &attr_uchar4_size);
1584                 }
1585         }
1586
1587         dscene->attributes_float.alloc(attr_float_size);
1588         dscene->attributes_float3.alloc(attr_float3_size);
1589         dscene->attributes_uchar4.alloc(attr_uchar4_size);
1590
1591         size_t attr_float_offset = 0;
1592         size_t attr_float3_offset = 0;
1593         size_t attr_uchar4_offset = 0;
1594
1595         /* Fill in attributes. */
1596         for(size_t i = 0; i < scene->meshes.size(); i++) {
1597                 Mesh *mesh = scene->meshes[i];
1598                 AttributeRequestSet& attributes = mesh_attributes[i];
1599
1600                 /* todo: we now store std and name attributes from requests even if
1601                  * they actually refer to the same mesh attributes, optimize */
1602                 foreach(AttributeRequest& req, attributes.requests) {
1603                         Attribute *triangle_mattr = mesh->attributes.find(req);
1604                         Attribute *curve_mattr = mesh->curve_attributes.find(req);
1605                         Attribute *subd_mattr = mesh->subd_attributes.find(req);
1606
1607                         update_attribute_element_offset(mesh,
1608                                                         dscene->attributes_float, attr_float_offset,
1609                                                         dscene->attributes_float3, attr_float3_offset,
1610                                                         dscene->attributes_uchar4, attr_uchar4_offset,
1611                                                         triangle_mattr,
1612                                                         ATTR_PRIM_TRIANGLE,
1613                                                         req.triangle_type,
1614                                                         req.triangle_desc);
1615
1616                         update_attribute_element_offset(mesh,
1617                                                         dscene->attributes_float, attr_float_offset,
1618                                                         dscene->attributes_float3, attr_float3_offset,
1619                                                         dscene->attributes_uchar4, attr_uchar4_offset,
1620                                                         curve_mattr,
1621                                                         ATTR_PRIM_CURVE,
1622                                                         req.curve_type,
1623                                                         req.curve_desc);
1624
1625                         update_attribute_element_offset(mesh,
1626                                                         dscene->attributes_float, attr_float_offset,
1627                                                         dscene->attributes_float3, attr_float3_offset,
1628                                                         dscene->attributes_uchar4, attr_uchar4_offset,
1629                                                         subd_mattr,
1630                                                         ATTR_PRIM_SUBD,
1631                                                         req.subd_type,
1632                                                         req.subd_desc);
1633
1634                         if(progress.get_cancel()) return;
1635                 }
1636         }
1637
1638         /* create attribute lookup maps */
1639         if(scene->shader_manager->use_osl())
1640                 update_osl_attributes(device, scene, mesh_attributes);
1641
1642         update_svm_attributes(device, dscene, scene, mesh_attributes);
1643
1644         if(progress.get_cancel()) return;
1645
1646         /* copy to device */
1647         progress.set_status("Updating Mesh", "Copying Attributes to device");
1648
1649         if(dscene->attributes_float.size()) {
1650                 dscene->attributes_float.copy_to_device();
1651         }
1652         if(dscene->attributes_float3.size()) {
1653                 dscene->attributes_float3.copy_to_device();
1654         }
1655         if(dscene->attributes_uchar4.size()) {
1656                 dscene->attributes_uchar4.copy_to_device();
1657         }
1658
1659         if(progress.get_cancel()) return;
1660
1661         /* After mesh attributes and patch tables have been copied to device memory,
1662          * we need to update offsets in the objects. */
1663         scene->object_manager->device_update_mesh_offsets(device, dscene, scene);
1664 }
1665
1666 void MeshManager::mesh_calc_offset(Scene *scene)
1667 {
1668         size_t vert_size = 0;
1669         size_t tri_size = 0;
1670
1671         size_t curve_key_size = 0;
1672         size_t curve_size = 0;
1673
1674         size_t patch_size = 0;
1675         size_t face_size = 0;
1676         size_t corner_size = 0;
1677
1678         foreach(Mesh *mesh, scene->meshes) {
1679                 mesh->vert_offset = vert_size;
1680                 mesh->tri_offset = tri_size;
1681
1682                 mesh->curvekey_offset = curve_key_size;
1683                 mesh->curve_offset = curve_size;
1684
1685                 mesh->patch_offset = patch_size;
1686                 mesh->face_offset = face_size;
1687                 mesh->corner_offset = corner_size;
1688
1689                 vert_size += mesh->verts.size();
1690                 tri_size += mesh->num_triangles();
1691
1692                 curve_key_size += mesh->curve_keys.size();
1693                 curve_size += mesh->num_curves();
1694
1695                 if(mesh->subd_faces.size()) {
1696                         Mesh::SubdFace& last = mesh->subd_faces[mesh->subd_faces.size()-1];
1697                         patch_size += (last.ptex_offset + last.num_ptex_faces()) * 8;
1698
1699                         /* patch tables are stored in same array so include them in patch_size */
1700                         if(mesh->patch_table) {
1701                                 mesh->patch_table_offset = patch_size;
1702                                 patch_size += mesh->patch_table->total_size();
1703                         }
1704                 }
1705                 face_size += mesh->subd_faces.size();
1706                 corner_size += mesh->subd_face_corners.size();
1707         }
1708 }
1709
1710 void MeshManager::device_update_mesh(Device *,
1711                                      DeviceScene *dscene,
1712                                      Scene *scene,
1713                                      bool for_displacement,
1714                                      Progress& progress)
1715 {
1716         /* Count. */
1717         size_t vert_size = 0;
1718         size_t tri_size = 0;
1719
1720         size_t curve_key_size = 0;
1721         size_t curve_size = 0;
1722
1723         size_t patch_size = 0;
1724
1725         foreach(Mesh *mesh, scene->meshes) {
1726                 vert_size += mesh->verts.size();
1727                 tri_size += mesh->num_triangles();
1728
1729                 curve_key_size += mesh->curve_keys.size();
1730                 curve_size += mesh->num_curves();
1731
1732                 if(mesh->subd_faces.size()) {
1733                         Mesh::SubdFace& last = mesh->subd_faces[mesh->subd_faces.size()-1];
1734                         patch_size += (last.ptex_offset + last.num_ptex_faces()) * 8;
1735
1736                         /* patch tables are stored in same array so include them in patch_size */
1737                         if(mesh->patch_table) {
1738                                 mesh->patch_table_offset = patch_size;
1739                                 patch_size += mesh->patch_table->total_size();
1740                         }
1741                 }
1742         }
1743
1744         /* Create mapping from triangle to primitive triangle array. */
1745         vector<uint> tri_prim_index(tri_size);
1746         if(for_displacement) {
1747                 /* For displacement kernels we do some trickery to make them believe
1748                  * we've got all required data ready. However, that data is different
1749                  * from final render kernels since we don't have BVH yet, so can't
1750                  * really use same semantic of arrays.
1751                  */
1752                 foreach(Mesh *mesh, scene->meshes) {
1753                         for(size_t i = 0; i < mesh->num_triangles(); ++i) {
1754                                 tri_prim_index[i + mesh->tri_offset] = 3 * (i + mesh->tri_offset);
1755                         }
1756                 }
1757         }
1758         else {
1759                 for(size_t i = 0; i < dscene->prim_index.size(); ++i) {
1760                         if((dscene->prim_type[i] & PRIMITIVE_ALL_TRIANGLE) != 0) {
1761                                 tri_prim_index[dscene->prim_index[i]] = dscene->prim_tri_index[i];
1762                         }
1763                 }
1764         }
1765
1766         /* Fill in all the arrays. */
1767         if(tri_size != 0) {
1768                 /* normals */
1769                 progress.set_status("Updating Mesh", "Computing normals");
1770
1771                 uint *tri_shader = dscene->tri_shader.alloc(tri_size);
1772                 float4 *vnormal = dscene->tri_vnormal.alloc(vert_size);
1773                 uint4 *tri_vindex = dscene->tri_vindex.alloc(tri_size);
1774                 uint *tri_patch = dscene->tri_patch.alloc(tri_size);
1775                 float2 *tri_patch_uv = dscene->tri_patch_uv.alloc(vert_size);
1776
1777                 foreach(Mesh *mesh, scene->meshes) {
1778                         mesh->pack_shaders(scene,
1779                                            &tri_shader[mesh->tri_offset]);
1780                         mesh->pack_normals(&vnormal[mesh->vert_offset]);
1781                         mesh->pack_verts(tri_prim_index,
1782                                          &tri_vindex[mesh->tri_offset],
1783                                          &tri_patch[mesh->tri_offset],
1784                                          &tri_patch_uv[mesh->vert_offset],
1785                                          mesh->vert_offset,
1786                                          mesh->tri_offset);
1787                         if(progress.get_cancel()) return;
1788                 }
1789
1790                 /* vertex coordinates */
1791                 progress.set_status("Updating Mesh", "Copying Mesh to device");
1792
1793                 dscene->tri_shader.copy_to_device();
1794                 dscene->tri_vnormal.copy_to_device();
1795                 dscene->tri_vindex.copy_to_device();
1796                 dscene->tri_patch.copy_to_device();
1797                 dscene->tri_patch_uv.copy_to_device();
1798         }
1799
1800         if(curve_size != 0) {
1801                 progress.set_status("Updating Mesh", "Copying Strands to device");
1802
1803                 float4 *curve_keys = dscene->curve_keys.alloc(curve_key_size);
1804                 float4 *curves = dscene->curves.alloc(curve_size);
1805
1806                 foreach(Mesh *mesh, scene->meshes) {
1807                         mesh->pack_curves(scene, &curve_keys[mesh->curvekey_offset], &curves[mesh->curve_offset], mesh->curvekey_offset);
1808                         if(progress.get_cancel()) return;
1809                 }
1810
1811                 dscene->curve_keys.copy_to_device();
1812                 dscene->curves.copy_to_device();
1813         }
1814
1815         if(patch_size != 0) {
1816                 progress.set_status("Updating Mesh", "Copying Patches to device");
1817
1818                 uint *patch_data = dscene->patches.alloc(patch_size);
1819
1820                 foreach(Mesh *mesh, scene->meshes) {
1821                         mesh->pack_patches(&patch_data[mesh->patch_offset], mesh->vert_offset, mesh->face_offset, mesh->corner_offset);
1822
1823                         if(mesh->patch_table) {
1824                                 mesh->patch_table->copy_adjusting_offsets(&patch_data[mesh->patch_table_offset], mesh->patch_table_offset);
1825                         }
1826
1827                         if(progress.get_cancel()) return;
1828                 }
1829
1830                 dscene->patches.copy_to_device();
1831         }
1832
1833         if(for_displacement) {
1834                 float4 *prim_tri_verts = dscene->prim_tri_verts.alloc(tri_size * 3);
1835                 foreach(Mesh *mesh, scene->meshes) {
1836                         for(size_t i = 0; i < mesh->num_triangles(); ++i) {
1837                                 Mesh::Triangle t = mesh->get_triangle(i);
1838                                 size_t offset = 3 * (i + mesh->tri_offset);
1839                                 prim_tri_verts[offset + 0] = float3_to_float4(mesh->verts[t.v[0]]);
1840                                 prim_tri_verts[offset + 1] = float3_to_float4(mesh->verts[t.v[1]]);
1841                                 prim_tri_verts[offset + 2] = float3_to_float4(mesh->verts[t.v[2]]);
1842                         }
1843                 }
1844                 dscene->prim_tri_verts.copy_to_device();
1845         }
1846 }
1847
1848 void MeshManager::device_update_bvh(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
1849 {
1850         /* bvh build */
1851         progress.set_status("Updating Scene BVH", "Building");
1852
1853         BVHParams bparams;
1854         bparams.top_level = true;
1855         bparams.bvh_layout = BVHParams::best_bvh_layout(
1856                 scene->params.bvh_layout,
1857                 device->info.bvh_layout_mask);
1858         bparams.use_spatial_split = scene->params.use_bvh_spatial_split;
1859         bparams.use_unaligned_nodes = dscene->data.bvh.have_curves &&
1860                                       scene->params.use_bvh_unaligned_nodes;
1861         bparams.num_motion_triangle_steps = scene->params.num_bvh_time_steps;
1862         bparams.num_motion_curve_steps = scene->params.num_bvh_time_steps;
1863
1864         VLOG(1) << "Using " << bvh_layout_name(bparams.bvh_layout)
1865                 << " layout.";
1866
1867         BVH *bvh = BVH::create(bparams, scene->objects);
1868         bvh->build(progress);
1869
1870         if(progress.get_cancel()) {
1871                 delete bvh;
1872                 return;
1873         }
1874
1875         /* copy to device */
1876         progress.set_status("Updating Scene BVH", "Copying BVH to device");
1877
1878         PackedBVH& pack = bvh->pack;
1879
1880         if(pack.nodes.size()) {
1881                 dscene->bvh_nodes.steal_data(pack.nodes);
1882                 dscene->bvh_nodes.copy_to_device();
1883         }
1884         if(pack.leaf_nodes.size()) {
1885                 dscene->bvh_leaf_nodes.steal_data(pack.leaf_nodes);
1886                 dscene->bvh_leaf_nodes.copy_to_device();
1887         }
1888         if(pack.object_node.size()) {
1889                 dscene->object_node.steal_data(pack.object_node);
1890                 dscene->object_node.copy_to_device();
1891         }
1892         if(pack.prim_tri_index.size()) {
1893                 dscene->prim_tri_index.steal_data(pack.prim_tri_index);
1894                 dscene->prim_tri_index.copy_to_device();
1895         }
1896         if(pack.prim_tri_verts.size()) {
1897                 dscene->prim_tri_verts.steal_data(pack.prim_tri_verts);
1898                 dscene->prim_tri_verts.copy_to_device();
1899         }
1900         if(pack.prim_type.size()) {
1901                 dscene->prim_type.steal_data(pack.prim_type);
1902                 dscene->prim_type.copy_to_device();
1903         }
1904         if(pack.prim_visibility.size()) {
1905                 dscene->prim_visibility.steal_data(pack.prim_visibility);
1906                 dscene->prim_visibility.copy_to_device();
1907         }
1908         if(pack.prim_index.size()) {
1909                 dscene->prim_index.steal_data(pack.prim_index);
1910                 dscene->prim_index.copy_to_device();
1911         }
1912         if(pack.prim_object.size()) {
1913                 dscene->prim_object.steal_data(pack.prim_object);
1914                 dscene->prim_object.copy_to_device();
1915         }
1916         if(pack.prim_time.size()) {
1917                 dscene->prim_time.steal_data(pack.prim_time);
1918                 dscene->prim_time.copy_to_device();
1919         }
1920
1921         dscene->data.bvh.root = pack.root_index;
1922         dscene->data.bvh.bvh_layout = bparams.bvh_layout;
1923         dscene->data.bvh.use_bvh_steps = (scene->params.num_bvh_time_steps != 0);
1924
1925         delete bvh;
1926 }
1927
1928 void MeshManager::device_update_preprocess(Device *device,
1929                                            Scene *scene,
1930                                            Progress& progress)
1931 {
1932         if(!need_update && !need_flags_update) {
1933                 return;
1934         }
1935
1936         progress.set_status("Updating Meshes Flags");
1937
1938         /* Update flags. */
1939         bool volume_images_updated = false;
1940
1941         foreach(Mesh *mesh, scene->meshes) {
1942                 mesh->has_volume = false;
1943
1944                 foreach(const Shader *shader, mesh->used_shaders) {
1945                         if(shader->has_volume) {
1946                                 mesh->has_volume = true;
1947                         }
1948                         if(shader->has_surface_bssrdf) {
1949                                 mesh->has_surface_bssrdf = true;
1950                         }
1951                 }
1952
1953                 if(need_update && mesh->has_volume) {
1954                         /* Create volume meshes if there is voxel data. */
1955                         bool has_voxel_attributes = false;
1956
1957                         foreach(Attribute& attr, mesh->attributes.attributes) {
1958                                 if(attr.element == ATTR_ELEMENT_VOXEL) {
1959                                         has_voxel_attributes = true;
1960                                 }
1961                         }
1962
1963                         if(has_voxel_attributes) {
1964                                 if(!volume_images_updated) {
1965                                         progress.set_status("Updating Meshes Volume Bounds");
1966                                         device_update_volume_images(device, scene, progress);
1967                                         volume_images_updated = true;
1968                                 }
1969
1970                                 create_volume_mesh(scene, mesh, progress);
1971                         }
1972                 }
1973         }
1974
1975         need_flags_update = false;
1976 }
1977
1978 void MeshManager::device_update_displacement_images(Device *device,
1979                                                     Scene *scene,
1980                                                     Progress& progress)
1981 {
1982         progress.set_status("Updating Displacement Images");
1983         TaskPool pool;
1984         ImageManager *image_manager = scene->image_manager;
1985         set<int> bump_images;
1986         foreach(Mesh *mesh, scene->meshes) {
1987                 if(mesh->need_update) {
1988                         foreach(Shader *shader, mesh->used_shaders) {
1989                                 if(!shader->has_displacement || shader->displacement_method == DISPLACE_BUMP) {
1990                                         continue;
1991                                 }
1992                                 foreach(ShaderNode* node, shader->graph->nodes) {
1993                                         if(node->special_type != SHADER_SPECIAL_TYPE_IMAGE_SLOT) {
1994                                                 continue;
1995                                         }
1996
1997                                         ImageSlotTextureNode *image_node = static_cast<ImageSlotTextureNode*>(node);
1998                                         int slot = image_node->slot;
1999                                         if(slot != -1) {
2000                                                 bump_images.insert(slot);
2001                                         }
2002                                 }
2003                         }
2004                 }
2005         }
2006         foreach(int slot, bump_images) {
2007                 pool.push(function_bind(&ImageManager::device_update_slot,
2008                                         image_manager,
2009                                         device,
2010                                         scene,
2011                                         slot,
2012                                         &progress));
2013         }
2014         pool.wait_work();
2015 }
2016
2017 void MeshManager::device_update_volume_images(Device *device,
2018                                                                                           Scene *scene,
2019                                                                                           Progress& progress)
2020 {
2021         progress.set_status("Updating Volume Images");
2022         TaskPool pool;
2023         ImageManager *image_manager = scene->image_manager;
2024         set<int> volume_images;
2025
2026         foreach(Mesh *mesh, scene->meshes) {
2027                 if(!mesh->need_update) {
2028                         continue;
2029                 }
2030
2031                 foreach(Attribute& attr, mesh->attributes.attributes) {
2032                         if(attr.element != ATTR_ELEMENT_VOXEL) {
2033                                 continue;
2034                         }
2035
2036                         VoxelAttribute *voxel = attr.data_voxel();
2037
2038                         if(voxel->slot != -1) {
2039                                 volume_images.insert(voxel->slot);
2040                         }
2041                 }
2042         }
2043
2044         foreach(int slot, volume_images) {
2045                 pool.push(function_bind(&ImageManager::device_update_slot,
2046                                                                 image_manager,
2047                                                                 device,
2048                                                                 scene,
2049                                                                 slot,
2050                                                                 &progress));
2051         }
2052         pool.wait_work();
2053 }
2054
2055 void MeshManager::device_update(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
2056 {
2057         if(!need_update)
2058                 return;
2059
2060         VLOG(1) << "Total " << scene->meshes.size() << " meshes.";
2061
2062         bool true_displacement_used = false;
2063         size_t total_tess_needed = 0;
2064
2065         foreach(Mesh *mesh, scene->meshes) {
2066                 foreach(Shader *shader, mesh->used_shaders) {
2067                         if(shader->need_update_mesh)
2068                                 mesh->need_update = true;
2069                 }
2070
2071                 if(mesh->need_update) {
2072                         /* Update normals. */
2073                         mesh->add_face_normals();
2074                         mesh->add_vertex_normals();
2075
2076                         if(mesh->need_attribute(scene, ATTR_STD_POSITION_UNDISPLACED)) {
2077                                 mesh->add_undisplaced();
2078                         }
2079
2080                         /* Test if we need tesselation. */
2081                         if(mesh->subdivision_type != Mesh::SUBDIVISION_NONE &&
2082                            mesh->num_subd_verts == 0 &&
2083                            mesh->subd_params)
2084                         {
2085                                 total_tess_needed++;
2086                         }
2087
2088                         /* Test if we need displacement. */
2089                         if(mesh->has_true_displacement()) {
2090                                 true_displacement_used = true;
2091                         }
2092
2093                         if(progress.get_cancel()) return;
2094                 }
2095         }
2096
2097         /* Tessellate meshes that are using subdivision */
2098         if(total_tess_needed) {
2099                 size_t i = 0;
2100                 foreach(Mesh *mesh, scene->meshes) {
2101                         if(mesh->need_update &&
2102                            mesh->subdivision_type != Mesh::SUBDIVISION_NONE &&
2103                            mesh->num_subd_verts == 0 &&
2104                            mesh->subd_params)
2105                         {
2106                                 string msg = "Tessellating ";
2107                                 if(mesh->name == "")
2108                                         msg += string_printf("%u/%u", (uint)(i+1), (uint)total_tess_needed);
2109                                 else
2110                                         msg += string_printf("%s %u/%u", mesh->name.c_str(), (uint)(i+1), (uint)total_tess_needed);
2111
2112                                 progress.set_status("Updating Mesh", msg);
2113
2114                                 DiagSplit dsplit(*mesh->subd_params);
2115                                 mesh->tessellate(&dsplit);
2116
2117                                 i++;
2118
2119                                 if(progress.get_cancel()) return;
2120                         }
2121
2122                 }
2123         }
2124
2125         /* Update images needed for true displacement. */
2126         bool old_need_object_flags_update = false;
2127         if(true_displacement_used) {
2128                 VLOG(1) << "Updating images used for true displacement.";
2129                 device_update_displacement_images(device, scene, progress);
2130                 old_need_object_flags_update = scene->object_manager->need_flags_update;
2131                 scene->object_manager->device_update_flags(device,
2132                                                            dscene,
2133                                                            scene,
2134                                                            progress,
2135                                                            false);
2136         }
2137
2138         /* Device update. */
2139         device_free(device, dscene);
2140
2141         mesh_calc_offset(scene);
2142         if(true_displacement_used) {
2143                 device_update_mesh(device, dscene, scene, true, progress);
2144         }
2145         if(progress.get_cancel()) return;
2146
2147         device_update_attributes(device, dscene, scene, progress);
2148         if(progress.get_cancel()) return;
2149
2150         /* Update displacement. */
2151         bool displacement_done = false;
2152         size_t num_bvh = 0;
2153
2154         foreach(Mesh *mesh, scene->meshes) {
2155                 if(mesh->need_update) {
2156                         if(displace(device, dscene, scene, mesh, progress)) {
2157                                 displacement_done = true;
2158                         }
2159
2160                         if(mesh->need_build_bvh()) {
2161                                 num_bvh++;
2162                         }
2163                 }
2164         }
2165
2166         /* TODO: properly handle cancel halfway displacement */
2167         if(progress.get_cancel()) return;
2168
2169         /* Device re-update after displacement. */
2170         if(displacement_done) {
2171                 device_free(device, dscene);
2172
2173                 device_update_attributes(device, dscene, scene, progress);
2174                 if(progress.get_cancel()) return;
2175         }
2176
2177         TaskPool pool;
2178
2179         size_t i = 0;
2180         foreach(Mesh *mesh, scene->meshes) {
2181                 if(mesh->need_update) {
2182                         pool.push(function_bind(&Mesh::compute_bvh,
2183                                                 mesh,
2184                                                 device,
2185                                                 dscene,
2186                                                 &scene->params,
2187                                                 &progress,
2188                                                 i,
2189                                                 num_bvh));
2190                         if(mesh->need_build_bvh()) {
2191                                 i++;
2192                         }
2193                 }
2194         }
2195
2196         TaskPool::Summary summary;
2197         pool.wait_work(&summary);
2198         VLOG(2) << "Objects BVH build pool statistics:\n"
2199                 << summary.full_report();
2200
2201         foreach(Shader *shader, scene->shaders) {
2202                 shader->need_update_mesh = false;
2203         }
2204
2205         Scene::MotionType need_motion = scene->need_motion();
2206         bool motion_blur = need_motion == Scene::MOTION_BLUR;
2207
2208         /* Update objects. */
2209         vector<Object *> volume_objects;
2210         foreach(Object *object, scene->objects) {
2211                 object->compute_bounds(motion_blur);
2212         }
2213
2214         if(progress.get_cancel()) return;
2215
2216         device_update_bvh(device, dscene, scene, progress);
2217         if(progress.get_cancel()) return;
2218
2219         device_update_mesh(device, dscene, scene, false, progress);
2220         if(progress.get_cancel()) return;
2221
2222         need_update = false;
2223
2224         if(true_displacement_used) {
2225                 /* Re-tag flags for update, so they're re-evaluated
2226                  * for meshes with correct bounding boxes.
2227                  *
2228                  * This wouldn't cause wrong results, just true
2229                  * displacement might be less optimal ot calculate.
2230                  */
2231                 scene->object_manager->need_flags_update = old_need_object_flags_update;
2232         }
2233 }
2234
2235 void MeshManager::device_free(Device *device, DeviceScene *dscene)
2236 {
2237         dscene->bvh_nodes.free();
2238         dscene->bvh_leaf_nodes.free();
2239         dscene->object_node.free();
2240         dscene->prim_tri_verts.free();
2241         dscene->prim_tri_index.free();
2242         dscene->prim_type.free();
2243         dscene->prim_visibility.free();
2244         dscene->prim_index.free();
2245         dscene->prim_object.free();
2246         dscene->prim_time.free();
2247         dscene->tri_shader.free();
2248         dscene->tri_vnormal.free();
2249         dscene->tri_vindex.free();
2250         dscene->tri_patch.free();
2251         dscene->tri_patch_uv.free();
2252         dscene->curves.free();
2253         dscene->curve_keys.free();
2254         dscene->patches.free();
2255         dscene->attributes_map.free();
2256         dscene->attributes_float.free();
2257         dscene->attributes_float3.free();
2258         dscene->attributes_uchar4.free();
2259
2260 #ifdef WITH_OSL
2261         OSLGlobals *og = (OSLGlobals*)device->osl_memory();
2262
2263         if(og) {
2264                 og->object_name_map.clear();
2265                 og->attribute_map.clear();
2266                 og->object_names.clear();
2267         }
2268 #else
2269         (void)device;
2270 #endif
2271 }
2272
2273 void MeshManager::tag_update(Scene *scene)
2274 {
2275         need_update = true;
2276         scene->object_manager->need_update = true;
2277 }
2278
2279 bool Mesh::need_attribute(Scene *scene, AttributeStandard std)
2280 {
2281         if(std == ATTR_STD_NONE)
2282                 return false;
2283
2284         if(scene->need_global_attribute(std))
2285                 return true;
2286
2287         foreach(Shader *shader, used_shaders)
2288                 if(shader->attributes.find(std))
2289                         return true;
2290
2291         return false;
2292 }
2293
2294 bool Mesh::need_attribute(Scene * /*scene*/, ustring name)
2295 {
2296         if(name == ustring())
2297                 return false;
2298
2299         foreach(Shader *shader, used_shaders)
2300                 if(shader->attributes.find(name))
2301                         return true;
2302
2303         return false;
2304 }
2305
2306 CCL_NAMESPACE_END