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