Fix T43311: using displacement shader crashes blender
[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 "shader.h"
24 #include "light.h"
25 #include "mesh.h"
26 #include "object.h"
27 #include "scene.h"
28
29 #include "osl_globals.h"
30
31 #include "util_cache.h"
32 #include "util_foreach.h"
33 #include "util_logging.h"
34 #include "util_progress.h"
35 #include "util_set.h"
36
37 CCL_NAMESPACE_BEGIN
38
39 /* Triangle */
40
41 void Mesh::Triangle::bounds_grow(const float3 *verts, BoundBox& bounds) const
42 {
43         bounds.grow(verts[v[0]]);
44         bounds.grow(verts[v[1]]);
45         bounds.grow(verts[v[2]]);
46 }
47
48 /* Curve */
49
50 void Mesh::Curve::bounds_grow(const int k, const float4 *curve_keys, BoundBox& bounds) const
51 {
52         float3 P[4];
53
54         P[0] = float4_to_float3(curve_keys[max(first_key + k - 1,first_key)]);
55         P[1] = float4_to_float3(curve_keys[first_key + k]);
56         P[2] = float4_to_float3(curve_keys[first_key + k + 1]);
57         P[3] = float4_to_float3(curve_keys[min(first_key + k + 2, first_key + num_keys - 1)]);
58
59         float3 lower;
60         float3 upper;
61
62         curvebounds(&lower.x, &upper.x, P, 0);
63         curvebounds(&lower.y, &upper.y, P, 1);
64         curvebounds(&lower.z, &upper.z, P, 2);
65
66         float mr = max(curve_keys[first_key + k].w, curve_keys[first_key + k + 1].w);
67
68         bounds.grow(lower, mr);
69         bounds.grow(upper, mr);
70 }
71
72 /* Mesh */
73
74 Mesh::Mesh()
75 {
76         need_update = true;
77         need_update_rebuild = false;
78         transform_applied = false;
79         transform_negative_scaled = false;
80         transform_normal = transform_identity();
81         displacement_method = DISPLACE_BUMP;
82         bounds = BoundBox::empty;
83
84         motion_steps = 3;
85         use_motion_blur = false;
86
87         bvh = NULL;
88
89         tri_offset = 0;
90         vert_offset = 0;
91
92         curve_offset = 0;
93         curvekey_offset = 0;
94
95         attributes.triangle_mesh = this;
96         curve_attributes.curve_mesh = this;
97
98         has_volume = false;
99 }
100
101 Mesh::~Mesh()
102 {
103         delete bvh;
104 }
105
106 void Mesh::reserve(int numverts, int numtris, int numcurves, int numcurvekeys)
107 {
108         /* reserve space to add verts and triangles later */
109         verts.resize(numverts);
110         triangles.resize(numtris);
111         shader.resize(numtris);
112         smooth.resize(numtris);
113         curve_keys.resize(numcurvekeys);
114         curves.resize(numcurves);
115
116         attributes.reserve();
117         curve_attributes.reserve();
118 }
119
120 void Mesh::clear()
121 {
122         /* clear all verts and triangles */
123         verts.clear();
124         triangles.clear();
125         shader.clear();
126         smooth.clear();
127
128         curve_keys.clear();
129         curves.clear();
130
131         attributes.clear();
132         curve_attributes.clear();
133         used_shaders.clear();
134
135         transform_applied = false;
136         transform_negative_scaled = false;
137         transform_normal = transform_identity();
138         geometry_synced = false;
139 }
140
141 int Mesh::split_vertex(int vertex)
142 {
143         /* copy vertex location and vertex attributes */
144         verts.push_back(verts[vertex]);
145
146         foreach(Attribute& attr, attributes.attributes) {
147                 if(attr.element == ATTR_ELEMENT_VERTEX) {
148                         vector<char> tmp(attr.data_sizeof());
149                         memcpy(&tmp[0], attr.data() + tmp.size()*vertex, tmp.size());
150                         attr.add(&tmp[0]);
151                 }
152         }
153
154         return verts.size() - 1;
155 }
156
157 void Mesh::set_triangle(int i, int v0, int v1, int v2, int shader_, bool smooth_)
158 {
159         Triangle tri;
160         tri.v[0] = v0;
161         tri.v[1] = v1;
162         tri.v[2] = v2;
163
164         triangles[i] = tri;
165         shader[i] = shader_;
166         smooth[i] = smooth_;
167 }
168
169 void Mesh::add_triangle(int v0, int v1, int v2, int shader_, bool smooth_)
170 {
171         Triangle tri;
172         tri.v[0] = v0;
173         tri.v[1] = v1;
174         tri.v[2] = v2;
175
176         triangles.push_back(tri);
177         shader.push_back(shader_);
178         smooth.push_back(smooth_);
179 }
180
181 void Mesh::add_curve_key(float3 co, float radius)
182 {
183         float4 key = float3_to_float4(co);
184         key.w = radius;
185
186         curve_keys.push_back(key);
187 }
188
189 void Mesh::add_curve(int first_key, int num_keys, int shader)
190 {
191         Curve curve;
192         curve.first_key = first_key;
193         curve.num_keys = num_keys;
194         curve.shader = shader;
195
196         curves.push_back(curve);
197 }
198
199 void Mesh::compute_bounds()
200 {
201         BoundBox bnds = BoundBox::empty;
202         size_t verts_size = verts.size();
203         size_t curve_keys_size = curve_keys.size();
204
205         if(verts_size + curve_keys_size > 0) {
206                 for(size_t i = 0; i < verts_size; i++)
207                         bnds.grow(verts[i]);
208
209                 for(size_t i = 0; i < curve_keys_size; i++)
210                         bnds.grow(float4_to_float3(curve_keys[i]), curve_keys[i].w);
211
212                 Attribute *attr = attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
213                 if (use_motion_blur && attr) {
214                         size_t steps_size = verts.size() * (motion_steps - 1);
215                         float3 *vert_steps = attr->data_float3();
216         
217                         for (size_t i = 0; i < steps_size; i++)
218                                 bnds.grow(vert_steps[i]);
219                 }
220
221                 Attribute *curve_attr = curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
222                 if(use_motion_blur && curve_attr) {
223                         size_t steps_size = curve_keys.size() * (motion_steps - 1);
224                         float3 *key_steps = curve_attr->data_float3();
225         
226                         for (size_t i = 0; i < steps_size; i++)
227                                 bnds.grow(key_steps[i]);
228                 }
229
230                 if(!bnds.valid()) {
231                         bnds = BoundBox::empty;
232
233                         /* skip nan or inf coordinates */
234                         for(size_t i = 0; i < verts_size; i++)
235                                 bnds.grow_safe(verts[i]);
236
237                         for(size_t i = 0; i < curve_keys_size; i++)
238                                 bnds.grow_safe(float4_to_float3(curve_keys[i]), curve_keys[i].w);
239                         
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_safe(vert_steps[i]);
246                         }
247
248                         if (use_motion_blur && curve_attr) {
249                                 size_t steps_size = curve_keys.size() * (motion_steps - 1);
250                                 float3 *key_steps = curve_attr->data_float3();
251                 
252                                 for (size_t i = 0; i < steps_size; i++)
253                                         bnds.grow_safe(key_steps[i]);
254                         }
255                 }
256         }
257
258         if(!bnds.valid()) {
259                 /* empty mesh */
260                 bnds.grow(make_float3(0.0f, 0.0f, 0.0f));
261         }
262
263         bounds = bnds;
264 }
265
266 static float3 compute_face_normal(const Mesh::Triangle& t, float3 *verts)
267 {
268         float3 v0 = verts[t.v[0]];
269         float3 v1 = verts[t.v[1]];
270         float3 v2 = verts[t.v[2]];
271
272         float3 norm = cross(v1 - v0, v2 - v0);
273         float normlen = len(norm);
274
275         if(normlen == 0.0f)
276                 return make_float3(0.0f, 0.0f, 0.0f);
277
278         return norm / normlen;
279 }
280
281 void Mesh::add_face_normals()
282 {
283         /* don't compute if already there */
284         if(attributes.find(ATTR_STD_FACE_NORMAL))
285                 return;
286         
287         /* get attributes */
288         Attribute *attr_fN = attributes.add(ATTR_STD_FACE_NORMAL);
289         float3 *fN = attr_fN->data_float3();
290
291         /* compute face normals */
292         size_t triangles_size = triangles.size();
293         bool flip = transform_negative_scaled;
294
295         if(triangles_size) {
296                 float3 *verts_ptr = &verts[0];
297                 Triangle *triangles_ptr = &triangles[0];
298
299                 for(size_t i = 0; i < triangles_size; i++) {
300                         fN[i] = compute_face_normal(triangles_ptr[i], verts_ptr);
301
302                         if(flip)
303                                 fN[i] = -fN[i];
304                 }
305         }
306
307         /* expected to be in local space */
308         if(transform_applied) {
309                 Transform ntfm = transform_inverse(transform_normal);
310
311                 for(size_t i = 0; i < triangles_size; i++)
312                         fN[i] = normalize(transform_direction(&ntfm, fN[i]));
313         }
314 }
315
316 void Mesh::add_vertex_normals()
317 {
318         bool flip = transform_negative_scaled;
319         size_t verts_size = verts.size();
320         size_t triangles_size = triangles.size();
321
322         /* static vertex normals */
323         if(!attributes.find(ATTR_STD_VERTEX_NORMAL)) {
324                 /* get attributes */
325                 Attribute *attr_fN = attributes.find(ATTR_STD_FACE_NORMAL);
326                 Attribute *attr_vN = attributes.add(ATTR_STD_VERTEX_NORMAL);
327
328                 float3 *fN = attr_fN->data_float3();
329                 float3 *vN = attr_vN->data_float3();
330
331                 /* compute vertex normals */
332                 memset(vN, 0, verts.size()*sizeof(float3));
333
334                 if(triangles_size) {
335                         Triangle *triangles_ptr = &triangles[0];
336
337                         for(size_t i = 0; i < triangles_size; i++)
338                                 for(size_t j = 0; j < 3; j++)
339                                         vN[triangles_ptr[i].v[j]] += fN[i];
340                 }
341
342                 for(size_t i = 0; i < verts_size; i++) {
343                         vN[i] = normalize(vN[i]);
344                         if(flip)
345                                 vN[i] = -vN[i];
346                 }
347         }
348
349         /* motion vertex normals */
350         Attribute *attr_mP = attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
351         Attribute *attr_mN = attributes.find(ATTR_STD_MOTION_VERTEX_NORMAL);
352
353         if(has_motion_blur() && attr_mP && !attr_mN) {
354                 /* create attribute */
355                 attr_mN = attributes.add(ATTR_STD_MOTION_VERTEX_NORMAL);
356
357                 for(int step = 0; step < motion_steps - 1; step++) {
358                         float3 *mP = attr_mP->data_float3() + step*verts.size();
359                         float3 *mN = attr_mN->data_float3() + step*verts.size();
360
361                         /* compute */
362                         memset(mN, 0, verts.size()*sizeof(float3));
363
364                         if(triangles_size) {
365                                 Triangle *triangles_ptr = &triangles[0];
366
367                                 for(size_t i = 0; i < triangles_size; i++) {
368                                         for(size_t j = 0; j < 3; j++) {
369                                                 float3 fN = compute_face_normal(triangles_ptr[i], mP);
370                                                 mN[triangles_ptr[i].v[j]] += fN;
371                                         }
372                                 }
373                         }
374
375                         for(size_t i = 0; i < verts_size; i++) {
376                                 mN[i] = normalize(mN[i]);
377                                 if(flip)
378                                         mN[i] = -mN[i];
379                         }
380                 }
381         }
382 }
383
384 void Mesh::pack_normals(Scene *scene, uint *tri_shader, float4 *vnormal)
385 {
386         Attribute *attr_vN = attributes.find(ATTR_STD_VERTEX_NORMAL);
387
388         float3 *vN = attr_vN->data_float3();
389         uint shader_id = 0;
390         uint last_shader = -1;
391         bool last_smooth = false;
392
393         size_t triangles_size = triangles.size();
394         uint *shader_ptr = (shader.size())? &shader[0]: NULL;
395
396         bool do_transform = transform_applied;
397         Transform ntfm = transform_normal;
398
399         /* save shader */
400         for(size_t i = 0; i < triangles_size; i++) {
401                 if(shader_ptr[i] != last_shader || last_smooth != smooth[i]) {
402                         last_shader = shader_ptr[i];
403                         last_smooth = smooth[i];
404                         shader_id = scene->shader_manager->get_shader_id(last_shader, this, last_smooth);
405                 }
406
407                 tri_shader[i] = shader_id;
408         }
409
410         size_t verts_size = verts.size();
411
412         for(size_t i = 0; i < verts_size; i++) {
413                 float3 vNi = vN[i];
414
415                 if(do_transform)
416                         vNi = normalize(transform_direction(&ntfm, vNi));
417
418                 vnormal[i] = make_float4(vNi.x, vNi.y, vNi.z, 0.0f);
419         }
420 }
421
422 void Mesh::pack_verts(float4 *tri_verts, float4 *tri_vindex, size_t vert_offset)
423 {
424         size_t verts_size = verts.size();
425
426         if(verts_size) {
427                 float3 *verts_ptr = &verts[0];
428
429                 for(size_t i = 0; i < verts_size; i++) {
430                         float3 p = verts_ptr[i];
431                         tri_verts[i] = make_float4(p.x, p.y, p.z, 0.0f);
432                 }
433         }
434
435         size_t triangles_size = triangles.size();
436
437         if(triangles_size) {
438                 Triangle *triangles_ptr = &triangles[0];
439
440                 for(size_t i = 0; i < triangles_size; i++) {
441                         Triangle t = triangles_ptr[i];
442
443                         tri_vindex[i] = make_float4(
444                                 __int_as_float(t.v[0] + vert_offset),
445                                 __int_as_float(t.v[1] + vert_offset),
446                                 __int_as_float(t.v[2] + vert_offset),
447                                 0);
448                 }
449         }
450 }
451
452 void Mesh::pack_curves(Scene *scene, float4 *curve_key_co, float4 *curve_data, size_t curvekey_offset)
453 {
454         size_t curve_keys_size = curve_keys.size();
455         float4 *keys_ptr = NULL;
456
457         /* pack curve keys */
458         if(curve_keys_size) {
459                 keys_ptr = &curve_keys[0];
460
461                 for(size_t i = 0; i < curve_keys_size; i++)
462                         curve_key_co[i] = keys_ptr[i];
463         }
464
465         /* pack curve segments */
466         size_t curve_num = curves.size();
467
468         if(curve_num) {
469                 Curve *curve_ptr = &curves[0];
470                 int shader_id = 0;
471                 
472                 for(size_t i = 0; i < curve_num; i++) {
473                         Curve curve = curve_ptr[i];
474                         shader_id = scene->shader_manager->get_shader_id(curve.shader, this, false);
475
476                         curve_data[i] = make_float4(
477                                 __int_as_float(curve.first_key + curvekey_offset),
478                                 __int_as_float(curve.num_keys),
479                                 __int_as_float(shader_id),
480                                 0.0f);
481                 }
482         }
483 }
484
485 void Mesh::compute_bvh(SceneParams *params, Progress *progress, int n, int total)
486 {
487         if(progress->get_cancel())
488                 return;
489
490         compute_bounds();
491
492         if(!transform_applied) {
493                 string msg = "Updating Mesh BVH ";
494                 if(name == "")
495                         msg += string_printf("%u/%u", (uint)(n+1), (uint)total);
496                 else
497                         msg += string_printf("%s %u/%u", name.c_str(), (uint)(n+1), (uint)total);
498
499                 Object object;
500                 object.mesh = this;
501
502                 vector<Object*> objects;
503                 objects.push_back(&object);
504
505                 if(bvh && !need_update_rebuild) {
506                         progress->set_status(msg, "Refitting BVH");
507                         bvh->objects = objects;
508                         bvh->refit(*progress);
509                 }
510                 else {
511                         progress->set_status(msg, "Building BVH");
512
513                         BVHParams bparams;
514                         bparams.use_cache = params->use_bvh_cache;
515                         bparams.use_spatial_split = params->use_bvh_spatial_split;
516                         bparams.use_qbvh = params->use_qbvh;
517
518                         delete bvh;
519                         bvh = BVH::create(bparams, objects);
520                         bvh->build(*progress);
521                 }
522         }
523
524         need_update = false;
525         need_update_rebuild = false;
526 }
527
528 void Mesh::tag_update(Scene *scene, bool rebuild)
529 {
530         need_update = true;
531
532         if(rebuild) {
533                 need_update_rebuild = true;
534                 scene->light_manager->need_update = true;
535         }
536         else {
537                 foreach(uint sindex, used_shaders)
538                         if(scene->shaders[sindex]->has_surface_emission)
539                                 scene->light_manager->need_update = true;
540         }
541
542         scene->mesh_manager->need_update = true;
543         scene->object_manager->need_update = true;
544 }
545
546 bool Mesh::has_motion_blur() const
547 {
548         return (use_motion_blur &&
549                 (attributes.find(ATTR_STD_MOTION_VERTEX_POSITION) ||
550                  curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION)));
551 }
552
553 /* Mesh Manager */
554
555 MeshManager::MeshManager()
556 {
557         bvh = NULL;
558         need_update = true;
559         need_flags_update = true;
560 }
561
562 MeshManager::~MeshManager()
563 {
564         delete bvh;
565 }
566
567 void MeshManager::update_osl_attributes(Device *device, Scene *scene, vector<AttributeRequestSet>& mesh_attributes)
568 {
569 #ifdef WITH_OSL
570         /* for OSL, a hash map is used to lookup the attribute by name. */
571         OSLGlobals *og = (OSLGlobals*)device->osl_memory();
572
573         og->object_name_map.clear();
574         og->attribute_map.clear();
575         og->object_names.clear();
576
577         og->attribute_map.resize(scene->objects.size()*ATTR_PRIM_TYPES);
578
579         for(size_t i = 0; i < scene->objects.size(); i++) {
580                 /* set object name to object index map */
581                 Object *object = scene->objects[i];
582                 og->object_name_map[object->name] = i;
583                 og->object_names.push_back(object->name);
584
585                 /* set object attributes */
586                 foreach(ParamValue& attr, object->attributes) {
587                         OSLGlobals::Attribute osl_attr;
588
589                         osl_attr.type = attr.type();
590                         osl_attr.elem = ATTR_ELEMENT_OBJECT;
591                         osl_attr.value = attr;
592                         osl_attr.offset = 0;
593
594                         og->attribute_map[i*ATTR_PRIM_TYPES][attr.name()] = osl_attr;
595                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][attr.name()] = osl_attr;
596                 }
597
598                 /* find mesh attributes */
599                 size_t j;
600
601                 for(j = 0; j < scene->meshes.size(); j++)
602                         if(scene->meshes[j] == object->mesh)
603                                 break;
604
605                 AttributeRequestSet& attributes = mesh_attributes[j];
606
607                 /* set object attributes */
608                 foreach(AttributeRequest& req, attributes.requests) {
609                         OSLGlobals::Attribute osl_attr;
610
611                         if(req.triangle_element != ATTR_ELEMENT_NONE) {
612                                 osl_attr.elem = req.triangle_element;
613                                 osl_attr.offset = req.triangle_offset;
614
615                                 if(req.triangle_type == TypeDesc::TypeFloat)
616                                         osl_attr.type = TypeDesc::TypeFloat;
617                                 else if(req.triangle_type == TypeDesc::TypeMatrix)
618                                         osl_attr.type = TypeDesc::TypeMatrix;
619                                 else
620                                         osl_attr.type = TypeDesc::TypeColor;
621
622                                 if(req.std != ATTR_STD_NONE) {
623                                         /* if standard attribute, add lookup by geom: name convention */
624                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
625                                         og->attribute_map[i*ATTR_PRIM_TYPES][stdname] = osl_attr;
626                                 }
627                                 else if(req.name != ustring()) {
628                                         /* add lookup by mesh attribute name */
629                                         og->attribute_map[i*ATTR_PRIM_TYPES][req.name] = osl_attr;
630                                 }
631                         }
632
633                         if(req.curve_element != ATTR_ELEMENT_NONE) {
634                                 osl_attr.elem = req.curve_element;
635                                 osl_attr.offset = req.curve_offset;
636
637                                 if(req.curve_type == TypeDesc::TypeFloat)
638                                         osl_attr.type = TypeDesc::TypeFloat;
639                                 else if(req.curve_type == TypeDesc::TypeMatrix)
640                                         osl_attr.type = TypeDesc::TypeMatrix;
641                                 else
642                                         osl_attr.type = TypeDesc::TypeColor;
643
644                                 if(req.std != ATTR_STD_NONE) {
645                                         /* if standard attribute, add lookup by geom: name convention */
646                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
647                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][stdname] = osl_attr;
648                                 }
649                                 else if(req.name != ustring()) {
650                                         /* add lookup by mesh attribute name */
651                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][req.name] = osl_attr;
652                                 }
653                         }
654                 }
655         }
656 #endif
657 }
658
659 void MeshManager::update_svm_attributes(Device *device, DeviceScene *dscene, Scene *scene, vector<AttributeRequestSet>& mesh_attributes)
660 {
661         /* for SVM, the attributes_map table is used to lookup the offset of an
662          * attribute, based on a unique shader attribute id. */
663
664         /* compute array stride */
665         int attr_map_stride = 0;
666
667         for(size_t i = 0; i < scene->meshes.size(); i++)
668                 attr_map_stride = max(attr_map_stride, (mesh_attributes[i].size() + 1)*ATTR_PRIM_TYPES);
669
670         if(attr_map_stride == 0)
671                 return;
672         
673         /* create attribute map */
674         uint4 *attr_map = dscene->attributes_map.resize(attr_map_stride*scene->objects.size());
675         memset(attr_map, 0, dscene->attributes_map.size()*sizeof(uint));
676
677         for(size_t i = 0; i < scene->objects.size(); i++) {
678                 Object *object = scene->objects[i];
679                 Mesh *mesh = object->mesh;
680
681                 /* find mesh attributes */
682                 size_t j;
683
684                 for(j = 0; j < scene->meshes.size(); j++)
685                         if(scene->meshes[j] == mesh)
686                                 break;
687
688                 AttributeRequestSet& attributes = mesh_attributes[j];
689
690                 /* set object attributes */
691                 int index = i*attr_map_stride;
692
693                 foreach(AttributeRequest& req, attributes.requests) {
694                         uint id;
695
696                         if(req.std == ATTR_STD_NONE)
697                                 id = scene->shader_manager->get_attribute_id(req.name);
698                         else
699                                 id = scene->shader_manager->get_attribute_id(req.std);
700
701                         if(mesh->triangles.size()) {
702                                 attr_map[index].x = id;
703                                 attr_map[index].y = req.triangle_element;
704                                 attr_map[index].z = as_uint(req.triangle_offset);
705
706                                 if(req.triangle_type == TypeDesc::TypeFloat)
707                                         attr_map[index].w = NODE_ATTR_FLOAT;
708                                 else if(req.triangle_type == TypeDesc::TypeMatrix)
709                                         attr_map[index].w = NODE_ATTR_MATRIX;
710                                 else
711                                         attr_map[index].w = NODE_ATTR_FLOAT3;
712                         }
713
714                         index++;
715
716                         if(mesh->curves.size()) {
717                                 attr_map[index].x = id;
718                                 attr_map[index].y = req.curve_element;
719                                 attr_map[index].z = as_uint(req.curve_offset);
720
721                                 if(req.curve_type == TypeDesc::TypeFloat)
722                                         attr_map[index].w = NODE_ATTR_FLOAT;
723                                 else if(req.curve_type == TypeDesc::TypeMatrix)
724                                         attr_map[index].w = NODE_ATTR_MATRIX;
725                                 else
726                                         attr_map[index].w = NODE_ATTR_FLOAT3;
727                         }
728
729                         index++;
730                 }
731
732                 /* terminator */
733                 attr_map[index].x = ATTR_STD_NONE;
734                 attr_map[index].y = 0;
735                 attr_map[index].z = 0;
736                 attr_map[index].w = 0;
737
738                 index++;
739
740                 attr_map[index].x = ATTR_STD_NONE;
741                 attr_map[index].y = 0;
742                 attr_map[index].z = 0;
743                 attr_map[index].w = 0;
744
745                 index++;
746         }
747
748         /* copy to device */
749         dscene->data.bvh.attributes_map_stride = attr_map_stride;
750         device->tex_alloc("__attributes_map", dscene->attributes_map);
751 }
752
753 static void update_attribute_element_offset(Mesh *mesh, vector<float>& attr_float, vector<float4>& attr_float3, vector<uchar4>& attr_uchar4,
754         Attribute *mattr, TypeDesc& type, int& offset, AttributeElement& element)
755 {
756         if(mattr) {
757                 /* store element and type */
758                 element = mattr->element;
759                 type = mattr->type;
760
761                 /* store attribute data in arrays */
762                 size_t size = mattr->element_size(
763                         mesh->verts.size(),
764                         mesh->triangles.size(),
765                         mesh->motion_steps,
766                         mesh->curves.size(),
767                         mesh->curve_keys.size());
768
769                 if(mattr->element == ATTR_ELEMENT_VOXEL) {
770                         /* store slot in offset value */
771                         VoxelAttribute *voxel_data = mattr->data_voxel();
772                         offset = voxel_data->slot;
773                 }
774                 else if(mattr->element == ATTR_ELEMENT_CORNER_BYTE) {
775                         uchar4 *data = mattr->data_uchar4();
776                         offset = attr_uchar4.size();
777
778                         attr_uchar4.resize(attr_uchar4.size() + size);
779
780                         for(size_t k = 0; k < size; k++)
781                                 attr_uchar4[offset+k] = data[k];
782                 }
783                 else if(mattr->type == TypeDesc::TypeFloat) {
784                         float *data = mattr->data_float();
785                         offset = attr_float.size();
786
787                         attr_float.resize(attr_float.size() + size);
788
789                         for(size_t k = 0; k < size; k++)
790                                 attr_float[offset+k] = data[k];
791                 }
792                 else if(mattr->type == TypeDesc::TypeMatrix) {
793                         Transform *tfm = mattr->data_transform();
794                         offset = attr_float3.size();
795
796                         attr_float3.resize(attr_float3.size() + size*4);
797
798                         for(size_t k = 0; k < size*4; k++)
799                                 attr_float3[offset+k] = (&tfm->x)[k];
800                 }
801                 else {
802                         float4 *data = mattr->data_float4();
803                         offset = attr_float3.size();
804
805                         attr_float3.resize(attr_float3.size() + size);
806
807                         for(size_t k = 0; k < size; k++)
808                                 attr_float3[offset+k] = data[k];
809                 }
810
811                 /* mesh vertex/curve index is global, not per object, so we sneak
812                  * a correction for that in here */
813                 if(element == ATTR_ELEMENT_VERTEX)
814                         offset -= mesh->vert_offset;
815                 else if(element == ATTR_ELEMENT_VERTEX_MOTION)
816                         offset -= mesh->vert_offset;
817                 else if(element == ATTR_ELEMENT_FACE)
818                         offset -= mesh->tri_offset;
819                 else if(element == ATTR_ELEMENT_CORNER || element == ATTR_ELEMENT_CORNER_BYTE)
820                         offset -= 3*mesh->tri_offset;
821                 else if(element == ATTR_ELEMENT_CURVE)
822                         offset -= mesh->curve_offset;
823                 else if(element == ATTR_ELEMENT_CURVE_KEY)
824                         offset -= mesh->curvekey_offset;
825                 else if(element == ATTR_ELEMENT_CURVE_KEY_MOTION)
826                         offset -= mesh->curvekey_offset;
827         }
828         else {
829                 /* attribute not found */
830                 element = ATTR_ELEMENT_NONE;
831                 offset = 0;
832         }
833 }
834
835 void MeshManager::device_update_attributes(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
836 {
837         progress.set_status("Updating Mesh", "Computing attributes");
838
839         /* gather per mesh requested attributes. as meshes may have multiple
840          * shaders assigned, this merges the requested attributes that have
841          * been set per shader by the shader manager */
842         vector<AttributeRequestSet> mesh_attributes(scene->meshes.size());
843
844         for(size_t i = 0; i < scene->meshes.size(); i++) {
845                 Mesh *mesh = scene->meshes[i];
846
847                 scene->need_global_attributes(mesh_attributes[i]);
848
849                 foreach(uint sindex, mesh->used_shaders) {
850                         Shader *shader = scene->shaders[sindex];
851                         mesh_attributes[i].add(shader->attributes);
852                 }
853         }
854
855         /* mesh attribute are stored in a single array per data type. here we fill
856          * those arrays, and set the offset and element type to create attribute
857          * maps next */
858         vector<float> attr_float;
859         vector<float4> attr_float3;
860         vector<uchar4> attr_uchar4;
861
862         for(size_t i = 0; i < scene->meshes.size(); i++) {
863                 Mesh *mesh = scene->meshes[i];
864                 AttributeRequestSet& attributes = mesh_attributes[i];
865
866                 /* todo: we now store std and name attributes from requests even if
867                  * they actually refer to the same mesh attributes, optimize */
868                 foreach(AttributeRequest& req, attributes.requests) {
869                         Attribute *triangle_mattr = mesh->attributes.find(req);
870                         Attribute *curve_mattr = mesh->curve_attributes.find(req);
871
872                         /* todo: get rid of this exception, it's only here for giving some
873                          * working texture coordinate for subdivision as we can't preserve
874                          * any attributes yet */
875                         if(!triangle_mattr && req.std == ATTR_STD_GENERATED) {
876                                 triangle_mattr = mesh->attributes.add(ATTR_STD_GENERATED);
877                                 if(mesh->verts.size())
878                                         memcpy(triangle_mattr->data_float3(), &mesh->verts[0], sizeof(float3)*mesh->verts.size());
879                         }
880
881                         update_attribute_element_offset(mesh, attr_float, attr_float3, attr_uchar4, triangle_mattr,
882                                 req.triangle_type, req.triangle_offset, req.triangle_element);
883
884                         update_attribute_element_offset(mesh, attr_float, attr_float3, attr_uchar4, curve_mattr,
885                                 req.curve_type, req.curve_offset, req.curve_element);
886         
887                         if(progress.get_cancel()) return;
888                 }
889         }
890
891         /* create attribute lookup maps */
892         if(scene->shader_manager->use_osl())
893                 update_osl_attributes(device, scene, mesh_attributes);
894
895         update_svm_attributes(device, dscene, scene, mesh_attributes);
896
897         if(progress.get_cancel()) return;
898
899         /* copy to device */
900         progress.set_status("Updating Mesh", "Copying Attributes to device");
901
902         if(attr_float.size()) {
903                 dscene->attributes_float.copy(&attr_float[0], attr_float.size());
904                 device->tex_alloc("__attributes_float", dscene->attributes_float);
905         }
906         if(attr_float3.size()) {
907                 dscene->attributes_float3.copy(&attr_float3[0], attr_float3.size());
908                 device->tex_alloc("__attributes_float3", dscene->attributes_float3);
909         }
910         if(attr_uchar4.size()) {
911                 dscene->attributes_uchar4.copy(&attr_uchar4[0], attr_uchar4.size());
912                 device->tex_alloc("__attributes_uchar4", dscene->attributes_uchar4);
913         }
914 }
915
916 void MeshManager::device_update_mesh(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
917 {
918         /* count and update offsets */
919         size_t vert_size = 0;
920         size_t tri_size = 0;
921
922         size_t curve_key_size = 0;
923         size_t curve_size = 0;
924
925         foreach(Mesh *mesh, scene->meshes) {
926                 mesh->vert_offset = vert_size;
927                 mesh->tri_offset = tri_size;
928
929                 mesh->curvekey_offset = curve_key_size;
930                 mesh->curve_offset = curve_size;
931
932                 vert_size += mesh->verts.size();
933                 tri_size += mesh->triangles.size();
934
935                 curve_key_size += mesh->curve_keys.size();
936                 curve_size += mesh->curves.size();
937         }
938
939         if(tri_size != 0) {
940                 /* normals */
941                 progress.set_status("Updating Mesh", "Computing normals");
942
943                 uint *tri_shader = dscene->tri_shader.resize(tri_size);
944                 float4 *vnormal = dscene->tri_vnormal.resize(vert_size);
945                 float4 *tri_verts = dscene->tri_verts.resize(vert_size);
946                 float4 *tri_vindex = dscene->tri_vindex.resize(tri_size);
947
948                 foreach(Mesh *mesh, scene->meshes) {
949                         mesh->pack_normals(scene, &tri_shader[mesh->tri_offset], &vnormal[mesh->vert_offset]);
950                         mesh->pack_verts(&tri_verts[mesh->vert_offset], &tri_vindex[mesh->tri_offset], mesh->vert_offset);
951
952                         if(progress.get_cancel()) return;
953                 }
954
955                 /* vertex coordinates */
956                 progress.set_status("Updating Mesh", "Copying Mesh to device");
957
958                 device->tex_alloc("__tri_shader", dscene->tri_shader);
959                 device->tex_alloc("__tri_vnormal", dscene->tri_vnormal);
960                 device->tex_alloc("__tri_verts", dscene->tri_verts);
961                 device->tex_alloc("__tri_vindex", dscene->tri_vindex);
962         }
963
964         if(curve_size != 0) {
965                 progress.set_status("Updating Mesh", "Copying Strands to device");
966
967                 float4 *curve_keys = dscene->curve_keys.resize(curve_key_size);
968                 float4 *curves = dscene->curves.resize(curve_size);
969
970                 foreach(Mesh *mesh, scene->meshes) {
971                         mesh->pack_curves(scene, &curve_keys[mesh->curvekey_offset], &curves[mesh->curve_offset], mesh->curvekey_offset);
972                         if(progress.get_cancel()) return;
973                 }
974
975                 device->tex_alloc("__curve_keys", dscene->curve_keys);
976                 device->tex_alloc("__curves", dscene->curves);
977         }
978 }
979
980 void MeshManager::device_update_bvh(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
981 {
982         /* bvh build */
983         progress.set_status("Updating Scene BVH", "Building");
984
985         VLOG(1) << (scene->params.use_qbvh ? "Using QBVH optimization structure"
986                                            : "Using regular BVH optimization structure");
987
988         BVHParams bparams;
989         bparams.top_level = true;
990         bparams.use_qbvh = scene->params.use_qbvh;
991         bparams.use_spatial_split = scene->params.use_bvh_spatial_split;
992         bparams.use_cache = scene->params.use_bvh_cache;
993
994         delete bvh;
995         bvh = BVH::create(bparams, scene->objects);
996         bvh->build(progress);
997
998         if(progress.get_cancel()) return;
999
1000         /* copy to device */
1001         progress.set_status("Updating Scene BVH", "Copying BVH to device");
1002
1003         PackedBVH& pack = bvh->pack;
1004
1005         if(pack.nodes.size()) {
1006                 dscene->bvh_nodes.reference((float4*)&pack.nodes[0], pack.nodes.size());
1007                 device->tex_alloc("__bvh_nodes", dscene->bvh_nodes);
1008         }
1009         if(pack.object_node.size()) {
1010                 dscene->object_node.reference((uint*)&pack.object_node[0], pack.object_node.size());
1011                 device->tex_alloc("__object_node", dscene->object_node);
1012         }
1013         if(pack.tri_woop.size()) {
1014                 dscene->tri_woop.reference(&pack.tri_woop[0], pack.tri_woop.size());
1015                 device->tex_alloc("__tri_woop", dscene->tri_woop);
1016         }
1017         if(pack.prim_type.size()) {
1018                 dscene->prim_type.reference((uint*)&pack.prim_type[0], pack.prim_type.size());
1019                 device->tex_alloc("__prim_type", dscene->prim_type);
1020         }
1021         if(pack.prim_visibility.size()) {
1022                 dscene->prim_visibility.reference((uint*)&pack.prim_visibility[0], pack.prim_visibility.size());
1023                 device->tex_alloc("__prim_visibility", dscene->prim_visibility);
1024         }
1025         if(pack.prim_index.size()) {
1026                 dscene->prim_index.reference((uint*)&pack.prim_index[0], pack.prim_index.size());
1027                 device->tex_alloc("__prim_index", dscene->prim_index);
1028         }
1029         if(pack.prim_object.size()) {
1030                 dscene->prim_object.reference((uint*)&pack.prim_object[0], pack.prim_object.size());
1031                 device->tex_alloc("__prim_object", dscene->prim_object);
1032         }
1033
1034         dscene->data.bvh.root = pack.root_index;
1035         dscene->data.bvh.use_qbvh = scene->params.use_qbvh;
1036 }
1037
1038 void MeshManager::device_update_flags(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
1039 {
1040         if(!need_update && !need_flags_update) {
1041                 return;
1042         }
1043         /* update flags */
1044         foreach(Mesh *mesh, scene->meshes) {
1045                 mesh->has_volume = false;
1046                 foreach(uint shader, mesh->used_shaders) {
1047                         if(scene->shaders[shader]->has_volume) {
1048                                 mesh->has_volume = true;
1049                         }
1050                 }
1051         }
1052         need_flags_update = false;
1053 }
1054
1055 void MeshManager::device_update(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
1056 {
1057         if(!need_update)
1058                 return;
1059
1060         /* update normals */
1061         foreach(Mesh *mesh, scene->meshes) {
1062                 foreach(uint shader, mesh->used_shaders) {
1063                         if(scene->shaders[shader]->need_update_attributes)
1064                                 mesh->need_update = true;
1065                 }
1066
1067                 if(mesh->need_update) {
1068                         mesh->add_face_normals();
1069                         mesh->add_vertex_normals();
1070
1071                         if(progress.get_cancel()) return;
1072                 }
1073         }
1074
1075         /* device update */
1076         device_free(device, dscene);
1077
1078         device_update_mesh(device, dscene, scene, progress);
1079         if(progress.get_cancel()) return;
1080
1081         device_update_attributes(device, dscene, scene, progress);
1082         if(progress.get_cancel()) return;
1083
1084         /* update displacement */
1085         bool displacement_done = false;
1086
1087         foreach(Mesh *mesh, scene->meshes)
1088                 if(mesh->need_update && displace(device, dscene, scene, mesh, progress))
1089                         displacement_done = true;
1090
1091         /* todo: properly handle cancel halfway displacement */
1092         if(progress.get_cancel()) return;
1093
1094         /* device re-update after displacement */
1095         if(displacement_done) {
1096                 device_free(device, dscene);
1097
1098                 device_update_mesh(device, dscene, scene, progress);
1099                 if(progress.get_cancel()) return;
1100
1101                 device_update_attributes(device, dscene, scene, progress);
1102                 if(progress.get_cancel()) return;
1103         }
1104
1105         /* update bvh */
1106         size_t i = 0, num_bvh = 0;
1107
1108         foreach(Mesh *mesh, scene->meshes)
1109                 if(mesh->need_update && !mesh->transform_applied)
1110                         num_bvh++;
1111
1112         TaskPool pool;
1113
1114         foreach(Mesh *mesh, scene->meshes) {
1115                 if(mesh->need_update) {
1116                         pool.push(function_bind(&Mesh::compute_bvh,
1117                                                 mesh,
1118                                                 &scene->params,
1119                                                 &progress,
1120                                                 i,
1121                                                 num_bvh));
1122                         i++;
1123                 }
1124         }
1125
1126         pool.wait_work();
1127         
1128         foreach(Shader *shader, scene->shaders)
1129                 shader->need_update_attributes = false;
1130
1131 #ifdef __OBJECT_MOTION__
1132         Scene::MotionType need_motion = scene->need_motion(device->info.advanced_shading);
1133         bool motion_blur = need_motion == Scene::MOTION_BLUR;
1134 #else
1135         bool motion_blur = false;
1136 #endif
1137
1138         /* update obejcts */
1139         vector<Object *> volume_objects;
1140         foreach(Object *object, scene->objects)
1141                 object->compute_bounds(motion_blur);
1142
1143         if(progress.get_cancel()) return;
1144
1145         device_update_bvh(device, dscene, scene, progress);
1146
1147         need_update = false;
1148 }
1149
1150 void MeshManager::device_free(Device *device, DeviceScene *dscene)
1151 {
1152         device->tex_free(dscene->bvh_nodes);
1153         device->tex_free(dscene->object_node);
1154         device->tex_free(dscene->tri_woop);
1155         device->tex_free(dscene->prim_type);
1156         device->tex_free(dscene->prim_visibility);
1157         device->tex_free(dscene->prim_index);
1158         device->tex_free(dscene->prim_object);
1159         device->tex_free(dscene->tri_shader);
1160         device->tex_free(dscene->tri_vnormal);
1161         device->tex_free(dscene->tri_vindex);
1162         device->tex_free(dscene->tri_verts);
1163         device->tex_free(dscene->curves);
1164         device->tex_free(dscene->curve_keys);
1165         device->tex_free(dscene->attributes_map);
1166         device->tex_free(dscene->attributes_float);
1167         device->tex_free(dscene->attributes_float3);
1168         device->tex_free(dscene->attributes_uchar4);
1169
1170         dscene->bvh_nodes.clear();
1171         dscene->object_node.clear();
1172         dscene->tri_woop.clear();
1173         dscene->prim_type.clear();
1174         dscene->prim_visibility.clear();
1175         dscene->prim_index.clear();
1176         dscene->prim_object.clear();
1177         dscene->tri_shader.clear();
1178         dscene->tri_vnormal.clear();
1179         dscene->tri_vindex.clear();
1180         dscene->tri_verts.clear();
1181         dscene->curves.clear();
1182         dscene->curve_keys.clear();
1183         dscene->attributes_map.clear();
1184         dscene->attributes_float.clear();
1185         dscene->attributes_float3.clear();
1186         dscene->attributes_uchar4.clear();
1187
1188 #ifdef WITH_OSL
1189         OSLGlobals *og = (OSLGlobals*)device->osl_memory();
1190
1191         if(og) {
1192                 og->object_name_map.clear();
1193                 og->attribute_map.clear();
1194                 og->object_names.clear();
1195         }
1196 #endif
1197 }
1198
1199 void MeshManager::tag_update(Scene *scene)
1200 {
1201         need_update = true;
1202         scene->object_manager->need_update = true;
1203 }
1204
1205 bool Mesh::need_attribute(Scene *scene, AttributeStandard std)
1206 {
1207         if(std == ATTR_STD_NONE)
1208                 return false;
1209         
1210         if(scene->need_global_attribute(std))
1211                 return true;
1212
1213         foreach(uint shader, used_shaders)
1214                 if(scene->shaders[shader]->attributes.find(std))
1215                         return true;
1216         
1217         return false;
1218 }
1219
1220 bool Mesh::need_attribute(Scene *scene, ustring name)
1221 {
1222         if(name == ustring())
1223                 return false;
1224
1225         foreach(uint shader, used_shaders)
1226                 if(scene->shaders[shader]->attributes.find(name))
1227                         return true;
1228         
1229         return false;
1230 }
1231
1232 CCL_NAMESPACE_END
1233