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