Cycles: Add option to disable new Hair BVH
[blender-staging.git] / intern / cycles / render / mesh.cpp
1 /*
2  * Copyright 2011-2013 Blender Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "bvh.h"
18 #include "bvh_build.h"
19
20 #include "camera.h"
21 #include "curves.h"
22 #include "device.h"
23 #include "graph.h"
24 #include "shader.h"
25 #include "light.h"
26 #include "mesh.h"
27 #include "nodes.h"
28 #include "object.h"
29 #include "scene.h"
30
31 #include "osl_globals.h"
32
33 #include "util_foreach.h"
34 #include "util_logging.h"
35 #include "util_progress.h"
36 #include "util_set.h"
37
38 #include "subd_split.h"
39 #include "subd_patch.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 /* Curve */
53
54 void Mesh::Curve::bounds_grow(const int k, const float3 *curve_keys, const float *curve_radius, BoundBox& bounds) const
55 {
56         float3 P[4];
57
58         P[0] = curve_keys[max(first_key + k - 1,first_key)];
59         P[1] = curve_keys[first_key + k];
60         P[2] = curve_keys[first_key + k + 1];
61         P[3] = curve_keys[min(first_key + k + 2, first_key + num_keys - 1)];
62
63         float3 lower;
64         float3 upper;
65
66         curvebounds(&lower.x, &upper.x, P, 0);
67         curvebounds(&lower.y, &upper.y, P, 1);
68         curvebounds(&lower.z, &upper.z, P, 2);
69
70         float mr = max(curve_radius[first_key + k], curve_radius[first_key + k + 1]);
71
72         bounds.grow(lower, mr);
73         bounds.grow(upper, mr);
74 }
75
76 void Mesh::Curve::bounds_grow(const int k,
77                               const float3 *curve_keys,
78                               const float *curve_radius,
79                               const Transform& aligned_space,
80                               BoundBox& bounds) const
81 {
82         float3 P[4];
83
84         P[0] = curve_keys[max(first_key + k - 1,first_key)];
85         P[1] = curve_keys[first_key + k];
86         P[2] = curve_keys[first_key + k + 1];
87         P[3] = curve_keys[min(first_key + k + 2, first_key + num_keys - 1)];
88
89         P[0] = transform_point(&aligned_space, P[0]);
90         P[1] = transform_point(&aligned_space, P[1]);
91         P[2] = transform_point(&aligned_space, P[2]);
92         P[3] = transform_point(&aligned_space, P[3]);
93
94         float3 lower;
95         float3 upper;
96
97         curvebounds(&lower.x, &upper.x, P, 0);
98         curvebounds(&lower.y, &upper.y, P, 1);
99         curvebounds(&lower.z, &upper.z, P, 2);
100
101         float mr = max(curve_radius[first_key + k], curve_radius[first_key + k + 1]);
102
103         bounds.grow(lower, mr);
104         bounds.grow(upper, mr);
105 }
106
107 /* Mesh */
108
109 NODE_DEFINE(Mesh)
110 {
111         NodeType* type = NodeType::add("mesh", create);
112
113         static NodeEnum displacement_method_enum;
114         displacement_method_enum.insert("bump", DISPLACE_BUMP);
115         displacement_method_enum.insert("true", DISPLACE_TRUE);
116         displacement_method_enum.insert("both", DISPLACE_BOTH);
117         SOCKET_ENUM(displacement_method, "Displacement Method", displacement_method_enum, DISPLACE_BUMP);
118
119         SOCKET_UINT(motion_steps, "Motion Steps", 3);
120         SOCKET_BOOLEAN(use_motion_blur, "Use Motion Blur", false);
121
122         SOCKET_INT_ARRAY(triangles, "Triangles", array<int>());
123         SOCKET_POINT_ARRAY(verts, "Vertices", array<float3>());
124         SOCKET_INT_ARRAY(shader, "Shader", array<int>());
125         SOCKET_BOOLEAN_ARRAY(smooth, "Smooth", array<bool>());
126
127         SOCKET_POINT_ARRAY(curve_keys, "Curve Keys", array<float3>());
128         SOCKET_FLOAT_ARRAY(curve_radius, "Curve Radius", array<float>());
129         SOCKET_INT_ARRAY(curve_first_key, "Curve First Key", array<int>());
130         SOCKET_INT_ARRAY(curve_shader, "Curve Shader", array<int>());
131
132         return type;
133 }
134
135 Mesh::Mesh()
136 : Node(node_type)
137 {
138         need_update = true;
139         need_update_rebuild = false;
140         transform_applied = false;
141         transform_negative_scaled = false;
142         transform_normal = transform_identity();
143         bounds = BoundBox::empty;
144
145         bvh = NULL;
146
147         tri_offset = 0;
148         vert_offset = 0;
149
150         curve_offset = 0;
151         curvekey_offset = 0;
152
153         attributes.triangle_mesh = this;
154         curve_attributes.curve_mesh = this;
155
156         geometry_flags = GEOMETRY_NONE;
157
158         has_volume = false;
159         has_surface_bssrdf = false;
160 }
161
162 Mesh::~Mesh()
163 {
164         delete bvh;
165 }
166
167 void Mesh::resize_mesh(int numverts, int numtris)
168 {
169         verts.resize(numverts);
170         triangles.resize(numtris * 3);
171         shader.resize(numtris);
172         smooth.resize(numtris);
173
174         forms_quad.resize(numtris);
175
176         attributes.resize();
177 }
178
179 void Mesh::reserve_mesh(int numverts, int numtris)
180 {
181         /* reserve space to add verts and triangles later */
182         verts.reserve(numverts);
183         triangles.reserve(numtris * 3);
184         shader.reserve(numtris);
185         smooth.reserve(numtris);
186
187         forms_quad.reserve(numtris);
188
189         attributes.resize(true);
190 }
191
192 void Mesh::resize_curves(int numcurves, int numkeys)
193 {
194         curve_keys.resize(numkeys);
195         curve_radius.resize(numkeys);
196         curve_first_key.resize(numcurves);
197         curve_shader.resize(numcurves);
198
199         curve_attributes.resize();
200 }
201
202 void Mesh::reserve_curves(int numcurves, int numkeys)
203 {
204         curve_keys.reserve(numkeys);
205         curve_radius.reserve(numkeys);
206         curve_first_key.reserve(numcurves);
207         curve_shader.reserve(numcurves);
208
209         curve_attributes.resize(true);
210 }
211
212 void Mesh::clear()
213 {
214         /* clear all verts and triangles */
215         verts.clear();
216         triangles.clear();
217         shader.clear();
218         smooth.clear();
219
220         forms_quad.clear();
221
222         curve_keys.clear();
223         curve_radius.clear();
224         curve_first_key.clear();
225         curve_shader.clear();
226
227         attributes.clear();
228         curve_attributes.clear();
229         used_shaders.clear();
230
231         transform_applied = false;
232         transform_negative_scaled = false;
233         transform_normal = transform_identity();
234         geometry_flags = GEOMETRY_NONE;
235 }
236
237 int Mesh::split_vertex(int vertex)
238 {
239         /* copy vertex location and vertex attributes */
240         add_vertex_slow(verts[vertex]);
241
242         foreach(Attribute& attr, attributes.attributes) {
243                 if(attr.element == ATTR_ELEMENT_VERTEX) {
244                         vector<char> tmp(attr.data_sizeof());
245                         memcpy(&tmp[0], attr.data() + tmp.size()*vertex, tmp.size());
246                         attr.add(&tmp[0]);
247                 }
248         }
249
250         return verts.size() - 1;
251 }
252
253 void Mesh::add_vertex(float3 P)
254 {
255         verts.push_back_reserved(P);
256 }
257
258 void Mesh::add_vertex_slow(float3 P)
259 {
260         verts.push_back_slow(P);
261 }
262
263 void Mesh::add_triangle(int v0, int v1, int v2, int shader_, bool smooth_, bool forms_quad_)
264 {
265         triangles.push_back_reserved(v0);
266         triangles.push_back_reserved(v1);
267         triangles.push_back_reserved(v2);
268         shader.push_back_reserved(shader_);
269         smooth.push_back_reserved(smooth_);
270         forms_quad.push_back_reserved(forms_quad_);
271 }
272
273 void Mesh::add_curve_key(float3 co, float radius)
274 {
275         curve_keys.push_back_reserved(co);
276         curve_radius.push_back_reserved(radius);
277 }
278
279 void Mesh::add_curve(int first_key, int shader)
280 {
281         curve_first_key.push_back_reserved(first_key);
282         curve_shader.push_back_reserved(shader);
283 }
284
285 void Mesh::compute_bounds()
286 {
287         BoundBox bnds = BoundBox::empty;
288         size_t verts_size = verts.size();
289         size_t curve_keys_size = curve_keys.size();
290
291         if(verts_size + curve_keys_size > 0) {
292                 for(size_t i = 0; i < verts_size; i++)
293                         bnds.grow(verts[i]);
294
295                 for(size_t i = 0; i < curve_keys_size; i++)
296                         bnds.grow(curve_keys[i], curve_radius[i]);
297
298                 Attribute *attr = attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
299                 if(use_motion_blur && attr) {
300                         size_t steps_size = verts.size() * (motion_steps - 1);
301                         float3 *vert_steps = attr->data_float3();
302         
303                         for(size_t i = 0; i < steps_size; i++)
304                                 bnds.grow(vert_steps[i]);
305                 }
306
307                 Attribute *curve_attr = curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
308                 if(use_motion_blur && curve_attr) {
309                         size_t steps_size = curve_keys.size() * (motion_steps - 1);
310                         float3 *key_steps = curve_attr->data_float3();
311         
312                         for(size_t i = 0; i < steps_size; i++)
313                                 bnds.grow(key_steps[i]);
314                 }
315
316                 if(!bnds.valid()) {
317                         bnds = BoundBox::empty;
318
319                         /* skip nan or inf coordinates */
320                         for(size_t i = 0; i < verts_size; i++)
321                                 bnds.grow_safe(verts[i]);
322
323                         for(size_t i = 0; i < curve_keys_size; i++)
324                                 bnds.grow_safe(curve_keys[i], curve_radius[i]);
325                         
326                         if(use_motion_blur && attr) {
327                                 size_t steps_size = verts.size() * (motion_steps - 1);
328                                 float3 *vert_steps = attr->data_float3();
329                 
330                                 for(size_t i = 0; i < steps_size; i++)
331                                         bnds.grow_safe(vert_steps[i]);
332                         }
333
334                         if(use_motion_blur && curve_attr) {
335                                 size_t steps_size = curve_keys.size() * (motion_steps - 1);
336                                 float3 *key_steps = curve_attr->data_float3();
337                 
338                                 for(size_t i = 0; i < steps_size; i++)
339                                         bnds.grow_safe(key_steps[i]);
340                         }
341                 }
342         }
343
344         if(!bnds.valid()) {
345                 /* empty mesh */
346                 bnds.grow(make_float3(0.0f, 0.0f, 0.0f));
347         }
348
349         bounds = bnds;
350 }
351
352 static float3 compute_face_normal(const Mesh::Triangle& t, float3 *verts)
353 {
354         float3 v0 = verts[t.v[0]];
355         float3 v1 = verts[t.v[1]];
356         float3 v2 = verts[t.v[2]];
357
358         float3 norm = cross(v1 - v0, v2 - v0);
359         float normlen = len(norm);
360
361         if(normlen == 0.0f)
362                 return make_float3(1.0f, 0.0f, 0.0f);
363
364         return norm / normlen;
365 }
366
367 void Mesh::add_face_normals()
368 {
369         /* don't compute if already there */
370         if(attributes.find(ATTR_STD_FACE_NORMAL))
371                 return;
372         
373         /* get attributes */
374         Attribute *attr_fN = attributes.add(ATTR_STD_FACE_NORMAL);
375         float3 *fN = attr_fN->data_float3();
376
377         /* compute face normals */
378         size_t triangles_size = num_triangles();
379         bool flip = transform_negative_scaled;
380
381         if(triangles_size) {
382                 float3 *verts_ptr = &verts[0];
383
384                 for(size_t i = 0; i < triangles_size; i++) {
385                         fN[i] = compute_face_normal(get_triangle(i), verts_ptr);
386
387                         if(flip)
388                                 fN[i] = -fN[i];
389                 }
390         }
391
392         /* expected to be in local space */
393         if(transform_applied) {
394                 Transform ntfm = transform_inverse(transform_normal);
395
396                 for(size_t i = 0; i < triangles_size; i++)
397                         fN[i] = normalize(transform_direction(&ntfm, fN[i]));
398         }
399 }
400
401 void Mesh::add_vertex_normals()
402 {
403         bool flip = transform_negative_scaled;
404         size_t verts_size = verts.size();
405         size_t triangles_size = num_triangles();
406
407         /* static vertex normals */
408         if(!attributes.find(ATTR_STD_VERTEX_NORMAL)) {
409                 /* get attributes */
410                 Attribute *attr_fN = attributes.find(ATTR_STD_FACE_NORMAL);
411                 Attribute *attr_vN = attributes.add(ATTR_STD_VERTEX_NORMAL);
412
413                 float3 *fN = attr_fN->data_float3();
414                 float3 *vN = attr_vN->data_float3();
415
416                 /* compute vertex normals */
417                 memset(vN, 0, verts.size()*sizeof(float3));
418
419                 if(triangles_size) {
420
421                         for(size_t i = 0; i < triangles_size; i++)
422                                 for(size_t j = 0; j < 3; j++)
423                                         vN[get_triangle(i).v[j]] += fN[i];
424                 }
425
426                 for(size_t i = 0; i < verts_size; i++) {
427                         vN[i] = normalize(vN[i]);
428                         if(flip)
429                                 vN[i] = -vN[i];
430                 }
431         }
432
433         /* motion vertex normals */
434         Attribute *attr_mP = attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
435         Attribute *attr_mN = attributes.find(ATTR_STD_MOTION_VERTEX_NORMAL);
436
437         if(has_motion_blur() && attr_mP && !attr_mN) {
438                 /* create attribute */
439                 attr_mN = attributes.add(ATTR_STD_MOTION_VERTEX_NORMAL);
440
441                 for(int step = 0; step < motion_steps - 1; step++) {
442                         float3 *mP = attr_mP->data_float3() + step*verts.size();
443                         float3 *mN = attr_mN->data_float3() + step*verts.size();
444
445                         /* compute */
446                         memset(mN, 0, verts.size()*sizeof(float3));
447
448                         if(triangles_size) {
449                                 for(size_t i = 0; i < triangles_size; i++) {
450                                         for(size_t j = 0; j < 3; j++) {
451                                                 float3 fN = compute_face_normal(get_triangle(i), mP);
452                                                 mN[get_triangle(i).v[j]] += fN;
453                                         }
454                                 }
455                         }
456
457                         for(size_t i = 0; i < verts_size; i++) {
458                                 mN[i] = normalize(mN[i]);
459                                 if(flip)
460                                         mN[i] = -mN[i];
461                         }
462                 }
463         }
464 }
465
466 void Mesh::pack_normals(Scene *scene, uint *tri_shader, float4 *vnormal)
467 {
468         Attribute *attr_vN = attributes.find(ATTR_STD_VERTEX_NORMAL);
469
470         float3 *vN = attr_vN->data_float3();
471         uint shader_id = 0;
472         uint last_shader = -1;
473         bool last_smooth = false;
474
475         size_t triangles_size = num_triangles();
476         int *shader_ptr = (shader.size())? &shader[0]: NULL;
477
478         bool do_transform = transform_applied;
479         Transform ntfm = transform_normal;
480
481         /* save shader */
482         for(size_t i = 0; i < triangles_size; i++) {
483                 if(shader_ptr[i] != last_shader || last_smooth != smooth[i]) {
484                         last_shader = shader_ptr[i];
485                         last_smooth = smooth[i];
486                         Shader *shader = (last_shader < used_shaders.size()) ?
487                                 used_shaders[last_shader] : scene->default_surface;
488                         shader_id = scene->shader_manager->get_shader_id(shader, this, last_smooth);
489                 }
490
491                 tri_shader[i] = shader_id;
492         }
493
494         size_t verts_size = verts.size();
495
496         for(size_t i = 0; i < verts_size; i++) {
497                 float3 vNi = vN[i];
498
499                 if(do_transform)
500                         vNi = normalize(transform_direction(&ntfm, vNi));
501
502                 vnormal[i] = make_float4(vNi.x, vNi.y, vNi.z, 0.0f);
503         }
504 }
505
506 void Mesh::pack_verts(const vector<uint>& tri_prim_index,
507                       uint4 *tri_vindex,
508                       size_t vert_offset,
509                       size_t tri_offset)
510 {
511         const size_t triangles_size = num_triangles();
512         if(triangles_size) {
513                 for(size_t i = 0; i < triangles_size; i++) {
514                         Triangle t = get_triangle(i);
515                         tri_vindex[i] = make_uint4(t.v[0] + vert_offset,
516                                                    t.v[1] + vert_offset,
517                                                    t.v[2] + vert_offset,
518                                                    tri_prim_index[i + tri_offset]);
519                 }
520         }
521 }
522
523 void Mesh::pack_curves(Scene *scene, float4 *curve_key_co, float4 *curve_data, size_t curvekey_offset)
524 {
525         size_t curve_keys_size = curve_keys.size();
526
527         /* pack curve keys */
528         if(curve_keys_size) {
529                 float3 *keys_ptr = &curve_keys[0];
530                 float *radius_ptr = &curve_radius[0];
531
532                 for(size_t i = 0; i < curve_keys_size; i++)
533                         curve_key_co[i] = make_float4(keys_ptr[i].x, keys_ptr[i].y, keys_ptr[i].z, radius_ptr[i]);
534         }
535
536         /* pack curve segments */
537         size_t curve_num = num_curves();
538
539         if(curve_num) {
540                 for(size_t i = 0; i < curve_num; i++) {
541                         Curve curve = get_curve(i);
542                         int shader_id = curve_shader[i];
543                         Shader *shader = (shader_id < used_shaders.size()) ?
544                                 used_shaders[shader_id] : scene->default_surface;
545                         shader_id = scene->shader_manager->get_shader_id(shader, this, false);
546
547                         curve_data[i] = make_float4(
548                                 __int_as_float(curve.first_key + curvekey_offset),
549                                 __int_as_float(curve.num_keys),
550                                 __int_as_float(shader_id),
551                                 0.0f);
552                 }
553         }
554 }
555
556 void Mesh::compute_bvh(DeviceScene *dscene,
557                        SceneParams *params,
558                        Progress *progress,
559                        int n,
560                        int total)
561 {
562         if(progress->get_cancel())
563                 return;
564
565         compute_bounds();
566
567         if(need_build_bvh()) {
568                 string msg = "Updating Mesh BVH ";
569                 if(name == "")
570                         msg += string_printf("%u/%u", (uint)(n+1), (uint)total);
571                 else
572                         msg += string_printf("%s %u/%u", name.c_str(), (uint)(n+1), (uint)total);
573
574                 Object object;
575                 object.mesh = this;
576
577                 vector<Object*> objects;
578                 objects.push_back(&object);
579
580                 if(bvh && !need_update_rebuild) {
581                         progress->set_status(msg, "Refitting BVH");
582                         bvh->objects = objects;
583                         bvh->refit(*progress);
584                 }
585                 else {
586                         progress->set_status(msg, "Building BVH");
587
588                         BVHParams bparams;
589                         bparams.use_spatial_split = params->use_bvh_spatial_split;
590                         bparams.use_qbvh = params->use_qbvh;
591                         bparams.use_unaligned_nodes = dscene->data.bvh.have_curves &&
592                                                       params->use_bvh_unaligned_nodes;
593
594                         delete bvh;
595                         bvh = BVH::create(bparams, objects);
596                         MEM_GUARDED_CALL(progress, bvh->build, *progress);
597                 }
598         }
599
600         need_update = false;
601         need_update_rebuild = false;
602 }
603
604 void Mesh::tag_update(Scene *scene, bool rebuild)
605 {
606         need_update = true;
607
608         if(rebuild) {
609                 need_update_rebuild = true;
610                 scene->light_manager->need_update = true;
611         }
612         else {
613                 foreach(Shader *shader, used_shaders)
614                         if(shader->has_surface_emission)
615                                 scene->light_manager->need_update = true;
616         }
617
618         scene->mesh_manager->need_update = true;
619         scene->object_manager->need_update = true;
620 }
621
622 bool Mesh::has_motion_blur() const
623 {
624         return (use_motion_blur &&
625                 (attributes.find(ATTR_STD_MOTION_VERTEX_POSITION) ||
626                  curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION)));
627 }
628
629 bool Mesh::need_build_bvh() const
630 {
631         return !transform_applied || has_surface_bssrdf;
632 }
633
634 bool Mesh::is_instanced() const
635 {
636         /* Currently we treat subsurface objects as instanced.
637          *
638          * While it might be not very optimal for ray traversal, it avoids having
639          * duplicated BVH in the memory, saving quite some space.
640          */
641         return !transform_applied || has_surface_bssrdf;
642 }
643
644 /* Mesh Manager */
645
646 MeshManager::MeshManager()
647 {
648         bvh = NULL;
649         need_update = true;
650         need_flags_update = true;
651 }
652
653 MeshManager::~MeshManager()
654 {
655         delete bvh;
656 }
657
658 void MeshManager::update_osl_attributes(Device *device, Scene *scene, vector<AttributeRequestSet>& mesh_attributes)
659 {
660 #ifdef WITH_OSL
661         /* for OSL, a hash map is used to lookup the attribute by name. */
662         OSLGlobals *og = (OSLGlobals*)device->osl_memory();
663
664         og->object_name_map.clear();
665         og->attribute_map.clear();
666         og->object_names.clear();
667
668         og->attribute_map.resize(scene->objects.size()*ATTR_PRIM_TYPES);
669
670         for(size_t i = 0; i < scene->objects.size(); i++) {
671                 /* set object name to object index map */
672                 Object *object = scene->objects[i];
673                 og->object_name_map[object->name] = i;
674                 og->object_names.push_back(object->name);
675
676                 /* set object attributes */
677                 foreach(ParamValue& attr, object->attributes) {
678                         OSLGlobals::Attribute osl_attr;
679
680                         osl_attr.type = attr.type();
681                         osl_attr.elem = ATTR_ELEMENT_OBJECT;
682                         osl_attr.value = attr;
683                         osl_attr.offset = 0;
684
685                         og->attribute_map[i*ATTR_PRIM_TYPES][attr.name()] = osl_attr;
686                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][attr.name()] = osl_attr;
687                 }
688
689                 /* find mesh attributes */
690                 size_t j;
691
692                 for(j = 0; j < scene->meshes.size(); j++)
693                         if(scene->meshes[j] == object->mesh)
694                                 break;
695
696                 AttributeRequestSet& attributes = mesh_attributes[j];
697
698                 /* set object attributes */
699                 foreach(AttributeRequest& req, attributes.requests) {
700                         OSLGlobals::Attribute osl_attr;
701
702                         if(req.triangle_element != ATTR_ELEMENT_NONE) {
703                                 osl_attr.elem = req.triangle_element;
704                                 osl_attr.offset = req.triangle_offset;
705
706                                 if(req.triangle_type == TypeDesc::TypeFloat)
707                                         osl_attr.type = TypeDesc::TypeFloat;
708                                 else if(req.triangle_type == TypeDesc::TypeMatrix)
709                                         osl_attr.type = TypeDesc::TypeMatrix;
710                                 else
711                                         osl_attr.type = TypeDesc::TypeColor;
712
713                                 if(req.std != ATTR_STD_NONE) {
714                                         /* if standard attribute, add lookup by geom: name convention */
715                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
716                                         og->attribute_map[i*ATTR_PRIM_TYPES][stdname] = osl_attr;
717                                 }
718                                 else if(req.name != ustring()) {
719                                         /* add lookup by mesh attribute name */
720                                         og->attribute_map[i*ATTR_PRIM_TYPES][req.name] = osl_attr;
721                                 }
722                         }
723
724                         if(req.curve_element != ATTR_ELEMENT_NONE) {
725                                 osl_attr.elem = req.curve_element;
726                                 osl_attr.offset = req.curve_offset;
727
728                                 if(req.curve_type == TypeDesc::TypeFloat)
729                                         osl_attr.type = TypeDesc::TypeFloat;
730                                 else if(req.curve_type == TypeDesc::TypeMatrix)
731                                         osl_attr.type = TypeDesc::TypeMatrix;
732                                 else
733                                         osl_attr.type = TypeDesc::TypeColor;
734
735                                 if(req.std != ATTR_STD_NONE) {
736                                         /* if standard attribute, add lookup by geom: name convention */
737                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
738                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][stdname] = osl_attr;
739                                 }
740                                 else if(req.name != ustring()) {
741                                         /* add lookup by mesh attribute name */
742                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][req.name] = osl_attr;
743                                 }
744                         }
745                 }
746         }
747 #else
748         (void)device;
749         (void)scene;
750         (void)mesh_attributes;
751 #endif
752 }
753
754 void MeshManager::update_svm_attributes(Device *device, DeviceScene *dscene, Scene *scene, vector<AttributeRequestSet>& mesh_attributes)
755 {
756         /* for SVM, the attributes_map table is used to lookup the offset of an
757          * attribute, based on a unique shader attribute id. */
758
759         /* compute array stride */
760         int attr_map_stride = 0;
761
762         for(size_t i = 0; i < scene->meshes.size(); i++)
763                 attr_map_stride = max(attr_map_stride, (mesh_attributes[i].size() + 1)*ATTR_PRIM_TYPES);
764
765         if(attr_map_stride == 0)
766                 return;
767         
768         /* create attribute map */
769         uint4 *attr_map = dscene->attributes_map.resize(attr_map_stride*scene->objects.size());
770         memset(attr_map, 0, dscene->attributes_map.size()*sizeof(uint));
771
772         for(size_t i = 0; i < scene->objects.size(); i++) {
773                 Object *object = scene->objects[i];
774                 Mesh *mesh = object->mesh;
775
776                 /* find mesh attributes */
777                 size_t j;
778
779                 for(j = 0; j < scene->meshes.size(); j++)
780                         if(scene->meshes[j] == mesh)
781                                 break;
782
783                 AttributeRequestSet& attributes = mesh_attributes[j];
784
785                 /* set object attributes */
786                 int index = i*attr_map_stride;
787
788                 foreach(AttributeRequest& req, attributes.requests) {
789                         uint id;
790
791                         if(req.std == ATTR_STD_NONE)
792                                 id = scene->shader_manager->get_attribute_id(req.name);
793                         else
794                                 id = scene->shader_manager->get_attribute_id(req.std);
795
796                         if(mesh->num_triangles()) {
797                                 attr_map[index].x = id;
798                                 attr_map[index].y = req.triangle_element;
799                                 attr_map[index].z = as_uint(req.triangle_offset);
800
801                                 if(req.triangle_type == TypeDesc::TypeFloat)
802                                         attr_map[index].w = NODE_ATTR_FLOAT;
803                                 else if(req.triangle_type == TypeDesc::TypeMatrix)
804                                         attr_map[index].w = NODE_ATTR_MATRIX;
805                                 else
806                                         attr_map[index].w = NODE_ATTR_FLOAT3;
807                         }
808
809                         index++;
810
811                         if(mesh->num_curves()) {
812                                 attr_map[index].x = id;
813                                 attr_map[index].y = req.curve_element;
814                                 attr_map[index].z = as_uint(req.curve_offset);
815
816                                 if(req.curve_type == TypeDesc::TypeFloat)
817                                         attr_map[index].w = NODE_ATTR_FLOAT;
818                                 else if(req.curve_type == TypeDesc::TypeMatrix)
819                                         attr_map[index].w = NODE_ATTR_MATRIX;
820                                 else
821                                         attr_map[index].w = NODE_ATTR_FLOAT3;
822                         }
823
824                         index++;
825                 }
826
827                 /* terminator */
828                 attr_map[index].x = ATTR_STD_NONE;
829                 attr_map[index].y = 0;
830                 attr_map[index].z = 0;
831                 attr_map[index].w = 0;
832
833                 index++;
834
835                 attr_map[index].x = ATTR_STD_NONE;
836                 attr_map[index].y = 0;
837                 attr_map[index].z = 0;
838                 attr_map[index].w = 0;
839
840                 index++;
841         }
842
843         /* copy to device */
844         dscene->data.bvh.attributes_map_stride = attr_map_stride;
845         device->tex_alloc("__attributes_map", dscene->attributes_map);
846 }
847
848 static void update_attribute_element_size(Mesh *mesh,
849                                           Attribute *mattr,
850                                           size_t *attr_float_size,
851                                           size_t *attr_float3_size,
852                                           size_t *attr_uchar4_size)
853 {
854         if(mattr) {
855                 size_t size = mattr->element_size(
856                         mesh->verts.size(),
857                         mesh->num_triangles(),
858                         mesh->motion_steps,
859                         mesh->num_curves(),
860                         mesh->curve_keys.size());
861
862                 if(mattr->element == ATTR_ELEMENT_VOXEL) {
863                         /* pass */
864                 }
865                 else if(mattr->element == ATTR_ELEMENT_CORNER_BYTE) {
866                         *attr_uchar4_size += size;
867                 }
868                 else if(mattr->type == TypeDesc::TypeFloat) {
869                         *attr_float_size += size;
870                 }
871                 else if(mattr->type == TypeDesc::TypeMatrix) {
872                         *attr_float3_size += size * 4;
873                 }
874                 else {
875                         *attr_float3_size += size;
876                 }
877         }
878 }
879
880 static void update_attribute_element_offset(Mesh *mesh,
881                                             vector<float>& attr_float,
882                                             size_t& attr_float_offset,
883                                             vector<float4>& attr_float3,
884                                             size_t& attr_float3_offset,
885                                             vector<uchar4>& attr_uchar4,
886                                             size_t& attr_uchar4_offset,
887                                             Attribute *mattr,
888                                             TypeDesc& type,
889                                             int& offset,
890                                             AttributeElement& element)
891 {
892         if(mattr) {
893                 /* store element and type */
894                 element = mattr->element;
895                 type = mattr->type;
896
897                 /* store attribute data in arrays */
898                 size_t size = mattr->element_size(
899                         mesh->verts.size(),
900                         mesh->num_triangles(),
901                         mesh->motion_steps,
902                         mesh->num_curves(),
903                         mesh->curve_keys.size());
904
905                 if(mattr->element == ATTR_ELEMENT_VOXEL) {
906                         /* store slot in offset value */
907                         VoxelAttribute *voxel_data = mattr->data_voxel();
908                         offset = voxel_data->slot;
909                 }
910                 else if(mattr->element == ATTR_ELEMENT_CORNER_BYTE) {
911                         uchar4 *data = mattr->data_uchar4();
912                         offset = attr_uchar4_offset;
913
914                         assert(attr_uchar4.capacity() >= offset + size);
915                         for(size_t k = 0; k < size; k++) {
916                                 attr_uchar4[offset+k] = data[k];
917                         }
918                         attr_uchar4_offset += size;
919                 }
920                 else if(mattr->type == TypeDesc::TypeFloat) {
921                         float *data = mattr->data_float();
922                         offset = attr_float_offset;
923
924                         assert(attr_float.capacity() >= offset + size);
925                         for(size_t k = 0; k < size; k++) {
926                                 attr_float[offset+k] = data[k];
927                         }
928                         attr_float_offset += size;
929                 }
930                 else if(mattr->type == TypeDesc::TypeMatrix) {
931                         Transform *tfm = mattr->data_transform();
932                         offset = attr_float3_offset;
933
934                         assert(attr_float3.capacity() >= offset + size * 4);
935                         for(size_t k = 0; k < size*4; k++) {
936                                 attr_float3[offset+k] = (&tfm->x)[k];
937                         }
938                         attr_float3_offset += size * 4;
939                 }
940                 else {
941                         float4 *data = mattr->data_float4();
942                         offset = attr_float3_offset;
943
944                         assert(attr_float3.capacity() >= offset + size);
945                         for(size_t k = 0; k < size; k++) {
946                                 attr_float3[offset+k] = data[k];
947                         }
948                         attr_float3_offset += size;
949                 }
950
951                 /* mesh vertex/curve index is global, not per object, so we sneak
952                  * a correction for that in here */
953                 if(element == ATTR_ELEMENT_VERTEX)
954                         offset -= mesh->vert_offset;
955                 else if(element == ATTR_ELEMENT_VERTEX_MOTION)
956                         offset -= mesh->vert_offset;
957                 else if(element == ATTR_ELEMENT_FACE)
958                         offset -= mesh->tri_offset;
959                 else if(element == ATTR_ELEMENT_CORNER || element == ATTR_ELEMENT_CORNER_BYTE)
960                         offset -= 3*mesh->tri_offset;
961                 else if(element == ATTR_ELEMENT_CURVE)
962                         offset -= mesh->curve_offset;
963                 else if(element == ATTR_ELEMENT_CURVE_KEY)
964                         offset -= mesh->curvekey_offset;
965                 else if(element == ATTR_ELEMENT_CURVE_KEY_MOTION)
966                         offset -= mesh->curvekey_offset;
967         }
968         else {
969                 /* attribute not found */
970                 element = ATTR_ELEMENT_NONE;
971                 offset = 0;
972         }
973 }
974
975 void MeshManager::device_update_attributes(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
976 {
977         progress.set_status("Updating Mesh", "Computing attributes");
978
979         /* gather per mesh requested attributes. as meshes may have multiple
980          * shaders assigned, this merges the requested attributes that have
981          * been set per shader by the shader manager */
982         vector<AttributeRequestSet> mesh_attributes(scene->meshes.size());
983
984         for(size_t i = 0; i < scene->meshes.size(); i++) {
985                 Mesh *mesh = scene->meshes[i];
986
987                 scene->need_global_attributes(mesh_attributes[i]);
988
989                 foreach(Shader *shader, mesh->used_shaders) {
990                         mesh_attributes[i].add(shader->attributes);
991                 }
992         }
993
994         /* mesh attribute are stored in a single array per data type. here we fill
995          * those arrays, and set the offset and element type to create attribute
996          * maps next */
997
998         /* Pre-allocate attributes to avoid arrays re-allocation which would
999          * take 2x of overall attribute memory usage.
1000          */
1001         size_t attr_float_size = 0;
1002         size_t attr_float3_size = 0;
1003         size_t attr_uchar4_size = 0;
1004         for(size_t i = 0; i < scene->meshes.size(); i++) {
1005                 Mesh *mesh = scene->meshes[i];
1006                 AttributeRequestSet& attributes = mesh_attributes[i];
1007                 foreach(AttributeRequest& req, attributes.requests) {
1008                         Attribute *triangle_mattr = mesh->attributes.find(req);
1009                         Attribute *curve_mattr = mesh->curve_attributes.find(req);
1010
1011                         /* todo: get rid of this exception, it's only here for giving some
1012                          * working texture coordinate for subdivision as we can't preserve
1013                          * any attributes yet */
1014                         if(!triangle_mattr && req.std == ATTR_STD_GENERATED) {
1015                                 triangle_mattr = mesh->attributes.add(ATTR_STD_GENERATED);
1016                                 if(mesh->verts.size())
1017                                         memcpy(triangle_mattr->data_float3(), &mesh->verts[0], sizeof(float3)*mesh->verts.size());
1018                         }
1019
1020                         update_attribute_element_size(mesh,
1021                                                       triangle_mattr,
1022                                                       &attr_float_size,
1023                                                       &attr_float3_size,
1024                                                       &attr_uchar4_size);
1025                         update_attribute_element_size(mesh,
1026                                                       curve_mattr,
1027                                                       &attr_float_size,
1028                                                       &attr_float3_size,
1029                                                       &attr_uchar4_size);
1030                 }
1031         }
1032
1033         vector<float> attr_float(attr_float_size);
1034         vector<float4> attr_float3(attr_float3_size);
1035         vector<uchar4> attr_uchar4(attr_uchar4_size);
1036
1037         size_t attr_float_offset = 0;
1038         size_t attr_float3_offset = 0;
1039         size_t attr_uchar4_offset = 0;
1040
1041         /* Fill in attributes. */
1042         for(size_t i = 0; i < scene->meshes.size(); i++) {
1043                 Mesh *mesh = scene->meshes[i];
1044                 AttributeRequestSet& attributes = mesh_attributes[i];
1045
1046                 /* todo: we now store std and name attributes from requests even if
1047                  * they actually refer to the same mesh attributes, optimize */
1048                 foreach(AttributeRequest& req, attributes.requests) {
1049                         Attribute *triangle_mattr = mesh->attributes.find(req);
1050                         Attribute *curve_mattr = mesh->curve_attributes.find(req);
1051
1052                         update_attribute_element_offset(mesh,
1053                                                         attr_float, attr_float_offset,
1054                                                         attr_float3, attr_float3_offset,
1055                                                         attr_uchar4, attr_uchar4_offset,
1056                                                         triangle_mattr,
1057                                                         req.triangle_type,
1058                                                         req.triangle_offset,
1059                                                         req.triangle_element);
1060
1061                         update_attribute_element_offset(mesh,
1062                                                         attr_float, attr_float_offset,
1063                                                         attr_float3, attr_float3_offset,
1064                                                         attr_uchar4, attr_uchar4_offset,
1065                                                         curve_mattr,
1066                                                         req.curve_type,
1067                                                         req.curve_offset,
1068                                                         req.curve_element);
1069
1070                         if(progress.get_cancel()) return;
1071                 }
1072         }
1073
1074         /* create attribute lookup maps */
1075         if(scene->shader_manager->use_osl())
1076                 update_osl_attributes(device, scene, mesh_attributes);
1077
1078         update_svm_attributes(device, dscene, scene, mesh_attributes);
1079
1080         if(progress.get_cancel()) return;
1081
1082         /* copy to device */
1083         progress.set_status("Updating Mesh", "Copying Attributes to device");
1084
1085         if(attr_float.size()) {
1086                 dscene->attributes_float.copy(&attr_float[0], attr_float.size());
1087                 device->tex_alloc("__attributes_float", dscene->attributes_float);
1088         }
1089         if(attr_float3.size()) {
1090                 dscene->attributes_float3.copy(&attr_float3[0], attr_float3.size());
1091                 device->tex_alloc("__attributes_float3", dscene->attributes_float3);
1092         }
1093         if(attr_uchar4.size()) {
1094                 dscene->attributes_uchar4.copy(&attr_uchar4[0], attr_uchar4.size());
1095                 device->tex_alloc("__attributes_uchar4", dscene->attributes_uchar4);
1096         }
1097 }
1098
1099 void MeshManager::mesh_calc_offset(Scene *scene)
1100 {
1101         size_t vert_size = 0;
1102         size_t tri_size = 0;
1103         size_t curve_key_size = 0;
1104         size_t curve_size = 0;
1105
1106         foreach(Mesh *mesh, scene->meshes) {
1107                 mesh->vert_offset = vert_size;
1108                 mesh->tri_offset = tri_size;
1109                 mesh->curvekey_offset = curve_key_size;
1110                 mesh->curve_offset = curve_size;
1111
1112                 vert_size += mesh->verts.size();
1113                 tri_size += mesh->num_triangles();
1114                 curve_key_size += mesh->curve_keys.size();
1115                 curve_size += mesh->num_curves();
1116         }
1117 }
1118
1119 void MeshManager::device_update_mesh(Device *device,
1120                                      DeviceScene *dscene,
1121                                      Scene *scene,
1122                                      bool for_displacement,
1123                                      Progress& progress)
1124 {
1125         /* Count. */
1126         size_t vert_size = 0;
1127         size_t tri_size = 0;
1128         size_t curve_key_size = 0;
1129         size_t curve_size = 0;
1130         foreach(Mesh *mesh, scene->meshes) {
1131                 vert_size += mesh->verts.size();
1132                 tri_size += mesh->num_triangles();
1133                 curve_key_size += mesh->curve_keys.size();
1134                 curve_size += mesh->num_curves();
1135         }
1136         /* Create mapping from triangle to primitive triangle array. */
1137         vector<uint> tri_prim_index(tri_size);
1138         if(for_displacement) {
1139                 /* For displacement kernels we do some trickery to make them believe
1140                  * we've got all required data ready. However, that data is different
1141                  * from final render kernels since we don't have BVH yet, so can't
1142                  * really use same semantic of arrays.
1143                  */
1144                 foreach(Mesh *mesh, scene->meshes) {
1145                         for(size_t i = 0; i < mesh->num_triangles(); ++i) {
1146                                 tri_prim_index[i + mesh->tri_offset] = 3 * (i + mesh->tri_offset);
1147                         }
1148                 }
1149         }
1150         else {
1151                 PackedBVH& pack = bvh->pack;
1152                 for(size_t i = 0; i < pack.prim_index.size(); ++i) {
1153                         if ((pack.prim_type[i] & PRIMITIVE_ALL_TRIANGLE) != 0) {
1154                                 tri_prim_index[pack.prim_index[i]] = pack.prim_tri_index[i];
1155                         }
1156                 }
1157         }
1158         /* Fill in all the arrays. */
1159         if(tri_size != 0) {
1160                 /* normals */
1161                 progress.set_status("Updating Mesh", "Computing normals");
1162
1163                 uint *tri_shader = dscene->tri_shader.resize(tri_size);
1164                 float4 *vnormal = dscene->tri_vnormal.resize(vert_size);
1165                 uint4 *tri_vindex = dscene->tri_vindex.resize(tri_size);
1166
1167                 foreach(Mesh *mesh, scene->meshes) {
1168                         mesh->pack_normals(scene,
1169                                            &tri_shader[mesh->tri_offset],
1170                                            &vnormal[mesh->vert_offset]);
1171                         mesh->pack_verts(tri_prim_index,
1172                                          &tri_vindex[mesh->tri_offset],
1173                                          mesh->vert_offset,
1174                                          mesh->tri_offset);
1175                         if(progress.get_cancel()) return;
1176                 }
1177
1178                 /* vertex coordinates */
1179                 progress.set_status("Updating Mesh", "Copying Mesh to device");
1180
1181                 device->tex_alloc("__tri_shader", dscene->tri_shader);
1182                 device->tex_alloc("__tri_vnormal", dscene->tri_vnormal);
1183                 device->tex_alloc("__tri_vindex", dscene->tri_vindex);
1184         }
1185         if(curve_size != 0) {
1186                 progress.set_status("Updating Mesh", "Copying Strands to device");
1187
1188                 float4 *curve_keys = dscene->curve_keys.resize(curve_key_size);
1189                 float4 *curves = dscene->curves.resize(curve_size);
1190
1191                 foreach(Mesh *mesh, scene->meshes) {
1192                         mesh->pack_curves(scene, &curve_keys[mesh->curvekey_offset], &curves[mesh->curve_offset], mesh->curvekey_offset);
1193                         if(progress.get_cancel()) return;
1194                 }
1195
1196                 device->tex_alloc("__curve_keys", dscene->curve_keys);
1197                 device->tex_alloc("__curves", dscene->curves);
1198         }
1199         if(for_displacement) {
1200                 float4 *prim_tri_verts = dscene->prim_tri_verts.resize(tri_size * 3);
1201                 foreach(Mesh *mesh, scene->meshes) {
1202                         for(size_t i = 0; i < mesh->num_triangles(); ++i) {
1203                                 Mesh::Triangle t = mesh->get_triangle(i);
1204                                 size_t offset = 3 * (i + mesh->tri_offset);
1205                                 prim_tri_verts[offset + 0] = float3_to_float4(mesh->verts[t.v[0]]);
1206                                 prim_tri_verts[offset + 1] = float3_to_float4(mesh->verts[t.v[1]]);
1207                                 prim_tri_verts[offset + 2] = float3_to_float4(mesh->verts[t.v[2]]);
1208                         }
1209                 }
1210                 device->tex_alloc("__prim_tri_verts", dscene->prim_tri_verts);
1211         }
1212 }
1213
1214 void MeshManager::device_update_bvh(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
1215 {
1216         /* bvh build */
1217         progress.set_status("Updating Scene BVH", "Building");
1218
1219         VLOG(1) << (scene->params.use_qbvh ? "Using QBVH optimization structure"
1220                                            : "Using regular BVH optimization structure");
1221
1222         BVHParams bparams;
1223         bparams.top_level = true;
1224         bparams.use_qbvh = scene->params.use_qbvh;
1225         bparams.use_spatial_split = scene->params.use_bvh_spatial_split;
1226         bparams.use_unaligned_nodes = dscene->data.bvh.have_curves &&
1227                                       scene->params.use_bvh_unaligned_nodes;
1228
1229         delete bvh;
1230         bvh = BVH::create(bparams, scene->objects);
1231         bvh->build(progress);
1232
1233         if(progress.get_cancel()) return;
1234
1235         /* copy to device */
1236         progress.set_status("Updating Scene BVH", "Copying BVH to device");
1237
1238         PackedBVH& pack = bvh->pack;
1239
1240         if(pack.nodes.size()) {
1241                 dscene->bvh_nodes.reference((float4*)&pack.nodes[0], pack.nodes.size());
1242                 device->tex_alloc("__bvh_nodes", dscene->bvh_nodes);
1243         }
1244         if(pack.leaf_nodes.size()) {
1245                 dscene->bvh_leaf_nodes.reference((float4*)&pack.leaf_nodes[0], pack.leaf_nodes.size());
1246                 device->tex_alloc("__bvh_leaf_nodes", dscene->bvh_leaf_nodes);
1247         }
1248         if(pack.object_node.size()) {
1249                 dscene->object_node.reference((uint*)&pack.object_node[0], pack.object_node.size());
1250                 device->tex_alloc("__object_node", dscene->object_node);
1251         }
1252         if(pack.prim_tri_index.size()) {
1253                 dscene->prim_tri_index.reference((uint*)&pack.prim_tri_index[0], pack.prim_tri_index.size());
1254                 device->tex_alloc("__prim_tri_index", dscene->prim_tri_index);
1255         }
1256         if(pack.prim_tri_verts.size()) {
1257                 dscene->prim_tri_verts.reference((float4*)&pack.prim_tri_verts[0], pack.prim_tri_verts.size());
1258                 device->tex_alloc("__prim_tri_verts", dscene->prim_tri_verts);
1259         }
1260         if(pack.prim_type.size()) {
1261                 dscene->prim_type.reference((uint*)&pack.prim_type[0], pack.prim_type.size());
1262                 device->tex_alloc("__prim_type", dscene->prim_type);
1263         }
1264         if(pack.prim_visibility.size()) {
1265                 dscene->prim_visibility.reference((uint*)&pack.prim_visibility[0], pack.prim_visibility.size());
1266                 device->tex_alloc("__prim_visibility", dscene->prim_visibility);
1267         }
1268         if(pack.prim_index.size()) {
1269                 dscene->prim_index.reference((uint*)&pack.prim_index[0], pack.prim_index.size());
1270                 device->tex_alloc("__prim_index", dscene->prim_index);
1271         }
1272         if(pack.prim_object.size()) {
1273                 dscene->prim_object.reference((uint*)&pack.prim_object[0], pack.prim_object.size());
1274                 device->tex_alloc("__prim_object", dscene->prim_object);
1275         }
1276
1277         dscene->data.bvh.root = pack.root_index;
1278         dscene->data.bvh.use_qbvh = scene->params.use_qbvh;
1279 }
1280
1281 void MeshManager::device_update_flags(Device * /*device*/,
1282                                       DeviceScene * /*dscene*/,
1283                                       Scene * scene,
1284                                       Progress& /*progress*/)
1285 {
1286         if(!need_update && !need_flags_update) {
1287                 return;
1288         }
1289         /* update flags */
1290         foreach(Mesh *mesh, scene->meshes) {
1291                 mesh->has_volume = false;
1292                 foreach(const Shader *shader, mesh->used_shaders) {
1293                         if(shader->has_volume) {
1294                                 mesh->has_volume = true;
1295                         }
1296                         if(shader->has_surface_bssrdf) {
1297                                 mesh->has_surface_bssrdf = true;
1298                         }
1299                 }
1300         }
1301         need_flags_update = false;
1302 }
1303
1304 void MeshManager::device_update_displacement_images(Device *device,
1305                                                     DeviceScene *dscene,
1306                                                     Scene *scene,
1307                                                     Progress& progress)
1308 {
1309         progress.set_status("Updating Displacement Images");
1310         TaskPool pool;
1311         ImageManager *image_manager = scene->image_manager;
1312         set<int> bump_images;
1313         foreach(Mesh *mesh, scene->meshes) {
1314                 if(mesh->need_update) {
1315                         foreach(Shader *shader, mesh->used_shaders) {
1316                                 if(shader->graph_bump == NULL) {
1317                                         continue;
1318                                 }
1319                                 foreach(ShaderNode* node, shader->graph_bump->nodes) {
1320                                         if(node->special_type != SHADER_SPECIAL_TYPE_IMAGE_SLOT) {
1321                                                 continue;
1322                                         }
1323                                         if(device->info.pack_images) {
1324                                                 /* If device requires packed images we need to update all
1325                                                  * images now, even if they're not used for displacement.
1326                                                  */
1327                                                 image_manager->device_update(device,
1328                                                                              dscene,
1329                                                                              progress);
1330                                                 return;
1331                                         }
1332                                         ImageSlotTextureNode *image_node = static_cast<ImageSlotTextureNode*>(node);
1333                                         int slot = image_node->slot;
1334                                         if(slot != -1) {
1335                                                 bump_images.insert(slot);
1336                                         }
1337                                 }
1338                         }
1339                 }
1340         }
1341         foreach(int slot, bump_images) {
1342                 pool.push(function_bind(&ImageManager::device_update_slot,
1343                                         image_manager,
1344                                         device,
1345                                         dscene,
1346                                         slot,
1347                                         &progress));
1348         }
1349         pool.wait_work();
1350 }
1351
1352 void MeshManager::device_update(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
1353 {
1354         if(!need_update)
1355                 return;
1356
1357         VLOG(1) << "Total " << scene->meshes.size() << " meshes.";
1358
1359         /* Update normals. */
1360         foreach(Mesh *mesh, scene->meshes) {
1361                 foreach(Shader *shader, mesh->used_shaders) {
1362                         if(shader->need_update_attributes)
1363                                 mesh->need_update = true;
1364                 }
1365
1366                 if(mesh->need_update) {
1367                         mesh->add_face_normals();
1368                         mesh->add_vertex_normals();
1369
1370                         if(progress.get_cancel()) return;
1371                 }
1372         }
1373
1374         /* Update images needed for true displacement. */
1375         bool true_displacement_used = false;
1376         bool old_need_object_flags_update = false;
1377         foreach(Mesh *mesh, scene->meshes) {
1378                 if(mesh->need_update &&
1379                    mesh->displacement_method != Mesh::DISPLACE_BUMP)
1380                 {
1381                         true_displacement_used = true;
1382                         break;
1383                 }
1384         }
1385         if(true_displacement_used) {
1386                 VLOG(1) << "Updating images used for true displacement.";
1387                 device_update_displacement_images(device, dscene, scene, progress);
1388                 old_need_object_flags_update = scene->object_manager->need_flags_update;
1389                 scene->object_manager->device_update_flags(device,
1390                                                            dscene,
1391                                                            scene,
1392                                                            progress,
1393                                                            false);
1394         }
1395
1396         /* Device update. */
1397         device_free(device, dscene);
1398
1399         mesh_calc_offset(scene);
1400         if(true_displacement_used) {
1401                 device_update_mesh(device, dscene, scene, true, progress);
1402         }
1403         if(progress.get_cancel()) return;
1404
1405         device_update_attributes(device, dscene, scene, progress);
1406         if(progress.get_cancel()) return;
1407
1408         /* Update displacement. */
1409         bool displacement_done = false;
1410         foreach(Mesh *mesh, scene->meshes) {
1411                 if(mesh->need_update &&
1412                    displace(device, dscene, scene, mesh, progress))
1413                 {
1414                         displacement_done = true;
1415                 }
1416         }
1417
1418         /* TODO: properly handle cancel halfway displacement */
1419         if(progress.get_cancel()) return;
1420
1421         /* Device re-update after displacement. */
1422         if(displacement_done) {
1423                 device_free(device, dscene);
1424
1425                 device_update_attributes(device, dscene, scene, progress);
1426                 if(progress.get_cancel()) return;
1427         }
1428
1429         /* Update bvh. */
1430         size_t i = 0, num_bvh = 0;
1431         foreach(Mesh *mesh, scene->meshes) {
1432                 if(mesh->need_update && mesh->need_build_bvh()) {
1433                         num_bvh++;
1434                 }
1435         }
1436         TaskPool pool;
1437         foreach(Mesh *mesh, scene->meshes) {
1438                 if(mesh->need_update) {
1439                         pool.push(function_bind(&Mesh::compute_bvh,
1440                                                 mesh,
1441                                                 dscene,
1442                                                 &scene->params,
1443                                                 &progress,
1444                                                 i,
1445                                                 num_bvh));
1446                         if(mesh->need_build_bvh()) {
1447                                 i++;
1448                         }
1449                 }
1450         }
1451         TaskPool::Summary summary;
1452         pool.wait_work(&summary);
1453         VLOG(2) << "Objects BVH build pool statistics:\n"
1454                 << summary.full_report();
1455
1456         foreach(Shader *shader, scene->shaders) {
1457                 shader->need_update_attributes = false;
1458         }
1459
1460 #ifdef __OBJECT_MOTION__
1461         Scene::MotionType need_motion = scene->need_motion(device->info.advanced_shading);
1462         bool motion_blur = need_motion == Scene::MOTION_BLUR;
1463 #else
1464         bool motion_blur = false;
1465 #endif
1466
1467         /* Update objects. */
1468         vector<Object *> volume_objects;
1469         foreach(Object *object, scene->objects) {
1470                 object->compute_bounds(motion_blur);
1471         }
1472
1473         if(progress.get_cancel()) return;
1474
1475         device_update_bvh(device, dscene, scene, progress);
1476         if(progress.get_cancel()) return;
1477
1478         device_update_mesh(device, dscene, scene, false, progress);
1479         if(progress.get_cancel()) return;
1480
1481         need_update = false;
1482
1483         if(true_displacement_used) {
1484                 /* Re-tag flags for update, so they're re-evaluated
1485                  * for meshes with correct bounding boxes.
1486                  *
1487                  * This wouldn't cause wrong results, just true
1488                  * displacement might be less optimal ot calculate.
1489                  */
1490                 scene->object_manager->need_flags_update = old_need_object_flags_update;
1491         }
1492 }
1493
1494 void MeshManager::device_free(Device *device, DeviceScene *dscene)
1495 {
1496         device->tex_free(dscene->bvh_nodes);
1497         device->tex_free(dscene->bvh_leaf_nodes);
1498         device->tex_free(dscene->object_node);
1499         device->tex_free(dscene->prim_tri_verts);
1500         device->tex_free(dscene->prim_tri_index);
1501         device->tex_free(dscene->prim_type);
1502         device->tex_free(dscene->prim_visibility);
1503         device->tex_free(dscene->prim_index);
1504         device->tex_free(dscene->prim_object);
1505         device->tex_free(dscene->tri_shader);
1506         device->tex_free(dscene->tri_vnormal);
1507         device->tex_free(dscene->tri_vindex);
1508         device->tex_free(dscene->curves);
1509         device->tex_free(dscene->curve_keys);
1510         device->tex_free(dscene->attributes_map);
1511         device->tex_free(dscene->attributes_float);
1512         device->tex_free(dscene->attributes_float3);
1513         device->tex_free(dscene->attributes_uchar4);
1514
1515         dscene->bvh_nodes.clear();
1516         dscene->object_node.clear();
1517         dscene->prim_tri_verts.clear();
1518         dscene->prim_tri_index.clear();
1519         dscene->prim_type.clear();
1520         dscene->prim_visibility.clear();
1521         dscene->prim_index.clear();
1522         dscene->prim_object.clear();
1523         dscene->tri_shader.clear();
1524         dscene->tri_vnormal.clear();
1525         dscene->tri_vindex.clear();
1526         dscene->curves.clear();
1527         dscene->curve_keys.clear();
1528         dscene->attributes_map.clear();
1529         dscene->attributes_float.clear();
1530         dscene->attributes_float3.clear();
1531         dscene->attributes_uchar4.clear();
1532
1533 #ifdef WITH_OSL
1534         OSLGlobals *og = (OSLGlobals*)device->osl_memory();
1535
1536         if(og) {
1537                 og->object_name_map.clear();
1538                 og->attribute_map.clear();
1539                 og->object_names.clear();
1540         }
1541 #endif
1542 }
1543
1544 void MeshManager::tag_update(Scene *scene)
1545 {
1546         need_update = true;
1547         scene->object_manager->need_update = true;
1548 }
1549
1550 bool Mesh::need_attribute(Scene *scene, AttributeStandard std)
1551 {
1552         if(std == ATTR_STD_NONE)
1553                 return false;
1554         
1555         if(scene->need_global_attribute(std))
1556                 return true;
1557
1558         foreach(Shader *shader, used_shaders)
1559                 if(shader->attributes.find(std))
1560                         return true;
1561         
1562         return false;
1563 }
1564
1565 bool Mesh::need_attribute(Scene * /*scene*/, ustring name)
1566 {
1567         if(name == ustring())
1568                 return false;
1569
1570         foreach(Shader *shader, used_shaders)
1571                 if(shader->attributes.find(name))
1572                         return true;
1573         
1574         return false;
1575 }
1576
1577 void Mesh::tessellate(DiagSplit *split)
1578 {
1579         int num_faces = num_triangles();
1580
1581         add_face_normals();
1582         add_vertex_normals();
1583
1584         Attribute *attr_fN = attributes.find(ATTR_STD_FACE_NORMAL);
1585         float3 *fN = attr_fN->data_float3();
1586
1587         Attribute *attr_vN = attributes.find(ATTR_STD_VERTEX_NORMAL);
1588         float3 *vN = attr_vN->data_float3();
1589
1590         for(int f = 0; f < num_faces; f++) {
1591                 if(!forms_quad[f]) {
1592                         /* triangle */
1593                         LinearTrianglePatch patch;
1594                         Triangle triangle = get_triangle(f);
1595                         float3 *hull = patch.hull;
1596                         float3 *normals = patch.normals;
1597
1598                         for(int i = 0; i < 3; i++) {
1599                                 hull[i] = verts[triangle.v[i]];
1600                         }
1601
1602                         if(smooth[f]) {
1603                                 for(int i = 0; i < 3; i++) {
1604                                         normals[i] = vN[triangle.v[i]];
1605                                 }
1606                         }
1607                         else {
1608                                 for(int i = 0; i < 3; i++) {
1609                                         normals[i] = fN[f];
1610                                 }
1611                         }
1612
1613                         split->split_triangle(&patch);
1614                 }
1615                 else {
1616                         /* quad */
1617                         LinearQuadPatch patch;
1618                         Triangle triangle0 = get_triangle(f);
1619                         Triangle triangle1 = get_triangle(f+1);
1620                         float3 *hull = patch.hull;
1621                         float3 *normals = patch.normals;
1622
1623                         hull[0] = verts[triangle0.v[0]];
1624                         hull[1] = verts[triangle0.v[1]];
1625                         hull[3] = verts[triangle0.v[2]];
1626                         hull[2] = verts[triangle1.v[2]];
1627
1628                         if(smooth[f]) {
1629                                 normals[0] = vN[triangle0.v[0]];
1630                                 normals[1] = vN[triangle0.v[1]];
1631                                 normals[3] = vN[triangle0.v[2]];
1632                                 normals[2] = vN[triangle1.v[2]];
1633                         }
1634                         else {
1635                                 for(int i = 0; i < 4; i++) {
1636                                         normals[i] = fN[f];
1637                                 }
1638                         }
1639
1640                         split->split_quad(&patch);
1641
1642                         // consume second triangle in quad
1643                         f++;
1644                 }
1645
1646         }
1647 }
1648
1649 CCL_NAMESPACE_END
1650