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