Fix Cycles viewport render not updating when tweaking displacement shader.
[blender.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         has_volume = false;
450         has_surface_bssrdf = false;
451
452         num_ngons = 0;
453
454         subdivision_type = SUBDIVISION_NONE;
455         subd_params = NULL;
456
457         patch_table = NULL;
458 }
459
460 Mesh::~Mesh()
461 {
462         delete bvh;
463         delete patch_table;
464         delete subd_params;
465 }
466
467 void Mesh::resize_mesh(int numverts, int numtris)
468 {
469         verts.resize(numverts);
470         triangles.resize(numtris * 3);
471         shader.resize(numtris);
472         smooth.resize(numtris);
473
474         if(subd_faces.size()) {
475                 triangle_patch.resize(numtris);
476                 vert_patch_uv.resize(numverts);
477         }
478
479         attributes.resize();
480 }
481
482 void Mesh::reserve_mesh(int numverts, int numtris)
483 {
484         /* reserve space to add verts and triangles later */
485         verts.reserve(numverts);
486         triangles.reserve(numtris * 3);
487         shader.reserve(numtris);
488         smooth.reserve(numtris);
489
490         if(subd_faces.size()) {
491                 triangle_patch.reserve(numtris);
492                 vert_patch_uv.reserve(numverts);
493         }
494
495         attributes.resize(true);
496 }
497
498 void Mesh::resize_curves(int numcurves, int numkeys)
499 {
500         curve_keys.resize(numkeys);
501         curve_radius.resize(numkeys);
502         curve_first_key.resize(numcurves);
503         curve_shader.resize(numcurves);
504
505         curve_attributes.resize();
506 }
507
508 void Mesh::reserve_curves(int numcurves, int numkeys)
509 {
510         curve_keys.reserve(numkeys);
511         curve_radius.reserve(numkeys);
512         curve_first_key.reserve(numcurves);
513         curve_shader.reserve(numcurves);
514
515         curve_attributes.resize(true);
516 }
517
518 void Mesh::resize_subd_faces(int numfaces, int num_ngons_, int numcorners)
519 {
520         subd_faces.resize(numfaces);
521         subd_face_corners.resize(numcorners);
522         num_ngons = num_ngons_;
523
524         subd_attributes.resize();
525 }
526
527 void Mesh::reserve_subd_faces(int numfaces, int num_ngons_, int numcorners)
528 {
529         subd_faces.reserve(numfaces);
530         subd_face_corners.reserve(numcorners);
531         num_ngons = num_ngons_;
532
533         subd_attributes.resize(true);
534 }
535
536 void Mesh::clear()
537 {
538         /* clear all verts and triangles */
539         verts.clear();
540         triangles.clear();
541         shader.clear();
542         smooth.clear();
543
544         triangle_patch.clear();
545         vert_patch_uv.clear();
546
547         curve_keys.clear();
548         curve_radius.clear();
549         curve_first_key.clear();
550         curve_shader.clear();
551
552         subd_faces.clear();
553         subd_face_corners.clear();
554
555         num_subd_verts = 0;
556
557         subd_creases.clear();
558
559         attributes.clear();
560         curve_attributes.clear();
561         subd_attributes.clear();
562         used_shaders.clear();
563
564         transform_applied = false;
565         transform_negative_scaled = false;
566         transform_normal = transform_identity();
567         geometry_flags = GEOMETRY_NONE;
568
569         delete patch_table;
570         patch_table = NULL;
571 }
572
573 int Mesh::split_vertex(int vertex)
574 {
575         /* copy vertex location and vertex attributes */
576         add_vertex_slow(verts[vertex]);
577
578         foreach(Attribute& attr, attributes.attributes) {
579                 if(attr.element == ATTR_ELEMENT_VERTEX) {
580                         array<char> tmp(attr.data_sizeof());
581                         memcpy(tmp.data(), attr.data() + tmp.size()*vertex, tmp.size());
582                         attr.add(tmp.data());
583                 }
584         }
585
586         foreach(Attribute& attr, subd_attributes.attributes) {
587                 if(attr.element == ATTR_ELEMENT_VERTEX) {
588                         array<char> tmp(attr.data_sizeof());
589                         memcpy(tmp.data(), attr.data() + tmp.size()*vertex, tmp.size());
590                         attr.add(tmp.data());
591                 }
592         }
593
594         return verts.size() - 1;
595 }
596
597 void Mesh::add_vertex(float3 P)
598 {
599         verts.push_back_reserved(P);
600
601         if(subd_faces.size()) {
602                 vert_patch_uv.push_back_reserved(make_float2(0.0f, 0.0f));
603         }
604 }
605
606 void Mesh::add_vertex_slow(float3 P)
607 {
608         verts.push_back_slow(P);
609
610         if(subd_faces.size()) {
611                 vert_patch_uv.push_back_slow(make_float2(0.0f, 0.0f));
612         }
613 }
614
615 void Mesh::add_triangle(int v0, int v1, int v2, int shader_, bool smooth_)
616 {
617         triangles.push_back_reserved(v0);
618         triangles.push_back_reserved(v1);
619         triangles.push_back_reserved(v2);
620         shader.push_back_reserved(shader_);
621         smooth.push_back_reserved(smooth_);
622
623         if(subd_faces.size()) {
624                 triangle_patch.push_back_reserved(-1);
625         }
626 }
627
628 void Mesh::add_curve_key(float3 co, float radius)
629 {
630         curve_keys.push_back_reserved(co);
631         curve_radius.push_back_reserved(radius);
632 }
633
634 void Mesh::add_curve(int first_key, int shader)
635 {
636         curve_first_key.push_back_reserved(first_key);
637         curve_shader.push_back_reserved(shader);
638 }
639
640 void Mesh::add_subd_face(int* corners, int num_corners, int shader_, bool smooth_)
641 {
642         int start_corner = subd_face_corners.size();
643
644         for(int i = 0; i < num_corners; i++) {
645                 subd_face_corners.push_back_reserved(corners[i]);
646         }
647
648         int ptex_offset = 0;
649
650         if(subd_faces.size()) {
651                 SubdFace& s = subd_faces[subd_faces.size()-1];
652                 ptex_offset = s.ptex_offset + s.num_ptex_faces();
653         }
654
655         SubdFace face = {start_corner, num_corners, shader_, smooth_, ptex_offset};
656         subd_faces.push_back_reserved(face);
657 }
658
659 void Mesh::compute_bounds()
660 {
661         BoundBox bnds = BoundBox::empty;
662         size_t verts_size = verts.size();
663         size_t curve_keys_size = curve_keys.size();
664
665         if(verts_size + curve_keys_size > 0) {
666                 for(size_t i = 0; i < verts_size; i++)
667                         bnds.grow(verts[i]);
668
669                 for(size_t i = 0; i < curve_keys_size; i++)
670                         bnds.grow(curve_keys[i], curve_radius[i]);
671
672                 Attribute *attr = attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
673                 if(use_motion_blur && attr) {
674                         size_t steps_size = verts.size() * (motion_steps - 1);
675                         float3 *vert_steps = attr->data_float3();
676
677                         for(size_t i = 0; i < steps_size; i++)
678                                 bnds.grow(vert_steps[i]);
679                 }
680
681                 Attribute *curve_attr = curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
682                 if(use_motion_blur && curve_attr) {
683                         size_t steps_size = curve_keys.size() * (motion_steps - 1);
684                         float3 *key_steps = curve_attr->data_float3();
685
686                         for(size_t i = 0; i < steps_size; i++)
687                                 bnds.grow(key_steps[i]);
688                 }
689
690                 if(!bnds.valid()) {
691                         bnds = BoundBox::empty;
692
693                         /* skip nan or inf coordinates */
694                         for(size_t i = 0; i < verts_size; i++)
695                                 bnds.grow_safe(verts[i]);
696
697                         for(size_t i = 0; i < curve_keys_size; i++)
698                                 bnds.grow_safe(curve_keys[i], curve_radius[i]);
699
700                         if(use_motion_blur && attr) {
701                                 size_t steps_size = verts.size() * (motion_steps - 1);
702                                 float3 *vert_steps = attr->data_float3();
703
704                                 for(size_t i = 0; i < steps_size; i++)
705                                         bnds.grow_safe(vert_steps[i]);
706                         }
707
708                         if(use_motion_blur && curve_attr) {
709                                 size_t steps_size = curve_keys.size() * (motion_steps - 1);
710                                 float3 *key_steps = curve_attr->data_float3();
711
712                                 for(size_t i = 0; i < steps_size; i++)
713                                         bnds.grow_safe(key_steps[i]);
714                         }
715                 }
716         }
717
718         if(!bnds.valid()) {
719                 /* empty mesh */
720                 bnds.grow(make_float3(0.0f, 0.0f, 0.0f));
721         }
722
723         bounds = bnds;
724 }
725
726 void Mesh::add_face_normals()
727 {
728         /* don't compute if already there */
729         if(attributes.find(ATTR_STD_FACE_NORMAL))
730                 return;
731
732         /* get attributes */
733         Attribute *attr_fN = attributes.add(ATTR_STD_FACE_NORMAL);
734         float3 *fN = attr_fN->data_float3();
735
736         /* compute face normals */
737         size_t triangles_size = num_triangles();
738
739         if(triangles_size) {
740                 float3 *verts_ptr = verts.data();
741
742                 for(size_t i = 0; i < triangles_size; i++) {
743                         fN[i] = get_triangle(i).compute_normal(verts_ptr);
744                 }
745         }
746
747         /* expected to be in local space */
748         if(transform_applied) {
749                 Transform ntfm = transform_inverse(transform_normal);
750
751                 for(size_t i = 0; i < triangles_size; i++)
752                         fN[i] = normalize(transform_direction(&ntfm, fN[i]));
753         }
754 }
755
756 void Mesh::add_vertex_normals()
757 {
758         bool flip = transform_negative_scaled;
759         size_t verts_size = verts.size();
760         size_t triangles_size = num_triangles();
761
762         /* static vertex normals */
763         if(!attributes.find(ATTR_STD_VERTEX_NORMAL) && triangles_size) {
764                 /* get attributes */
765                 Attribute *attr_fN = attributes.find(ATTR_STD_FACE_NORMAL);
766                 Attribute *attr_vN = attributes.add(ATTR_STD_VERTEX_NORMAL);
767
768                 float3 *fN = attr_fN->data_float3();
769                 float3 *vN = attr_vN->data_float3();
770
771                 /* compute vertex normals */
772                 memset(vN, 0, verts.size()*sizeof(float3));
773
774                 for(size_t i = 0; i < triangles_size; i++) {
775                         for(size_t j = 0; j < 3; j++) {
776                                 vN[get_triangle(i).v[j]] += fN[i];
777                         }
778                 }
779
780                 for(size_t i = 0; i < verts_size; i++) {
781                         vN[i] = normalize(vN[i]);
782                         if(flip) {
783                                 vN[i] = -vN[i];
784                         }
785                 }
786         }
787
788         /* motion vertex normals */
789         Attribute *attr_mP = attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
790         Attribute *attr_mN = attributes.find(ATTR_STD_MOTION_VERTEX_NORMAL);
791
792         if(has_motion_blur() && attr_mP && !attr_mN && triangles_size) {
793                 /* create attribute */
794                 attr_mN = attributes.add(ATTR_STD_MOTION_VERTEX_NORMAL);
795
796                 for(int step = 0; step < motion_steps - 1; step++) {
797                         float3 *mP = attr_mP->data_float3() + step*verts.size();
798                         float3 *mN = attr_mN->data_float3() + step*verts.size();
799
800                         /* compute */
801                         memset(mN, 0, verts.size()*sizeof(float3));
802
803                         for(size_t i = 0; i < triangles_size; i++) {
804                                 for(size_t j = 0; j < 3; j++) {
805                                         float3 fN = get_triangle(i).compute_normal(mP);
806                                         mN[get_triangle(i).v[j]] += fN;
807                                 }
808                         }
809
810                         for(size_t i = 0; i < verts_size; i++) {
811                                 mN[i] = normalize(mN[i]);
812                                 if(flip) {
813                                         mN[i] = -mN[i];
814                                 }
815                         }
816                 }
817         }
818
819         /* subd vertex normals */
820         if(!subd_attributes.find(ATTR_STD_VERTEX_NORMAL) && subd_faces.size()) {
821                 /* get attributes */
822                 Attribute *attr_vN = subd_attributes.add(ATTR_STD_VERTEX_NORMAL);
823                 float3 *vN = attr_vN->data_float3();
824
825                 /* compute vertex normals */
826                 memset(vN, 0, verts.size()*sizeof(float3));
827
828                 for(size_t i = 0; i < subd_faces.size(); i++) {
829                         SubdFace& face = subd_faces[i];
830                         float3 fN = face.normal(this);
831
832                         for(size_t j = 0; j < face.num_corners; j++) {
833                                 size_t corner = subd_face_corners[face.start_corner+j];
834                                 vN[corner] += fN;
835                         }
836                 }
837
838                 for(size_t i = 0; i < verts_size; i++) {
839                         vN[i] = normalize(vN[i]);
840                         if(flip) {
841                                 vN[i] = -vN[i];
842                         }
843                 }
844         }
845 }
846
847 void Mesh::add_undisplaced()
848 {
849         AttributeSet& attrs = (subdivision_type == SUBDIVISION_NONE) ? attributes : subd_attributes;
850
851         /* don't compute if already there */
852         if(attrs.find(ATTR_STD_POSITION_UNDISPLACED)) {
853                 return;
854         }
855
856         /* get attribute */
857         Attribute *attr = attrs.add(ATTR_STD_POSITION_UNDISPLACED);
858         attr->flags |= ATTR_SUBDIVIDED;
859
860         float3 *data = attr->data_float3();
861
862         /* copy verts */
863         size_t size = attr->buffer_size(this, (subdivision_type == SUBDIVISION_NONE) ? ATTR_PRIM_TRIANGLE : ATTR_PRIM_SUBD);
864
865         /* Center points for ngons aren't stored in Mesh::verts but are included in size since they will be
866          * calculated later, we subtract them from size here so we don't have an overflow while copying.
867          */
868         size -= num_ngons * attr->data_sizeof();
869
870         if(size) {
871                 memcpy(data, verts.data(), size);
872         }
873 }
874
875 void Mesh::pack_normals(Scene *scene, uint *tri_shader, float4 *vnormal)
876 {
877         Attribute *attr_vN = attributes.find(ATTR_STD_VERTEX_NORMAL);
878         if(attr_vN == NULL) {
879                 /* Happens on objects with just hair. */
880                 return;
881         }
882
883         float3 *vN = attr_vN->data_float3();
884         uint shader_id = 0;
885         uint last_shader = -1;
886         bool last_smooth = false;
887
888         size_t triangles_size = num_triangles();
889         int *shader_ptr = shader.data();
890
891         bool do_transform = transform_applied;
892         Transform ntfm = transform_normal;
893
894         /* save shader */
895         for(size_t i = 0; i < triangles_size; i++) {
896                 if(shader_ptr[i] != last_shader || last_smooth != smooth[i]) {
897                         last_shader = shader_ptr[i];
898                         last_smooth = smooth[i];
899                         Shader *shader = (last_shader < used_shaders.size()) ?
900                                 used_shaders[last_shader] : scene->default_surface;
901                         shader_id = scene->shader_manager->get_shader_id(shader, last_smooth);
902                 }
903
904                 tri_shader[i] = shader_id;
905         }
906
907         size_t verts_size = verts.size();
908
909         for(size_t i = 0; i < verts_size; i++) {
910                 float3 vNi = vN[i];
911
912                 if(do_transform)
913                         vNi = safe_normalize(transform_direction(&ntfm, vNi));
914
915                 vnormal[i] = make_float4(vNi.x, vNi.y, vNi.z, 0.0f);
916         }
917 }
918
919 void Mesh::pack_verts(const vector<uint>& tri_prim_index,
920                       uint4 *tri_vindex,
921                       uint *tri_patch,
922                       float2 *tri_patch_uv,
923                       size_t vert_offset,
924                       size_t tri_offset)
925 {
926         size_t verts_size = verts.size();
927
928         if(verts_size && subd_faces.size()) {
929                 float2 *vert_patch_uv_ptr = vert_patch_uv.data();
930
931                 for(size_t i = 0; i < verts_size; i++) {
932                         tri_patch_uv[i] = vert_patch_uv_ptr[i];
933                 }
934         }
935
936         size_t triangles_size = num_triangles();
937
938         for(size_t i = 0; i < triangles_size; i++) {
939                 Triangle t = get_triangle(i);
940                 tri_vindex[i] = make_uint4(t.v[0] + vert_offset,
941                                            t.v[1] + vert_offset,
942                                            t.v[2] + vert_offset,
943                                            tri_prim_index[i + tri_offset]);
944
945                 tri_patch[i] = (!subd_faces.size()) ? -1 : (triangle_patch[i]*8 + patch_offset);
946         }
947 }
948
949 void Mesh::pack_curves(Scene *scene, float4 *curve_key_co, float4 *curve_data, size_t curvekey_offset)
950 {
951         size_t curve_keys_size = curve_keys.size();
952
953         /* pack curve keys */
954         if(curve_keys_size) {
955                 float3 *keys_ptr = curve_keys.data();
956                 float *radius_ptr = curve_radius.data();
957
958                 for(size_t i = 0; i < curve_keys_size; i++)
959                         curve_key_co[i] = make_float4(keys_ptr[i].x, keys_ptr[i].y, keys_ptr[i].z, radius_ptr[i]);
960         }
961
962         /* pack curve segments */
963         size_t curve_num = num_curves();
964
965         for(size_t i = 0; i < curve_num; i++) {
966                 Curve curve = get_curve(i);
967                 int shader_id = curve_shader[i];
968                 Shader *shader = (shader_id < used_shaders.size()) ?
969                         used_shaders[shader_id] : scene->default_surface;
970                 shader_id = scene->shader_manager->get_shader_id(shader, false);
971
972                 curve_data[i] = make_float4(
973                         __int_as_float(curve.first_key + curvekey_offset),
974                         __int_as_float(curve.num_keys),
975                         __int_as_float(shader_id),
976                         0.0f);
977         }
978 }
979
980 void Mesh::pack_patches(uint *patch_data, uint vert_offset, uint face_offset, uint corner_offset)
981 {
982         size_t num_faces = subd_faces.size();
983         int ngons = 0;
984
985         for(size_t f = 0; f < num_faces; f++) {
986                 SubdFace face = subd_faces[f];
987
988                 if(face.is_quad()) {
989                         int c[4];
990                         memcpy(c, &subd_face_corners[face.start_corner], sizeof(int)*4);
991
992                         *(patch_data++) = c[0] + vert_offset;
993                         *(patch_data++) = c[1] + vert_offset;
994                         *(patch_data++) = c[2] + vert_offset;
995                         *(patch_data++) = c[3] + vert_offset;
996
997                         *(patch_data++) = f+face_offset;
998                         *(patch_data++) = face.num_corners;
999                         *(patch_data++) = face.start_corner + corner_offset;
1000                         *(patch_data++) = 0;
1001                 }
1002                 else {
1003                         for(int i = 0; i < face.num_corners; i++) {
1004                                 int c[4];
1005                                 c[0] = subd_face_corners[face.start_corner + mod(i + 0, face.num_corners)];
1006                                 c[1] = subd_face_corners[face.start_corner + mod(i + 1, face.num_corners)];
1007                                 c[2] = verts.size() - num_subd_verts + ngons;
1008                                 c[3] = subd_face_corners[face.start_corner + mod(i - 1, face.num_corners)];
1009
1010                                 *(patch_data++) = c[0] + vert_offset;
1011                                 *(patch_data++) = c[1] + vert_offset;
1012                                 *(patch_data++) = c[2] + vert_offset;
1013                                 *(patch_data++) = c[3] + vert_offset;
1014
1015                                 *(patch_data++) = f+face_offset;
1016                                 *(patch_data++) = face.num_corners | (i << 16);
1017                                 *(patch_data++) = face.start_corner + corner_offset;
1018                                 *(patch_data++) = subd_face_corners.size() + ngons + corner_offset;
1019                         }
1020
1021                         ngons++;
1022                 }
1023         }
1024 }
1025
1026 void Mesh::compute_bvh(Device *device,
1027                        DeviceScene *dscene,
1028                        SceneParams *params,
1029                        Progress *progress,
1030                        int n,
1031                        int total)
1032 {
1033         if(progress->get_cancel())
1034                 return;
1035
1036         compute_bounds();
1037
1038         if(need_build_bvh()) {
1039                 string msg = "Updating Mesh BVH ";
1040                 if(name == "")
1041                         msg += string_printf("%u/%u", (uint)(n+1), (uint)total);
1042                 else
1043                         msg += string_printf("%s %u/%u", name.c_str(), (uint)(n+1), (uint)total);
1044
1045                 Object object;
1046                 object.mesh = this;
1047
1048                 vector<Object*> objects;
1049                 objects.push_back(&object);
1050
1051                 if(bvh && !need_update_rebuild) {
1052                         progress->set_status(msg, "Refitting BVH");
1053                         bvh->objects = objects;
1054                         bvh->refit(*progress);
1055                 }
1056                 else {
1057                         progress->set_status(msg, "Building BVH");
1058
1059                         BVHParams bparams;
1060                         bparams.use_spatial_split = params->use_bvh_spatial_split;
1061                         bparams.bvh_layout = BVHParams::best_bvh_layout(
1062                                 params->bvh_layout,
1063                                 device->info.bvh_layout_mask);
1064                         bparams.use_unaligned_nodes = dscene->data.bvh.have_curves &&
1065                                                       params->use_bvh_unaligned_nodes;
1066                         bparams.num_motion_triangle_steps = params->num_bvh_time_steps;
1067                         bparams.num_motion_curve_steps = params->num_bvh_time_steps;
1068
1069                         delete bvh;
1070                         bvh = BVH::create(bparams, objects);
1071                         MEM_GUARDED_CALL(progress, bvh->build, *progress);
1072                 }
1073         }
1074
1075         need_update = false;
1076         need_update_rebuild = false;
1077 }
1078
1079 void Mesh::tag_update(Scene *scene, bool rebuild)
1080 {
1081         need_update = true;
1082
1083         if(rebuild) {
1084                 need_update_rebuild = true;
1085                 scene->light_manager->need_update = true;
1086         }
1087         else {
1088                 foreach(Shader *shader, used_shaders)
1089                         if(shader->has_surface_emission)
1090                                 scene->light_manager->need_update = true;
1091         }
1092
1093         scene->mesh_manager->need_update = true;
1094         scene->object_manager->need_update = true;
1095 }
1096
1097 bool Mesh::has_motion_blur() const
1098 {
1099         return (use_motion_blur &&
1100                 (attributes.find(ATTR_STD_MOTION_VERTEX_POSITION) ||
1101                  curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION)));
1102 }
1103
1104 bool Mesh::has_true_displacement() const
1105 {
1106         foreach(Shader *shader, used_shaders) {
1107                 if(shader->has_displacement && shader->displacement_method != DISPLACE_BUMP) {
1108                         return true;
1109                 }
1110         }
1111
1112         return false;
1113 }
1114
1115 bool Mesh::need_build_bvh() const
1116 {
1117         return !transform_applied || has_surface_bssrdf;
1118 }
1119
1120 bool Mesh::is_instanced() const
1121 {
1122         /* Currently we treat subsurface objects as instanced.
1123          *
1124          * While it might be not very optimal for ray traversal, it avoids having
1125          * duplicated BVH in the memory, saving quite some space.
1126          */
1127         return !transform_applied || has_surface_bssrdf;
1128 }
1129
1130 /* Mesh Manager */
1131
1132 MeshManager::MeshManager()
1133 {
1134         need_update = true;
1135         need_flags_update = true;
1136 }
1137
1138 MeshManager::~MeshManager()
1139 {
1140 }
1141
1142 void MeshManager::update_osl_attributes(Device *device, Scene *scene, vector<AttributeRequestSet>& mesh_attributes)
1143 {
1144 #ifdef WITH_OSL
1145         /* for OSL, a hash map is used to lookup the attribute by name. */
1146         OSLGlobals *og = (OSLGlobals*)device->osl_memory();
1147
1148         og->object_name_map.clear();
1149         og->attribute_map.clear();
1150         og->object_names.clear();
1151
1152         og->attribute_map.resize(scene->objects.size()*ATTR_PRIM_TYPES);
1153
1154         for(size_t i = 0; i < scene->objects.size(); i++) {
1155                 /* set object name to object index map */
1156                 Object *object = scene->objects[i];
1157                 og->object_name_map[object->name] = i;
1158                 og->object_names.push_back(object->name);
1159
1160                 /* set object attributes */
1161                 foreach(ParamValue& attr, object->attributes) {
1162                         OSLGlobals::Attribute osl_attr;
1163
1164                         osl_attr.type = attr.type();
1165                         osl_attr.desc.element = ATTR_ELEMENT_OBJECT;
1166                         osl_attr.value = attr;
1167                         osl_attr.desc.offset = 0;
1168                         osl_attr.desc.flags = 0;
1169
1170                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_TRIANGLE][attr.name()] = osl_attr;
1171                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][attr.name()] = osl_attr;
1172                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_SUBD][attr.name()] = osl_attr;
1173                 }
1174
1175                 /* find mesh attributes */
1176                 size_t j;
1177
1178                 for(j = 0; j < scene->meshes.size(); j++)
1179                         if(scene->meshes[j] == object->mesh)
1180                                 break;
1181
1182                 AttributeRequestSet& attributes = mesh_attributes[j];
1183
1184                 /* set object attributes */
1185                 foreach(AttributeRequest& req, attributes.requests) {
1186                         OSLGlobals::Attribute osl_attr;
1187
1188                         if(req.triangle_desc.element != ATTR_ELEMENT_NONE) {
1189                                 osl_attr.desc = req.triangle_desc;
1190
1191                                 if(req.triangle_type == TypeDesc::TypeFloat)
1192                                         osl_attr.type = TypeDesc::TypeFloat;
1193                                 else if(req.triangle_type == TypeDesc::TypeMatrix)
1194                                         osl_attr.type = TypeDesc::TypeMatrix;
1195                                 else
1196                                         osl_attr.type = TypeDesc::TypeColor;
1197
1198                                 if(req.std != ATTR_STD_NONE) {
1199                                         /* if standard attribute, add lookup by geom: name convention */
1200                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
1201                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_TRIANGLE][stdname] = osl_attr;
1202                                 }
1203                                 else if(req.name != ustring()) {
1204                                         /* add lookup by mesh attribute name */
1205                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_TRIANGLE][req.name] = osl_attr;
1206                                 }
1207                         }
1208
1209                         if(req.curve_desc.element != ATTR_ELEMENT_NONE) {
1210                                 osl_attr.desc = req.curve_desc;
1211
1212                                 if(req.curve_type == TypeDesc::TypeFloat)
1213                                         osl_attr.type = TypeDesc::TypeFloat;
1214                                 else if(req.curve_type == TypeDesc::TypeMatrix)
1215                                         osl_attr.type = TypeDesc::TypeMatrix;
1216                                 else
1217                                         osl_attr.type = TypeDesc::TypeColor;
1218
1219                                 if(req.std != ATTR_STD_NONE) {
1220                                         /* if standard attribute, add lookup by geom: name convention */
1221                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
1222                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][stdname] = osl_attr;
1223                                 }
1224                                 else if(req.name != ustring()) {
1225                                         /* add lookup by mesh attribute name */
1226                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][req.name] = osl_attr;
1227                                 }
1228                         }
1229
1230                         if(req.subd_desc.element != ATTR_ELEMENT_NONE) {
1231                                 osl_attr.desc = req.subd_desc;
1232
1233                                 if(req.subd_type == TypeDesc::TypeFloat)
1234                                         osl_attr.type = TypeDesc::TypeFloat;
1235                                 else if(req.subd_type == TypeDesc::TypeMatrix)
1236                                         osl_attr.type = TypeDesc::TypeMatrix;
1237                                 else
1238                                         osl_attr.type = TypeDesc::TypeColor;
1239
1240                                 if(req.std != ATTR_STD_NONE) {
1241                                         /* if standard attribute, add lookup by geom: name convention */
1242                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
1243                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_SUBD][stdname] = osl_attr;
1244                                 }
1245                                 else if(req.name != ustring()) {
1246                                         /* add lookup by mesh attribute name */
1247                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_SUBD][req.name] = osl_attr;
1248                                 }
1249                         }
1250                 }
1251         }
1252 #else
1253         (void)device;
1254         (void)scene;
1255         (void)mesh_attributes;
1256 #endif
1257 }
1258
1259 void MeshManager::update_svm_attributes(Device *, DeviceScene *dscene, Scene *scene, vector<AttributeRequestSet>& mesh_attributes)
1260 {
1261         /* for SVM, the attributes_map table is used to lookup the offset of an
1262          * attribute, based on a unique shader attribute id. */
1263
1264         /* compute array stride */
1265         int attr_map_size = 0;
1266
1267         for(size_t i = 0; i < scene->meshes.size(); i++) {
1268                 Mesh *mesh = scene->meshes[i];
1269                 mesh->attr_map_offset = attr_map_size;
1270                 attr_map_size += (mesh_attributes[i].size() + 1)*ATTR_PRIM_TYPES;
1271         }
1272
1273         if(attr_map_size == 0)
1274                 return;
1275
1276         /* create attribute map */
1277         uint4 *attr_map = dscene->attributes_map.alloc(attr_map_size*scene->meshes.size());
1278         memset(attr_map, 0, dscene->attributes_map.size()*sizeof(uint));
1279
1280         for(size_t i = 0; i < scene->meshes.size(); i++) {
1281                 Mesh *mesh = scene->meshes[i];
1282                 AttributeRequestSet& attributes = mesh_attributes[i];
1283
1284                 /* set object attributes */
1285                 int index = mesh->attr_map_offset;
1286
1287                 foreach(AttributeRequest& req, attributes.requests) {
1288                         uint id;
1289
1290                         if(req.std == ATTR_STD_NONE)
1291                                 id = scene->shader_manager->get_attribute_id(req.name);
1292                         else
1293                                 id = scene->shader_manager->get_attribute_id(req.std);
1294
1295                         if(mesh->num_triangles()) {
1296                                 attr_map[index].x = id;
1297                                 attr_map[index].y = req.triangle_desc.element;
1298                                 attr_map[index].z = as_uint(req.triangle_desc.offset);
1299
1300                                 if(req.triangle_type == TypeDesc::TypeFloat)
1301                                         attr_map[index].w = NODE_ATTR_FLOAT;
1302                                 else if(req.triangle_type == TypeDesc::TypeMatrix)
1303                                         attr_map[index].w = NODE_ATTR_MATRIX;
1304                                 else
1305                                         attr_map[index].w = NODE_ATTR_FLOAT3;
1306
1307                                 attr_map[index].w |= req.triangle_desc.flags << 8;
1308                         }
1309
1310                         index++;
1311
1312                         if(mesh->num_curves()) {
1313                                 attr_map[index].x = id;
1314                                 attr_map[index].y = req.curve_desc.element;
1315                                 attr_map[index].z = as_uint(req.curve_desc.offset);
1316
1317                                 if(req.curve_type == TypeDesc::TypeFloat)
1318                                         attr_map[index].w = NODE_ATTR_FLOAT;
1319                                 else if(req.curve_type == TypeDesc::TypeMatrix)
1320                                         attr_map[index].w = NODE_ATTR_MATRIX;
1321                                 else
1322                                         attr_map[index].w = NODE_ATTR_FLOAT3;
1323
1324                                 attr_map[index].w |= req.curve_desc.flags << 8;
1325                         }
1326
1327                         index++;
1328
1329                         if(mesh->subd_faces.size()) {
1330                                 attr_map[index].x = id;
1331                                 attr_map[index].y = req.subd_desc.element;
1332                                 attr_map[index].z = as_uint(req.subd_desc.offset);
1333
1334                                 if(req.subd_type == TypeDesc::TypeFloat)
1335                                         attr_map[index].w = NODE_ATTR_FLOAT;
1336                                 else if(req.subd_type == TypeDesc::TypeMatrix)
1337                                         attr_map[index].w = NODE_ATTR_MATRIX;
1338                                 else
1339                                         attr_map[index].w = NODE_ATTR_FLOAT3;
1340
1341                                 attr_map[index].w |= req.subd_desc.flags << 8;
1342                         }
1343
1344                         index++;
1345                 }
1346
1347                 /* terminator */
1348                 for(int j = 0; j < ATTR_PRIM_TYPES; j++) {
1349                         attr_map[index].x = ATTR_STD_NONE;
1350                         attr_map[index].y = 0;
1351                         attr_map[index].z = 0;
1352                         attr_map[index].w = 0;
1353
1354                         index++;
1355                 }
1356         }
1357
1358         /* copy to device */
1359         dscene->attributes_map.copy_to_device();
1360 }
1361
1362 static void update_attribute_element_size(Mesh *mesh,
1363                                           Attribute *mattr,
1364                                           AttributePrimitive prim,
1365                                           size_t *attr_float_size,
1366                                           size_t *attr_float3_size,
1367                                           size_t *attr_uchar4_size)
1368 {
1369         if(mattr) {
1370                 size_t size = mattr->element_size(mesh, prim);
1371
1372                 if(mattr->element == ATTR_ELEMENT_VOXEL) {
1373                         /* pass */
1374                 }
1375                 else if(mattr->element == ATTR_ELEMENT_CORNER_BYTE) {
1376                         *attr_uchar4_size += size;
1377                 }
1378                 else if(mattr->type == TypeDesc::TypeFloat) {
1379                         *attr_float_size += size;
1380                 }
1381                 else if(mattr->type == TypeDesc::TypeMatrix) {
1382                         *attr_float3_size += size * 4;
1383                 }
1384                 else {
1385                         *attr_float3_size += size;
1386                 }
1387         }
1388 }
1389
1390 static void update_attribute_element_offset(Mesh *mesh,
1391                                             device_vector<float>& attr_float,
1392                                             size_t& attr_float_offset,
1393                                             device_vector<float4>& attr_float3,
1394                                             size_t& attr_float3_offset,
1395                                             device_vector<uchar4>& attr_uchar4,
1396                                             size_t& attr_uchar4_offset,
1397                                             Attribute *mattr,
1398                                             AttributePrimitive prim,
1399                                             TypeDesc& type,
1400                                             AttributeDescriptor& desc)
1401 {
1402         if(mattr) {
1403                 /* store element and type */
1404                 desc.element = mattr->element;
1405                 desc.flags = mattr->flags;
1406                 type = mattr->type;
1407
1408                 /* store attribute data in arrays */
1409                 size_t size = mattr->element_size(mesh, prim);
1410
1411                 AttributeElement& element = desc.element;
1412                 int& offset = desc.offset;
1413
1414                 if(mattr->element == ATTR_ELEMENT_VOXEL) {
1415                         /* store slot in offset value */
1416                         VoxelAttribute *voxel_data = mattr->data_voxel();
1417                         offset = voxel_data->slot;
1418                 }
1419                 else if(mattr->element == ATTR_ELEMENT_CORNER_BYTE) {
1420                         uchar4 *data = mattr->data_uchar4();
1421                         offset = attr_uchar4_offset;
1422
1423                         assert(attr_uchar4.size() >= offset + size);
1424                         for(size_t k = 0; k < size; k++) {
1425                                 attr_uchar4[offset+k] = data[k];
1426                         }
1427                         attr_uchar4_offset += size;
1428                 }
1429                 else if(mattr->type == TypeDesc::TypeFloat) {
1430                         float *data = mattr->data_float();
1431                         offset = attr_float_offset;
1432
1433                         assert(attr_float.size() >= offset + size);
1434                         for(size_t k = 0; k < size; k++) {
1435                                 attr_float[offset+k] = data[k];
1436                         }
1437                         attr_float_offset += size;
1438                 }
1439                 else if(mattr->type == TypeDesc::TypeMatrix) {
1440                         Transform *tfm = mattr->data_transform();
1441                         offset = attr_float3_offset;
1442
1443                         assert(attr_float3.size() >= offset + size * 4);
1444                         for(size_t k = 0; k < size*4; k++) {
1445                                 attr_float3[offset+k] = (&tfm->x)[k];
1446                         }
1447                         attr_float3_offset += size * 4;
1448                 }
1449                 else {
1450                         float4 *data = mattr->data_float4();
1451                         offset = attr_float3_offset;
1452
1453                         assert(attr_float3.size() >= offset + size);
1454                         for(size_t k = 0; k < size; k++) {
1455                                 attr_float3[offset+k] = data[k];
1456                         }
1457                         attr_float3_offset += size;
1458                 }
1459
1460                 /* mesh vertex/curve index is global, not per object, so we sneak
1461                  * a correction for that in here */
1462                 if(mesh->subdivision_type == Mesh::SUBDIVISION_CATMULL_CLARK && desc.flags & ATTR_SUBDIVIDED) {
1463                         /* indices for subdivided attributes are retrieved
1464                          * from patch table so no need for correction here*/
1465                 }
1466                 else if(element == ATTR_ELEMENT_VERTEX)
1467                         offset -= mesh->vert_offset;
1468                 else if(element == ATTR_ELEMENT_VERTEX_MOTION)
1469                         offset -= mesh->vert_offset;
1470                 else if(element == ATTR_ELEMENT_FACE) {
1471                         if(prim == ATTR_PRIM_TRIANGLE)
1472                                 offset -= mesh->tri_offset;
1473                         else
1474                                 offset -= mesh->face_offset;
1475                 }
1476                 else if(element == ATTR_ELEMENT_CORNER || element == ATTR_ELEMENT_CORNER_BYTE) {
1477                         if(prim == ATTR_PRIM_TRIANGLE)
1478                                 offset -= 3*mesh->tri_offset;
1479                         else
1480                                 offset -= mesh->corner_offset;
1481                 }
1482                 else if(element == ATTR_ELEMENT_CURVE)
1483                         offset -= mesh->curve_offset;
1484                 else if(element == ATTR_ELEMENT_CURVE_KEY)
1485                         offset -= mesh->curvekey_offset;
1486                 else if(element == ATTR_ELEMENT_CURVE_KEY_MOTION)
1487                         offset -= mesh->curvekey_offset;
1488         }
1489         else {
1490                 /* attribute not found */
1491                 desc.element = ATTR_ELEMENT_NONE;
1492                 desc.offset = 0;
1493         }
1494 }
1495
1496 void MeshManager::device_update_attributes(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
1497 {
1498         progress.set_status("Updating Mesh", "Computing attributes");
1499
1500         /* gather per mesh requested attributes. as meshes may have multiple
1501          * shaders assigned, this merges the requested attributes that have
1502          * been set per shader by the shader manager */
1503         vector<AttributeRequestSet> mesh_attributes(scene->meshes.size());
1504
1505         for(size_t i = 0; i < scene->meshes.size(); i++) {
1506                 Mesh *mesh = scene->meshes[i];
1507
1508                 scene->need_global_attributes(mesh_attributes[i]);
1509
1510                 foreach(Shader *shader, mesh->used_shaders) {
1511                         mesh_attributes[i].add(shader->attributes);
1512                 }
1513         }
1514
1515         /* mesh attribute are stored in a single array per data type. here we fill
1516          * those arrays, and set the offset and element type to create attribute
1517          * maps next */
1518
1519         /* Pre-allocate attributes to avoid arrays re-allocation which would
1520          * take 2x of overall attribute memory usage.
1521          */
1522         size_t attr_float_size = 0;
1523         size_t attr_float3_size = 0;
1524         size_t attr_uchar4_size = 0;
1525         for(size_t i = 0; i < scene->meshes.size(); i++) {
1526                 Mesh *mesh = scene->meshes[i];
1527                 AttributeRequestSet& attributes = mesh_attributes[i];
1528                 foreach(AttributeRequest& req, attributes.requests) {
1529                         Attribute *triangle_mattr = mesh->attributes.find(req);
1530                         Attribute *curve_mattr = mesh->curve_attributes.find(req);
1531                         Attribute *subd_mattr = mesh->subd_attributes.find(req);
1532
1533                         update_attribute_element_size(mesh,
1534                                                       triangle_mattr,
1535                                                       ATTR_PRIM_TRIANGLE,
1536                                                       &attr_float_size,
1537                                                       &attr_float3_size,
1538                                                       &attr_uchar4_size);
1539                         update_attribute_element_size(mesh,
1540                                                       curve_mattr,
1541                                                       ATTR_PRIM_CURVE,
1542                                                       &attr_float_size,
1543                                                       &attr_float3_size,
1544                                                       &attr_uchar4_size);
1545                         update_attribute_element_size(mesh,
1546                                                       subd_mattr,
1547                                                       ATTR_PRIM_SUBD,
1548                                                       &attr_float_size,
1549                                                       &attr_float3_size,
1550                                                       &attr_uchar4_size);
1551                 }
1552         }
1553
1554         dscene->attributes_float.alloc(attr_float_size);
1555         dscene->attributes_float3.alloc(attr_float3_size);
1556         dscene->attributes_uchar4.alloc(attr_uchar4_size);
1557
1558         size_t attr_float_offset = 0;
1559         size_t attr_float3_offset = 0;
1560         size_t attr_uchar4_offset = 0;
1561
1562         /* Fill in attributes. */
1563         for(size_t i = 0; i < scene->meshes.size(); i++) {
1564                 Mesh *mesh = scene->meshes[i];
1565                 AttributeRequestSet& attributes = mesh_attributes[i];
1566
1567                 /* todo: we now store std and name attributes from requests even if
1568                  * they actually refer to the same mesh attributes, optimize */
1569                 foreach(AttributeRequest& req, attributes.requests) {
1570                         Attribute *triangle_mattr = mesh->attributes.find(req);
1571                         Attribute *curve_mattr = mesh->curve_attributes.find(req);
1572                         Attribute *subd_mattr = mesh->subd_attributes.find(req);
1573
1574                         update_attribute_element_offset(mesh,
1575                                                         dscene->attributes_float, attr_float_offset,
1576                                                         dscene->attributes_float3, attr_float3_offset,
1577                                                         dscene->attributes_uchar4, attr_uchar4_offset,
1578                                                         triangle_mattr,
1579                                                         ATTR_PRIM_TRIANGLE,
1580                                                         req.triangle_type,
1581                                                         req.triangle_desc);
1582
1583                         update_attribute_element_offset(mesh,
1584                                                         dscene->attributes_float, attr_float_offset,
1585                                                         dscene->attributes_float3, attr_float3_offset,
1586                                                         dscene->attributes_uchar4, attr_uchar4_offset,
1587                                                         curve_mattr,
1588                                                         ATTR_PRIM_CURVE,
1589                                                         req.curve_type,
1590                                                         req.curve_desc);
1591
1592                         update_attribute_element_offset(mesh,
1593                                                         dscene->attributes_float, attr_float_offset,
1594                                                         dscene->attributes_float3, attr_float3_offset,
1595                                                         dscene->attributes_uchar4, attr_uchar4_offset,
1596                                                         subd_mattr,
1597                                                         ATTR_PRIM_SUBD,
1598                                                         req.subd_type,
1599                                                         req.subd_desc);
1600
1601                         if(progress.get_cancel()) return;
1602                 }
1603         }
1604
1605         /* create attribute lookup maps */
1606         if(scene->shader_manager->use_osl())
1607                 update_osl_attributes(device, scene, mesh_attributes);
1608
1609         update_svm_attributes(device, dscene, scene, mesh_attributes);
1610
1611         if(progress.get_cancel()) return;
1612
1613         /* copy to device */
1614         progress.set_status("Updating Mesh", "Copying Attributes to device");
1615
1616         if(dscene->attributes_float.size()) {
1617                 dscene->attributes_float.copy_to_device();
1618         }
1619         if(dscene->attributes_float3.size()) {
1620                 dscene->attributes_float3.copy_to_device();
1621         }
1622         if(dscene->attributes_uchar4.size()) {
1623                 dscene->attributes_uchar4.copy_to_device();
1624         }
1625
1626         if(progress.get_cancel()) return;
1627
1628         /* After mesh attributes and patch tables have been copied to device memory,
1629          * we need to update offsets in the objects. */
1630         scene->object_manager->device_update_mesh_offsets(device, dscene, scene);
1631 }
1632
1633 void MeshManager::mesh_calc_offset(Scene *scene)
1634 {
1635         size_t vert_size = 0;
1636         size_t tri_size = 0;
1637
1638         size_t curve_key_size = 0;
1639         size_t curve_size = 0;
1640
1641         size_t patch_size = 0;
1642         size_t face_size = 0;
1643         size_t corner_size = 0;
1644
1645         foreach(Mesh *mesh, scene->meshes) {
1646                 mesh->vert_offset = vert_size;
1647                 mesh->tri_offset = tri_size;
1648
1649                 mesh->curvekey_offset = curve_key_size;
1650                 mesh->curve_offset = curve_size;
1651
1652                 mesh->patch_offset = patch_size;
1653                 mesh->face_offset = face_size;
1654                 mesh->corner_offset = corner_size;
1655
1656                 vert_size += mesh->verts.size();
1657                 tri_size += mesh->num_triangles();
1658
1659                 curve_key_size += mesh->curve_keys.size();
1660                 curve_size += mesh->num_curves();
1661
1662                 if(mesh->subd_faces.size()) {
1663                         Mesh::SubdFace& last = mesh->subd_faces[mesh->subd_faces.size()-1];
1664                         patch_size += (last.ptex_offset + last.num_ptex_faces()) * 8;
1665
1666                         /* patch tables are stored in same array so include them in patch_size */
1667                         if(mesh->patch_table) {
1668                                 mesh->patch_table_offset = patch_size;
1669                                 patch_size += mesh->patch_table->total_size();
1670                         }
1671                 }
1672                 face_size += mesh->subd_faces.size();
1673                 corner_size += mesh->subd_face_corners.size();
1674         }
1675 }
1676
1677 void MeshManager::device_update_mesh(Device *,
1678                                      DeviceScene *dscene,
1679                                      Scene *scene,
1680                                      bool for_displacement,
1681                                      Progress& progress)
1682 {
1683         /* Count. */
1684         size_t vert_size = 0;
1685         size_t tri_size = 0;
1686
1687         size_t curve_key_size = 0;
1688         size_t curve_size = 0;
1689
1690         size_t patch_size = 0;
1691
1692         foreach(Mesh *mesh, scene->meshes) {
1693                 vert_size += mesh->verts.size();
1694                 tri_size += mesh->num_triangles();
1695
1696                 curve_key_size += mesh->curve_keys.size();
1697                 curve_size += mesh->num_curves();
1698
1699                 if(mesh->subd_faces.size()) {
1700                         Mesh::SubdFace& last = mesh->subd_faces[mesh->subd_faces.size()-1];
1701                         patch_size += (last.ptex_offset + last.num_ptex_faces()) * 8;
1702
1703                         /* patch tables are stored in same array so include them in patch_size */
1704                         if(mesh->patch_table) {
1705                                 mesh->patch_table_offset = patch_size;
1706                                 patch_size += mesh->patch_table->total_size();
1707                         }
1708                 }
1709         }
1710
1711         /* Create mapping from triangle to primitive triangle array. */
1712         vector<uint> tri_prim_index(tri_size);
1713         if(for_displacement) {
1714                 /* For displacement kernels we do some trickery to make them believe
1715                  * we've got all required data ready. However, that data is different
1716                  * from final render kernels since we don't have BVH yet, so can't
1717                  * really use same semantic of arrays.
1718                  */
1719                 foreach(Mesh *mesh, scene->meshes) {
1720                         for(size_t i = 0; i < mesh->num_triangles(); ++i) {
1721                                 tri_prim_index[i + mesh->tri_offset] = 3 * (i + mesh->tri_offset);
1722                         }
1723                 }
1724         }
1725         else {
1726                 for(size_t i = 0; i < dscene->prim_index.size(); ++i) {
1727                         if((dscene->prim_type[i] & PRIMITIVE_ALL_TRIANGLE) != 0) {
1728                                 tri_prim_index[dscene->prim_index[i]] = dscene->prim_tri_index[i];
1729                         }
1730                 }
1731         }
1732
1733         /* Fill in all the arrays. */
1734         if(tri_size != 0) {
1735                 /* normals */
1736                 progress.set_status("Updating Mesh", "Computing normals");
1737
1738                 uint *tri_shader = dscene->tri_shader.alloc(tri_size);
1739                 float4 *vnormal = dscene->tri_vnormal.alloc(vert_size);
1740                 uint4 *tri_vindex = dscene->tri_vindex.alloc(tri_size);
1741                 uint *tri_patch = dscene->tri_patch.alloc(tri_size);
1742                 float2 *tri_patch_uv = dscene->tri_patch_uv.alloc(vert_size);
1743
1744                 foreach(Mesh *mesh, scene->meshes) {
1745                         mesh->pack_normals(scene,
1746                                            &tri_shader[mesh->tri_offset],
1747                                            &vnormal[mesh->vert_offset]);
1748                         mesh->pack_verts(tri_prim_index,
1749                                          &tri_vindex[mesh->tri_offset],
1750                                          &tri_patch[mesh->tri_offset],
1751                                          &tri_patch_uv[mesh->vert_offset],
1752                                          mesh->vert_offset,
1753                                          mesh->tri_offset);
1754                         if(progress.get_cancel()) return;
1755                 }
1756
1757                 /* vertex coordinates */
1758                 progress.set_status("Updating Mesh", "Copying Mesh to device");
1759
1760                 dscene->tri_shader.copy_to_device();
1761                 dscene->tri_vnormal.copy_to_device();
1762                 dscene->tri_vindex.copy_to_device();
1763                 dscene->tri_patch.copy_to_device();
1764                 dscene->tri_patch_uv.copy_to_device();
1765         }
1766
1767         if(curve_size != 0) {
1768                 progress.set_status("Updating Mesh", "Copying Strands to device");
1769
1770                 float4 *curve_keys = dscene->curve_keys.alloc(curve_key_size);
1771                 float4 *curves = dscene->curves.alloc(curve_size);
1772
1773                 foreach(Mesh *mesh, scene->meshes) {
1774                         mesh->pack_curves(scene, &curve_keys[mesh->curvekey_offset], &curves[mesh->curve_offset], mesh->curvekey_offset);
1775                         if(progress.get_cancel()) return;
1776                 }
1777
1778                 dscene->curve_keys.copy_to_device();
1779                 dscene->curves.copy_to_device();
1780         }
1781
1782         if(patch_size != 0) {
1783                 progress.set_status("Updating Mesh", "Copying Patches to device");
1784
1785                 uint *patch_data = dscene->patches.alloc(patch_size);
1786
1787                 foreach(Mesh *mesh, scene->meshes) {
1788                         mesh->pack_patches(&patch_data[mesh->patch_offset], mesh->vert_offset, mesh->face_offset, mesh->corner_offset);
1789
1790                         if(mesh->patch_table) {
1791                                 mesh->patch_table->copy_adjusting_offsets(&patch_data[mesh->patch_table_offset], mesh->patch_table_offset);
1792                         }
1793
1794                         if(progress.get_cancel()) return;
1795                 }
1796
1797                 dscene->patches.copy_to_device();
1798         }
1799
1800         if(for_displacement) {
1801                 float4 *prim_tri_verts = dscene->prim_tri_verts.alloc(tri_size * 3);
1802                 foreach(Mesh *mesh, scene->meshes) {
1803                         for(size_t i = 0; i < mesh->num_triangles(); ++i) {
1804                                 Mesh::Triangle t = mesh->get_triangle(i);
1805                                 size_t offset = 3 * (i + mesh->tri_offset);
1806                                 prim_tri_verts[offset + 0] = float3_to_float4(mesh->verts[t.v[0]]);
1807                                 prim_tri_verts[offset + 1] = float3_to_float4(mesh->verts[t.v[1]]);
1808                                 prim_tri_verts[offset + 2] = float3_to_float4(mesh->verts[t.v[2]]);
1809                         }
1810                 }
1811                 dscene->prim_tri_verts.copy_to_device();
1812         }
1813 }
1814
1815 void MeshManager::device_update_bvh(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
1816 {
1817         /* bvh build */
1818         progress.set_status("Updating Scene BVH", "Building");
1819
1820         BVHParams bparams;
1821         bparams.top_level = true;
1822         bparams.bvh_layout = BVHParams::best_bvh_layout(
1823                 scene->params.bvh_layout,
1824                 device->info.bvh_layout_mask);
1825         bparams.use_spatial_split = scene->params.use_bvh_spatial_split;
1826         bparams.use_unaligned_nodes = dscene->data.bvh.have_curves &&
1827                                       scene->params.use_bvh_unaligned_nodes;
1828         bparams.num_motion_triangle_steps = scene->params.num_bvh_time_steps;
1829         bparams.num_motion_curve_steps = scene->params.num_bvh_time_steps;
1830
1831         VLOG(1) << "Using " << bvh_layout_name(bparams.bvh_layout)
1832                 << " layout.";
1833
1834         BVH *bvh = BVH::create(bparams, scene->objects);
1835         bvh->build(progress);
1836
1837         if(progress.get_cancel()) {
1838                 delete bvh;
1839                 return;
1840         }
1841
1842         /* copy to device */
1843         progress.set_status("Updating Scene BVH", "Copying BVH to device");
1844
1845         PackedBVH& pack = bvh->pack;
1846
1847         if(pack.nodes.size()) {
1848                 dscene->bvh_nodes.steal_data(pack.nodes);
1849                 dscene->bvh_nodes.copy_to_device();
1850         }
1851         if(pack.leaf_nodes.size()) {
1852                 dscene->bvh_leaf_nodes.steal_data(pack.leaf_nodes);
1853                 dscene->bvh_leaf_nodes.copy_to_device();
1854         }
1855         if(pack.object_node.size()) {
1856                 dscene->object_node.steal_data(pack.object_node);
1857                 dscene->object_node.copy_to_device();
1858         }
1859         if(pack.prim_tri_index.size()) {
1860                 dscene->prim_tri_index.steal_data(pack.prim_tri_index);
1861                 dscene->prim_tri_index.copy_to_device();
1862         }
1863         if(pack.prim_tri_verts.size()) {
1864                 dscene->prim_tri_verts.steal_data(pack.prim_tri_verts);
1865                 dscene->prim_tri_verts.copy_to_device();
1866         }
1867         if(pack.prim_type.size()) {
1868                 dscene->prim_type.steal_data(pack.prim_type);
1869                 dscene->prim_type.copy_to_device();
1870         }
1871         if(pack.prim_visibility.size()) {
1872                 dscene->prim_visibility.steal_data(pack.prim_visibility);
1873                 dscene->prim_visibility.copy_to_device();
1874         }
1875         if(pack.prim_index.size()) {
1876                 dscene->prim_index.steal_data(pack.prim_index);
1877                 dscene->prim_index.copy_to_device();
1878         }
1879         if(pack.prim_object.size()) {
1880                 dscene->prim_object.steal_data(pack.prim_object);
1881                 dscene->prim_object.copy_to_device();
1882         }
1883         if(pack.prim_time.size()) {
1884                 dscene->prim_time.steal_data(pack.prim_time);
1885                 dscene->prim_time.copy_to_device();
1886         }
1887
1888         dscene->data.bvh.root = pack.root_index;
1889         dscene->data.bvh.bvh_layout = bparams.bvh_layout;
1890         dscene->data.bvh.use_bvh_steps = (scene->params.num_bvh_time_steps != 0);
1891
1892         delete bvh;
1893 }
1894
1895 void MeshManager::device_update_flags(Device * /*device*/,
1896                                       DeviceScene * /*dscene*/,
1897                                       Scene * scene,
1898                                       Progress& /*progress*/)
1899 {
1900         if(!need_update && !need_flags_update) {
1901                 return;
1902         }
1903         /* update flags */
1904         foreach(Mesh *mesh, scene->meshes) {
1905                 mesh->has_volume = false;
1906                 foreach(const Shader *shader, mesh->used_shaders) {
1907                         if(shader->has_volume) {
1908                                 mesh->has_volume = true;
1909                         }
1910                         if(shader->has_surface_bssrdf) {
1911                                 mesh->has_surface_bssrdf = true;
1912                         }
1913                 }
1914         }
1915         need_flags_update = false;
1916 }
1917
1918 void MeshManager::device_update_displacement_images(Device *device,
1919                                                     Scene *scene,
1920                                                     Progress& progress)
1921 {
1922         progress.set_status("Updating Displacement Images");
1923         TaskPool pool;
1924         ImageManager *image_manager = scene->image_manager;
1925         set<int> bump_images;
1926         foreach(Mesh *mesh, scene->meshes) {
1927                 if(mesh->need_update) {
1928                         foreach(Shader *shader, mesh->used_shaders) {
1929                                 if(!shader->has_displacement || shader->displacement_method == DISPLACE_BUMP) {
1930                                         continue;
1931                                 }
1932                                 foreach(ShaderNode* node, shader->graph->nodes) {
1933                                         if(node->special_type != SHADER_SPECIAL_TYPE_IMAGE_SLOT) {
1934                                                 continue;
1935                                         }
1936
1937                                         ImageSlotTextureNode *image_node = static_cast<ImageSlotTextureNode*>(node);
1938                                         int slot = image_node->slot;
1939                                         if(slot != -1) {
1940                                                 bump_images.insert(slot);
1941                                         }
1942                                 }
1943                         }
1944                 }
1945         }
1946         foreach(int slot, bump_images) {
1947                 pool.push(function_bind(&ImageManager::device_update_slot,
1948                                         image_manager,
1949                                         device,
1950                                         scene,
1951                                         slot,
1952                                         &progress));
1953         }
1954         pool.wait_work();
1955 }
1956
1957 void MeshManager::device_update(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
1958 {
1959         if(!need_update)
1960                 return;
1961
1962         VLOG(1) << "Total " << scene->meshes.size() << " meshes.";
1963
1964         /* Update normals. */
1965         foreach(Mesh *mesh, scene->meshes) {
1966                 foreach(Shader *shader, mesh->used_shaders) {
1967                         if(shader->need_update_mesh)
1968                                 mesh->need_update = true;
1969                 }
1970
1971                 if(mesh->need_update) {
1972                         mesh->add_face_normals();
1973                         mesh->add_vertex_normals();
1974
1975                         if(mesh->need_attribute(scene, ATTR_STD_POSITION_UNDISPLACED)) {
1976                                 mesh->add_undisplaced();
1977                         }
1978
1979                         if(progress.get_cancel()) return;
1980                 }
1981         }
1982
1983         /* Tessellate meshes that are using subdivision */
1984         size_t total_tess_needed = 0;
1985         foreach(Mesh *mesh, scene->meshes) {
1986                 if(mesh->need_update &&
1987                    mesh->subdivision_type != Mesh::SUBDIVISION_NONE &&
1988                    mesh->num_subd_verts == 0 &&
1989                    mesh->subd_params)
1990                 {
1991                         total_tess_needed++;
1992                 }
1993         }
1994
1995         size_t i = 0;
1996         foreach(Mesh *mesh, scene->meshes) {
1997                 if(mesh->need_update &&
1998                    mesh->subdivision_type != Mesh::SUBDIVISION_NONE &&
1999                    mesh->num_subd_verts == 0 &&
2000                    mesh->subd_params)
2001                 {
2002                         string msg = "Tessellating ";
2003                         if(mesh->name == "")
2004                                 msg += string_printf("%u/%u", (uint)(i+1), (uint)total_tess_needed);
2005                         else
2006                                 msg += string_printf("%s %u/%u", mesh->name.c_str(), (uint)(i+1), (uint)total_tess_needed);
2007
2008                         progress.set_status("Updating Mesh", msg);
2009
2010                         DiagSplit dsplit(*mesh->subd_params);
2011                         mesh->tessellate(&dsplit);
2012
2013                         i++;
2014
2015                         if(progress.get_cancel()) return;
2016                 }
2017         }
2018
2019         /* Update images needed for true displacement. */
2020         bool true_displacement_used = false;
2021         bool old_need_object_flags_update = false;
2022         foreach(Mesh *mesh, scene->meshes) {
2023                 if(mesh->need_update &&
2024                    mesh->has_true_displacement())
2025                 {
2026                         true_displacement_used = true;
2027                         break;
2028                 }
2029         }
2030         if(true_displacement_used) {
2031                 VLOG(1) << "Updating images used for true displacement.";
2032                 device_update_displacement_images(device, scene, progress);
2033                 old_need_object_flags_update = scene->object_manager->need_flags_update;
2034                 scene->object_manager->device_update_flags(device,
2035                                                            dscene,
2036                                                            scene,
2037                                                            progress,
2038                                                            false);
2039         }
2040
2041         /* Device update. */
2042         device_free(device, dscene);
2043
2044         mesh_calc_offset(scene);
2045         if(true_displacement_used) {
2046                 device_update_mesh(device, dscene, scene, true, progress);
2047         }
2048         if(progress.get_cancel()) return;
2049
2050         device_update_attributes(device, dscene, scene, progress);
2051         if(progress.get_cancel()) return;
2052
2053         /* Update displacement. */
2054         bool displacement_done = false;
2055         foreach(Mesh *mesh, scene->meshes) {
2056                 if(mesh->need_update &&
2057                    displace(device, dscene, scene, mesh, progress))
2058                 {
2059                         displacement_done = true;
2060                 }
2061         }
2062
2063         /* TODO: properly handle cancel halfway displacement */
2064         if(progress.get_cancel()) return;
2065
2066         /* Device re-update after displacement. */
2067         if(displacement_done) {
2068                 device_free(device, dscene);
2069
2070                 device_update_attributes(device, dscene, scene, progress);
2071                 if(progress.get_cancel()) return;
2072         }
2073
2074         /* Update bvh. */
2075         size_t num_bvh = 0;
2076         foreach(Mesh *mesh, scene->meshes) {
2077                 if(mesh->need_update && mesh->need_build_bvh()) {
2078                         num_bvh++;
2079                 }
2080         }
2081
2082         TaskPool pool;
2083
2084         i = 0;
2085         foreach(Mesh *mesh, scene->meshes) {
2086                 if(mesh->need_update) {
2087                         pool.push(function_bind(&Mesh::compute_bvh,
2088                                                 mesh,
2089                                                 device,
2090                                                 dscene,
2091                                                 &scene->params,
2092                                                 &progress,
2093                                                 i,
2094                                                 num_bvh));
2095                         if(mesh->need_build_bvh()) {
2096                                 i++;
2097                         }
2098                 }
2099         }
2100
2101         TaskPool::Summary summary;
2102         pool.wait_work(&summary);
2103         VLOG(2) << "Objects BVH build pool statistics:\n"
2104                 << summary.full_report();
2105
2106         foreach(Shader *shader, scene->shaders) {
2107                 shader->need_update_mesh = false;
2108         }
2109
2110         Scene::MotionType need_motion = scene->need_motion();
2111         bool motion_blur = need_motion == Scene::MOTION_BLUR;
2112
2113         /* Update objects. */
2114         vector<Object *> volume_objects;
2115         foreach(Object *object, scene->objects) {
2116                 object->compute_bounds(motion_blur);
2117         }
2118
2119         if(progress.get_cancel()) return;
2120
2121         device_update_bvh(device, dscene, scene, progress);
2122         if(progress.get_cancel()) return;
2123
2124         device_update_mesh(device, dscene, scene, false, progress);
2125         if(progress.get_cancel()) return;
2126
2127         need_update = false;
2128
2129         if(true_displacement_used) {
2130                 /* Re-tag flags for update, so they're re-evaluated
2131                  * for meshes with correct bounding boxes.
2132                  *
2133                  * This wouldn't cause wrong results, just true
2134                  * displacement might be less optimal ot calculate.
2135                  */
2136                 scene->object_manager->need_flags_update = old_need_object_flags_update;
2137         }
2138 }
2139
2140 void MeshManager::device_free(Device *device, DeviceScene *dscene)
2141 {
2142         dscene->bvh_nodes.free();
2143         dscene->bvh_leaf_nodes.free();
2144         dscene->object_node.free();
2145         dscene->prim_tri_verts.free();
2146         dscene->prim_tri_index.free();
2147         dscene->prim_type.free();
2148         dscene->prim_visibility.free();
2149         dscene->prim_index.free();
2150         dscene->prim_object.free();
2151         dscene->prim_time.free();
2152         dscene->tri_shader.free();
2153         dscene->tri_vnormal.free();
2154         dscene->tri_vindex.free();
2155         dscene->tri_patch.free();
2156         dscene->tri_patch_uv.free();
2157         dscene->curves.free();
2158         dscene->curve_keys.free();
2159         dscene->patches.free();
2160         dscene->attributes_map.free();
2161         dscene->attributes_float.free();
2162         dscene->attributes_float3.free();
2163         dscene->attributes_uchar4.free();
2164
2165 #ifdef WITH_OSL
2166         OSLGlobals *og = (OSLGlobals*)device->osl_memory();
2167
2168         if(og) {
2169                 og->object_name_map.clear();
2170                 og->attribute_map.clear();
2171                 og->object_names.clear();
2172         }
2173 #else
2174         (void)device;
2175 #endif
2176 }
2177
2178 void MeshManager::tag_update(Scene *scene)
2179 {
2180         need_update = true;
2181         scene->object_manager->need_update = true;
2182 }
2183
2184 bool Mesh::need_attribute(Scene *scene, AttributeStandard std)
2185 {
2186         if(std == ATTR_STD_NONE)
2187                 return false;
2188
2189         if(scene->need_global_attribute(std))
2190                 return true;
2191
2192         foreach(Shader *shader, used_shaders)
2193                 if(shader->attributes.find(std))
2194                         return true;
2195
2196         return false;
2197 }
2198
2199 bool Mesh::need_attribute(Scene * /*scene*/, ustring name)
2200 {
2201         if(name == ustring())
2202                 return false;
2203
2204         foreach(Shader *shader, used_shaders)
2205                 if(shader->attributes.find(name))
2206                         return true;
2207
2208         return false;
2209 }
2210
2211 CCL_NAMESPACE_END