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