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