Cycles: Add option to split triangle motion primitives by time steps
[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_triangle_steps = params->num_bvh_time_steps;
1057                         bparams.num_motion_curve_steps = params->num_bvh_time_steps;
1058
1059                         delete bvh;
1060                         bvh = BVH::create(bparams, objects);
1061                         MEM_GUARDED_CALL(progress, bvh->build, *progress);
1062                 }
1063         }
1064
1065         need_update = false;
1066         need_update_rebuild = false;
1067 }
1068
1069 void Mesh::tag_update(Scene *scene, bool rebuild)
1070 {
1071         need_update = true;
1072
1073         if(rebuild) {
1074                 need_update_rebuild = true;
1075                 scene->light_manager->need_update = true;
1076         }
1077         else {
1078                 foreach(Shader *shader, used_shaders)
1079                         if(shader->has_surface_emission)
1080                                 scene->light_manager->need_update = true;
1081         }
1082
1083         scene->mesh_manager->need_update = true;
1084         scene->object_manager->need_update = true;
1085 }
1086
1087 bool Mesh::has_motion_blur() const
1088 {
1089         return (use_motion_blur &&
1090                 (attributes.find(ATTR_STD_MOTION_VERTEX_POSITION) ||
1091                  curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION)));
1092 }
1093
1094 bool Mesh::has_true_displacement() const
1095 {
1096         foreach(Shader *shader, used_shaders) {
1097                 if(shader->has_displacement && shader->displacement_method != DISPLACE_BUMP) {
1098                         return true;
1099                 }
1100         }
1101
1102         return false;
1103 }
1104
1105 bool Mesh::need_build_bvh() const
1106 {
1107         return !transform_applied || has_surface_bssrdf;
1108 }
1109
1110 bool Mesh::is_instanced() const
1111 {
1112         /* Currently we treat subsurface objects as instanced.
1113          *
1114          * While it might be not very optimal for ray traversal, it avoids having
1115          * duplicated BVH in the memory, saving quite some space.
1116          */
1117         return !transform_applied || has_surface_bssrdf;
1118 }
1119
1120 /* Mesh Manager */
1121
1122 MeshManager::MeshManager()
1123 {
1124         bvh = NULL;
1125         need_update = true;
1126         need_flags_update = true;
1127 }
1128
1129 MeshManager::~MeshManager()
1130 {
1131         delete bvh;
1132 }
1133
1134 void MeshManager::update_osl_attributes(Device *device, Scene *scene, vector<AttributeRequestSet>& mesh_attributes)
1135 {
1136 #ifdef WITH_OSL
1137         /* for OSL, a hash map is used to lookup the attribute by name. */
1138         OSLGlobals *og = (OSLGlobals*)device->osl_memory();
1139
1140         og->object_name_map.clear();
1141         og->attribute_map.clear();
1142         og->object_names.clear();
1143
1144         og->attribute_map.resize(scene->objects.size()*ATTR_PRIM_TYPES);
1145
1146         for(size_t i = 0; i < scene->objects.size(); i++) {
1147                 /* set object name to object index map */
1148                 Object *object = scene->objects[i];
1149                 og->object_name_map[object->name] = i;
1150                 og->object_names.push_back(object->name);
1151
1152                 /* set object attributes */
1153                 foreach(ParamValue& attr, object->attributes) {
1154                         OSLGlobals::Attribute osl_attr;
1155
1156                         osl_attr.type = attr.type();
1157                         osl_attr.desc.element = ATTR_ELEMENT_OBJECT;
1158                         osl_attr.value = attr;
1159                         osl_attr.desc.offset = 0;
1160                         osl_attr.desc.flags = 0;
1161
1162                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_TRIANGLE][attr.name()] = osl_attr;
1163                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][attr.name()] = osl_attr;
1164                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_SUBD][attr.name()] = osl_attr;
1165                 }
1166
1167                 /* find mesh attributes */
1168                 size_t j;
1169
1170                 for(j = 0; j < scene->meshes.size(); j++)
1171                         if(scene->meshes[j] == object->mesh)
1172                                 break;
1173
1174                 AttributeRequestSet& attributes = mesh_attributes[j];
1175
1176                 /* set object attributes */
1177                 foreach(AttributeRequest& req, attributes.requests) {
1178                         OSLGlobals::Attribute osl_attr;
1179
1180                         if(req.triangle_desc.element != ATTR_ELEMENT_NONE) {
1181                                 osl_attr.desc = req.triangle_desc;
1182
1183                                 if(req.triangle_type == TypeDesc::TypeFloat)
1184                                         osl_attr.type = TypeDesc::TypeFloat;
1185                                 else if(req.triangle_type == TypeDesc::TypeMatrix)
1186                                         osl_attr.type = TypeDesc::TypeMatrix;
1187                                 else
1188                                         osl_attr.type = TypeDesc::TypeColor;
1189
1190                                 if(req.std != ATTR_STD_NONE) {
1191                                         /* if standard attribute, add lookup by geom: name convention */
1192                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
1193                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_TRIANGLE][stdname] = osl_attr;
1194                                 }
1195                                 else if(req.name != ustring()) {
1196                                         /* add lookup by mesh attribute name */
1197                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_TRIANGLE][req.name] = osl_attr;
1198                                 }
1199                         }
1200
1201                         if(req.curve_desc.element != ATTR_ELEMENT_NONE) {
1202                                 osl_attr.desc = req.curve_desc;
1203
1204                                 if(req.curve_type == TypeDesc::TypeFloat)
1205                                         osl_attr.type = TypeDesc::TypeFloat;
1206                                 else if(req.curve_type == TypeDesc::TypeMatrix)
1207                                         osl_attr.type = TypeDesc::TypeMatrix;
1208                                 else
1209                                         osl_attr.type = TypeDesc::TypeColor;
1210
1211                                 if(req.std != ATTR_STD_NONE) {
1212                                         /* if standard attribute, add lookup by geom: name convention */
1213                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
1214                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][stdname] = osl_attr;
1215                                 }
1216                                 else if(req.name != ustring()) {
1217                                         /* add lookup by mesh attribute name */
1218                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][req.name] = osl_attr;
1219                                 }
1220                         }
1221
1222                         if(req.subd_desc.element != ATTR_ELEMENT_NONE) {
1223                                 osl_attr.desc = req.subd_desc;
1224
1225                                 if(req.subd_type == TypeDesc::TypeFloat)
1226                                         osl_attr.type = TypeDesc::TypeFloat;
1227                                 else if(req.subd_type == TypeDesc::TypeMatrix)
1228                                         osl_attr.type = TypeDesc::TypeMatrix;
1229                                 else
1230                                         osl_attr.type = TypeDesc::TypeColor;
1231
1232                                 if(req.std != ATTR_STD_NONE) {
1233                                         /* if standard attribute, add lookup by geom: name convention */
1234                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
1235                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_SUBD][stdname] = osl_attr;
1236                                 }
1237                                 else if(req.name != ustring()) {
1238                                         /* add lookup by mesh attribute name */
1239                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_SUBD][req.name] = osl_attr;
1240                                 }
1241                         }
1242                 }
1243         }
1244 #else
1245         (void)device;
1246         (void)scene;
1247         (void)mesh_attributes;
1248 #endif
1249 }
1250
1251 void MeshManager::update_svm_attributes(Device *device, DeviceScene *dscene, Scene *scene, vector<AttributeRequestSet>& mesh_attributes)
1252 {
1253         /* for SVM, the attributes_map table is used to lookup the offset of an
1254          * attribute, based on a unique shader attribute id. */
1255
1256         /* compute array stride */
1257         int attr_map_stride = 0;
1258
1259         for(size_t i = 0; i < scene->meshes.size(); i++)
1260                 attr_map_stride = max(attr_map_stride, (mesh_attributes[i].size() + 1)*ATTR_PRIM_TYPES);
1261
1262         if(attr_map_stride == 0)
1263                 return;
1264
1265         /* create attribute map */
1266         uint4 *attr_map = dscene->attributes_map.resize(attr_map_stride*scene->objects.size());
1267         memset(attr_map, 0, dscene->attributes_map.size()*sizeof(uint));
1268
1269         for(size_t i = 0; i < scene->objects.size(); i++) {
1270                 Object *object = scene->objects[i];
1271                 Mesh *mesh = object->mesh;
1272
1273                 /* find mesh attributes */
1274                 size_t j;
1275
1276                 for(j = 0; j < scene->meshes.size(); j++)
1277                         if(scene->meshes[j] == mesh)
1278                                 break;
1279
1280                 AttributeRequestSet& attributes = mesh_attributes[j];
1281
1282                 /* set object attributes */
1283                 int index = i*attr_map_stride;
1284
1285                 foreach(AttributeRequest& req, attributes.requests) {
1286                         uint id;
1287
1288                         if(req.std == ATTR_STD_NONE)
1289                                 id = scene->shader_manager->get_attribute_id(req.name);
1290                         else
1291                                 id = scene->shader_manager->get_attribute_id(req.std);
1292
1293                         if(mesh->num_triangles()) {
1294                                 attr_map[index].x = id;
1295                                 attr_map[index].y = req.triangle_desc.element;
1296                                 attr_map[index].z = as_uint(req.triangle_desc.offset);
1297
1298                                 if(req.triangle_type == TypeDesc::TypeFloat)
1299                                         attr_map[index].w = NODE_ATTR_FLOAT;
1300                                 else if(req.triangle_type == TypeDesc::TypeMatrix)
1301                                         attr_map[index].w = NODE_ATTR_MATRIX;
1302                                 else
1303                                         attr_map[index].w = NODE_ATTR_FLOAT3;
1304
1305                                 attr_map[index].w |= req.triangle_desc.flags << 8;
1306                         }
1307
1308                         index++;
1309
1310                         if(mesh->num_curves()) {
1311                                 attr_map[index].x = id;
1312                                 attr_map[index].y = req.curve_desc.element;
1313                                 attr_map[index].z = as_uint(req.curve_desc.offset);
1314
1315                                 if(req.curve_type == TypeDesc::TypeFloat)
1316                                         attr_map[index].w = NODE_ATTR_FLOAT;
1317                                 else if(req.curve_type == TypeDesc::TypeMatrix)
1318                                         attr_map[index].w = NODE_ATTR_MATRIX;
1319                                 else
1320                                         attr_map[index].w = NODE_ATTR_FLOAT3;
1321
1322                                 attr_map[index].w |= req.curve_desc.flags << 8;
1323                         }
1324
1325                         index++;
1326
1327                         if(mesh->subd_faces.size()) {
1328                                 attr_map[index].x = id;
1329                                 attr_map[index].y = req.subd_desc.element;
1330                                 attr_map[index].z = as_uint(req.subd_desc.offset);
1331
1332                                 if(req.subd_type == TypeDesc::TypeFloat)
1333                                         attr_map[index].w = NODE_ATTR_FLOAT;
1334                                 else if(req.subd_type == TypeDesc::TypeMatrix)
1335                                         attr_map[index].w = NODE_ATTR_MATRIX;
1336                                 else
1337                                         attr_map[index].w = NODE_ATTR_FLOAT3;
1338
1339                                 attr_map[index].w |= req.subd_desc.flags << 8;
1340                         }
1341
1342                         index++;
1343                 }
1344
1345                 /* terminator */
1346                 for(int j = 0; j < ATTR_PRIM_TYPES; j++) {
1347                         attr_map[index].x = ATTR_STD_NONE;
1348                         attr_map[index].y = 0;
1349                         attr_map[index].z = 0;
1350                         attr_map[index].w = 0;
1351
1352                         index++;
1353                 }
1354         }
1355
1356         /* copy to device */
1357         dscene->data.bvh.attributes_map_stride = attr_map_stride;
1358         device->tex_alloc("__attributes_map", dscene->attributes_map);
1359 }
1360
1361 static void update_attribute_element_size(Mesh *mesh,
1362                                           Attribute *mattr,
1363                                           AttributePrimitive prim,
1364                                           size_t *attr_float_size,
1365                                           size_t *attr_float3_size,
1366                                           size_t *attr_uchar4_size)
1367 {
1368         if(mattr) {
1369                 size_t size = mattr->element_size(mesh, prim);
1370
1371                 if(mattr->element == ATTR_ELEMENT_VOXEL) {
1372                         /* pass */
1373                 }
1374                 else if(mattr->element == ATTR_ELEMENT_CORNER_BYTE) {
1375                         *attr_uchar4_size += size;
1376                 }
1377                 else if(mattr->type == TypeDesc::TypeFloat) {
1378                         *attr_float_size += size;
1379                 }
1380                 else if(mattr->type == TypeDesc::TypeMatrix) {
1381                         *attr_float3_size += size * 4;
1382                 }
1383                 else {
1384                         *attr_float3_size += size;
1385                 }
1386         }
1387 }
1388
1389 static void update_attribute_element_offset(Mesh *mesh,
1390                                             vector<float>& attr_float,
1391                                             size_t& attr_float_offset,
1392                                             vector<float4>& attr_float3,
1393                                             size_t& attr_float3_offset,
1394                                             vector<uchar4>& attr_uchar4,
1395                                             size_t& attr_uchar4_offset,
1396                                             Attribute *mattr,
1397                                             AttributePrimitive prim,
1398                                             TypeDesc& type,
1399                                             AttributeDescriptor& desc)
1400 {
1401         if(mattr) {
1402                 /* store element and type */
1403                 desc.element = mattr->element;
1404                 desc.flags = mattr->flags;
1405                 type = mattr->type;
1406
1407                 /* store attribute data in arrays */
1408                 size_t size = mattr->element_size(mesh, prim);
1409
1410                 AttributeElement& element = desc.element;
1411                 int& offset = desc.offset;
1412
1413                 if(mattr->element == ATTR_ELEMENT_VOXEL) {
1414                         /* store slot in offset value */
1415                         VoxelAttribute *voxel_data = mattr->data_voxel();
1416                         offset = voxel_data->slot;
1417                 }
1418                 else if(mattr->element == ATTR_ELEMENT_CORNER_BYTE) {
1419                         uchar4 *data = mattr->data_uchar4();
1420                         offset = attr_uchar4_offset;
1421
1422                         assert(attr_uchar4.capacity() >= offset + size);
1423                         for(size_t k = 0; k < size; k++) {
1424                                 attr_uchar4[offset+k] = data[k];
1425                         }
1426                         attr_uchar4_offset += size;
1427                 }
1428                 else if(mattr->type == TypeDesc::TypeFloat) {
1429                         float *data = mattr->data_float();
1430                         offset = attr_float_offset;
1431
1432                         assert(attr_float.capacity() >= offset + size);
1433                         for(size_t k = 0; k < size; k++) {
1434                                 attr_float[offset+k] = data[k];
1435                         }
1436                         attr_float_offset += size;
1437                 }
1438                 else if(mattr->type == TypeDesc::TypeMatrix) {
1439                         Transform *tfm = mattr->data_transform();
1440                         offset = attr_float3_offset;
1441
1442                         assert(attr_float3.capacity() >= offset + size * 4);
1443                         for(size_t k = 0; k < size*4; k++) {
1444                                 attr_float3[offset+k] = (&tfm->x)[k];
1445                         }
1446                         attr_float3_offset += size * 4;
1447                 }
1448                 else {
1449                         float4 *data = mattr->data_float4();
1450                         offset = attr_float3_offset;
1451
1452                         assert(attr_float3.capacity() >= offset + size);
1453                         for(size_t k = 0; k < size; k++) {
1454                                 attr_float3[offset+k] = data[k];
1455                         }
1456                         attr_float3_offset += size;
1457                 }
1458
1459                 /* mesh vertex/curve index is global, not per object, so we sneak
1460                  * a correction for that in here */
1461                 if(mesh->subdivision_type == Mesh::SUBDIVISION_CATMULL_CLARK && desc.flags & ATTR_SUBDIVIDED) {
1462                         /* indices for subdivided attributes are retrieved
1463                          * from patch table so no need for correction here*/
1464                 }
1465                 else if(element == ATTR_ELEMENT_VERTEX)
1466                         offset -= mesh->vert_offset;
1467                 else if(element == ATTR_ELEMENT_VERTEX_MOTION)
1468                         offset -= mesh->vert_offset;
1469                 else if(element == ATTR_ELEMENT_FACE) {
1470                         if(prim == ATTR_PRIM_TRIANGLE)
1471                                 offset -= mesh->tri_offset;
1472                         else
1473                                 offset -= mesh->face_offset;
1474                 }
1475                 else if(element == ATTR_ELEMENT_CORNER || element == ATTR_ELEMENT_CORNER_BYTE) {
1476                         if(prim == ATTR_PRIM_TRIANGLE)
1477                                 offset -= 3*mesh->tri_offset;
1478                         else
1479                                 offset -= mesh->corner_offset;
1480                 }
1481                 else if(element == ATTR_ELEMENT_CURVE)
1482                         offset -= mesh->curve_offset;
1483                 else if(element == ATTR_ELEMENT_CURVE_KEY)
1484                         offset -= mesh->curvekey_offset;
1485                 else if(element == ATTR_ELEMENT_CURVE_KEY_MOTION)
1486                         offset -= mesh->curvekey_offset;
1487         }
1488         else {
1489                 /* attribute not found */
1490                 desc.element = ATTR_ELEMENT_NONE;
1491                 desc.offset = 0;
1492         }
1493 }
1494
1495 void MeshManager::device_update_attributes(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
1496 {
1497         progress.set_status("Updating Mesh", "Computing attributes");
1498
1499         /* gather per mesh requested attributes. as meshes may have multiple
1500          * shaders assigned, this merges the requested attributes that have
1501          * been set per shader by the shader manager */
1502         vector<AttributeRequestSet> mesh_attributes(scene->meshes.size());
1503
1504         for(size_t i = 0; i < scene->meshes.size(); i++) {
1505                 Mesh *mesh = scene->meshes[i];
1506
1507                 scene->need_global_attributes(mesh_attributes[i]);
1508
1509                 foreach(Shader *shader, mesh->used_shaders) {
1510                         mesh_attributes[i].add(shader->attributes);
1511                 }
1512         }
1513
1514         /* mesh attribute are stored in a single array per data type. here we fill
1515          * those arrays, and set the offset and element type to create attribute
1516          * maps next */
1517
1518         /* Pre-allocate attributes to avoid arrays re-allocation which would
1519          * take 2x of overall attribute memory usage.
1520          */
1521         size_t attr_float_size = 0;
1522         size_t attr_float3_size = 0;
1523         size_t attr_uchar4_size = 0;
1524         for(size_t i = 0; i < scene->meshes.size(); i++) {
1525                 Mesh *mesh = scene->meshes[i];
1526                 AttributeRequestSet& attributes = mesh_attributes[i];
1527                 foreach(AttributeRequest& req, attributes.requests) {
1528                         Attribute *triangle_mattr = mesh->attributes.find(req);
1529                         Attribute *curve_mattr = mesh->curve_attributes.find(req);
1530                         Attribute *subd_mattr = mesh->subd_attributes.find(req);
1531
1532                         update_attribute_element_size(mesh,
1533                                                       triangle_mattr,
1534                                                       ATTR_PRIM_TRIANGLE,
1535                                                       &attr_float_size,
1536                                                       &attr_float3_size,
1537                                                       &attr_uchar4_size);
1538                         update_attribute_element_size(mesh,
1539                                                       curve_mattr,
1540                                                       ATTR_PRIM_CURVE,
1541                                                       &attr_float_size,
1542                                                       &attr_float3_size,
1543                                                       &attr_uchar4_size);
1544                         update_attribute_element_size(mesh,
1545                                                       subd_mattr,
1546                                                       ATTR_PRIM_SUBD,
1547                                                       &attr_float_size,
1548                                                       &attr_float3_size,
1549                                                       &attr_uchar4_size);
1550                 }
1551         }
1552
1553         vector<float> attr_float(attr_float_size);
1554         vector<float4> attr_float3(attr_float3_size);
1555         vector<uchar4> attr_uchar4(attr_uchar4_size);
1556
1557         size_t attr_float_offset = 0;
1558         size_t attr_float3_offset = 0;
1559         size_t attr_uchar4_offset = 0;
1560
1561         /* Fill in attributes. */
1562         for(size_t i = 0; i < scene->meshes.size(); i++) {
1563                 Mesh *mesh = scene->meshes[i];
1564                 AttributeRequestSet& attributes = mesh_attributes[i];
1565
1566                 /* todo: we now store std and name attributes from requests even if
1567                  * they actually refer to the same mesh attributes, optimize */
1568                 foreach(AttributeRequest& req, attributes.requests) {
1569                         Attribute *triangle_mattr = mesh->attributes.find(req);
1570                         Attribute *curve_mattr = mesh->curve_attributes.find(req);
1571                         Attribute *subd_mattr = mesh->subd_attributes.find(req);
1572
1573                         update_attribute_element_offset(mesh,
1574                                                         attr_float, attr_float_offset,
1575                                                         attr_float3, attr_float3_offset,
1576                                                         attr_uchar4, attr_uchar4_offset,
1577                                                         triangle_mattr,
1578                                                         ATTR_PRIM_TRIANGLE,
1579                                                         req.triangle_type,
1580                                                         req.triangle_desc);
1581
1582                         update_attribute_element_offset(mesh,
1583                                                         attr_float, attr_float_offset,
1584                                                         attr_float3, attr_float3_offset,
1585                                                         attr_uchar4, attr_uchar4_offset,
1586                                                         curve_mattr,
1587                                                         ATTR_PRIM_CURVE,
1588                                                         req.curve_type,
1589                                                         req.curve_desc);
1590
1591                         update_attribute_element_offset(mesh,
1592                                                         attr_float, attr_float_offset,
1593                                                         attr_float3, attr_float3_offset,
1594                                                         attr_uchar4, attr_uchar4_offset,
1595                                                         subd_mattr,
1596                                                         ATTR_PRIM_SUBD,
1597                                                         req.subd_type,
1598                                                         req.subd_desc);
1599
1600                         if(progress.get_cancel()) return;
1601                 }
1602         }
1603
1604         /* create attribute lookup maps */
1605         if(scene->shader_manager->use_osl())
1606                 update_osl_attributes(device, scene, mesh_attributes);
1607
1608         update_svm_attributes(device, dscene, scene, mesh_attributes);
1609
1610         if(progress.get_cancel()) return;
1611
1612         /* copy to device */
1613         progress.set_status("Updating Mesh", "Copying Attributes to device");
1614
1615         if(attr_float.size()) {
1616                 dscene->attributes_float.copy(&attr_float[0], attr_float.size());
1617                 device->tex_alloc("__attributes_float", dscene->attributes_float);
1618         }
1619         if(attr_float3.size()) {
1620                 dscene->attributes_float3.copy(&attr_float3[0], attr_float3.size());
1621                 device->tex_alloc("__attributes_float3", dscene->attributes_float3);
1622         }
1623         if(attr_uchar4.size()) {
1624                 dscene->attributes_uchar4.copy(&attr_uchar4[0], attr_uchar4.size());
1625                 device->tex_alloc("__attributes_uchar4", dscene->attributes_uchar4);
1626         }
1627 }
1628
1629 void MeshManager::mesh_calc_offset(Scene *scene)
1630 {
1631         size_t vert_size = 0;
1632         size_t tri_size = 0;
1633
1634         size_t curve_key_size = 0;
1635         size_t curve_size = 0;
1636
1637         size_t patch_size = 0;
1638         size_t face_size = 0;
1639         size_t corner_size = 0;
1640
1641         foreach(Mesh *mesh, scene->meshes) {
1642                 mesh->vert_offset = vert_size;
1643                 mesh->tri_offset = tri_size;
1644
1645                 mesh->curvekey_offset = curve_key_size;
1646                 mesh->curve_offset = curve_size;
1647
1648                 mesh->patch_offset = patch_size;
1649                 mesh->face_offset = face_size;
1650                 mesh->corner_offset = corner_size;
1651
1652                 vert_size += mesh->verts.size();
1653                 tri_size += mesh->num_triangles();
1654
1655                 curve_key_size += mesh->curve_keys.size();
1656                 curve_size += mesh->num_curves();
1657
1658                 if(mesh->subd_faces.size()) {
1659                         Mesh::SubdFace& last = mesh->subd_faces[mesh->subd_faces.size()-1];
1660                         patch_size += (last.ptex_offset + last.num_ptex_faces()) * 8;
1661
1662                         /* patch tables are stored in same array so include them in patch_size */
1663                         if(mesh->patch_table) {
1664                                 mesh->patch_table_offset = patch_size;
1665                                 patch_size += mesh->patch_table->total_size();
1666                         }
1667                 }
1668                 face_size += mesh->subd_faces.size();
1669                 corner_size += mesh->subd_face_corners.size();
1670         }
1671 }
1672
1673 void MeshManager::device_update_mesh(Device *device,
1674                                      DeviceScene *dscene,
1675                                      Scene *scene,
1676                                      bool for_displacement,
1677                                      Progress& progress)
1678 {
1679         /* Count. */
1680         size_t vert_size = 0;
1681         size_t tri_size = 0;
1682
1683         size_t curve_key_size = 0;
1684         size_t curve_size = 0;
1685
1686         size_t patch_size = 0;
1687
1688         foreach(Mesh *mesh, scene->meshes) {
1689                 vert_size += mesh->verts.size();
1690                 tri_size += mesh->num_triangles();
1691
1692                 curve_key_size += mesh->curve_keys.size();
1693                 curve_size += mesh->num_curves();
1694
1695                 if(mesh->subd_faces.size()) {
1696                         Mesh::SubdFace& last = mesh->subd_faces[mesh->subd_faces.size()-1];
1697                         patch_size += (last.ptex_offset + last.num_ptex_faces()) * 8;
1698
1699                         /* patch tables are stored in same array so include them in patch_size */
1700                         if(mesh->patch_table) {
1701                                 mesh->patch_table_offset = patch_size;
1702                                 patch_size += mesh->patch_table->total_size();
1703                         }
1704                 }
1705         }
1706
1707         /* Create mapping from triangle to primitive triangle array. */
1708         vector<uint> tri_prim_index(tri_size);
1709         if(for_displacement) {
1710                 /* For displacement kernels we do some trickery to make them believe
1711                  * we've got all required data ready. However, that data is different
1712                  * from final render kernels since we don't have BVH yet, so can't
1713                  * really use same semantic of arrays.
1714                  */
1715                 foreach(Mesh *mesh, scene->meshes) {
1716                         for(size_t i = 0; i < mesh->num_triangles(); ++i) {
1717                                 tri_prim_index[i + mesh->tri_offset] = 3 * (i + mesh->tri_offset);
1718                         }
1719                 }
1720         }
1721         else {
1722                 PackedBVH& pack = bvh->pack;
1723                 for(size_t i = 0; i < pack.prim_index.size(); ++i) {
1724                         if((pack.prim_type[i] & PRIMITIVE_ALL_TRIANGLE) != 0) {
1725                                 tri_prim_index[pack.prim_index[i]] = pack.prim_tri_index[i];
1726                         }
1727                 }
1728         }
1729
1730         /* Fill in all the arrays. */
1731         if(tri_size != 0) {
1732                 /* normals */
1733                 progress.set_status("Updating Mesh", "Computing normals");
1734
1735                 uint *tri_shader = dscene->tri_shader.resize(tri_size);
1736                 float4 *vnormal = dscene->tri_vnormal.resize(vert_size);
1737                 uint4 *tri_vindex = dscene->tri_vindex.resize(tri_size);
1738                 uint *tri_patch = dscene->tri_patch.resize(tri_size);
1739                 float2 *tri_patch_uv = dscene->tri_patch_uv.resize(vert_size);
1740
1741                 foreach(Mesh *mesh, scene->meshes) {
1742                         mesh->pack_normals(scene,
1743                                            &tri_shader[mesh->tri_offset],
1744                                            &vnormal[mesh->vert_offset]);
1745                         mesh->pack_verts(tri_prim_index,
1746                                          &tri_vindex[mesh->tri_offset],
1747                                          &tri_patch[mesh->tri_offset],
1748                                          &tri_patch_uv[mesh->vert_offset],
1749                                          mesh->vert_offset,
1750                                          mesh->tri_offset);
1751                         if(progress.get_cancel()) return;
1752                 }
1753
1754                 /* vertex coordinates */
1755                 progress.set_status("Updating Mesh", "Copying Mesh to device");
1756
1757                 device->tex_alloc("__tri_shader", dscene->tri_shader);
1758                 device->tex_alloc("__tri_vnormal", dscene->tri_vnormal);
1759                 device->tex_alloc("__tri_vindex", dscene->tri_vindex);
1760                 device->tex_alloc("__tri_patch", dscene->tri_patch);
1761                 device->tex_alloc("__tri_patch_uv", dscene->tri_patch_uv);
1762         }
1763
1764         if(curve_size != 0) {
1765                 progress.set_status("Updating Mesh", "Copying Strands to device");
1766
1767                 float4 *curve_keys = dscene->curve_keys.resize(curve_key_size);
1768                 float4 *curves = dscene->curves.resize(curve_size);
1769
1770                 foreach(Mesh *mesh, scene->meshes) {
1771                         mesh->pack_curves(scene, &curve_keys[mesh->curvekey_offset], &curves[mesh->curve_offset], mesh->curvekey_offset);
1772                         if(progress.get_cancel()) return;
1773                 }
1774
1775                 device->tex_alloc("__curve_keys", dscene->curve_keys);
1776                 device->tex_alloc("__curves", dscene->curves);
1777         }
1778
1779         if(patch_size != 0) {
1780                 progress.set_status("Updating Mesh", "Copying Patches to device");
1781
1782                 uint *patch_data = dscene->patches.resize(patch_size);
1783
1784                 foreach(Mesh *mesh, scene->meshes) {
1785                         mesh->pack_patches(&patch_data[mesh->patch_offset], mesh->vert_offset, mesh->face_offset, mesh->corner_offset);
1786
1787                         if(mesh->patch_table) {
1788                                 mesh->patch_table->copy_adjusting_offsets(&patch_data[mesh->patch_table_offset], mesh->patch_table_offset);
1789                         }
1790
1791                         if(progress.get_cancel()) return;
1792                 }
1793
1794                 device->tex_alloc("__patches", dscene->patches);
1795         }
1796
1797         if(for_displacement) {
1798                 float4 *prim_tri_verts = dscene->prim_tri_verts.resize(tri_size * 3);
1799                 foreach(Mesh *mesh, scene->meshes) {
1800                         for(size_t i = 0; i < mesh->num_triangles(); ++i) {
1801                                 Mesh::Triangle t = mesh->get_triangle(i);
1802                                 size_t offset = 3 * (i + mesh->tri_offset);
1803                                 prim_tri_verts[offset + 0] = float3_to_float4(mesh->verts[t.v[0]]);
1804                                 prim_tri_verts[offset + 1] = float3_to_float4(mesh->verts[t.v[1]]);
1805                                 prim_tri_verts[offset + 2] = float3_to_float4(mesh->verts[t.v[2]]);
1806                         }
1807                 }
1808                 device->tex_alloc("__prim_tri_verts", dscene->prim_tri_verts);
1809         }
1810 }
1811
1812 void MeshManager::device_update_bvh(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
1813 {
1814         /* bvh build */
1815         progress.set_status("Updating Scene BVH", "Building");
1816
1817         VLOG(1) << (scene->params.use_qbvh ? "Using QBVH optimization structure"
1818                                            : "Using regular BVH optimization structure");
1819
1820         BVHParams bparams;
1821         bparams.top_level = true;
1822         bparams.use_qbvh = scene->params.use_qbvh;
1823         bparams.use_spatial_split = scene->params.use_bvh_spatial_split;
1824         bparams.use_unaligned_nodes = dscene->data.bvh.have_curves &&
1825                                       scene->params.use_bvh_unaligned_nodes;
1826         bparams.num_motion_triangle_steps = scene->params.num_bvh_time_steps;
1827         bparams.num_motion_curve_steps = scene->params.num_bvh_time_steps;
1828
1829         delete bvh;
1830         bvh = BVH::create(bparams, scene->objects);
1831         bvh->build(progress);
1832
1833         if(progress.get_cancel()) return;
1834
1835         /* copy to device */
1836         progress.set_status("Updating Scene BVH", "Copying BVH to device");
1837
1838         PackedBVH& pack = bvh->pack;
1839
1840         if(pack.nodes.size()) {
1841                 dscene->bvh_nodes.reference((float4*)&pack.nodes[0], pack.nodes.size());
1842                 device->tex_alloc("__bvh_nodes", dscene->bvh_nodes);
1843         }
1844         if(pack.leaf_nodes.size()) {
1845                 dscene->bvh_leaf_nodes.reference((float4*)&pack.leaf_nodes[0], pack.leaf_nodes.size());
1846                 device->tex_alloc("__bvh_leaf_nodes", dscene->bvh_leaf_nodes);
1847         }
1848         if(pack.object_node.size()) {
1849                 dscene->object_node.reference((uint*)&pack.object_node[0], pack.object_node.size());
1850                 device->tex_alloc("__object_node", dscene->object_node);
1851         }
1852         if(pack.prim_tri_index.size()) {
1853                 dscene->prim_tri_index.reference((uint*)&pack.prim_tri_index[0], pack.prim_tri_index.size());
1854                 device->tex_alloc("__prim_tri_index", dscene->prim_tri_index);
1855         }
1856         if(pack.prim_tri_verts.size()) {
1857                 dscene->prim_tri_verts.reference((float4*)&pack.prim_tri_verts[0], pack.prim_tri_verts.size());
1858                 device->tex_alloc("__prim_tri_verts", dscene->prim_tri_verts);
1859         }
1860         if(pack.prim_type.size()) {
1861                 dscene->prim_type.reference((uint*)&pack.prim_type[0], pack.prim_type.size());
1862                 device->tex_alloc("__prim_type", dscene->prim_type);
1863         }
1864         if(pack.prim_visibility.size()) {
1865                 dscene->prim_visibility.reference((uint*)&pack.prim_visibility[0], pack.prim_visibility.size());
1866                 device->tex_alloc("__prim_visibility", dscene->prim_visibility);
1867         }
1868         if(pack.prim_index.size()) {
1869                 dscene->prim_index.reference((uint*)&pack.prim_index[0], pack.prim_index.size());
1870                 device->tex_alloc("__prim_index", dscene->prim_index);
1871         }
1872         if(pack.prim_object.size()) {
1873                 dscene->prim_object.reference((uint*)&pack.prim_object[0], pack.prim_object.size());
1874                 device->tex_alloc("__prim_object", dscene->prim_object);
1875         }
1876
1877         dscene->data.bvh.root = pack.root_index;
1878         dscene->data.bvh.use_qbvh = scene->params.use_qbvh;
1879 }
1880
1881 void MeshManager::device_update_flags(Device * /*device*/,
1882                                       DeviceScene * /*dscene*/,
1883                                       Scene * scene,
1884                                       Progress& /*progress*/)
1885 {
1886         if(!need_update && !need_flags_update) {
1887                 return;
1888         }
1889         /* update flags */
1890         foreach(Mesh *mesh, scene->meshes) {
1891                 mesh->has_volume = false;
1892                 foreach(const Shader *shader, mesh->used_shaders) {
1893                         if(shader->has_volume) {
1894                                 mesh->has_volume = true;
1895                         }
1896                         if(shader->has_surface_bssrdf) {
1897                                 mesh->has_surface_bssrdf = true;
1898                         }
1899                 }
1900         }
1901         need_flags_update = false;
1902 }
1903
1904 void MeshManager::device_update_displacement_images(Device *device,
1905                                                     DeviceScene *dscene,
1906                                                     Scene *scene,
1907                                                     Progress& progress)
1908 {
1909         progress.set_status("Updating Displacement Images");
1910         TaskPool pool;
1911         ImageManager *image_manager = scene->image_manager;
1912         set<int> bump_images;
1913         foreach(Mesh *mesh, scene->meshes) {
1914                 if(mesh->need_update) {
1915                         foreach(Shader *shader, mesh->used_shaders) {
1916                                 if(!shader->has_displacement || shader->displacement_method == DISPLACE_BUMP) {
1917                                         continue;
1918                                 }
1919                                 foreach(ShaderNode* node, shader->graph->nodes) {
1920                                         if(node->special_type != SHADER_SPECIAL_TYPE_IMAGE_SLOT) {
1921                                                 continue;
1922                                         }
1923                                         if(device->info.pack_images) {
1924                                                 /* If device requires packed images we need to update all
1925                                                  * images now, even if they're not used for displacement.
1926                                                  */
1927                                                 image_manager->device_update(device,
1928                                                                              dscene,
1929                                                                              scene,
1930                                                                              progress);
1931                                                 return;
1932                                         }
1933                                         ImageSlotTextureNode *image_node = static_cast<ImageSlotTextureNode*>(node);
1934                                         int slot = image_node->slot;
1935                                         if(slot != -1) {
1936                                                 bump_images.insert(slot);
1937                                         }
1938                                 }
1939                         }
1940                 }
1941         }
1942         foreach(int slot, bump_images) {
1943                 pool.push(function_bind(&ImageManager::device_update_slot,
1944                                         image_manager,
1945                                         device,
1946                                         dscene,
1947                                         scene,
1948                                         slot,
1949                                         &progress));
1950         }
1951         pool.wait_work();
1952 }
1953
1954 void MeshManager::device_update(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
1955 {
1956         if(!need_update)
1957                 return;
1958
1959         VLOG(1) << "Total " << scene->meshes.size() << " meshes.";
1960
1961         /* Update normals. */
1962         foreach(Mesh *mesh, scene->meshes) {
1963                 foreach(Shader *shader, mesh->used_shaders) {
1964                         if(shader->need_update_attributes)
1965                                 mesh->need_update = true;
1966                 }
1967
1968                 if(mesh->need_update) {
1969                         mesh->add_face_normals();
1970                         mesh->add_vertex_normals();
1971
1972                         if(mesh->need_attribute(scene, ATTR_STD_POSITION_UNDISPLACED)) {
1973                                 mesh->add_undisplaced();
1974                         }
1975
1976                         if(progress.get_cancel()) return;
1977                 }
1978         }
1979
1980         /* Tessellate meshes that are using subdivision */
1981         size_t total_tess_needed = 0;
1982         foreach(Mesh *mesh, scene->meshes) {
1983                 if(mesh->need_update &&
1984                    mesh->subdivision_type != Mesh::SUBDIVISION_NONE &&
1985                    mesh->num_subd_verts == 0 &&
1986                    mesh->subd_params)
1987                 {
1988                         total_tess_needed++;
1989                 }
1990         }
1991
1992         size_t i = 0;
1993         foreach(Mesh *mesh, scene->meshes) {
1994                 if(mesh->need_update &&
1995                    mesh->subdivision_type != Mesh::SUBDIVISION_NONE &&
1996                    mesh->num_subd_verts == 0 &&
1997                    mesh->subd_params)
1998                 {
1999                         string msg = "Tessellating ";
2000                         if(mesh->name == "")
2001                                 msg += string_printf("%u/%u", (uint)(i+1), (uint)total_tess_needed);
2002                         else
2003                                 msg += string_printf("%s %u/%u", mesh->name.c_str(), (uint)(i+1), (uint)total_tess_needed);
2004
2005                         progress.set_status("Updating Mesh", msg);
2006
2007                         DiagSplit dsplit(*mesh->subd_params);
2008                         mesh->tessellate(&dsplit);
2009
2010                         i++;
2011
2012                         if(progress.get_cancel()) return;
2013                 }
2014         }
2015
2016         /* Update images needed for true displacement. */
2017         bool true_displacement_used = false;
2018         bool old_need_object_flags_update = false;
2019         foreach(Mesh *mesh, scene->meshes) {
2020                 if(mesh->need_update &&
2021                    mesh->has_true_displacement())
2022                 {
2023                         true_displacement_used = true;
2024                         break;
2025                 }
2026         }
2027         if(true_displacement_used) {
2028                 VLOG(1) << "Updating images used for true displacement.";
2029                 device_update_displacement_images(device, dscene, scene, progress);
2030                 old_need_object_flags_update = scene->object_manager->need_flags_update;
2031                 scene->object_manager->device_update_flags(device,
2032                                                            dscene,
2033                                                            scene,
2034                                                            progress,
2035                                                            false);
2036         }
2037
2038         /* Device update. */
2039         device_free(device, dscene);
2040
2041         mesh_calc_offset(scene);
2042         if(true_displacement_used) {
2043                 device_update_mesh(device, dscene, scene, true, progress);
2044         }
2045         if(progress.get_cancel()) return;
2046
2047         /* after mesh data has been copied to device memory we need to update
2048          * offsets for patch tables as this can't be known before hand */
2049         scene->object_manager->device_update_patch_map_offsets(device, dscene, scene);
2050
2051         device_update_attributes(device, dscene, scene, progress);
2052         if(progress.get_cancel()) return;
2053
2054         /* Update displacement. */
2055         bool displacement_done = false;
2056         foreach(Mesh *mesh, scene->meshes) {
2057                 if(mesh->need_update &&
2058                    displace(device, dscene, scene, mesh, progress))
2059                 {
2060                         displacement_done = true;
2061                 }
2062         }
2063
2064         /* TODO: properly handle cancel halfway displacement */
2065         if(progress.get_cancel()) return;
2066
2067         /* Device re-update after displacement. */
2068         if(displacement_done) {
2069                 device_free(device, dscene);
2070
2071                 device_update_attributes(device, dscene, scene, progress);
2072                 if(progress.get_cancel()) return;
2073         }
2074
2075         /* Update bvh. */
2076         size_t num_bvh = 0;
2077         foreach(Mesh *mesh, scene->meshes) {
2078                 if(mesh->need_update && mesh->need_build_bvh()) {
2079                         num_bvh++;
2080                 }
2081         }
2082
2083         TaskPool pool;
2084
2085         i = 0;
2086         foreach(Mesh *mesh, scene->meshes) {
2087                 if(mesh->need_update) {
2088                         pool.push(function_bind(&Mesh::compute_bvh,
2089                                                 mesh,
2090                                                 dscene,
2091                                                 &scene->params,
2092                                                 &progress,
2093                                                 i,
2094                                                 num_bvh));
2095                         if(mesh->need_build_bvh()) {
2096                                 i++;
2097                         }
2098                 }
2099         }
2100
2101         TaskPool::Summary summary;
2102         pool.wait_work(&summary);
2103         VLOG(2) << "Objects BVH build pool statistics:\n"
2104                 << summary.full_report();
2105
2106         foreach(Shader *shader, scene->shaders) {
2107                 shader->need_update_attributes = false;
2108         }
2109
2110 #ifdef __OBJECT_MOTION__
2111         Scene::MotionType need_motion = scene->need_motion(device->info.advanced_shading);
2112         bool motion_blur = need_motion == Scene::MOTION_BLUR;
2113 #else
2114         bool motion_blur = false;
2115 #endif
2116
2117         /* Update objects. */
2118         vector<Object *> volume_objects;
2119         foreach(Object *object, scene->objects) {
2120                 object->compute_bounds(motion_blur);
2121         }
2122
2123         if(progress.get_cancel()) return;
2124
2125         device_update_bvh(device, dscene, scene, progress);
2126         if(progress.get_cancel()) return;
2127
2128         device_update_mesh(device, dscene, scene, false, progress);
2129         if(progress.get_cancel()) return;
2130
2131         need_update = false;
2132
2133         if(true_displacement_used) {
2134                 /* Re-tag flags for update, so they're re-evaluated
2135                  * for meshes with correct bounding boxes.
2136                  *
2137                  * This wouldn't cause wrong results, just true
2138                  * displacement might be less optimal ot calculate.
2139                  */
2140                 scene->object_manager->need_flags_update = old_need_object_flags_update;
2141         }
2142 }
2143
2144 void MeshManager::device_free(Device *device, DeviceScene *dscene)
2145 {
2146         device->tex_free(dscene->bvh_nodes);
2147         device->tex_free(dscene->bvh_leaf_nodes);
2148         device->tex_free(dscene->object_node);
2149         device->tex_free(dscene->prim_tri_verts);
2150         device->tex_free(dscene->prim_tri_index);
2151         device->tex_free(dscene->prim_type);
2152         device->tex_free(dscene->prim_visibility);
2153         device->tex_free(dscene->prim_index);
2154         device->tex_free(dscene->prim_object);
2155         device->tex_free(dscene->tri_shader);
2156         device->tex_free(dscene->tri_vnormal);
2157         device->tex_free(dscene->tri_vindex);
2158         device->tex_free(dscene->tri_patch);
2159         device->tex_free(dscene->tri_patch_uv);
2160         device->tex_free(dscene->curves);
2161         device->tex_free(dscene->curve_keys);
2162         device->tex_free(dscene->patches);
2163         device->tex_free(dscene->attributes_map);
2164         device->tex_free(dscene->attributes_float);
2165         device->tex_free(dscene->attributes_float3);
2166         device->tex_free(dscene->attributes_uchar4);
2167
2168         dscene->bvh_nodes.clear();
2169         dscene->object_node.clear();
2170         dscene->prim_tri_verts.clear();
2171         dscene->prim_tri_index.clear();
2172         dscene->prim_type.clear();
2173         dscene->prim_visibility.clear();
2174         dscene->prim_index.clear();
2175         dscene->prim_object.clear();
2176         dscene->tri_shader.clear();
2177         dscene->tri_vnormal.clear();
2178         dscene->tri_vindex.clear();
2179         dscene->tri_patch.clear();
2180         dscene->tri_patch_uv.clear();
2181         dscene->curves.clear();
2182         dscene->curve_keys.clear();
2183         dscene->patches.clear();
2184         dscene->attributes_map.clear();
2185         dscene->attributes_float.clear();
2186         dscene->attributes_float3.clear();
2187         dscene->attributes_uchar4.clear();
2188
2189 #ifdef WITH_OSL
2190         OSLGlobals *og = (OSLGlobals*)device->osl_memory();
2191
2192         if(og) {
2193                 og->object_name_map.clear();
2194                 og->attribute_map.clear();
2195                 og->object_names.clear();
2196         }
2197 #endif
2198 }
2199
2200 void MeshManager::tag_update(Scene *scene)
2201 {
2202         need_update = true;
2203         scene->object_manager->need_update = true;
2204 }
2205
2206 bool Mesh::need_attribute(Scene *scene, AttributeStandard std)
2207 {
2208         if(std == ATTR_STD_NONE)
2209                 return false;
2210
2211         if(scene->need_global_attribute(std))
2212                 return true;
2213
2214         foreach(Shader *shader, used_shaders)
2215                 if(shader->attributes.find(std))
2216                         return true;
2217
2218         return false;
2219 }
2220
2221 bool Mesh::need_attribute(Scene * /*scene*/, ustring name)
2222 {
2223         if(name == ustring())
2224                 return false;
2225
2226         foreach(Shader *shader, used_shaders)
2227                 if(shader->attributes.find(name))
2228                         return true;
2229
2230         return false;
2231 }
2232
2233 CCL_NAMESPACE_END