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