Fix #34040: Moving Normal Node with enabled Cycles Material Preview crashes
[blender.git] / intern / cycles / blender / blender_mesh.cpp
1 /*
2  * Copyright 2011, Blender Foundation.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  */
18
19  
20 #include "mesh.h"
21 #include "object.h"
22 #include "scene.h"
23
24 #include "blender_sync.h"
25 #include "blender_util.h"
26
27 #include "subd_mesh.h"
28 #include "subd_patch.h"
29 #include "subd_split.h"
30
31 #include "util_foreach.h"
32
33 #include "mikktspace.h"
34
35 CCL_NAMESPACE_BEGIN
36
37 /* Tangent Space */
38
39 struct MikkUserData {
40         MikkUserData(const BL::Mesh mesh_, const BL::MeshTextureFaceLayer layer_, int num_faces_)
41         : mesh(mesh_), layer(layer_), num_faces(num_faces_)
42         {
43                 tangent.resize(num_faces*4);
44         }
45
46         BL::Mesh mesh;
47         BL::MeshTextureFaceLayer layer;
48         int num_faces;
49         vector<float4> tangent;
50 };
51
52 static int mikk_get_num_faces(const SMikkTSpaceContext *context)
53 {
54         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
55         return userdata->num_faces;
56 }
57
58 static int mikk_get_num_verts_of_face(const SMikkTSpaceContext *context, const int face_num)
59 {
60         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
61         BL::MeshTessFace f = userdata->mesh.tessfaces[face_num];
62         int4 vi = get_int4(f.vertices_raw());
63
64         return (vi[3] == 0)? 3: 4;
65 }
66
67 static void mikk_get_position(const SMikkTSpaceContext *context, float P[3], const int face_num, const int vert_num)
68 {
69         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
70         BL::MeshTessFace f = userdata->mesh.tessfaces[face_num];
71         int4 vi = get_int4(f.vertices_raw());
72         BL::MeshVertex v = userdata->mesh.vertices[vi[vert_num]];
73         float3 vP = get_float3(v.co());
74
75         P[0] = vP.x;
76         P[1] = vP.y;
77         P[2] = vP.z;
78 }
79
80 static void mikk_get_texture_coordinate(const SMikkTSpaceContext *context, float uv[2], const int face_num, const int vert_num)
81 {
82         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
83         BL::MeshTextureFace tf = userdata->layer.data[face_num];
84         float3 tfuv;
85
86         if(vert_num == 0)
87                 tfuv = get_float3(tf.uv1());
88         else if(vert_num == 1)
89                 tfuv = get_float3(tf.uv2());
90         else if(vert_num == 2)
91                 tfuv = get_float3(tf.uv3());
92         else
93                 tfuv = get_float3(tf.uv4());
94         
95         uv[0] = tfuv.x;
96         uv[1] = tfuv.y;
97 }
98
99 static void mikk_get_normal(const SMikkTSpaceContext *context, float N[3], const int face_num, const int vert_num)
100 {
101         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
102         BL::MeshTessFace f = userdata->mesh.tessfaces[face_num];
103         int4 vi = get_int4(f.vertices_raw());
104         BL::MeshVertex v = userdata->mesh.vertices[vi[vert_num]];
105         float3 vN = get_float3(v.normal());
106
107         N[0] = vN.x;
108         N[1] = vN.y;
109         N[2] = vN.z;
110 }
111
112 static void mikk_set_tangent_space(const SMikkTSpaceContext *context, const float T[], const float sign, const int face, const int vert)
113 {
114         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
115
116         userdata->tangent[face*4 + vert] = make_float4(T[0], T[1], T[2], sign);
117 }
118
119 static void mikk_compute_tangents(BL::Mesh b_mesh, BL::MeshTextureFaceLayer b_layer, Mesh *mesh, vector<int>& nverts, bool need_sign, bool active_render)
120 {
121         /* setup userdata */
122         MikkUserData userdata(b_mesh, b_layer, nverts.size());
123
124         /* setup interface */
125         SMikkTSpaceInterface sm_interface;
126         memset(&sm_interface, 0, sizeof(sm_interface));
127         sm_interface.m_getNumFaces = mikk_get_num_faces;
128         sm_interface.m_getNumVerticesOfFace = mikk_get_num_verts_of_face;
129         sm_interface.m_getPosition = mikk_get_position;
130         sm_interface.m_getTexCoord = mikk_get_texture_coordinate;
131         sm_interface.m_getNormal = mikk_get_normal;
132         sm_interface.m_setTSpaceBasic = mikk_set_tangent_space;
133
134         /* setup context */
135         SMikkTSpaceContext context;
136         memset(&context, 0, sizeof(context));
137         context.m_pUserData = &userdata;
138         context.m_pInterface = &sm_interface;
139
140         /* compute tangents */
141         genTangSpaceDefault(&context);
142
143         /* create tangent attributes */
144         Attribute *attr;
145         ustring name = ustring((string(b_layer.name().c_str()) + ".tangent").c_str());
146
147         if(active_render)
148                 attr = mesh->attributes.add(ATTR_STD_UV_TANGENT, name);
149         else
150                 attr = mesh->attributes.add(name, TypeDesc::TypeVector, ATTR_ELEMENT_CORNER);
151
152         float3 *tangent = attr->data_float3();
153
154         /* create bitangent sign attribute */
155         float *tangent_sign = NULL;
156
157         if(need_sign) {
158                 Attribute *attr_sign;
159                 ustring name_sign = ustring((string(b_layer.name().c_str()) + ".tangent_sign").c_str());
160
161                 if(active_render)
162                         attr_sign = mesh->attributes.add(ATTR_STD_UV_TANGENT_SIGN, name_sign);
163                 else
164                         attr_sign = mesh->attributes.add(name_sign, TypeDesc::TypeFloat, ATTR_ELEMENT_CORNER);
165
166                 tangent_sign = attr_sign->data_float();
167         }
168
169         for(int i = 0; i < nverts.size(); i++) {
170                 tangent[0] = float4_to_float3(userdata.tangent[i*4 + 0]);
171                 tangent[1] = float4_to_float3(userdata.tangent[i*4 + 1]);
172                 tangent[2] = float4_to_float3(userdata.tangent[i*4 + 2]);
173                 tangent += 3;
174
175                 if(tangent_sign) {
176                         tangent_sign[0] = userdata.tangent[i*4 + 0].w;
177                         tangent_sign[1] = userdata.tangent[i*4 + 1].w;
178                         tangent_sign[2] = userdata.tangent[i*4 + 2].w;
179                         tangent_sign += 3;
180                 }
181
182                 if(nverts[i] == 4) {
183                         tangent[0] = float4_to_float3(userdata.tangent[i*4 + 0]);
184                         tangent[1] = float4_to_float3(userdata.tangent[i*4 + 2]);
185                         tangent[2] = float4_to_float3(userdata.tangent[i*4 + 3]);
186                         tangent += 3;
187
188                         if(tangent_sign) {
189                                 tangent_sign[0] = userdata.tangent[i*4 + 0].w;
190                                 tangent_sign[1] = userdata.tangent[i*4 + 2].w;
191                                 tangent_sign[2] = userdata.tangent[i*4 + 3].w;
192                                 tangent_sign += 3;
193                         }
194                 }
195         }
196 }
197
198 /* Create Mesh */
199
200 static void create_mesh(Scene *scene, Mesh *mesh, BL::Mesh b_mesh, const vector<uint>& used_shaders)
201 {
202         /* create vertices */
203         BL::Mesh::vertices_iterator v;
204
205         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
206                 mesh->verts.push_back(get_float3(v->co()));
207
208         /* create vertex normals */
209         Attribute *attr_N = mesh->attributes.add(ATTR_STD_VERTEX_NORMAL);
210         float3 *N = attr_N->data_float3();
211
212         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v, ++N)
213                 *N = get_float3(v->normal());
214
215         /* create faces */
216         BL::Mesh::tessfaces_iterator f;
217         vector<int> nverts;
218
219         for(b_mesh.tessfaces.begin(f); f != b_mesh.tessfaces.end(); ++f) {
220                 int4 vi = get_int4(f->vertices_raw());
221                 int n = (vi[3] == 0)? 3: 4;
222                 int mi = clamp(f->material_index(), 0, used_shaders.size()-1);
223                 int shader = used_shaders[mi];
224                 bool smooth = f->use_smooth();
225
226                 if(n == 4) {
227                         if(len_squared(cross(mesh->verts[vi[1]] - mesh->verts[vi[0]], mesh->verts[vi[2]] - mesh->verts[vi[0]])) == 0.0f ||
228                                 len_squared(cross(mesh->verts[vi[2]] - mesh->verts[vi[0]], mesh->verts[vi[3]] - mesh->verts[vi[0]])) == 0.0f) {
229                                 mesh->add_triangle(vi[0], vi[1], vi[3], shader, smooth);
230                                 mesh->add_triangle(vi[2], vi[3], vi[1], shader, smooth);
231                         }
232                         else {
233                                 mesh->add_triangle(vi[0], vi[1], vi[2], shader, smooth);
234                                 mesh->add_triangle(vi[0], vi[2], vi[3], shader, smooth);
235                         }
236                 }
237                 else
238                         mesh->add_triangle(vi[0], vi[1], vi[2], shader, smooth);
239
240                 nverts.push_back(n);
241         }
242
243         /* create vertex color attributes */
244         {
245                 BL::Mesh::tessface_vertex_colors_iterator l;
246
247                 for(b_mesh.tessface_vertex_colors.begin(l); l != b_mesh.tessface_vertex_colors.end(); ++l) {
248                         if(!mesh->need_attribute(scene, ustring(l->name().c_str())))
249                                 continue;
250
251                         Attribute *attr = mesh->attributes.add(
252                                 ustring(l->name().c_str()), TypeDesc::TypeColor, ATTR_ELEMENT_CORNER);
253
254                         BL::MeshColorLayer::data_iterator c;
255                         float3 *fdata = attr->data_float3();
256                         size_t i = 0;
257
258                         for(l->data.begin(c); c != l->data.end(); ++c, ++i) {
259                                 fdata[0] = color_srgb_to_scene_linear(get_float3(c->color1()));
260                                 fdata[1] = color_srgb_to_scene_linear(get_float3(c->color2()));
261                                 fdata[2] = color_srgb_to_scene_linear(get_float3(c->color3()));
262
263                                 if(nverts[i] == 4) {
264                                         fdata[3] = fdata[0];
265                                         fdata[4] = fdata[2];
266                                         fdata[5] = color_srgb_to_scene_linear(get_float3(c->color4()));
267                                         fdata += 6;
268                                 }
269                                 else
270                                         fdata += 3;
271                         }
272                 }
273         }
274
275         /* create uv map attributes */
276         {
277                 BL::Mesh::tessface_uv_textures_iterator l;
278
279                 for(b_mesh.tessface_uv_textures.begin(l); l != b_mesh.tessface_uv_textures.end(); ++l) {
280                         bool active_render = l->active_render();
281                         AttributeStandard std = (active_render)? ATTR_STD_UV: ATTR_STD_NONE;
282                         ustring name = ustring(l->name().c_str());
283
284                         /* UV map */
285                         if(mesh->need_attribute(scene, name) || mesh->need_attribute(scene, std)) {
286                                 Attribute *attr;
287
288                                 if(active_render)
289                                         attr = mesh->attributes.add(std, name);
290                                 else
291                                         attr = mesh->attributes.add(name, TypeDesc::TypePoint, ATTR_ELEMENT_CORNER);
292
293                                 BL::MeshTextureFaceLayer::data_iterator t;
294                                 float3 *fdata = attr->data_float3();
295                                 size_t i = 0;
296
297                                 for(l->data.begin(t); t != l->data.end(); ++t, ++i) {
298                                         fdata[0] =  get_float3(t->uv1());
299                                         fdata[1] =  get_float3(t->uv2());
300                                         fdata[2] =  get_float3(t->uv3());
301                                         fdata += 3;
302
303                                         if(nverts[i] == 4) {
304                                                 fdata[0] =  get_float3(t->uv1());
305                                                 fdata[1] =  get_float3(t->uv3());
306                                                 fdata[2] =  get_float3(t->uv4());
307                                                 fdata += 3;
308                                         }
309                                 }
310                         }
311
312                         /* UV tangent */
313                         std = (active_render)? ATTR_STD_UV_TANGENT: ATTR_STD_NONE;
314                         name = ustring((string(l->name().c_str()) + ".tangent").c_str());
315
316                         if(mesh->need_attribute(scene, name) || (active_render && mesh->need_attribute(scene, std))) {
317                                 std = (active_render)? ATTR_STD_UV_TANGENT_SIGN: ATTR_STD_NONE;
318                                 name = ustring((string(l->name().c_str()) + ".tangent_sign").c_str());
319                                 bool need_sign = (mesh->need_attribute(scene, name) || mesh->need_attribute(scene, std));
320
321                                 mikk_compute_tangents(b_mesh, *l, mesh, nverts, need_sign, active_render);
322                         }
323                 }
324         }
325
326         /* create generated coordinates. todo: we should actually get the orco
327          * coordinates from modifiers, for now we use texspace loc/size which
328          * is available in the api. */
329         if(mesh->need_attribute(scene, ATTR_STD_GENERATED)) {
330                 Attribute *attr = mesh->attributes.add(ATTR_STD_GENERATED);
331
332                 float3 loc, size;
333                 mesh_texture_space(b_mesh, loc, size);
334
335                 float3 *generated = attr->data_float3();
336                 size_t i = 0;
337
338                 for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
339                         generated[i++] = get_float3(v->co())*size - loc;
340         }
341 }
342
343 static void create_subd_mesh(Mesh *mesh, BL::Mesh b_mesh, PointerRNA *cmesh, const vector<uint>& used_shaders)
344 {
345         /* create subd mesh */
346         SubdMesh sdmesh;
347
348         /* create vertices */
349         BL::Mesh::vertices_iterator v;
350
351         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
352                 sdmesh.add_vert(get_float3(v->co()));
353
354         /* create faces */
355         BL::Mesh::tessfaces_iterator f;
356
357         for(b_mesh.tessfaces.begin(f); f != b_mesh.tessfaces.end(); ++f) {
358                 int4 vi = get_int4(f->vertices_raw());
359                 int n = (vi[3] == 0) ? 3: 4;
360                 //int shader = used_shaders[f->material_index()];
361
362                 if(n == 4)
363                         sdmesh.add_face(vi[0], vi[1], vi[2], vi[3]);
364 #if 0
365                 else
366                         sdmesh.add_face(vi[0], vi[1], vi[2]);
367 #endif
368         }
369
370         /* finalize subd mesh */
371         sdmesh.link_boundary();
372
373         /* subdivide */
374         DiagSplit dsplit;
375         dsplit.camera = NULL;
376         dsplit.dicing_rate = RNA_float_get(cmesh, "dicing_rate");
377
378         sdmesh.tessellate(&dsplit, false, mesh, used_shaders[0], true);
379 }
380
381 /* Sync */
382
383 Mesh *BlenderSync::sync_mesh(BL::Object b_ob, bool object_updated, bool hide_tris)
384 {
385         /* test if we can instance or if the object is modified */
386         BL::ID b_ob_data = b_ob.data();
387         BL::ID key = (BKE_object_is_modified(b_ob))? b_ob: b_ob_data;
388         BL::Material material_override = render_layer.material_override;
389
390         /* find shader indices */
391         vector<uint> used_shaders;
392
393         BL::Object::material_slots_iterator slot;
394         for(b_ob.material_slots.begin(slot); slot != b_ob.material_slots.end(); ++slot) {
395                 if(material_override)
396                         find_shader(material_override, used_shaders, scene->default_surface);
397                 else
398                         find_shader(slot->material(), used_shaders, scene->default_surface);
399         }
400
401         if(used_shaders.size() == 0) {
402                 if(material_override)
403                         find_shader(material_override, used_shaders, scene->default_surface);
404                 else
405                         used_shaders.push_back(scene->default_surface);
406         }
407         
408         /* test if we need to sync */
409         Mesh *mesh;
410
411         if(!mesh_map.sync(&mesh, key)) {
412                 /* if transform was applied to mesh, need full update */
413                 if(object_updated && mesh->transform_applied);
414                 /* test if shaders changed, these can be object level so mesh
415                  * does not get tagged for recalc */
416                 else if(mesh->used_shaders != used_shaders);
417                 else {
418                         /* even if not tagged for recalc, we may need to sync anyway
419                          * because the shader needs different mesh attributes */
420                         bool attribute_recalc = false;
421
422                         foreach(uint shader, mesh->used_shaders)
423                                 if(scene->shaders[shader]->need_update_attributes)
424                                         attribute_recalc = true;
425
426                         if(!attribute_recalc)
427                                 return mesh;
428                 }
429         }
430
431         /* ensure we only sync instanced meshes once */
432         if(mesh_synced.find(mesh) != mesh_synced.end())
433                 return mesh;
434         
435         mesh_synced.insert(mesh);
436
437         /* create derived mesh */
438         BL::Mesh b_mesh = object_to_mesh(b_data, b_ob, b_scene, true, !preview);
439         PointerRNA cmesh = RNA_pointer_get(&b_ob_data.ptr, "cycles");
440
441         vector<Mesh::Triangle> oldtriangle = mesh->triangles;
442         
443         /* compares curve_keys rather than strands in order to handle quick hair adjustsments in dynamic BVH - other methods could probably do this better*/
444         vector<Mesh::CurveKey> oldcurve_keys = mesh->curve_keys;
445
446         mesh->clear();
447         mesh->used_shaders = used_shaders;
448         mesh->name = ustring(b_ob_data.name().c_str());
449
450         if(b_mesh) {
451                 if(!(hide_tris && experimental && is_cpu)) {
452                         if(cmesh.data && experimental && RNA_boolean_get(&cmesh, "use_subdivision"))
453                                 create_subd_mesh(mesh, b_mesh, &cmesh, used_shaders);
454                         else
455                                 create_mesh(scene, mesh, b_mesh, used_shaders);
456                 }
457
458                 if(experimental && is_cpu)
459                         sync_curves(mesh, b_mesh, b_ob, object_updated);
460
461                 /* free derived mesh */
462                 b_data.meshes.remove(b_mesh);
463         }
464
465         /* displacement method */
466         if(cmesh.data) {
467                 int method = RNA_enum_get(&cmesh, "displacement_method");
468
469                 if(method == 0 || !experimental)
470                         mesh->displacement_method = Mesh::DISPLACE_BUMP;
471                 else if(method == 1)
472                         mesh->displacement_method = Mesh::DISPLACE_TRUE;
473                 else
474                         mesh->displacement_method = Mesh::DISPLACE_BOTH;
475         }
476
477         /* tag update */
478         bool rebuild = false;
479
480         if(oldtriangle.size() != mesh->triangles.size())
481                 rebuild = true;
482         else if(oldtriangle.size()) {
483                 if(memcmp(&oldtriangle[0], &mesh->triangles[0], sizeof(Mesh::Triangle)*oldtriangle.size()) != 0)
484                         rebuild = true;
485         }
486
487         if(oldcurve_keys.size() != mesh->curve_keys.size())
488                 rebuild = true;
489         else if(oldcurve_keys.size()) {
490                 if(memcmp(&oldcurve_keys[0], &mesh->curve_keys[0], sizeof(Mesh::CurveKey)*oldcurve_keys.size()) != 0)
491                         rebuild = true;
492         }
493         
494         mesh->tag_update(scene, rebuild);
495
496         return mesh;
497 }
498
499 void BlenderSync::sync_mesh_motion(BL::Object b_ob, Mesh *mesh, int motion)
500 {
501         /* todo: displacement, subdivision */
502         size_t size = mesh->verts.size();
503
504         /* skip objects without deforming modifiers. this is not a totally reliable,
505          * would need a more extensive check to see which objects are animated */
506         if(!size || !ccl::BKE_object_is_deform_modified(b_ob, b_scene, preview))
507                 return;
508
509         /* get derived mesh */
510         BL::Mesh b_mesh = object_to_mesh(b_data, b_ob, b_scene, true, !preview);
511
512         if(b_mesh) {
513                 BL::Mesh::vertices_iterator v;
514                 AttributeStandard std = (motion == -1)? ATTR_STD_MOTION_PRE: ATTR_STD_MOTION_POST;
515                 Attribute *attr_M = mesh->attributes.add(std);
516                 float3 *M = attr_M->data_float3(), *cur_M;
517                 size_t i = 0;
518
519                 for(b_mesh.vertices.begin(v), cur_M = M; v != b_mesh.vertices.end() && i < size; ++v, cur_M++, i++)
520                         *cur_M = get_float3(v->co());
521
522                 /* if number of vertices changed, or if coordinates stayed the same, drop it */
523                 if(i != size || memcmp(M, &mesh->verts[0], sizeof(float3)*size) == 0)
524                         mesh->attributes.remove(std);
525
526                 /* free derived mesh */
527                 b_data.meshes.remove(b_mesh);
528         }
529 }
530
531 CCL_NAMESPACE_END
532