Fix Cycles viewport render not updating when tweaking displacement shader.
[blender.git] / intern / cycles / blender / blender_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 "render/mesh.h"
18 #include "render/object.h"
19 #include "render/scene.h"
20 #include "render/camera.h"
21
22 #include "blender/blender_sync.h"
23 #include "blender/blender_session.h"
24 #include "blender/blender_util.h"
25
26 #include "subd/subd_patch.h"
27 #include "subd/subd_split.h"
28
29 #include "util/util_algorithm.h"
30 #include "util/util_foreach.h"
31 #include "util/util_logging.h"
32 #include "util/util_math.h"
33
34 #include "mikktspace.h"
35
36 CCL_NAMESPACE_BEGIN
37
38 /* Per-face bit flags. */
39 enum {
40         /* Face has no special flags. */
41         FACE_FLAG_NONE      = (0 << 0),
42         /* Quad face was split using 1-3 diagonal. */
43         FACE_FLAG_DIVIDE_13 = (1 << 0),
44         /* Quad face was split using 2-4 diagonal. */
45         FACE_FLAG_DIVIDE_24 = (1 << 1),
46 };
47
48 /* Get vertex indices to create triangles from a given face.
49  *
50  * Two triangles has vertex indices in the original Blender-side face.
51  * If face is already a quad tri_b will not be initialized.
52  */
53 inline void face_split_tri_indices(const int face_flag,
54                                    int tri_a[3],
55                                    int tri_b[3])
56 {
57         if(face_flag & FACE_FLAG_DIVIDE_24) {
58                 tri_a[0] = 0;
59                 tri_a[1] = 1;
60                 tri_a[2] = 3;
61
62                 tri_b[0] = 2;
63                 tri_b[1] = 3;
64                 tri_b[2] = 1;
65         }
66         else {
67                 /* Quad with FACE_FLAG_DIVIDE_13 or single triangle. */
68                 tri_a[0] = 0;
69                 tri_a[1] = 1;
70                 tri_a[2] = 2;
71
72                 tri_b[0] = 0;
73                 tri_b[1] = 2;
74                 tri_b[2] = 3;
75         }
76 }
77
78 /* Tangent Space */
79
80 struct MikkUserData {
81         MikkUserData(const BL::Mesh& b_mesh,
82                      const char *layer_name,
83                      const Mesh *mesh,
84                      float3 *tangent,
85                      float *tangent_sign)
86                 : mesh(mesh),
87                   texface(NULL),
88                   orco(NULL),
89                   tangent(tangent),
90                   tangent_sign(tangent_sign)
91         {
92                 const AttributeSet& attributes = (mesh->subd_faces.size()) ?
93                         mesh->subd_attributes : mesh->attributes;
94
95                 Attribute *attr_vN = attributes.find(ATTR_STD_VERTEX_NORMAL);
96                 vertex_normal = attr_vN->data_float3();
97
98                 if(layer_name == NULL) {
99                         Attribute *attr_orco = attributes.find(ATTR_STD_GENERATED);
100                         orco = attr_orco->data_float3();
101                         mesh_texture_space(*(BL::Mesh*)&b_mesh, orco_loc, orco_size);
102                 }
103                 else {
104                         Attribute *attr_uv = attributes.find(ustring(layer_name));
105                         if(attr_uv != NULL) {
106                                 texface = attr_uv->data_float3();
107                         }
108                 }
109         }
110
111         const Mesh *mesh;
112         int num_faces;
113
114         float3 *vertex_normal;
115         float3 *texface;
116         float3 *orco;
117         float3 orco_loc, orco_size;
118
119         float3 *tangent;
120         float *tangent_sign;
121 };
122
123 static int mikk_get_num_faces(const SMikkTSpaceContext *context)
124 {
125         const MikkUserData *userdata = (const MikkUserData *)context->m_pUserData;
126         if(userdata->mesh->subd_faces.size()) {
127                 return userdata->mesh->subd_faces.size();
128         }
129         else {
130                 return userdata->mesh->num_triangles();
131         }
132 }
133
134 static int mikk_get_num_verts_of_face(const SMikkTSpaceContext *context,
135                                       const int face_num)
136 {
137         const MikkUserData *userdata = (const MikkUserData *)context->m_pUserData;
138         if(userdata->mesh->subd_faces.size()) {
139                 const Mesh *mesh = userdata->mesh;
140                 return mesh->subd_faces[face_num].num_corners;
141         }
142         else {
143                 return 3;
144         }
145 }
146
147 static int mikk_vertex_index(const Mesh *mesh, const int face_num, const int vert_num)
148 {
149         if(mesh->subd_faces.size()) {
150                 const Mesh::SubdFace& face = mesh->subd_faces[face_num];
151                 return mesh->subd_face_corners[face.start_corner + vert_num];
152         }
153         else {
154                 return mesh->triangles[face_num * 3 + vert_num];
155         }
156 }
157
158 static int mikk_corner_index(const Mesh *mesh, const int face_num, const int vert_num)
159 {
160         if(mesh->subd_faces.size()) {
161                 const Mesh::SubdFace& face = mesh->subd_faces[face_num];
162                 return face.start_corner + vert_num;
163         }
164         else {
165                 return face_num * 3 + vert_num;
166         }
167 }
168
169 static void mikk_get_position(const SMikkTSpaceContext *context,
170                               float P[3],
171                               const int face_num, const int vert_num)
172 {
173         const MikkUserData *userdata = (const MikkUserData *)context->m_pUserData;
174         const Mesh *mesh = userdata->mesh;
175         const int vertex_index = mikk_vertex_index(mesh, face_num, vert_num);
176         const float3 vP = mesh->verts[vertex_index];
177         P[0] = vP.x;
178         P[1] = vP.y;
179         P[2] = vP.z;
180 }
181
182 static void mikk_get_texture_coordinate(const SMikkTSpaceContext *context,
183                                         float uv[2],
184                                         const int face_num, const int vert_num)
185 {
186         const MikkUserData *userdata = (const MikkUserData *)context->m_pUserData;
187         const Mesh *mesh = userdata->mesh;
188         if(userdata->texface != NULL) {
189                 const int corner_index = mikk_corner_index(mesh, face_num, vert_num);
190                 float3 tfuv = userdata->texface[corner_index];
191                 uv[0] = tfuv.x;
192                 uv[1] = tfuv.y;
193         }
194         else if(userdata->orco != NULL) {
195                 const int vertex_index = mikk_vertex_index(mesh, face_num, vert_num);
196                 const float3 orco_loc = userdata->orco_loc;
197                 const float3 orco_size = userdata->orco_size;
198                 const float3 orco = (userdata->orco[vertex_index] + orco_loc) / orco_size;
199
200                 const float2 tmp = map_to_sphere(orco);
201                 uv[0] = tmp.x;
202                 uv[1] = tmp.y;
203         }
204         else {
205                 uv[0] = 0.0f;
206                 uv[1] = 0.0f;
207         }
208 }
209
210 static void mikk_get_normal(const SMikkTSpaceContext *context, float N[3],
211                             const int face_num, const int vert_num)
212 {
213         const MikkUserData *userdata = (const MikkUserData *)context->m_pUserData;
214         const Mesh *mesh = userdata->mesh;
215         float3 vN;
216         if(mesh->subd_faces.size()) {
217                 const Mesh::SubdFace& face = mesh->subd_faces[face_num];
218                 if(face.smooth) {
219                         const int vertex_index = mikk_vertex_index(mesh, face_num, vert_num);
220                         vN = userdata->vertex_normal[vertex_index];
221                 }
222                 else {
223                         vN = face.normal(mesh);
224                 }
225         }
226         else {
227                 if(mesh->smooth[face_num]) {
228                         const int vertex_index = mikk_vertex_index(mesh, face_num, vert_num);
229                         vN = userdata->vertex_normal[vertex_index];
230                 }
231                 else {
232                         const Mesh::Triangle tri = mesh->get_triangle(face_num);
233                         vN = tri.compute_normal(&mesh->verts[0]);
234                 }
235         }
236         N[0] = vN.x;
237         N[1] = vN.y;
238         N[2] = vN.z;
239 }
240
241 static void mikk_set_tangent_space(const SMikkTSpaceContext *context,
242                                    const float T[],
243                                    const float sign,
244                                    const int face_num, const int vert_num)
245 {
246         MikkUserData *userdata = (MikkUserData *)context->m_pUserData;
247         const Mesh *mesh = userdata->mesh;
248         const int corner_index = mikk_corner_index(mesh, face_num, vert_num);
249         userdata->tangent[corner_index] = make_float3(T[0], T[1], T[2]);
250         if(userdata->tangent_sign != NULL) {
251                 userdata->tangent_sign[corner_index] = sign;
252         }
253 }
254
255 static void mikk_compute_tangents(const BL::Mesh& b_mesh,
256                                   const char *layer_name,
257                                   Mesh *mesh,
258                                   bool need_sign,
259                                   bool active_render)
260 {
261         /* Create tangent attributes. */
262         AttributeSet& attributes = (mesh->subd_faces.size()) ?
263                 mesh->subd_attributes : mesh->attributes;
264         Attribute *attr;
265         ustring name;
266         if(layer_name != NULL) {
267                 name = ustring((string(layer_name) + ".tangent").c_str());
268         }
269         else {
270                 name = ustring("orco.tangent");
271         }
272         if(active_render) {
273                 attr = attributes.add(ATTR_STD_UV_TANGENT, name);
274         }
275         else {
276                 attr = attributes.add(name, TypeDesc::TypeVector, ATTR_ELEMENT_CORNER);
277         }
278         float3 *tangent = attr->data_float3();
279         /* Create bitangent sign attribute. */
280         float *tangent_sign = NULL;
281         if(need_sign) {
282                 Attribute *attr_sign;
283                 ustring name_sign;
284                 if(layer_name != NULL) {
285                         name_sign = ustring((string(layer_name) +
286                                                    ".tangent_sign").c_str());
287                 }
288                 else {
289                         name_sign = ustring("orco.tangent_sign");
290                 }
291
292                 if(active_render) {
293                         attr_sign = attributes.add(ATTR_STD_UV_TANGENT_SIGN, name_sign);
294                 }
295                 else {
296                         attr_sign = attributes.add(name_sign,
297                                                    TypeDesc::TypeFloat,
298                                                    ATTR_ELEMENT_CORNER);
299                 }
300                 tangent_sign = attr_sign->data_float();
301         }
302         /* Setup userdata. */
303         MikkUserData userdata(b_mesh, layer_name, mesh, tangent, tangent_sign);
304         /* Setup interface. */
305         SMikkTSpaceInterface sm_interface;
306         memset(&sm_interface, 0, sizeof(sm_interface));
307         sm_interface.m_getNumFaces = mikk_get_num_faces;
308         sm_interface.m_getNumVerticesOfFace = mikk_get_num_verts_of_face;
309         sm_interface.m_getPosition = mikk_get_position;
310         sm_interface.m_getTexCoord = mikk_get_texture_coordinate;
311         sm_interface.m_getNormal = mikk_get_normal;
312         sm_interface.m_setTSpaceBasic = mikk_set_tangent_space;
313         /* Setup context. */
314         SMikkTSpaceContext context;
315         memset(&context, 0, sizeof(context));
316         context.m_pUserData = &userdata;
317         context.m_pInterface = &sm_interface;
318         /* Compute tangents. */
319         genTangSpaceDefault(&context);
320 }
321
322 /* Create Volume Attribute */
323
324 static void create_mesh_volume_attribute(BL::Object& b_ob,
325                                          Mesh *mesh,
326                                          ImageManager *image_manager,
327                                          AttributeStandard std,
328                                          float frame)
329 {
330         BL::SmokeDomainSettings b_domain = object_smoke_domain_find(b_ob);
331
332         if(!b_domain)
333                 return;
334
335         Attribute *attr = mesh->attributes.add(std);
336         VoxelAttribute *volume_data = attr->data_voxel();
337         bool is_float, is_linear;
338         bool animated = false;
339
340         volume_data->manager = image_manager;
341         volume_data->slot = image_manager->add_image(
342                 Attribute::standard_name(std),
343                 b_ob.ptr.data,
344                 animated,
345                 frame,
346                 is_float,
347                 is_linear,
348                 INTERPOLATION_LINEAR,
349                 EXTENSION_CLIP,
350                 true);
351 }
352
353 static void create_mesh_volume_attributes(Scene *scene,
354                                           BL::Object& b_ob,
355                                           Mesh *mesh,
356                                           float frame)
357 {
358         /* for smoke volume rendering */
359         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_DENSITY))
360                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_DENSITY, frame);
361         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_COLOR))
362                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_COLOR, frame);
363         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_FLAME))
364                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_FLAME, frame);
365         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_HEAT))
366                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_HEAT, frame);
367         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_VELOCITY))
368                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_VELOCITY, frame);
369 }
370
371 /* Create vertex color attributes. */
372 static void attr_create_vertex_color(Scene *scene,
373                                      Mesh *mesh,
374                                      BL::Mesh& b_mesh,
375                                      const vector<int>& nverts,
376                                      const vector<int>& face_flags,
377                                      bool subdivision)
378 {
379         if(subdivision) {
380                 BL::Mesh::vertex_colors_iterator l;
381
382                 for(b_mesh.vertex_colors.begin(l); l != b_mesh.vertex_colors.end(); ++l) {
383                         if(!mesh->need_attribute(scene, ustring(l->name().c_str())))
384                                 continue;
385
386                         Attribute *attr = mesh->subd_attributes.add(ustring(l->name().c_str()),
387                                                                     TypeDesc::TypeColor,
388                                                                     ATTR_ELEMENT_CORNER_BYTE);
389
390                         BL::Mesh::polygons_iterator p;
391                         uchar4 *cdata = attr->data_uchar4();
392
393                         for(b_mesh.polygons.begin(p); p != b_mesh.polygons.end(); ++p) {
394                                 int n = p->loop_total();
395                                 for(int i = 0; i < n; i++) {
396                                         float3 color = get_float3(l->data[p->loop_start() + i].color());
397                                         *(cdata++) = color_float_to_byte(color_srgb_to_scene_linear_v3(color));
398                                 }
399                         }
400                 }
401         }
402         else {
403                 BL::Mesh::tessface_vertex_colors_iterator l;
404                 for(b_mesh.tessface_vertex_colors.begin(l); l != b_mesh.tessface_vertex_colors.end(); ++l) {
405                         if(!mesh->need_attribute(scene, ustring(l->name().c_str())))
406                                 continue;
407
408                         Attribute *attr = mesh->attributes.add(ustring(l->name().c_str()),
409                                                                TypeDesc::TypeColor,
410                                                                ATTR_ELEMENT_CORNER_BYTE);
411
412                         BL::MeshColorLayer::data_iterator c;
413                         uchar4 *cdata = attr->data_uchar4();
414                         size_t i = 0;
415
416                         for(l->data.begin(c); c != l->data.end(); ++c, ++i) {
417                                 int tri_a[3], tri_b[3];
418                                 face_split_tri_indices(face_flags[i], tri_a, tri_b);
419
420                                 uchar4 colors[4];
421                                 colors[0] = color_float_to_byte(color_srgb_to_scene_linear_v3(get_float3(c->color1())));
422                                 colors[1] = color_float_to_byte(color_srgb_to_scene_linear_v3(get_float3(c->color2())));
423                                 colors[2] = color_float_to_byte(color_srgb_to_scene_linear_v3(get_float3(c->color3())));
424                                 if(nverts[i] == 4) {
425                                         colors[3] = color_float_to_byte(color_srgb_to_scene_linear_v3(get_float3(c->color4())));
426                                 }
427
428                                 cdata[0] = colors[tri_a[0]];
429                                 cdata[1] = colors[tri_a[1]];
430                                 cdata[2] = colors[tri_a[2]];
431
432                                 if(nverts[i] == 4) {
433                                         cdata[3] = colors[tri_b[0]];
434                                         cdata[4] = colors[tri_b[1]];
435                                         cdata[5] = colors[tri_b[2]];
436                                         cdata += 6;
437                                 }
438                                 else
439                                         cdata += 3;
440                         }
441                 }
442         }
443 }
444
445 /* Create uv map attributes. */
446 static void attr_create_uv_map(Scene *scene,
447                                Mesh *mesh,
448                                BL::Mesh& b_mesh,
449                                const vector<int>& nverts,
450                                const vector<int>& face_flags)
451 {
452         if(b_mesh.tessface_uv_textures.length() != 0) {
453                 BL::Mesh::tessface_uv_textures_iterator l;
454
455                 for(b_mesh.tessface_uv_textures.begin(l); l != b_mesh.tessface_uv_textures.end(); ++l) {
456                         const bool active_render = l->active_render();
457                         AttributeStandard uv_std = (active_render)? ATTR_STD_UV: ATTR_STD_NONE;
458                         ustring uv_name = ustring(l->name().c_str());
459                         AttributeStandard tangent_std = (active_render)? ATTR_STD_UV_TANGENT
460                                                                        : ATTR_STD_NONE;
461                         ustring tangent_name = ustring(
462                                 (string(l->name().c_str()) + ".tangent").c_str());
463
464                         /* Denotes whether UV map was requested directly. */
465                         const bool need_uv = mesh->need_attribute(scene, uv_name) ||
466                                              mesh->need_attribute(scene, uv_std);
467                         /* Denotes whether tangent was requested directly. */
468                         const bool need_tangent =
469                                mesh->need_attribute(scene, tangent_name) ||
470                                (active_render && mesh->need_attribute(scene, tangent_std));
471
472                         /* UV map */
473                         /* NOTE: We create temporary UV layer if its needed for tangent but
474                          * wasn't requested by other nodes in shaders.
475                          */
476                         Attribute *uv_attr = NULL;
477                         if(need_uv || need_tangent) {
478                                 if(active_render) {
479                                         uv_attr = mesh->attributes.add(uv_std, uv_name);
480                                 }
481                                 else {
482                                         uv_attr = mesh->attributes.add(uv_name,
483                                                                        TypeDesc::TypePoint,
484                                                                        ATTR_ELEMENT_CORNER);
485                                 }
486
487                                 BL::MeshTextureFaceLayer::data_iterator t;
488                                 float3 *fdata = uv_attr->data_float3();
489                                 size_t i = 0;
490
491                                 for(l->data.begin(t); t != l->data.end(); ++t, ++i) {
492                                         int tri_a[3], tri_b[3];
493                                         face_split_tri_indices(face_flags[i], tri_a, tri_b);
494
495                                         float3 uvs[4];
496                                         uvs[0] = get_float3(t->uv1());
497                                         uvs[1] = get_float3(t->uv2());
498                                         uvs[2] = get_float3(t->uv3());
499                                         if(nverts[i] == 4) {
500                                                 uvs[3] = get_float3(t->uv4());
501                                         }
502
503                                         fdata[0] = uvs[tri_a[0]];
504                                         fdata[1] = uvs[tri_a[1]];
505                                         fdata[2] = uvs[tri_a[2]];
506                                         fdata += 3;
507
508                                         if(nverts[i] == 4) {
509                                                 fdata[0] = uvs[tri_b[0]];
510                                                 fdata[1] = uvs[tri_b[1]];
511                                                 fdata[2] = uvs[tri_b[2]];
512                                                 fdata += 3;
513                                         }
514                                 }
515                         }
516
517                         /* UV tangent */
518                         if(need_tangent) {
519                                 AttributeStandard sign_std =
520                                         (active_render)? ATTR_STD_UV_TANGENT_SIGN
521                                                        : ATTR_STD_NONE;
522                                 ustring sign_name = ustring(
523                                         (string(l->name().c_str()) + ".tangent_sign").c_str());
524                                 bool need_sign = (mesh->need_attribute(scene, sign_name) ||
525                                                   mesh->need_attribute(scene, sign_std));
526                                 mikk_compute_tangents(b_mesh,
527                                                       l->name().c_str(),
528                                                       mesh,
529                                                       need_sign,
530                                                       active_render);
531                         }
532                         /* Remove temporarily created UV attribute. */
533                         if(!need_uv && uv_attr != NULL) {
534                                 mesh->attributes.remove(uv_attr);
535                         }
536                 }
537         }
538         else if(mesh->need_attribute(scene, ATTR_STD_UV_TANGENT)) {
539                 bool need_sign = mesh->need_attribute(scene, ATTR_STD_UV_TANGENT_SIGN);
540                 mikk_compute_tangents(b_mesh, NULL, mesh, need_sign, true);
541                 if(!mesh->need_attribute(scene, ATTR_STD_GENERATED)) {
542                         mesh->attributes.remove(ATTR_STD_GENERATED);
543                 }
544         }
545 }
546
547 static void attr_create_subd_uv_map(Scene *scene,
548                                     Mesh *mesh,
549                                     BL::Mesh& b_mesh,
550                                     bool subdivide_uvs)
551 {
552         if(b_mesh.uv_layers.length() != 0) {
553                 BL::Mesh::uv_layers_iterator l;
554                 int i = 0;
555
556                 for(b_mesh.uv_layers.begin(l); l != b_mesh.uv_layers.end(); ++l, ++i) {
557                         bool active_render = b_mesh.uv_textures[i].active_render();
558                         AttributeStandard uv_std = (active_render)? ATTR_STD_UV: ATTR_STD_NONE;
559                         ustring uv_name = ustring(l->name().c_str());
560                         AttributeStandard tangent_std = (active_render)? ATTR_STD_UV_TANGENT
561                                                                        : ATTR_STD_NONE;
562                         ustring tangent_name = ustring(
563                                 (string(l->name().c_str()) + ".tangent").c_str());
564
565                         /* Denotes whether UV map was requested directly. */
566                         const bool need_uv = mesh->need_attribute(scene, uv_name) ||
567                                              mesh->need_attribute(scene, uv_std);
568                         /* Denotes whether tangent was requested directly. */
569                         const bool need_tangent =
570                                mesh->need_attribute(scene, tangent_name) ||
571                                (active_render && mesh->need_attribute(scene, tangent_std));
572
573                         Attribute *uv_attr = NULL;
574
575                         /* UV map */
576                         if(need_uv || need_tangent) {
577                                 if(active_render)
578                                         uv_attr = mesh->subd_attributes.add(uv_std, uv_name);
579                                 else
580                                         uv_attr = mesh->subd_attributes.add(uv_name, TypeDesc::TypePoint, ATTR_ELEMENT_CORNER);
581
582                                 if(subdivide_uvs) {
583                                         uv_attr->flags |= ATTR_SUBDIVIDED;
584                                 }
585
586                                 BL::Mesh::polygons_iterator p;
587                                 float3 *fdata = uv_attr->data_float3();
588
589                                 for(b_mesh.polygons.begin(p); p != b_mesh.polygons.end(); ++p) {
590                                         int n = p->loop_total();
591                                         for(int j = 0; j < n; j++) {
592                                                 *(fdata++) = get_float3(l->data[p->loop_start() + j].uv());
593                                         }
594                                 }
595                         }
596
597                         /* UV tangent */
598                         if(need_tangent) {
599                                 AttributeStandard sign_std =
600                                         (active_render)? ATTR_STD_UV_TANGENT_SIGN
601                                                        : ATTR_STD_NONE;
602                                 ustring sign_name = ustring(
603                                         (string(l->name().c_str()) + ".tangent_sign").c_str());
604                                 bool need_sign = (mesh->need_attribute(scene, sign_name) ||
605                                                   mesh->need_attribute(scene, sign_std));
606                                 mikk_compute_tangents(b_mesh,
607                                                       l->name().c_str(),
608                                                       mesh,
609                                                       need_sign,
610                                                       active_render);
611                         }
612                         /* Remove temporarily created UV attribute. */
613                         if(!need_uv && uv_attr != NULL) {
614                                 mesh->subd_attributes.remove(uv_attr);
615                         }
616                 }
617         }
618         else if(mesh->need_attribute(scene, ATTR_STD_UV_TANGENT)) {
619                 bool need_sign = mesh->need_attribute(scene, ATTR_STD_UV_TANGENT_SIGN);
620                 mikk_compute_tangents(b_mesh, NULL, mesh, need_sign, true);
621                 if(!mesh->need_attribute(scene, ATTR_STD_GENERATED)) {
622                         mesh->subd_attributes.remove(ATTR_STD_GENERATED);
623                 }
624         }
625 }
626
627 /* Create vertex pointiness attributes. */
628
629 /* Compare vertices by sum of their coordinates. */
630 class VertexAverageComparator {
631 public:
632         VertexAverageComparator(const array<float3>& verts)
633                 : verts_(verts) {
634         }
635
636         bool operator()(const int& vert_idx_a, const int& vert_idx_b)
637         {
638                 const float3 &vert_a = verts_[vert_idx_a];
639                 const float3 &vert_b = verts_[vert_idx_b];
640                 if(vert_a == vert_b) {
641                         /* Special case for doubles, so we ensure ordering. */
642                         return vert_idx_a > vert_idx_b;
643                 }
644                 const float x1 = vert_a.x + vert_a.y + vert_a.z;
645                 const float x2 = vert_b.x + vert_b.y + vert_b.z;
646                 return x1 < x2;
647         }
648
649 protected:
650         const array<float3>& verts_;
651 };
652
653 static void attr_create_pointiness(Scene *scene,
654                                    Mesh *mesh,
655                                    BL::Mesh& b_mesh,
656                                    bool subdivision)
657 {
658         if(!mesh->need_attribute(scene, ATTR_STD_POINTINESS)) {
659                 return;
660         }
661         const int num_verts = b_mesh.vertices.length();
662         if(num_verts == 0) {
663                 return;
664         }
665         /* STEP 1: Find out duplicated vertices and point duplicates to a single
666          *         original vertex.
667          */
668         vector<int> sorted_vert_indeices(num_verts);
669         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
670                 sorted_vert_indeices[vert_index] = vert_index;
671         }
672         VertexAverageComparator compare(mesh->verts);
673         sort(sorted_vert_indeices.begin(), sorted_vert_indeices.end(), compare);
674         /* This array stores index of the original vertex for the given vertex
675          * index.
676          */
677         vector<int> vert_orig_index(num_verts);
678         for(int sorted_vert_index = 0;
679             sorted_vert_index < num_verts;
680             ++sorted_vert_index)
681         {
682                 const int vert_index = sorted_vert_indeices[sorted_vert_index];
683                 const float3 &vert_co = mesh->verts[vert_index];
684                 bool found = false;
685                 for(int other_sorted_vert_index = sorted_vert_index + 1;
686                     other_sorted_vert_index < num_verts;
687                     ++other_sorted_vert_index)
688                 {
689                         const int other_vert_index =
690                                 sorted_vert_indeices[other_sorted_vert_index];
691                         const float3 &other_vert_co = mesh->verts[other_vert_index];
692                         /* We are too far away now, we wouldn't have duplicate. */
693                         if((other_vert_co.x + other_vert_co.y + other_vert_co.z) -
694                            (vert_co.x + vert_co.y + vert_co.z) > 3 * FLT_EPSILON)
695                         {
696                                 break;
697                         }
698                         /* Found duplicate. */
699                         if(len_squared(other_vert_co - vert_co) < FLT_EPSILON) {
700                                 found = true;
701                                 vert_orig_index[vert_index] = other_vert_index;
702                                 break;
703                         }
704                 }
705                 if(!found) {
706                         vert_orig_index[vert_index] = vert_index;
707                 }
708         }
709         /* Make sure we always points to the very first orig vertex. */
710         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
711                 int orig_index = vert_orig_index[vert_index];
712                 while(orig_index != vert_orig_index[orig_index]) {
713                         orig_index = vert_orig_index[orig_index];
714                 }
715                 vert_orig_index[vert_index] = orig_index;
716         }
717         sorted_vert_indeices.free_memory();
718         /* STEP 2: Calculate vertex normals taking into account their possible
719          *         duplicates which gets "welded" together.
720          */
721         vector<float3> vert_normal(num_verts, make_float3(0.0f, 0.0f, 0.0f));
722         /* First we accumulate all vertex normals in the original index. */
723         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
724                 const float3 normal = get_float3(b_mesh.vertices[vert_index].normal());
725                 const int orig_index = vert_orig_index[vert_index];
726                 vert_normal[orig_index] += normal;
727         }
728         /* Then we normalize the accumulated result and flush it to all duplicates
729          * as well.
730          */
731         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
732                 const int orig_index = vert_orig_index[vert_index];
733                 vert_normal[vert_index] = normalize(vert_normal[orig_index]);
734         }
735         /* STEP 3: Calculate pointiness using single ring neighborhood. */
736         vector<int> counter(num_verts, 0);
737         vector<float> raw_data(num_verts, 0.0f);
738         vector<float3> edge_accum(num_verts, make_float3(0.0f, 0.0f, 0.0f));
739         BL::Mesh::edges_iterator e;
740         EdgeMap visited_edges;
741         int edge_index = 0;
742         memset(&counter[0], 0, sizeof(int) * counter.size());
743         for(b_mesh.edges.begin(e); e != b_mesh.edges.end(); ++e, ++edge_index) {
744                 const int v0 = vert_orig_index[b_mesh.edges[edge_index].vertices()[0]],
745                           v1 = vert_orig_index[b_mesh.edges[edge_index].vertices()[1]];
746                 if(visited_edges.exists(v0, v1)) {
747                         continue;
748                 }
749                 visited_edges.insert(v0, v1);
750                 float3 co0 = get_float3(b_mesh.vertices[v0].co()),
751                        co1 = get_float3(b_mesh.vertices[v1].co());
752                 float3 edge = normalize(co1 - co0);
753                 edge_accum[v0] += edge;
754                 edge_accum[v1] += -edge;
755                 ++counter[v0];
756                 ++counter[v1];
757         }
758         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
759                 const int orig_index = vert_orig_index[vert_index];
760                 if(orig_index != vert_index) {
761                         /* Skip duplicates, they'll be overwritten later on. */
762                         continue;
763                 }
764                 if(counter[vert_index] > 0) {
765                         const float3 normal = vert_normal[vert_index];
766                         const float angle =
767                                 safe_acosf(dot(normal,
768                                                edge_accum[vert_index] / counter[vert_index]));
769                         raw_data[vert_index] = angle * M_1_PI_F;
770                 }
771                 else {
772                         raw_data[vert_index] = 0.0f;
773                 }
774         }
775         /* STEP 3: Blur vertices to approximate 2 ring neighborhood. */
776         AttributeSet& attributes = (subdivision)? mesh->subd_attributes: mesh->attributes;
777         Attribute *attr = attributes.add(ATTR_STD_POINTINESS);
778         float *data = attr->data_float();
779         memcpy(data, &raw_data[0], sizeof(float) * raw_data.size());
780         memset(&counter[0], 0, sizeof(int) * counter.size());
781         edge_index = 0;
782         visited_edges.clear();
783         for(b_mesh.edges.begin(e); e != b_mesh.edges.end(); ++e, ++edge_index) {
784                 const int v0 = vert_orig_index[b_mesh.edges[edge_index].vertices()[0]],
785                           v1 = vert_orig_index[b_mesh.edges[edge_index].vertices()[1]];
786                 if(visited_edges.exists(v0, v1)) {
787                         continue;
788                 }
789                 visited_edges.insert(v0, v1);
790                 data[v0] += raw_data[v1];
791                 data[v1] += raw_data[v0];
792                 ++counter[v0];
793                 ++counter[v1];
794         }
795         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
796                 data[vert_index] /= counter[vert_index] + 1;
797         }
798         /* STEP 4: Copy attribute to the duplicated vertices. */
799         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
800                 const int orig_index = vert_orig_index[vert_index];
801                 data[vert_index] = data[orig_index];
802         }
803 }
804
805 /* Create Mesh */
806
807 static void create_mesh(Scene *scene,
808                         Mesh *mesh,
809                         BL::Mesh& b_mesh,
810                         const vector<Shader*>& used_shaders,
811                         bool subdivision = false,
812                         bool subdivide_uvs = true)
813 {
814         /* count vertices and faces */
815         int numverts = b_mesh.vertices.length();
816         int numfaces = (!subdivision) ? b_mesh.tessfaces.length() : b_mesh.polygons.length();
817         int numtris = 0;
818         int numcorners = 0;
819         int numngons = 0;
820         bool use_loop_normals = b_mesh.use_auto_smooth() && (mesh->subdivision_type != Mesh::SUBDIVISION_CATMULL_CLARK);
821
822         /* If no faces, create empty mesh. */
823         if(numfaces == 0) {
824                 return;
825         }
826
827         BL::Mesh::vertices_iterator v;
828         BL::Mesh::tessfaces_iterator f;
829         BL::Mesh::polygons_iterator p;
830
831         if(!subdivision) {
832                 for(b_mesh.tessfaces.begin(f); f != b_mesh.tessfaces.end(); ++f) {
833                         int4 vi = get_int4(f->vertices_raw());
834                         numtris += (vi[3] == 0)? 1: 2;
835                 }
836         }
837         else {
838                 for(b_mesh.polygons.begin(p); p != b_mesh.polygons.end(); ++p) {
839                         numngons += (p->loop_total() == 4)? 0: 1;
840                         numcorners += p->loop_total();
841                 }
842         }
843
844         /* allocate memory */
845         mesh->reserve_mesh(numverts, numtris);
846         mesh->reserve_subd_faces(numfaces, numngons, numcorners);
847
848         /* create vertex coordinates and normals */
849         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
850                 mesh->add_vertex(get_float3(v->co()));
851
852         AttributeSet& attributes = (subdivision)? mesh->subd_attributes: mesh->attributes;
853         Attribute *attr_N = attributes.add(ATTR_STD_VERTEX_NORMAL);
854         float3 *N = attr_N->data_float3();
855
856         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v, ++N)
857                 *N = get_float3(v->normal());
858         N = attr_N->data_float3();
859
860         /* create generated coordinates from undeformed coordinates */
861         const bool need_default_tangent =
862                 (subdivision == false) &&
863                 (b_mesh.tessface_uv_textures.length() == 0) &&
864                 (mesh->need_attribute(scene, ATTR_STD_UV_TANGENT));
865         if(mesh->need_attribute(scene, ATTR_STD_GENERATED) ||
866            need_default_tangent)
867         {
868                 Attribute *attr = attributes.add(ATTR_STD_GENERATED);
869                 attr->flags |= ATTR_SUBDIVIDED;
870
871                 float3 loc, size;
872                 mesh_texture_space(b_mesh, loc, size);
873
874                 float3 *generated = attr->data_float3();
875                 size_t i = 0;
876
877                 for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v) {
878                         generated[i++] = get_float3(v->undeformed_co())*size - loc;
879                 }
880         }
881
882         /* create faces */
883         vector<int> nverts(numfaces);
884         vector<int> face_flags(numfaces, FACE_FLAG_NONE);
885         int fi = 0;
886
887         if(!subdivision) {
888                 for(b_mesh.tessfaces.begin(f); f != b_mesh.tessfaces.end(); ++f, ++fi) {
889                         int4 vi = get_int4(f->vertices_raw());
890                         int n = (vi[3] == 0)? 3: 4;
891                         int shader = clamp(f->material_index(), 0, used_shaders.size()-1);
892                         bool smooth = f->use_smooth() || use_loop_normals;
893
894                         if(use_loop_normals) {
895                                 BL::Array<float, 12> loop_normals = f->split_normals();
896                                 for(int i = 0; i < n; i++) {
897                                         N[vi[i]] = make_float3(loop_normals[i * 3],
898                                                                loop_normals[i * 3 + 1],
899                                                                loop_normals[i * 3 + 2]);
900                                 }
901                         }
902
903                         /* Create triangles.
904                          *
905                          * NOTE: Autosmooth is already taken care about.
906                          */
907                         if(n == 4) {
908                                 if(is_zero(cross(mesh->verts[vi[1]] - mesh->verts[vi[0]], mesh->verts[vi[2]] - mesh->verts[vi[0]])) ||
909                                    is_zero(cross(mesh->verts[vi[2]] - mesh->verts[vi[0]], mesh->verts[vi[3]] - mesh->verts[vi[0]])))
910                                 {
911                                         mesh->add_triangle(vi[0], vi[1], vi[3], shader, smooth);
912                                         mesh->add_triangle(vi[2], vi[3], vi[1], shader, smooth);
913                                         face_flags[fi] |= FACE_FLAG_DIVIDE_24;
914                                 }
915                                 else {
916                                         mesh->add_triangle(vi[0], vi[1], vi[2], shader, smooth);
917                                         mesh->add_triangle(vi[0], vi[2], vi[3], shader, smooth);
918                                         face_flags[fi] |= FACE_FLAG_DIVIDE_13;
919                                 }
920                         }
921                         else {
922                                 mesh->add_triangle(vi[0], vi[1], vi[2], shader, smooth);
923                         }
924
925                         nverts[fi] = n;
926                 }
927         }
928         else {
929                 vector<int> vi;
930
931                 for(b_mesh.polygons.begin(p); p != b_mesh.polygons.end(); ++p) {
932                         int n = p->loop_total();
933                         int shader = clamp(p->material_index(), 0, used_shaders.size()-1);
934                         bool smooth = p->use_smooth() || use_loop_normals;
935
936                         vi.resize(n);
937                         for(int i = 0; i < n; i++) {
938                                 /* NOTE: Autosmooth is already taken care about. */
939                                 vi[i] = b_mesh.loops[p->loop_start() + i].vertex_index();
940                         }
941
942                         /* create subd faces */
943                         mesh->add_subd_face(&vi[0], n, shader, smooth);
944                 }
945         }
946
947         /* Create all needed attributes.
948          * The calculate functions will check whether they're needed or not.
949          */
950         attr_create_pointiness(scene, mesh, b_mesh, subdivision);
951         attr_create_vertex_color(scene, mesh, b_mesh, nverts, face_flags, subdivision);
952
953         if(subdivision) {
954                 attr_create_subd_uv_map(scene, mesh, b_mesh, subdivide_uvs);
955         }
956         else {
957                 attr_create_uv_map(scene, mesh, b_mesh, nverts, face_flags);
958         }
959
960         /* for volume objects, create a matrix to transform from object space to
961          * mesh texture space. this does not work with deformations but that can
962          * probably only be done well with a volume grid mapping of coordinates */
963         if(mesh->need_attribute(scene, ATTR_STD_GENERATED_TRANSFORM)) {
964                 Attribute *attr = mesh->attributes.add(ATTR_STD_GENERATED_TRANSFORM);
965                 Transform *tfm = attr->data_transform();
966
967                 float3 loc, size;
968                 mesh_texture_space(b_mesh, loc, size);
969
970                 *tfm = transform_translate(-loc)*transform_scale(size);
971         }
972 }
973
974 static void create_subd_mesh(Scene *scene,
975                              Mesh *mesh,
976                              BL::Object& b_ob,
977                              BL::Mesh& b_mesh,
978                              const vector<Shader*>& used_shaders,
979                              float dicing_rate,
980                              int max_subdivisions)
981 {
982         BL::SubsurfModifier subsurf_mod(b_ob.modifiers[b_ob.modifiers.length()-1]);
983         bool subdivide_uvs = subsurf_mod.use_subsurf_uv();
984
985         create_mesh(scene, mesh, b_mesh, used_shaders, true, subdivide_uvs);
986
987         /* export creases */
988         size_t num_creases = 0;
989         BL::Mesh::edges_iterator e;
990
991         for(b_mesh.edges.begin(e); e != b_mesh.edges.end(); ++e) {
992                 if(e->crease() != 0.0f) {
993                         num_creases++;
994                 }
995         }
996
997         mesh->subd_creases.resize(num_creases);
998
999         Mesh::SubdEdgeCrease* crease = mesh->subd_creases.data();
1000         for(b_mesh.edges.begin(e); e != b_mesh.edges.end(); ++e) {
1001                 if(e->crease() != 0.0f) {
1002                         crease->v[0] = e->vertices()[0];
1003                         crease->v[1] = e->vertices()[1];
1004                         crease->crease = e->crease();
1005
1006                         crease++;
1007                 }
1008         }
1009
1010         /* set subd params */
1011         if(!mesh->subd_params) {
1012                 mesh->subd_params = new SubdParams(mesh);
1013         }
1014         SubdParams& sdparams = *mesh->subd_params;
1015
1016         PointerRNA cobj = RNA_pointer_get(&b_ob.ptr, "cycles");
1017
1018         sdparams.dicing_rate = max(0.1f, RNA_float_get(&cobj, "dicing_rate") * dicing_rate);
1019         sdparams.max_level = max_subdivisions;
1020
1021         scene->dicing_camera->update(scene);
1022         sdparams.camera = scene->dicing_camera;
1023         sdparams.objecttoworld = get_transform(b_ob.matrix_world());
1024 }
1025
1026 /* Sync */
1027
1028 static void sync_mesh_fluid_motion(BL::Object& b_ob, Scene *scene, Mesh *mesh)
1029 {
1030         if(scene->need_motion() == Scene::MOTION_NONE)
1031                 return;
1032
1033         BL::DomainFluidSettings b_fluid_domain = object_fluid_domain_find(b_ob);
1034
1035         if(!b_fluid_domain)
1036                 return;
1037
1038         /* If the mesh has modifiers following the fluid domain we can't export motion. */
1039         if(b_fluid_domain.fluid_mesh_vertices.length() != mesh->verts.size())
1040                 return;
1041
1042         /* Find or add attribute */
1043         float3 *P = &mesh->verts[0];
1044         Attribute *attr_mP = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
1045
1046         if(!attr_mP) {
1047                 attr_mP = mesh->attributes.add(ATTR_STD_MOTION_VERTEX_POSITION);
1048         }
1049
1050         /* Only export previous and next frame, we don't have any in between data. */
1051         float motion_times[2] = {-1.0f, 1.0f};
1052         for(int step = 0; step < 2; step++) {
1053                 float relative_time = motion_times[step] * scene->motion_shutter_time() * 0.5f;
1054                 float3 *mP = attr_mP->data_float3() + step*mesh->verts.size();
1055
1056                 BL::DomainFluidSettings::fluid_mesh_vertices_iterator fvi;
1057                 int i = 0;
1058
1059                 for(b_fluid_domain.fluid_mesh_vertices.begin(fvi); fvi != b_fluid_domain.fluid_mesh_vertices.end(); ++fvi, ++i) {
1060                         mP[i] = P[i] + get_float3(fvi->velocity()) * relative_time;
1061                 }
1062         }
1063 }
1064
1065 Mesh *BlenderSync::sync_mesh(BL::Object& b_ob,
1066                              bool object_updated,
1067                              bool hide_tris)
1068 {
1069         /* When viewport display is not needed during render we can force some
1070          * caches to be releases from blender side in order to reduce peak memory
1071          * footprint during synchronization process.
1072          */
1073         const bool is_interface_locked = b_engine.render() &&
1074                                          b_engine.render().use_lock_interface();
1075         const bool can_free_caches = BlenderSession::headless || is_interface_locked;
1076
1077         /* test if we can instance or if the object is modified */
1078         BL::ID b_ob_data = b_ob.data();
1079         BL::ID key = (BKE_object_is_modified(b_ob))? b_ob: b_ob_data;
1080         BL::Material material_override = render_layer.material_override;
1081
1082         /* find shader indices */
1083         vector<Shader*> used_shaders;
1084
1085         BL::Object::material_slots_iterator slot;
1086         for(b_ob.material_slots.begin(slot); slot != b_ob.material_slots.end(); ++slot) {
1087                 if(material_override) {
1088                         find_shader(material_override, used_shaders, scene->default_surface);
1089                 }
1090                 else {
1091                         BL::ID b_material(slot->material());
1092                         find_shader(b_material, used_shaders, scene->default_surface);
1093                 }
1094         }
1095
1096         if(used_shaders.size() == 0) {
1097                 if(material_override)
1098                         find_shader(material_override, used_shaders, scene->default_surface);
1099                 else
1100                         used_shaders.push_back(scene->default_surface);
1101         }
1102
1103         /* test if we need to sync */
1104         int requested_geometry_flags = Mesh::GEOMETRY_NONE;
1105         if(render_layer.use_surfaces) {
1106                 requested_geometry_flags |= Mesh::GEOMETRY_TRIANGLES;
1107         }
1108         if(render_layer.use_hair) {
1109                 requested_geometry_flags |= Mesh::GEOMETRY_CURVES;
1110         }
1111         Mesh *mesh;
1112
1113         if(!mesh_map.sync(&mesh, key)) {
1114                 /* if transform was applied to mesh, need full update */
1115                 if(object_updated && mesh->transform_applied);
1116                 /* test if shaders changed, these can be object level so mesh
1117                  * does not get tagged for recalc */
1118                 else if(mesh->used_shaders != used_shaders);
1119                 else if(requested_geometry_flags != mesh->geometry_flags);
1120                 else {
1121                         /* even if not tagged for recalc, we may need to sync anyway
1122                          * because the shader needs different mesh attributes */
1123                         bool attribute_recalc = false;
1124
1125                         foreach(Shader *shader, mesh->used_shaders)
1126                                 if(shader->need_update_mesh)
1127                                         attribute_recalc = true;
1128
1129                         if(!attribute_recalc)
1130                                 return mesh;
1131                 }
1132         }
1133
1134         /* ensure we only sync instanced meshes once */
1135         if(mesh_synced.find(mesh) != mesh_synced.end())
1136                 return mesh;
1137
1138         mesh_synced.insert(mesh);
1139
1140         /* create derived mesh */
1141         array<int> oldtriangles;
1142         array<Mesh::SubdFace> oldsubd_faces;
1143         array<int> oldsubd_face_corners;
1144         oldtriangles.steal_data(mesh->triangles);
1145         oldsubd_faces.steal_data(mesh->subd_faces);
1146         oldsubd_face_corners.steal_data(mesh->subd_face_corners);
1147
1148         /* compares curve_keys rather than strands in order to handle quick hair
1149          * adjustments in dynamic BVH - other methods could probably do this better*/
1150         array<float3> oldcurve_keys;
1151         array<float> oldcurve_radius;
1152         oldcurve_keys.steal_data(mesh->curve_keys);
1153         oldcurve_radius.steal_data(mesh->curve_radius);
1154
1155         mesh->clear();
1156         mesh->used_shaders = used_shaders;
1157         mesh->name = ustring(b_ob_data.name().c_str());
1158
1159         if(requested_geometry_flags != Mesh::GEOMETRY_NONE) {
1160                 /* mesh objects does have special handle in the dependency graph,
1161                  * they're ensured to have properly updated.
1162                  *
1163                  * updating meshes here will end up having derived mesh referencing
1164                  * freed data from the blender side.
1165                  */
1166                 if(preview && b_ob.type() != BL::Object::type_MESH)
1167                         b_ob.update_from_editmode();
1168
1169                 bool need_undeformed = mesh->need_attribute(scene, ATTR_STD_GENERATED);
1170
1171                 mesh->subdivision_type = object_subdivision_type(b_ob, preview, experimental);
1172
1173                 /* Disable adaptive subdivision while baking as the baking system
1174                  * currently doesnt support the topology and will crash.
1175                  */
1176                 if(scene->bake_manager->get_baking()) {
1177                         mesh->subdivision_type = Mesh::SUBDIVISION_NONE;
1178                 }
1179
1180                 BL::Mesh b_mesh = object_to_mesh(b_data,
1181                                                  b_ob,
1182                                                  b_scene,
1183                                                  true,
1184                                                  !preview,
1185                                                  need_undeformed,
1186                                                  mesh->subdivision_type);
1187
1188                 if(b_mesh) {
1189                         if(render_layer.use_surfaces && !hide_tris) {
1190                                 if(mesh->subdivision_type != Mesh::SUBDIVISION_NONE)
1191                                         create_subd_mesh(scene, mesh, b_ob, b_mesh, used_shaders,
1192                                                          dicing_rate, max_subdivisions);
1193                                 else
1194                                         create_mesh(scene, mesh, b_mesh, used_shaders, false);
1195
1196                                 create_mesh_volume_attributes(scene, b_ob, mesh, b_scene.frame_current());
1197                         }
1198
1199                         if(render_layer.use_hair && mesh->subdivision_type == Mesh::SUBDIVISION_NONE)
1200                                 sync_curves(mesh, b_mesh, b_ob, false);
1201
1202                         if(can_free_caches) {
1203                                 b_ob.cache_release();
1204                         }
1205
1206                         /* free derived mesh */
1207                         b_data.meshes.remove(b_mesh, false, true, false);
1208                 }
1209         }
1210         mesh->geometry_flags = requested_geometry_flags;
1211
1212         /* fluid motion */
1213         sync_mesh_fluid_motion(b_ob, scene, mesh);
1214
1215         /* tag update */
1216         bool rebuild = (oldtriangles != mesh->triangles) ||
1217                        (oldsubd_faces != mesh->subd_faces) ||
1218                        (oldsubd_face_corners != mesh->subd_face_corners) ||
1219                        (oldcurve_keys != mesh->curve_keys) ||
1220                        (oldcurve_radius != mesh->curve_radius);
1221
1222         mesh->tag_update(scene, rebuild);
1223
1224         return mesh;
1225 }
1226
1227 void BlenderSync::sync_mesh_motion(BL::Object& b_ob,
1228                                    Object *object,
1229                                    float motion_time)
1230 {
1231         /* ensure we only sync instanced meshes once */
1232         Mesh *mesh = object->mesh;
1233
1234         if(mesh_motion_synced.find(mesh) != mesh_motion_synced.end())
1235                 return;
1236
1237         mesh_motion_synced.insert(mesh);
1238
1239         /* ensure we only motion sync meshes that also had mesh synced, to avoid
1240          * unnecessary work and to ensure that its attributes were clear */
1241         if(mesh_synced.find(mesh) == mesh_synced.end())
1242                 return;
1243
1244         /* for motion pass always compute, for motion blur it can be disabled */
1245         int time_index = 0;
1246
1247         if(scene->need_motion() == Scene::MOTION_BLUR) {
1248                 if(!mesh->use_motion_blur)
1249                         return;
1250
1251                 /* see if this mesh needs motion data at this time */
1252                 vector<float> object_times = object->motion_times();
1253                 bool found = false;
1254
1255                 foreach(float object_time, object_times) {
1256                         if(motion_time == object_time) {
1257                                 found = true;
1258                                 break;
1259                         }
1260                         else
1261                                 time_index++;
1262                 }
1263
1264                 if(!found)
1265                         return;
1266         }
1267         else {
1268                 if(motion_time == -1.0f)
1269                         time_index = 0;
1270                 else if(motion_time == 1.0f)
1271                         time_index = 1;
1272                 else
1273                         return;
1274         }
1275
1276         /* skip empty meshes */
1277         const size_t numverts = mesh->verts.size();
1278         const size_t numkeys = mesh->curve_keys.size();
1279
1280         if(!numverts && !numkeys)
1281                 return;
1282
1283         /* skip objects without deforming modifiers. this is not totally reliable,
1284          * would need a more extensive check to see which objects are animated */
1285         BL::Mesh b_mesh(PointerRNA_NULL);
1286
1287         /* fluid motion is exported immediate with mesh, skip here */
1288         BL::DomainFluidSettings b_fluid_domain = object_fluid_domain_find(b_ob);
1289         if(b_fluid_domain)
1290                 return;
1291
1292         if(ccl::BKE_object_is_deform_modified(b_ob, b_scene, preview)) {
1293                 /* get derived mesh */
1294                 b_mesh = object_to_mesh(b_data,
1295                                         b_ob,
1296                                         b_scene,
1297                                         true,
1298                                         !preview,
1299                                         false,
1300                                         Mesh::SUBDIVISION_NONE);
1301         }
1302
1303         if(!b_mesh) {
1304                 /* if we have no motion blur on this frame, but on other frames, copy */
1305                 if(numverts) {
1306                         /* triangles */
1307                         Attribute *attr_mP = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
1308
1309                         if(attr_mP) {
1310                                 Attribute *attr_mN = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_NORMAL);
1311                                 Attribute *attr_N = mesh->attributes.find(ATTR_STD_VERTEX_NORMAL);
1312                                 float3 *P = &mesh->verts[0];
1313                                 float3 *N = (attr_N)? attr_N->data_float3(): NULL;
1314
1315                                 memcpy(attr_mP->data_float3() + time_index*numverts, P, sizeof(float3)*numverts);
1316                                 if(attr_mN)
1317                                         memcpy(attr_mN->data_float3() + time_index*numverts, N, sizeof(float3)*numverts);
1318                         }
1319                 }
1320
1321                 if(numkeys) {
1322                         /* curves */
1323                         Attribute *attr_mP = mesh->curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
1324
1325                         if(attr_mP) {
1326                                 float3 *keys = &mesh->curve_keys[0];
1327                                 memcpy(attr_mP->data_float3() + time_index*numkeys, keys, sizeof(float3)*numkeys);
1328                         }
1329                 }
1330
1331                 return;
1332         }
1333
1334         /* TODO(sergey): Perform preliminary check for number of verticies. */
1335         if(numverts) {
1336                 /* Find attributes. */
1337                 Attribute *attr_mP = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
1338                 Attribute *attr_mN = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_NORMAL);
1339                 Attribute *attr_N = mesh->attributes.find(ATTR_STD_VERTEX_NORMAL);
1340                 bool new_attribute = false;
1341                 /* Add new attributes if they don't exist already. */
1342                 if(!attr_mP) {
1343                         attr_mP = mesh->attributes.add(ATTR_STD_MOTION_VERTEX_POSITION);
1344                         if(attr_N)
1345                                 attr_mN = mesh->attributes.add(ATTR_STD_MOTION_VERTEX_NORMAL);
1346
1347                         new_attribute = true;
1348                 }
1349                 /* Load vertex data from mesh. */
1350                 float3 *mP = attr_mP->data_float3() + time_index*numverts;
1351                 float3 *mN = (attr_mN)? attr_mN->data_float3() + time_index*numverts: NULL;
1352                 /* NOTE: We don't copy more that existing amount of vertices to prevent
1353                  * possible memory corruption.
1354                  */
1355                 BL::Mesh::vertices_iterator v;
1356                 int i = 0;
1357                 for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end() && i < numverts; ++v, ++i) {
1358                         mP[i] = get_float3(v->co());
1359                         if(mN)
1360                                 mN[i] = get_float3(v->normal());
1361                 }
1362                 if(new_attribute) {
1363                         /* In case of new attribute, we verify if there really was any motion. */
1364                         if(b_mesh.vertices.length() != numverts ||
1365                            memcmp(mP, &mesh->verts[0], sizeof(float3)*numverts) == 0)
1366                         {
1367                                 /* no motion, remove attributes again */
1368                                 if(b_mesh.vertices.length() != numverts) {
1369                                         VLOG(1) << "Topology differs, disabling motion blur for object "
1370                                                 << b_ob.name();
1371                                 }
1372                                 else {
1373                                         VLOG(1) << "No actual deformation motion for object "
1374                                                 << b_ob.name();
1375                                 }
1376                                 mesh->attributes.remove(ATTR_STD_MOTION_VERTEX_POSITION);
1377                                 if(attr_mN)
1378                                         mesh->attributes.remove(ATTR_STD_MOTION_VERTEX_NORMAL);
1379                         }
1380                         else if(time_index > 0) {
1381                                 VLOG(1) << "Filling deformation motion for object " << b_ob.name();
1382                                 /* motion, fill up previous steps that we might have skipped because
1383                                  * they had no motion, but we need them anyway now */
1384                                 float3 *P = &mesh->verts[0];
1385                                 float3 *N = (attr_N)? attr_N->data_float3(): NULL;
1386                                 for(int step = 0; step < time_index; step++) {
1387                                         memcpy(attr_mP->data_float3() + step*numverts, P, sizeof(float3)*numverts);
1388                                         if(attr_mN)
1389                                                 memcpy(attr_mN->data_float3() + step*numverts, N, sizeof(float3)*numverts);
1390                                 }
1391                         }
1392                 }
1393                 else {
1394                         if(b_mesh.vertices.length() != numverts) {
1395                                 VLOG(1) << "Topology differs, discarding motion blur for object "
1396                                         << b_ob.name() << " at time " << time_index;
1397                                 memcpy(mP, &mesh->verts[0], sizeof(float3)*numverts);
1398                                 if(mN != NULL) {
1399                                         memcpy(mN, attr_N->data_float3(), sizeof(float3)*numverts);
1400                                 }
1401                         }
1402                 }
1403         }
1404
1405         /* hair motion */
1406         if(numkeys)
1407                 sync_curves(mesh, b_mesh, b_ob, true, time_index);
1408
1409         /* free derived mesh */
1410         b_data.meshes.remove(b_mesh, false, true, false);
1411 }
1412
1413 CCL_NAMESPACE_END