style cleanup: follow style guide for/with/if spacing
[blender.git] / source / blender / blenkernel / intern / DerivedMesh.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
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  * The Original Code is Copyright (C) 2005 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/DerivedMesh.c
29  *  \ingroup bke
30  */
31
32
33 #include <string.h>
34 #include "limits.h"
35
36 #include "MEM_guardedalloc.h"
37
38 #include "DNA_cloth_types.h"
39 #include "DNA_key_types.h"
40 #include "DNA_mesh_types.h"
41 #include "DNA_meshdata_types.h"
42 #include "DNA_armature_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_scene_types.h" // N_T
45
46 #include "BLI_blenlib.h"
47 #include "BLI_math.h"
48 #include "BLI_memarena.h"
49 #include "BLI_array.h"
50 #include "BLI_pbvh.h"
51 #include "BLI_utildefines.h"
52 #include "BLI_linklist.h"
53
54 #include "BLF_translation.h"
55
56 #include "BKE_cdderivedmesh.h"
57 #include "BKE_displist.h"
58 #include "BKE_key.h"
59 #include "BKE_modifier.h"
60 #include "BKE_mesh.h"
61 #include "BKE_object.h"
62 #include "BKE_paint.h"
63 #include "BKE_texture.h"
64 #include "BKE_multires.h"
65 #include "BKE_armature.h"
66 #include "BKE_particle.h"
67 #include "BKE_tessmesh.h"
68 #include "BKE_bvhutils.h"
69 #include "BKE_deform.h"
70 #include "BKE_global.h" /* For debug flag, DM_update_tessface_data() func. */
71
72 #ifdef WITH_GAMEENGINE
73 #include "BKE_navmesh_conversion.h"
74 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm);
75 #endif
76
77 #include "BLO_sys_types.h" // for intptr_t support
78
79 #include "GL/glew.h"
80
81 #include "GPU_buffers.h"
82 #include "GPU_draw.h"
83 #include "GPU_extensions.h"
84 #include "GPU_material.h"
85
86 static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *ob);
87 static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid);
88
89 ///////////////////////////////////
90 ///////////////////////////////////
91
92 static MVert *dm_getVertArray(DerivedMesh *dm)
93 {
94         MVert *mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
95
96         if (!mvert) {
97                 mvert = CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL,
98                         dm->getNumVerts(dm));
99                 CustomData_set_layer_flag(&dm->vertData, CD_MVERT, CD_FLAG_TEMPORARY);
100                 dm->copyVertArray(dm, mvert);
101         }
102
103         return mvert;
104 }
105
106 static MEdge *dm_getEdgeArray(DerivedMesh *dm)
107 {
108         MEdge *medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
109
110         if (!medge) {
111                 medge = CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL,
112                         dm->getNumEdges(dm));
113                 CustomData_set_layer_flag(&dm->edgeData, CD_MEDGE, CD_FLAG_TEMPORARY);
114                 dm->copyEdgeArray(dm, medge);
115         }
116
117         return medge;
118 }
119
120 static MFace *dm_getTessFaceArray(DerivedMesh *dm)
121 {
122         MFace *mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
123
124         if (!mface) {
125                 int numTessFaces = dm->getNumTessFaces(dm);
126                 
127                 if (!numTessFaces) {
128                         /* Do not add layer if there's no elements in it, this leads to issues later when
129                          * this layer is needed with non-zero size, but currently CD stuff does not check
130                          * for requested layer size on creation and just returns layer which was previously
131                          * added (sergey) */
132                         return NULL;
133                 }
134                 
135                 mface = CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numTessFaces);
136                 CustomData_set_layer_flag(&dm->faceData, CD_MFACE, CD_FLAG_TEMPORARY);
137                 dm->copyTessFaceArray(dm, mface);
138         }
139
140         return mface;
141 }
142
143 static MLoop *dm_getLoopArray(DerivedMesh *dm)
144 {
145         MLoop *mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
146
147         if (!mloop) {
148                 mloop = CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_CALLOC, NULL,
149                         dm->getNumLoops(dm));
150                 CustomData_set_layer_flag(&dm->loopData, CD_MLOOP, CD_FLAG_TEMPORARY);
151                 dm->copyLoopArray(dm, mloop);
152         }
153
154         return mloop;
155 }
156
157 static MPoly *dm_getPolyArray(DerivedMesh *dm)
158 {
159         MPoly *mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
160
161         if (!mpoly) {
162                 mpoly = CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_CALLOC, NULL,
163                         dm->getNumPolys(dm));
164                 CustomData_set_layer_flag(&dm->polyData, CD_MPOLY, CD_FLAG_TEMPORARY);
165                 dm->copyPolyArray(dm, mpoly);
166         }
167
168         return mpoly;
169 }
170
171 static MVert *dm_dupVertArray(DerivedMesh *dm)
172 {
173         MVert *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumVerts(dm),
174                                                          "dm_dupVertArray tmp");
175
176         if (tmp) dm->copyVertArray(dm, tmp);
177
178         return tmp;
179 }
180
181 static MEdge *dm_dupEdgeArray(DerivedMesh *dm)
182 {
183         MEdge *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumEdges(dm),
184                                                          "dm_dupEdgeArray tmp");
185
186         if (tmp) dm->copyEdgeArray(dm, tmp);
187
188         return tmp;
189 }
190
191 static MFace *dm_dupFaceArray(DerivedMesh *dm)
192 {
193         MFace *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumTessFaces(dm),
194                                                          "dm_dupFaceArray tmp");
195
196         if (tmp) dm->copyTessFaceArray(dm, tmp);
197
198         return tmp;
199 }
200
201 static MLoop *dm_dupLoopArray(DerivedMesh *dm)
202 {
203         MLoop *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumLoops(dm),
204                                                          "dm_dupLoopArray tmp");
205
206         if (tmp) dm->copyLoopArray(dm, tmp);
207
208         return tmp;
209 }
210
211 static MPoly *dm_dupPolyArray(DerivedMesh *dm)
212 {
213         MPoly *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumPolys(dm),
214                                                          "dm_dupPolyArray tmp");
215
216         if (tmp) dm->copyPolyArray(dm, tmp);
217
218         return tmp;
219 }
220
221 static CustomData *dm_getVertCData(DerivedMesh *dm)
222 {
223         return &dm->vertData;
224 }
225
226 static CustomData *dm_getEdgeCData(DerivedMesh *dm)
227 {
228         return &dm->edgeData;
229 }
230
231 static CustomData *dm_getTessFaceCData(DerivedMesh *dm)
232 {
233         return &dm->faceData;
234 }
235
236 static CustomData *dm_getLoopCData(DerivedMesh *dm)
237 {
238         return &dm->loopData;
239 }
240
241 static CustomData *dm_getPolyCData(DerivedMesh *dm)
242 {
243         return &dm->polyData;
244 }
245
246 void DM_init_funcs(DerivedMesh *dm)
247 {
248         /* default function implementations */
249         dm->getVertArray = dm_getVertArray;
250         dm->getEdgeArray = dm_getEdgeArray;
251         dm->getTessFaceArray = dm_getTessFaceArray;
252         dm->getLoopArray = dm_getLoopArray;
253         dm->getPolyArray = dm_getPolyArray;
254         dm->dupVertArray = dm_dupVertArray;
255         dm->dupEdgeArray = dm_dupEdgeArray;
256         dm->dupTessFaceArray = dm_dupFaceArray;
257         dm->dupLoopArray = dm_dupLoopArray;
258         dm->dupPolyArray = dm_dupPolyArray;
259
260         dm->getVertDataLayout = dm_getVertCData;
261         dm->getEdgeDataLayout = dm_getEdgeCData;
262         dm->getTessFaceDataLayout = dm_getTessFaceCData;
263         dm->getLoopDataLayout = dm_getLoopCData;
264         dm->getPolyDataLayout = dm_getPolyCData;
265
266         dm->getVertData = DM_get_vert_data;
267         dm->getEdgeData = DM_get_edge_data;
268         dm->getTessFaceData = DM_get_tessface_data;
269         dm->getVertDataArray = DM_get_vert_data_layer;
270         dm->getEdgeDataArray = DM_get_edge_data_layer;
271         dm->getTessFaceDataArray = DM_get_tessface_data_layer;
272
273         bvhcache_init(&dm->bvhCache);
274 }
275
276 void DM_init(DerivedMesh *dm, DerivedMeshType type, int numVerts, int numEdges,
277              int numTessFaces, int numLoops, int numPolys)
278 {
279         dm->type = type;
280         dm->numVertData = numVerts;
281         dm->numEdgeData = numEdges;
282         dm->numTessFaceData = numTessFaces;
283         dm->numLoopData = numLoops;
284         dm->numPolyData = numPolys;
285
286         DM_init_funcs(dm);
287         
288         dm->needsFree = 1;
289         dm->auto_bump_scale = -1.0f;
290         dm->dirty = 0;
291 }
292
293 void DM_from_template(DerivedMesh *dm, DerivedMesh *source, DerivedMeshType type,
294                       int numVerts, int numEdges, int numTessFaces,
295                       int numLoops, int numPolys)
296 {
297         CustomData_copy(&source->vertData, &dm->vertData, CD_MASK_DERIVEDMESH,
298                                         CD_CALLOC, numVerts);
299         CustomData_copy(&source->edgeData, &dm->edgeData, CD_MASK_DERIVEDMESH,
300                                         CD_CALLOC, numEdges);
301         CustomData_copy(&source->faceData, &dm->faceData, CD_MASK_DERIVEDMESH,
302                                         CD_CALLOC, numTessFaces);
303         CustomData_copy(&source->loopData, &dm->loopData, CD_MASK_DERIVEDMESH,
304                         CD_CALLOC, numLoops);
305         CustomData_copy(&source->polyData, &dm->polyData, CD_MASK_DERIVEDMESH,
306                         CD_CALLOC, numPolys);
307
308         dm->type = type;
309         dm->numVertData = numVerts;
310         dm->numEdgeData = numEdges;
311         dm->numTessFaceData = numTessFaces;
312         dm->numLoopData = numLoops;
313         dm->numPolyData = numPolys;
314
315         DM_init_funcs(dm);
316
317         dm->needsFree = 1;
318         dm->dirty = 0;
319 }
320
321 int DM_release(DerivedMesh *dm)
322 {
323         if (dm->needsFree) {
324                 bvhcache_free(&dm->bvhCache);
325                 GPU_drawobject_free( dm );
326                 CustomData_free(&dm->vertData, dm->numVertData);
327                 CustomData_free(&dm->edgeData, dm->numEdgeData);
328                 CustomData_free(&dm->faceData, dm->numTessFaceData);
329                 CustomData_free(&dm->loopData, dm->numLoopData);
330                 CustomData_free(&dm->polyData, dm->numPolyData);
331
332                 return 1;
333         }
334         else {
335                 CustomData_free_temporary(&dm->vertData, dm->numVertData);
336                 CustomData_free_temporary(&dm->edgeData, dm->numEdgeData);
337                 CustomData_free_temporary(&dm->faceData, dm->numTessFaceData);
338                 CustomData_free_temporary(&dm->loopData, dm->numLoopData);
339                 CustomData_free_temporary(&dm->polyData, dm->numPolyData);
340
341                 return 0;
342         }
343 }
344
345 void DM_DupPolys(DerivedMesh *source, DerivedMesh *target)
346 {
347         CustomData_free(&target->loopData, source->numLoopData);
348         CustomData_free(&target->polyData, source->numPolyData);
349
350         CustomData_copy(&source->loopData, &target->loopData, CD_MASK_DERIVEDMESH, CD_DUPLICATE, source->numLoopData);
351         CustomData_copy(&source->polyData, &target->polyData, CD_MASK_DERIVEDMESH, CD_DUPLICATE, source->numPolyData);
352
353         target->numLoopData = source->numLoopData;
354         target->numPolyData = source->numPolyData;
355
356         if (!CustomData_has_layer(&target->polyData, CD_MPOLY)) {
357                 MPoly *mpoly;
358                 MLoop *mloop;
359
360                 mloop = source->dupLoopArray(source);
361                 mpoly = source->dupPolyArray(source);
362                 CustomData_add_layer(&target->loopData, CD_MLOOP, CD_ASSIGN, mloop, source->numLoopData);
363                 CustomData_add_layer(&target->polyData, CD_MPOLY, CD_ASSIGN, mpoly, source->numPolyData);
364         }
365 }
366
367 /* note: until all modifiers can take MPoly's as input,
368  * use this at the start of modifiers  */
369 void DM_ensure_tessface(DerivedMesh *dm)
370 {
371         const int numTessFaces = dm->getNumTessFaces(dm);
372         const int numPolys =     dm->getNumPolys(dm);
373
374         if ( (numTessFaces == 0) && (numPolys != 0)) {
375                 dm->recalcTessellation(dm);
376
377                 if (dm->getNumTessFaces(dm) != 0) {
378                         /* printf("info %s: polys -> ngons calculated\n", __func__); */
379                 }
380                 else {
381                         printf("warning %s: could not create tessfaces from %d polygons, dm->type=%d\n",
382                                __func__, numPolys, dm->type);
383                 }
384         }
385 }
386
387 /* Update tessface CD data from loop/poly ones. Needed when not retessellating after modstack evaluation. */
388 /* NOTE: Assumes dm has valid tessellated data! */
389 void DM_update_tessface_data(DerivedMesh *dm)
390 {
391         MFace *mf = dm->getTessFaceArray(dm);
392         MPoly *mp = dm->getPolyArray(dm);
393         MLoop *ml = dm->getLoopArray(dm);
394
395         CustomData *fdata = dm->getTessFaceDataLayout(dm);
396         CustomData *pdata = dm->getPolyDataLayout(dm);
397         CustomData *ldata = dm->getLoopDataLayout(dm);
398
399         const int numTex = CustomData_number_of_layers(pdata, CD_MTEXPOLY);
400         const int numCol = CustomData_number_of_layers(ldata, CD_MLOOPCOL);
401         const int hasPCol = CustomData_has_layer(ldata, CD_PREVIEW_MLOOPCOL);
402         const int hasOrigSpace = CustomData_has_layer(ldata, CD_ORIGSPACE_MLOOP);
403
404         int *polyindex = CustomData_get_layer(fdata, CD_POLYINDEX);
405
406         int mf_idx,
407             totface = dm->getNumTessFaces(dm),
408             ml_idx[4];
409
410         /* Should never occure, but better abort than segfault! */
411         if (!polyindex)
412                 return;
413
414         CustomData_from_bmeshpoly(fdata, pdata, ldata, totface);
415
416         for (mf_idx = 0; mf_idx < totface; mf_idx++, mf++) {
417                 const int mf_len = mf->v4 ? 4 : 3;
418                 int i, not_done;
419
420                 /* Find out loop indices. */
421                 /* XXX Is there a better way to do this? */
422                 /* NOTE: This assumes tessface are valid and in sync with loop/poly‚Ķ Else, most likely, segfault! */
423                 for (i = mp[polyindex[mf_idx]].loopstart, not_done = mf_len; not_done; i++) {
424                         MLoop *tml = &ml[i];
425                         if (tml->v == mf->v1) {
426                                 ml_idx[0] = i;
427                                 not_done--;
428                         }
429                         else if (tml->v == mf->v2) {
430                                 ml_idx[1] = i;
431                                 not_done--;
432                         }
433                         else if (tml->v == mf->v3) {
434                                 ml_idx[2] = i;
435                                 not_done--;
436                         }
437                         else if (mf_len == 4 && tml->v == mf->v4) {
438                                 ml_idx[3] = i;
439                                 not_done--;
440                         }
441                 }
442                 mesh_loops_to_mface_corners(fdata, ldata, pdata,
443                                             ml_idx, mf_idx, polyindex[mf_idx],
444                                             mf_len,
445                                             numTex, numCol, hasPCol, hasOrigSpace);
446         }
447
448         if (G.f & G_DEBUG)
449                 printf("Updated tessellated customdata of dm %p\n", dm);
450
451         dm->dirty &= ~DM_DIRTY_TESS_CDLAYERS;
452 }
453
454 void DM_to_mesh(DerivedMesh *dm, Mesh *me, Object *ob)
455 {
456         /* dm might depend on me, so we need to do everything with a local copy */
457         Mesh tmp = *me;
458         int totvert, totedge /*, totface */ /* UNUSED */, totloop, totpoly;
459         int did_shapekeys=0;
460         
461         memset(&tmp.vdata, 0, sizeof(tmp.vdata));
462         memset(&tmp.edata, 0, sizeof(tmp.edata));
463         memset(&tmp.fdata, 0, sizeof(tmp.fdata));
464         memset(&tmp.ldata, 0, sizeof(tmp.ldata));
465         memset(&tmp.pdata, 0, sizeof(tmp.pdata));
466
467         totvert = tmp.totvert = dm->getNumVerts(dm);
468         totedge = tmp.totedge = dm->getNumEdges(dm);
469         totloop = tmp.totloop = dm->getNumLoops(dm);
470         totpoly = tmp.totpoly = dm->getNumPolys(dm);
471
472         CustomData_copy(&dm->vertData, &tmp.vdata, CD_MASK_MESH, CD_DUPLICATE, totvert);
473         CustomData_copy(&dm->edgeData, &tmp.edata, CD_MASK_MESH, CD_DUPLICATE, totedge);
474         CustomData_copy(&dm->loopData, &tmp.ldata, CD_MASK_MESH, CD_DUPLICATE, totloop);
475         CustomData_copy(&dm->polyData, &tmp.pdata, CD_MASK_MESH, CD_DUPLICATE, totpoly);
476
477         if (CustomData_has_layer(&dm->vertData, CD_SHAPEKEY)) {
478                 KeyBlock *kb;
479                 int uid;
480                 
481                 if (ob) {
482                         kb = BLI_findlink(&me->key->block, ob->shapenr-1);
483                         if (kb) {
484                                 uid = kb->uid;
485                         }
486                         else {
487                                 printf("%s: error - could not find active shapekey %d!\n",
488                                        __func__, ob->shapenr-1);
489
490                                 uid = INT_MAX;
491                         }
492                 }
493                 else {
494                         /*if no object, set to INT_MAX so we don't mess up any shapekey layers*/
495                         uid = INT_MAX;
496                 }
497
498                 shapekey_layers_to_keyblocks(dm, me, uid);
499                 did_shapekeys = 1;
500         }
501         
502         /* not all DerivedMeshes store their verts/edges/faces in CustomData, so
503          * we set them here in case they are missing */
504         if (!CustomData_has_layer(&tmp.vdata, CD_MVERT))
505                 CustomData_add_layer(&tmp.vdata, CD_MVERT, CD_ASSIGN, dm->dupVertArray(dm), totvert);
506         if (!CustomData_has_layer(&tmp.edata, CD_MEDGE))
507                 CustomData_add_layer(&tmp.edata, CD_MEDGE, CD_ASSIGN, dm->dupEdgeArray(dm), totedge);
508         if (!CustomData_has_layer(&tmp.pdata, CD_MPOLY)) {
509                 tmp.mloop = dm->dupLoopArray(dm);
510                 tmp.mpoly = dm->dupPolyArray(dm);
511
512                 CustomData_add_layer(&tmp.ldata, CD_MLOOP, CD_ASSIGN, tmp.mloop, tmp.totloop);
513                 CustomData_add_layer(&tmp.pdata, CD_MPOLY, CD_ASSIGN, tmp.mpoly, tmp.totpoly);
514         }
515
516         /* object had got displacement layer, should copy this layer to save sculpted data */
517         /* NOTE: maybe some other layers should be copied? nazgul */
518         if (CustomData_has_layer(&me->ldata, CD_MDISPS)) {
519                 if (totloop == me->totloop) {
520                         MDisps *mdisps = CustomData_get_layer(&me->ldata, CD_MDISPS);
521                         CustomData_add_layer(&tmp.ldata, CD_MDISPS, CD_DUPLICATE, mdisps, totloop);
522                 }
523         }
524
525         /* yes, must be before _and_ after tessellate */
526         mesh_update_customdata_pointers(&tmp, TRUE);
527
528         BKE_mesh_tessface_calc(&tmp);
529
530         CustomData_free(&me->vdata, me->totvert);
531         CustomData_free(&me->edata, me->totedge);
532         CustomData_free(&me->fdata, me->totface);
533         CustomData_free(&me->ldata, me->totloop);
534         CustomData_free(&me->pdata, me->totpoly);
535
536         /* ok, this should now use new CD shapekey data,
537          * which shouuld be fed through the modifier
538          * stack*/
539         if (tmp.totvert != me->totvert && !did_shapekeys && me->key) {
540                 printf("YEEK! this should be recoded! Shape key loss!!!\n");
541                 if (tmp.key) tmp.key->id.us--;
542                 tmp.key = NULL;
543         }
544
545         *me = tmp;
546 }
547
548 void DM_to_meshkey(DerivedMesh *dm, Mesh *me, KeyBlock *kb)
549 {
550         int a, totvert = dm->getNumVerts(dm);
551         float *fp;
552         MVert *mvert;
553         
554         if (totvert==0 || me->totvert==0 || me->totvert!=totvert) return;
555         
556         if (kb->data) MEM_freeN(kb->data);
557         kb->data= MEM_callocN(me->key->elemsize*me->totvert, "kb->data");
558         kb->totelem= totvert;
559         
560         fp= kb->data;
561         mvert=dm->getVertDataArray(dm, CD_MVERT);
562         
563         for (a=0; a<kb->totelem; a++, fp+=3, mvert++) {
564                 copy_v3_v3(fp, mvert->co);
565         }
566 }
567
568 void DM_set_only_copy(DerivedMesh *dm, CustomDataMask mask)
569 {
570         CustomData_set_only_copy(&dm->vertData, mask);
571         CustomData_set_only_copy(&dm->edgeData, mask);
572         CustomData_set_only_copy(&dm->faceData, mask);
573 }
574
575 void DM_add_vert_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
576 {
577         CustomData_add_layer(&dm->vertData, type, alloctype, layer, dm->numVertData);
578 }
579
580 void DM_add_edge_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
581 {
582         CustomData_add_layer(&dm->edgeData, type, alloctype, layer, dm->numEdgeData);
583 }
584
585 void DM_add_tessface_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
586 {
587         CustomData_add_layer(&dm->faceData, type, alloctype, layer, dm->numTessFaceData);
588 }
589
590 void DM_add_loop_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
591 {
592         CustomData_add_layer(&dm->loopData, type, alloctype, layer, dm->numLoopData);
593 }
594
595 void DM_add_poly_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
596 {
597         CustomData_add_layer(&dm->polyData, type, alloctype, layer, dm->numPolyData);
598 }
599
600 void *DM_get_vert_data(DerivedMesh *dm, int index, int type)
601 {
602         return CustomData_get(&dm->vertData, index, type);
603 }
604
605 void *DM_get_edge_data(DerivedMesh *dm, int index, int type)
606 {
607         return CustomData_get(&dm->edgeData, index, type);
608 }
609
610 void *DM_get_tessface_data(DerivedMesh *dm, int index, int type)
611 {
612         return CustomData_get(&dm->faceData, index, type);
613 }
614
615 void *DM_get_vert_data_layer(DerivedMesh *dm, int type)
616 {
617         if (type == CD_MVERT)
618                 return dm->getVertArray(dm);
619
620         return CustomData_get_layer(&dm->vertData, type);
621 }
622
623 void *DM_get_edge_data_layer(DerivedMesh *dm, int type)
624 {
625         if (type == CD_MEDGE)
626                 return dm->getEdgeArray(dm);
627
628         return CustomData_get_layer(&dm->edgeData, type);
629 }
630
631 void *DM_get_tessface_data_layer(DerivedMesh *dm, int type)
632 {
633         if (type == CD_MFACE)
634                 return dm->getTessFaceArray(dm);
635
636         return CustomData_get_layer(&dm->faceData, type);
637 }
638
639 void *DM_get_poly_data_layer(DerivedMesh *dm, int type)
640 {
641         return CustomData_get_layer(&dm->polyData, type);
642 }
643
644 void *DM_get_loop_data_layer(DerivedMesh *dm, int type)
645 {
646         return CustomData_get_layer(&dm->loopData, type);
647 }
648
649 void DM_set_vert_data(DerivedMesh *dm, int index, int type, void *data)
650 {
651         CustomData_set(&dm->vertData, index, type, data);
652 }
653
654 void DM_set_edge_data(DerivedMesh *dm, int index, int type, void *data)
655 {
656         CustomData_set(&dm->edgeData, index, type, data);
657 }
658
659 void DM_set_tessface_data(DerivedMesh *dm, int index, int type, void *data)
660 {
661         CustomData_set(&dm->faceData, index, type, data);
662 }
663
664 void DM_copy_vert_data(DerivedMesh *source, DerivedMesh *dest,
665                                            int source_index, int dest_index, int count)
666 {
667         CustomData_copy_data(&source->vertData, &dest->vertData,
668                                                  source_index, dest_index, count);
669 }
670
671 void DM_copy_edge_data(DerivedMesh *source, DerivedMesh *dest,
672                                            int source_index, int dest_index, int count)
673 {
674         CustomData_copy_data(&source->edgeData, &dest->edgeData,
675                                                  source_index, dest_index, count);
676 }
677
678 void DM_copy_tessface_data(DerivedMesh *source, DerivedMesh *dest,
679                                            int source_index, int dest_index, int count)
680 {
681         CustomData_copy_data(&source->faceData, &dest->faceData,
682                                                  source_index, dest_index, count);
683 }
684
685 void DM_copy_loop_data(DerivedMesh *source, DerivedMesh *dest,
686                        int source_index, int dest_index, int count)
687 {
688         CustomData_copy_data(&source->loopData, &dest->loopData,
689                              source_index, dest_index, count);
690 }
691
692 void DM_copy_poly_data(DerivedMesh *source, DerivedMesh *dest,
693                        int source_index, int dest_index, int count)
694 {
695         CustomData_copy_data(&source->polyData, &dest->polyData,
696                              source_index, dest_index, count);
697 }
698
699 void DM_free_vert_data(struct DerivedMesh *dm, int index, int count)
700 {
701         CustomData_free_elem(&dm->vertData, index, count);
702 }
703
704 void DM_free_edge_data(struct DerivedMesh *dm, int index, int count)
705 {
706         CustomData_free_elem(&dm->edgeData, index, count);
707 }
708
709 void DM_free_tessface_data(struct DerivedMesh *dm, int index, int count)
710 {
711         CustomData_free_elem(&dm->faceData, index, count);
712 }
713
714 void DM_free_loop_data(struct DerivedMesh *dm, int index, int count)
715 {
716         CustomData_free_elem(&dm->loopData, index, count);
717 }
718
719 void DM_free_poly_data(struct DerivedMesh *dm, int index, int count)
720 {
721         CustomData_free_elem(&dm->polyData, index, count);
722 }
723
724 void DM_interp_vert_data(DerivedMesh *source, DerivedMesh *dest,
725                                                  int *src_indices, float *weights,
726                                                  int count, int dest_index)
727 {
728         CustomData_interp(&source->vertData, &dest->vertData, src_indices,
729                                           weights, NULL, count, dest_index);
730 }
731
732 void DM_interp_edge_data(DerivedMesh *source, DerivedMesh *dest,
733                                                  int *src_indices,
734                                                  float *weights, EdgeVertWeight *vert_weights,
735                                                  int count, int dest_index)
736 {
737         CustomData_interp(&source->edgeData, &dest->edgeData, src_indices,
738                                           weights, (float*)vert_weights, count, dest_index);
739 }
740
741 void DM_interp_tessface_data(DerivedMesh *source, DerivedMesh *dest,
742                                                  int *src_indices,
743                                                  float *weights, FaceVertWeight *vert_weights,
744                                                  int count, int dest_index)
745 {
746         CustomData_interp(&source->faceData, &dest->faceData, src_indices,
747                                           weights, (float*)vert_weights, count, dest_index);
748 }
749
750 void DM_swap_tessface_data(DerivedMesh *dm, int index, const int *corner_indices)
751 {
752         CustomData_swap(&dm->faceData, index, corner_indices);
753 }
754
755 void DM_interp_loop_data(DerivedMesh *source, DerivedMesh *dest,
756                          int *src_indices,
757                          float *weights, int count, int dest_index)
758 {
759         CustomData_interp(&source->loopData, &dest->loopData, src_indices,
760                           weights, NULL, count, dest_index);
761 }
762
763 void DM_interp_poly_data(DerivedMesh *source, DerivedMesh *dest,
764                          int *src_indices,
765                          float *weights, int count, int dest_index)
766 {
767         CustomData_interp(&source->polyData, &dest->polyData, src_indices,
768                           weights, NULL, count, dest_index);
769 }
770
771 ///
772 DerivedMesh *mesh_create_derived(Mesh *me, Object *ob, float (*vertCos)[3])
773 {
774         DerivedMesh *dm = CDDM_from_mesh(me, ob);
775         
776         if (!dm)
777                 return NULL;
778         
779         if (vertCos)
780                 CDDM_apply_vert_coords(dm, vertCos);
781
782         CDDM_calc_normals(dm);
783
784         return dm;
785 }
786
787 /***/
788
789 DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob, 
790                                               ModifierData *md, int build_shapekey_layers)
791 {
792         Mesh *me = ob->data;
793         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
794         DerivedMesh *dm;
795         KeyBlock *kb;
796
797         md->scene= scene;
798         
799         if (!(md->mode&eModifierMode_Realtime)) return NULL;
800         if (mti->isDisabled && mti->isDisabled(md, 0)) return NULL;
801         
802         if (build_shapekey_layers && me->key && (kb = BLI_findlink(&me->key->block, ob->shapenr-1))) {
803                 key_to_mesh(kb, me);
804         }
805         
806         if (mti->type==eModifierTypeType_OnlyDeform) {
807                 int numVerts;
808                 float (*deformedVerts)[3] = mesh_getVertexCos(me, &numVerts);
809
810                 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, 0, 0);
811                 dm = mesh_create_derived(me, ob, deformedVerts);
812
813                 if (build_shapekey_layers)
814                         add_shapekey_layers(dm, me, ob);
815                 
816                 MEM_freeN(deformedVerts);
817         }
818         else {
819                 DerivedMesh *tdm = mesh_create_derived(me, ob, NULL);
820
821                 if (build_shapekey_layers)
822                         add_shapekey_layers(tdm, me, ob);
823                 
824                 dm = mti->applyModifier(md, ob, tdm, 0, 0);
825
826                 if (tdm != dm) tdm->release(tdm);
827         }
828
829         return dm;
830 }
831
832 static float *get_editbmesh_orco_verts(BMEditMesh *em)
833 {
834         BMIter iter;
835         BMVert *eve;
836         float *orco;
837         int a, totvert;
838
839         /* these may not really be the orco's, but it's only for preview.
840          * could be solver better once, but isn't simple */
841
842         totvert= em->bm->totvert;
843         
844         orco = MEM_mallocN(sizeof(float)*3*totvert, "BMEditMesh Orco");
845
846         eve = BM_iter_new(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
847         for (a=0; eve; eve=BM_iter_step(&iter), a+=3) {
848                 copy_v3_v3(orco+a, eve->co);
849         }
850         
851         return orco;
852 }
853
854 /* orco custom data layer */
855 static void *get_orco_coords_dm(Object *ob, BMEditMesh *em, int layer, int *free)
856 {
857         *free= 0;
858
859         if (layer == CD_ORCO) {
860                 /* get original coordinates */
861                 *free= 1;
862
863                 if (em)
864                         return (float(*)[3])get_editbmesh_orco_verts(em);
865                 else
866                         return (float(*)[3])get_mesh_orco_verts(ob);
867         }
868         else if (layer == CD_CLOTH_ORCO) {
869                 /* apply shape key for cloth, this should really be solved
870                  * by a more flexible customdata system, but not simple */
871                 if (!em) {
872                         ClothModifierData *clmd = (ClothModifierData *)modifiers_findByType(ob, eModifierType_Cloth);
873                         KeyBlock *kb= key_get_keyblock(ob_get_key(ob), clmd->sim_parms->shapekey_rest);
874
875                         if (kb->data)
876                                 return kb->data;
877                 }
878
879                 return NULL;
880         }
881
882         return NULL;
883 }
884
885 static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, BMEditMesh *em, int layer)
886 {
887         DerivedMesh *dm;
888         float (*orco)[3];
889         int free;
890
891         if (em) dm= CDDM_from_BMEditMesh(em, me, FALSE, FALSE);
892         else dm= CDDM_from_mesh(me, ob);
893
894         orco= get_orco_coords_dm(ob, em, layer, &free);
895
896         if (orco) {
897                 CDDM_apply_vert_coords(dm, orco);
898                 if (free) MEM_freeN(orco);
899         }
900
901         CDDM_calc_normals(dm);
902
903         return dm;
904 }
905
906 static void add_orco_dm(Object *ob, BMEditMesh *em, DerivedMesh *dm,
907                                                 DerivedMesh *orcodm, int layer)
908 {
909         float (*orco)[3], (*layerorco)[3];
910         int totvert, free;
911
912         totvert= dm->getNumVerts(dm);
913
914         if (orcodm) {
915                 orco= MEM_callocN(sizeof(float)*3*totvert, "dm orco");
916                 free= 1;
917
918                 if (orcodm->getNumVerts(orcodm) == totvert)
919                         orcodm->getVertCos(orcodm, orco);
920                 else
921                         dm->getVertCos(dm, orco);
922         }
923         else
924                 orco= get_orco_coords_dm(ob, em, layer, &free);
925
926         if (orco) {
927                 if (layer == CD_ORCO)
928                         transform_mesh_orco_verts(ob->data, orco, totvert, 0);
929
930                 if (!(layerorco = DM_get_vert_data_layer(dm, layer))) {
931                         DM_add_vert_layer(dm, layer, CD_CALLOC, NULL);
932                         layerorco = DM_get_vert_data_layer(dm, layer);
933                 }
934
935                 memcpy(layerorco, orco, sizeof(float)*3*totvert);
936                 if (free) MEM_freeN(orco);
937         }
938 }
939
940 /* weight paint colors */
941
942 /* Something of a hack, at the moment deal with weightpaint
943  * by tucking into colors during modifier eval, only in
944  * wpaint mode. Works ok but need to make sure recalc
945  * happens on enter/exit wpaint.
946  */
947
948 void weight_to_rgb(float r_rgb[3], const float weight)
949 {
950         const float blend= ((weight/2.0f)+0.5f);
951
952         if (weight<=0.25f) {    // blue->cyan
953                 r_rgb[0]= 0.0f;
954                 r_rgb[1]= blend*weight*4.0f;
955                 r_rgb[2]= blend;
956         }
957         else if (weight<=0.50f) {       // cyan->green
958                 r_rgb[0]= 0.0f;
959                 r_rgb[1]= blend;
960                 r_rgb[2]= blend*(1.0f-((weight-0.25f)*4.0f));
961         }
962         else if (weight <= 0.75f) {     // green->yellow
963                 r_rgb[0]= blend * ((weight-0.50f)*4.0f);
964                 r_rgb[1]= blend;
965                 r_rgb[2]= 0.0f;
966         }
967         else if (weight <= 1.0f) { // yellow->red
968                 r_rgb[0]= blend;
969                 r_rgb[1]= blend * (1.0f-((weight-0.75f)*4.0f));
970                 r_rgb[2]= 0.0f;
971         }
972         else {
973                 /* exceptional value, unclamped or nan,
974                  * avoid uninitialized memory use */
975                 r_rgb[0]= 1.0f;
976                 r_rgb[1]= 0.0f;
977                 r_rgb[2]= 1.0f;
978         }
979 }
980
981 /* draw_flag's for calc_weightpaint_vert_color */
982 enum {
983         CALC_WP_MULTIPAINT= (1<<0),
984         CALC_WP_AUTO_NORMALIZE= (1<<1)
985 };
986
987 static void weightpaint_color(unsigned char r_col[4], ColorBand *coba, const float input)
988 {
989         float colf[4];
990
991         if (coba) {
992                 do_colorband(coba, input, colf);
993         }
994         else {
995                 weight_to_rgb(colf, input);
996         }
997
998         /* don't use rgb_float_to_uchar() here because
999          * the resulting float doesn't need 0-1 clamp check */
1000         r_col[0] = (unsigned char)(colf[0] * 255.0f);
1001         r_col[1] = (unsigned char)(colf[1] * 255.0f);
1002         r_col[2] = (unsigned char)(colf[2] * 255.0f);
1003         r_col[3] = 255;
1004 }
1005
1006
1007 static void calc_weightpaint_vert_color(
1008         unsigned char r_col[4],
1009         MDeformVert *dv, ColorBand *coba,
1010         const int defbase_tot, const int defbase_act,
1011         const char *dg_flags,
1012         const int selected, const int draw_flag)
1013 {
1014         float input = 0.0f;
1015         
1016         int make_black= FALSE;
1017
1018         if ((selected > 1) && (draw_flag & CALC_WP_MULTIPAINT)) {
1019                 int was_a_nonzero= FALSE;
1020                 unsigned int i;
1021
1022                 MDeformWeight *dw= dv->dw;
1023                 for (i = dv->totweight; i != 0; i--, dw++) {
1024                         /* in multipaint, get the average if auto normalize is inactive
1025                          * get the sum if it is active */
1026                         if (dw->def_nr < defbase_tot) {
1027                                 if (dg_flags[dw->def_nr]) {
1028                                         if (dw->weight) {
1029                                                 input += dw->weight;
1030                                                 was_a_nonzero= TRUE;
1031                                         }
1032                                 }
1033                         }
1034                 }
1035
1036                 /* make it black if the selected groups have no weight on a vertex */
1037                 if (was_a_nonzero == FALSE) {
1038                         make_black = TRUE;
1039                 }
1040                 else if ((draw_flag & CALC_WP_AUTO_NORMALIZE) == FALSE) {
1041                         input /= selected; /* get the average */
1042                 }
1043         }
1044         else {
1045                 /* default, non tricky behavior */
1046                 input= defvert_find_weight(dv, defbase_act);
1047         }
1048
1049         if (make_black) { /* TODO, theme color */
1050                 r_col[3] = 0;
1051                 r_col[2] = 0;
1052                 r_col[1] = 0;
1053                 r_col[0] = 255;
1054         }
1055         else {
1056                 CLAMP(input, 0.0f, 1.0f);
1057                 weightpaint_color(r_col, coba, input);
1058         }
1059 }
1060
1061 static ColorBand *stored_cb= NULL;
1062
1063 void vDM_ColorBand_store(ColorBand *coba)
1064 {
1065         stored_cb= coba;
1066 }
1067
1068 /* return an array of vertex weight colors, caller must free.
1069  *
1070  * note that we could save some memory and allocate RGB only but then we'd need to
1071  * re-arrange the colors when copying to the face since MCol has odd ordering,
1072  * so leave this as is - campbell */
1073 static unsigned char *calc_weightpaint_vert_array(Object *ob, DerivedMesh *dm, int const draw_flag, ColorBand *coba)
1074 {
1075         MDeformVert *dv = DM_get_vert_data_layer(dm, CD_MDEFORMVERT);
1076         int numVerts = dm->getNumVerts(dm);
1077         unsigned char *wtcol_v = MEM_mallocN (sizeof(unsigned char) * numVerts * 4, "weightmap_v");
1078
1079         if (dv) {
1080                 unsigned char *wc = wtcol_v;
1081                 unsigned int i;
1082
1083                 /* variables for multipaint */
1084                 const int defbase_tot = BLI_countlist(&ob->defbase);
1085                 const int defbase_act = ob->actdef-1;
1086                 char *dg_flags = MEM_mallocN(defbase_tot * sizeof(char), __func__);
1087                 const int selected = get_selected_defgroups(ob, dg_flags, defbase_tot);
1088
1089                 for (i = numVerts; i != 0; i--, wc += 4, dv++) {
1090                         calc_weightpaint_vert_color(wc, dv, coba, defbase_tot, defbase_act, dg_flags, selected, draw_flag);
1091                 }
1092
1093                 MEM_freeN(dg_flags);
1094         }
1095         else {
1096                 int col_i;
1097                 weightpaint_color((unsigned char *)&col_i, coba, 0.0f);
1098                 fill_vn_i((int *)wtcol_v, numVerts, col_i);
1099         }
1100
1101         return wtcol_v;
1102 }
1103
1104 /* return an array of vertex weight colors from given weights, caller must free.
1105  *
1106  * note that we could save some memory and allocate RGB only but then we'd need to
1107  * re-arrange the colors when copying to the face since MCol has odd ordering,
1108  * so leave this as is - campbell */
1109 static unsigned char *calc_colors_from_weights_array(const int num, float *weights)
1110 {
1111         unsigned char *wtcol_v = MEM_mallocN(sizeof(unsigned char) * num * 4, "weightmap_v");
1112         unsigned char *wc = wtcol_v;
1113         int i;
1114
1115         for (i = 0; i < num; i++, wc += 4, weights++)
1116                 weightpaint_color((unsigned char *) wc, NULL, *weights);
1117
1118         return wtcol_v;
1119 }
1120
1121 void DM_update_weight_mcol(Object *ob, DerivedMesh *dm, int const draw_flag,
1122                            float *weights, int num, const int *indices)
1123 {
1124         ColorBand *coba= stored_cb;     /* warning, not a local var */
1125
1126         unsigned char *wtcol_v;
1127 #if 0 /* See coment below. */
1128         unsigned char *wtcol_f = dm->getTessFaceDataArray(dm, CD_PREVIEW_MCOL);
1129 #endif
1130         unsigned char(*wtcol_l)[4] = CustomData_get_layer(dm->getLoopDataLayout(dm), CD_PREVIEW_MLOOPCOL);
1131 #if 0 /* See coment below. */
1132         MFace *mf = dm->getTessFaceArray(dm);
1133 #endif
1134         MLoop *mloop = dm->getLoopArray(dm), *ml;
1135         MPoly *mp = dm->getPolyArray(dm);
1136 #if 0
1137         int numFaces = dm->getNumTessFaces(dm);
1138 #endif
1139         int numVerts = dm->getNumVerts(dm);
1140         int totloop;
1141         int i, j;
1142
1143 #if 0 /* See comment below */
1144         /* If no CD_PREVIEW_MCOL existed yet, add a new one! */
1145         if (!wtcol_f)
1146                 wtcol_f = CustomData_add_layer(&dm->faceData, CD_PREVIEW_MCOL, CD_CALLOC, NULL, numFaces);
1147
1148         if (wtcol_f) {
1149                 unsigned char *wtcol_f_step = wtcol_f;
1150 # else
1151 #if 0
1152         /* XXX We have to create a CD_PREVIEW_MCOL, else it might sigsev (after a SubSurf mod, eg)... */
1153         if (!dm->getTessFaceDataArray(dm, CD_PREVIEW_MCOL))
1154                 CustomData_add_layer(&dm->faceData, CD_PREVIEW_MCOL, CD_CALLOC, NULL, numFaces);
1155 #endif
1156
1157         {
1158 #endif
1159
1160                 /* Weights are given by caller. */
1161                 if (weights) {
1162                         float *w = weights;
1163                         /* If indices is not NULL, it means we do not have weights for all vertices,
1164                          * so we must create them (and set them to zero)... */
1165                         if (indices) {
1166                                 w = MEM_callocN(sizeof(float)*numVerts, "Temp weight array DM_update_weight_mcol");
1167                                 i = num;
1168                                 while (i--)
1169                                         w[indices[i]] = weights[i];
1170                         }
1171
1172                         /* Convert float weights to colors. */
1173                         wtcol_v = calc_colors_from_weights_array(numVerts, w);
1174
1175                         if (indices)
1176                                 MEM_freeN(w);
1177                 }
1178
1179                 /* No weights given, take them from active vgroup(s). */
1180                 else
1181                         wtcol_v = calc_weightpaint_vert_array(ob, dm, draw_flag, coba);
1182
1183                 /* Now copy colors in all face verts. */
1184                 /*first add colors to the tessellation faces*/
1185                 /* XXX Why update that layer? We have to update WEIGHT_MLOOPCOL anyway, 
1186                  *     and tessellation recreates mface layers from mloop/mpoly ones, so no
1187                  *     need to fill WEIGHT_MCOL here. */
1188 #if 0
1189                 for (i = 0; i < numFaces; i++, mf++, wtcol_f_step += (4 * 4)) {
1190                         /*origindex being NULL means we're operating on original mesh data*/
1191 #if 0
1192                         unsigned int fidx= mf->v4 ? 3:2;
1193
1194 #else   /* better zero out triangles 4th component. else valgrind complains when the buffer's copied */
1195                         unsigned int fidx;
1196                         if (mf->v4) {
1197                                 fidx = 3;
1198                         }
1199                         else {
1200                                 fidx = 2;
1201                                 *(int *)(&wtcol_f_step[3 * 4]) = 0;
1202                         }
1203 #endif
1204
1205                         do {
1206                                 copy_v4_v4_char((char *)&wtcol_f_step[fidx * 4],
1207                                                 (char *)&wtcol_v[4 * (*(&mf->v1 + fidx))]);
1208                         } while (fidx--);
1209                 }
1210 #endif
1211                 /*now add to loops, so the data can be passed through the modifier stack*/
1212                 /* If no CD_PREVIEW_MLOOPCOL existed yet, we have to add a new one! */
1213                 if (!wtcol_l) {
1214                         BLI_array_declare(wtcol_l);
1215                         totloop = 0;
1216                         for (i=0; i<dm->numPolyData; i++, mp++) {
1217                                 ml = mloop + mp->loopstart;
1218
1219                                 BLI_array_growitems(wtcol_l, mp->totloop);
1220                                 for (j = 0; j < mp->totloop; j++, ml++, totloop++) {
1221                                         copy_v4_v4_char((char *)&wtcol_l[totloop],
1222                                                         (char *)&wtcol_v[4 * ml->v]);
1223                                 }
1224                         }
1225                         CustomData_add_layer(&dm->loopData, CD_PREVIEW_MLOOPCOL, CD_ASSIGN, wtcol_l, totloop);
1226                 }
1227                 else {
1228                         totloop = 0;
1229                         for (i=0; i < dm->numPolyData; i++, mp++) {
1230                                 ml = mloop + mp->loopstart;
1231
1232                                 for (j=0; j < mp->totloop; j++, ml++, totloop++) {
1233                                         copy_v4_v4_char((char *)&wtcol_l[totloop],
1234                                                         (char *)&wtcol_v[4 * ml->v]);
1235                                 }
1236                         }
1237                 }
1238                 MEM_freeN(wtcol_v);
1239         }
1240
1241         dm->dirty |= DM_DIRTY_TESS_CDLAYERS;
1242 }
1243
1244
1245 static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid)
1246 {
1247         KeyBlock *kb;
1248         int i, j, tot;
1249         
1250         if (!me->key)
1251                 return; 
1252         
1253         tot = CustomData_number_of_layers(&dm->vertData, CD_SHAPEKEY);
1254         for (i=0; i<tot; i++) {
1255                 CustomDataLayer *layer = &dm->vertData.layers[CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i)];
1256                 float (*cos)[3], (*kbcos)[3];
1257                 
1258                 for (kb=me->key->block.first; kb; kb=kb->next) {
1259                         if (kb->uid == layer->uid)
1260                                 break;
1261                 }
1262                 
1263                 if (!kb) {
1264                         kb = add_keyblock(me->key, layer->name);
1265                         kb->uid = layer->uid;
1266                 }
1267                 
1268                 if (kb->data)
1269                         MEM_freeN(kb->data);
1270                 
1271                 cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i);
1272                 kb->totelem = dm->numVertData;
1273
1274                 kb->data = kbcos = MEM_mallocN(sizeof(float)*3*kb->totelem, "kbcos DerivedMesh.c");
1275                 if (kb->uid == actshape_uid) {
1276                         MVert *mvert = dm->getVertArray(dm);
1277                         
1278                         for (j=0; j<dm->numVertData; j++, kbcos++, mvert++) {
1279                                 copy_v3_v3(*kbcos, mvert->co);
1280                         }
1281                 }
1282                 else {
1283                         for (j=0; j<kb->totelem; j++, cos++, kbcos++) {
1284                                 copy_v3_v3(*kbcos, *cos);
1285                         }
1286                 }
1287         }
1288         
1289         for (kb=me->key->block.first; kb; kb=kb->next) {
1290                 if (kb->totelem != dm->numVertData) {
1291                         if (kb->data)
1292                                 MEM_freeN(kb->data);
1293                         
1294                         kb->totelem = dm->numVertData;
1295                         kb->data = MEM_callocN(sizeof(float)*3*kb->totelem, "kb->data derivedmesh.c");
1296                         fprintf(stderr, "%s: lost a shapekey layer! (bmesh internal error)\n", __func__);
1297                 }
1298         }
1299 }
1300
1301 static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *UNUSED(ob))
1302 {
1303         KeyBlock *kb;
1304         Key *key = me->key;
1305         int i;
1306         const size_t shape_alloc_len = sizeof(float) * 3 * me->totvert;
1307
1308         if (!me->key)
1309                 return;
1310
1311         /* ensure we can use mesh vertex count for derived mesh custom data */
1312         if (me->totvert != dm->getNumVerts(dm)) {
1313                 fprintf(stderr,
1314                         "%s: vertex size mismatch (mesh/dm) '%s' (%d != %d)\n",
1315                         __func__, me->id.name+2, me->totvert, dm->getNumVerts(dm));
1316                 return;
1317         }
1318
1319         for (i=0, kb=key->block.first; kb; kb=kb->next, i++) {
1320                 int ci;
1321                 float *array;
1322
1323                 if (me->totvert != kb->totelem) {
1324                         fprintf(stderr,
1325                                 "%s: vertex size mismatch (mesh/keyblock) '%s' (%d != %d)\n",
1326                                 __func__, me->id.name+2, me->totvert, kb->totelem);
1327                         array = MEM_callocN(shape_alloc_len, __func__);
1328                 }
1329                 else {
1330                         array = MEM_mallocN(shape_alloc_len, __func__);
1331                         memcpy(array, kb->data, shape_alloc_len);
1332                 }
1333
1334                 CustomData_add_layer_named(&dm->vertData, CD_SHAPEKEY, CD_ASSIGN, array, dm->numVertData, kb->name);
1335                 ci = CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i);
1336
1337                 dm->vertData.layers[ci].uid = kb->uid;
1338         }
1339 }
1340
1341 /* new value for useDeform -1  (hack for the gameengine):
1342  * - apply only the modifier stack of the object, skipping the virtual modifiers,
1343  * - don't apply the key
1344  * - apply deform modifiers and input vertexco
1345  */
1346 static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos)[3],
1347                                                                 DerivedMesh **deform_r, DerivedMesh **final_r,
1348                                                                 int useRenderParams, int useDeform,
1349                                                                 int needMapping, CustomDataMask dataMask, 
1350                                                                 int index, int useCache, int build_shapekey_layers)
1351 {
1352         Mesh *me = ob->data;
1353         ModifierData *firstmd, *md, *previewmd = NULL;
1354         LinkNode *datamasks, *curr;
1355         /* XXX Always copying POLYINDEX, else tessellated data are no more valid! */
1356         CustomDataMask mask, nextmask, append_mask = CD_MASK_POLYINDEX;
1357         float (*deformedVerts)[3] = NULL;
1358         DerivedMesh *dm=NULL, *orcodm, *clothorcodm, *finaldm;
1359         int numVerts = me->totvert;
1360         int required_mode;
1361         int isPrevDeform= FALSE;
1362         int skipVirtualArmature = (useDeform < 0);
1363         MultiresModifierData *mmd= get_multires_modifier(scene, ob, 0);
1364         int has_multires = mmd != NULL, multires_applied = 0;
1365         int sculpt_mode = ob->mode & OB_MODE_SCULPT && ob->sculpt;
1366
1367         const int draw_flag= ((scene->toolsettings->multipaint ? CALC_WP_MULTIPAINT : 0) |
1368                               (scene->toolsettings->auto_normalize ? CALC_WP_AUTO_NORMALIZE : 0));
1369         /* Generic preview only in object mode! */
1370         const int do_mod_mcol = (ob->mode == OB_MODE_OBJECT);
1371 #if 0 /* XXX Will re-enable this when we have global mod stack options. */
1372         const int do_final_wmcol = (scene->toolsettings->weights_preview == WP_WPREVIEW_FINAL) && do_wmcol;
1373 #endif
1374         const int do_final_wmcol = FALSE;
1375         int do_init_wmcol = ((dataMask & CD_MASK_PREVIEW_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT) && !do_final_wmcol);
1376         /* XXX Same as above... For now, only weights preview in WPaint mode. */
1377         const int do_mod_wmcol = do_init_wmcol;
1378
1379         if (mmd && !mmd->sculptlvl)
1380                 has_multires = 0;
1381
1382         if (!skipVirtualArmature) {
1383                 firstmd = modifiers_getVirtualModifierList(ob);
1384         }
1385         else {
1386                 /* game engine exception */
1387                 firstmd = ob->modifiers.first;
1388                 if (firstmd && firstmd->type == eModifierType_Armature)
1389                         firstmd = firstmd->next;
1390         }
1391
1392         md = firstmd;
1393
1394         modifiers_clearErrors(ob);
1395
1396         if (useRenderParams) required_mode = eModifierMode_Render;
1397         else required_mode = eModifierMode_Realtime;
1398
1399         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1400         curr = datamasks;
1401
1402         if (do_mod_wmcol || do_mod_mcol) {
1403                 /* Find the last active modifier generating a preview, or NULL if none. */
1404                 /* XXX Currently, DPaint modifier just ignores this.
1405                  *     Needs a stupid hack...
1406                  *     The whole "modifier preview" thing has to be (re?)designed, anyway! */
1407                 previewmd = modifiers_getLastPreview(scene, md, required_mode);
1408         }
1409
1410         if (deform_r) *deform_r = NULL;
1411         *final_r = NULL;
1412
1413         if (useDeform) {
1414                 if (inputVertexCos)
1415                         deformedVerts = inputVertexCos;
1416                 
1417                 /* Apply all leading deforming modifiers */
1418                 for (;md; md = md->next, curr = curr->next) {
1419                         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1420
1421                         md->scene= scene;
1422                         
1423                         if (!modifier_isEnabled(scene, md, required_mode)) continue;
1424                         if (useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1425
1426                         if (mti->type == eModifierTypeType_OnlyDeform) {
1427                                 if (!deformedVerts)
1428                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1429
1430                                 mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, useRenderParams, useDeform);
1431                         }
1432                         else {
1433                                 break;
1434                         }
1435                         
1436                         /* grab modifiers until index i */
1437                         if ((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
1438                                 break;
1439                 }
1440
1441                 /* Result of all leading deforming modifiers is cached for
1442                  * places that wish to use the original mesh but with deformed
1443                  * coordinates (vpaint, etc.)
1444                  */
1445                 if (deform_r) {
1446                         *deform_r = CDDM_from_mesh(me, ob);
1447                          
1448                         if (build_shapekey_layers)
1449                                 add_shapekey_layers(dm, me, ob);
1450                         
1451                         if (deformedVerts) {
1452                                 CDDM_apply_vert_coords(*deform_r, deformedVerts);
1453                                 CDDM_calc_normals(*deform_r);
1454                         }
1455                 }
1456         }
1457         else {
1458                 /* default behavior for meshes */
1459                 if (inputVertexCos)
1460                         deformedVerts = inputVertexCos;
1461                 else
1462                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1463         }
1464
1465
1466         /* Now apply all remaining modifiers. If useDeform is off then skip
1467          * OnlyDeform ones. 
1468          */
1469         dm = NULL;
1470         orcodm = NULL;
1471         clothorcodm = NULL;
1472
1473         for (;md; md = md->next, curr = curr->next) {
1474                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1475
1476                 md->scene= scene;
1477
1478                 if (!modifier_isEnabled(scene, md, required_mode)) continue;
1479                 if (mti->type == eModifierTypeType_OnlyDeform && !useDeform) continue;
1480                 if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1481                         modifier_setError(md, "%s", TIP_("Modifier requires original data, bad stack position."));
1482                         continue;
1483                 }
1484                 if (sculpt_mode && (!has_multires || multires_applied)) {
1485                         int unsupported= 0;
1486
1487                         if (scene->toolsettings->sculpt->flags & SCULPT_ONLY_DEFORM)
1488                                 unsupported|= mti->type != eModifierTypeType_OnlyDeform;
1489
1490                         unsupported|= md->type == eModifierType_Multires && ((MultiresModifierData*)md)->sculptlvl==0;
1491                         unsupported|= multires_applied;
1492
1493                         if (unsupported) {
1494                                 modifier_setError(md, "%s", TIP_("Not supported in sculpt mode."));
1495                                 continue;
1496                         }
1497                 }
1498                 if (needMapping && !modifier_supportsMapping(md)) continue;
1499                 if (useDeform < 0 && mti->dependsOnTime && mti->dependsOnTime(md)) continue;
1500
1501                 /* add an orco layer if needed by this modifier */
1502                 if (mti->requiredDataMask)
1503                         mask = mti->requiredDataMask(ob, md);
1504                 else
1505                         mask = 0;
1506
1507                 if (dm && (mask & CD_MASK_ORCO))
1508                         add_orco_dm(ob, NULL, dm, orcodm, CD_ORCO);
1509
1510                 /* How to apply modifier depends on (a) what we already have as
1511                  * a result of previous modifiers (could be a DerivedMesh or just
1512                  * deformed vertices) and (b) what type the modifier is.
1513                  */
1514
1515                 if (mti->type == eModifierTypeType_OnlyDeform) {
1516                         /* No existing verts to deform, need to build them. */
1517                         if (!deformedVerts) {
1518                                 if (dm) {
1519                                         /* Deforming a derived mesh, read the vertex locations
1520                                          * out of the mesh and deform them. Once done with this
1521                                          * run of deformers verts will be written back.
1522                                          */
1523                                         numVerts = dm->getNumVerts(dm);
1524                                         deformedVerts =
1525                                                 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1526                                         dm->getVertCos(dm, deformedVerts);
1527                                 }
1528                                 else {
1529                                         deformedVerts = mesh_getVertexCos(me, &numVerts);
1530                                 }
1531                         }
1532
1533                         /* if this is not the last modifier in the stack then recalculate the normals
1534                          * to avoid giving bogus normals to the next modifier see: [#23673] */
1535                         if (isPrevDeform &&  mti->dependsOnNormals && mti->dependsOnNormals(md)) {
1536                                 /* XXX, this covers bug #23673, but we may need normal calc for other types */
1537                                 if (dm && dm->type == DM_TYPE_CDDM) {
1538                                         CDDM_apply_vert_coords(dm, deformedVerts);
1539                                         CDDM_calc_normals(dm);
1540                                 }
1541                         }
1542
1543                         mti->deformVerts(md, ob, dm, deformedVerts, numVerts, useRenderParams, useDeform);
1544                 }
1545                 else {
1546                         DerivedMesh *ndm;
1547
1548                         /* determine which data layers are needed by following modifiers */
1549                         if (curr->next)
1550                                 nextmask= (CustomDataMask)GET_INT_FROM_POINTER(curr->next->link);
1551                         else
1552                                 nextmask= dataMask;
1553
1554                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1555                         if (dm) {
1556                                 if (deformedVerts) {
1557                                         DerivedMesh *tdm = CDDM_copy(dm);
1558                                         dm->release(dm);
1559                                         dm = tdm;
1560
1561                                         CDDM_apply_vert_coords(dm, deformedVerts);
1562                                         CDDM_calc_normals(dm);
1563                                 }
1564                         }
1565                         else {
1566                                 dm = CDDM_from_mesh(me, ob);
1567
1568                                 if (build_shapekey_layers)
1569                                         add_shapekey_layers(dm, me, ob);
1570
1571                                 if (deformedVerts) {
1572                                         CDDM_apply_vert_coords(dm, deformedVerts);
1573                                         CDDM_calc_normals(dm);
1574                                 }
1575
1576                                 if (do_init_wmcol)
1577                                         DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
1578
1579                                 /* Constructive modifiers need to have an origindex
1580                                  * otherwise they wont have anywhere to copy the data from.
1581                                  *
1582                                  * Also create ORIGINDEX data if any of the following modifiers
1583                                  * requests it, this way Mirror, Solidify etc will keep ORIGINDEX
1584                                  * data by using generic DM_copy_vert_data() functions.
1585                                  */
1586                                 if (needMapping || (nextmask & CD_MASK_ORIGINDEX)) {
1587                                         /* calc */
1588                                         DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1589                                         DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1590                                         DM_add_poly_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
1591
1592                                         range_vn_i(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0);
1593                                         range_vn_i(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0);
1594                                         range_vn_i(DM_get_poly_data_layer(dm, CD_ORIGINDEX), dm->numPolyData, 0);
1595                                 }
1596                         }
1597
1598                         
1599                         /* set the DerivedMesh to only copy needed data */
1600                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
1601                         /* needMapping check here fixes bug [#28112], otherwise its
1602                          * possible that it wont be copied */
1603                         mask |= append_mask;
1604                         DM_set_only_copy(dm, mask | (needMapping ? CD_MASK_ORIGINDEX : 0));
1605                         
1606                         /* add cloth rest shape key if need */
1607                         if (mask & CD_MASK_CLOTH_ORCO)
1608                                 add_orco_dm(ob, NULL, dm, clothorcodm, CD_CLOTH_ORCO);
1609
1610                         /* add an origspace layer if needed */
1611                         if (((CustomDataMask)GET_INT_FROM_POINTER(curr->link)) & CD_MASK_ORIGSPACE_MLOOP) {
1612                                 if (!CustomData_has_layer(&dm->loopData, CD_ORIGSPACE_MLOOP)) {
1613                                         DM_add_loop_layer(dm, CD_ORIGSPACE_MLOOP, CD_CALLOC, NULL);
1614                                         DM_init_origspace(dm);
1615                                 }
1616                         }
1617
1618                         ndm = mti->applyModifier(md, ob, dm, useRenderParams, useCache);
1619
1620                         if (ndm) {
1621                                 /* if the modifier returned a new dm, release the old one */
1622                                 if (dm && dm != ndm) dm->release(dm);
1623
1624                                 dm = ndm;
1625
1626                                 if (deformedVerts) {
1627                                         if (deformedVerts != inputVertexCos)
1628                                                 MEM_freeN(deformedVerts);
1629
1630                                         deformedVerts = NULL;
1631                                 }
1632                         } 
1633
1634                         /* create an orco derivedmesh in parallel */
1635                         if (nextmask & CD_MASK_ORCO) {
1636                                 if (!orcodm)
1637                                         orcodm= create_orco_dm(ob, me, NULL, CD_ORCO);
1638
1639                                 nextmask &= ~CD_MASK_ORCO;
1640                                 DM_set_only_copy(orcodm, nextmask | CD_MASK_ORIGINDEX);
1641                                 ndm = mti->applyModifier(md, ob, orcodm, useRenderParams, 0);
1642
1643                                 if (ndm) {
1644                                         /* if the modifier returned a new dm, release the old one */
1645                                         if (orcodm && orcodm != ndm) orcodm->release(orcodm);
1646                                         orcodm = ndm;
1647                                 }
1648                         }
1649
1650                         /* create cloth orco derivedmesh in parallel */
1651                         if (nextmask & CD_MASK_CLOTH_ORCO) {
1652                                 if (!clothorcodm)
1653                                         clothorcodm= create_orco_dm(ob, me, NULL, CD_CLOTH_ORCO);
1654
1655                                 nextmask &= ~CD_MASK_CLOTH_ORCO;
1656                                 DM_set_only_copy(clothorcodm, nextmask | CD_MASK_ORIGINDEX);
1657                                 ndm = mti->applyModifier(md, ob, clothorcodm, useRenderParams, 0);
1658
1659                                 if (ndm) {
1660                                         /* if the modifier returned a new dm, release the old one */
1661                                         if (clothorcodm && clothorcodm != ndm) clothorcodm->release(clothorcodm);
1662                                         clothorcodm = ndm;
1663                                 }
1664                         }
1665
1666                         /* in case of dynamic paint, make sure preview mask remains for following modifiers */
1667                         /* XXX Temp and hackish solution! */
1668                         if (md->type == eModifierType_DynamicPaint)
1669                                 append_mask |= CD_MASK_PREVIEW_MLOOPCOL;
1670                         /* In case of active preview modifier, make sure preview mask remains for following modifiers. */
1671                         else if ((md == previewmd) && (do_mod_wmcol)) {
1672                                 DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
1673                                 append_mask |= CD_MASK_PREVIEW_MLOOPCOL;
1674                         }
1675                 }
1676
1677                 isPrevDeform= (mti->type == eModifierTypeType_OnlyDeform);
1678
1679                 /* grab modifiers until index i */
1680                 if ((index >= 0) && (modifiers_indexInObject(ob, md) >= index))
1681                         break;
1682
1683                 if (sculpt_mode && md->type == eModifierType_Multires)
1684                         multires_applied = 1;
1685         }
1686
1687         for (md=firstmd; md; md=md->next)
1688                 modifier_freeTemporaryData(md);
1689
1690         /* Yay, we are done. If we have a DerivedMesh and deformed vertices
1691          * need to apply these back onto the DerivedMesh. If we have no
1692          * DerivedMesh then we need to build one.
1693          */
1694         if (dm && deformedVerts) {
1695                 finaldm = CDDM_copy(dm);
1696
1697                 dm->release(dm);
1698
1699                 CDDM_apply_vert_coords(finaldm, deformedVerts);
1700                 CDDM_calc_normals(finaldm);
1701
1702 #if 0 /* For later nice mod preview! */
1703                 /* In case we need modified weights in CD_PREVIEW_MCOL, we have to re-compute it. */
1704                 if (do_final_wmcol)
1705                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1706 #endif
1707         }
1708         else if (dm) {
1709                 finaldm = dm;
1710
1711 #if 0 /* For later nice mod preview! */
1712                 /* In case we need modified weights in CD_PREVIEW_MCOL, we have to re-compute it. */
1713                 if (do_final_wmcol)
1714                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1715 #endif
1716         }
1717         else {
1718                 int recalc_normals= 0;
1719
1720                 finaldm = CDDM_from_mesh(me, ob);
1721                 
1722                 if (build_shapekey_layers) {
1723                         add_shapekey_layers(finaldm, me, ob);
1724                         recalc_normals= 1;
1725                 }
1726                 
1727                 if (deformedVerts) {
1728                         CDDM_apply_vert_coords(finaldm, deformedVerts);
1729                         recalc_normals= 1;
1730                 }
1731
1732                 if (recalc_normals) {
1733                         CDDM_calc_normals(finaldm);
1734                 }
1735
1736                 /* In this case, we should never have weight-modifying modifiers in stack... */
1737                 if (do_init_wmcol)
1738                         DM_update_weight_mcol(ob, finaldm, draw_flag, NULL, 0, NULL);
1739         }
1740
1741         /* add an orco layer if needed */
1742         if (dataMask & CD_MASK_ORCO) {
1743                 add_orco_dm(ob, NULL, finaldm, orcodm, CD_ORCO);
1744
1745                 if (deform_r && *deform_r)
1746                         add_orco_dm(ob, NULL, *deform_r, NULL, CD_ORCO);
1747         }
1748
1749 #ifdef WITH_GAMEENGINE
1750         /* NavMesh - this is a hack but saves having a NavMesh modifier */
1751         if ((ob->gameflag & OB_NAVMESH) && (finaldm->type == DM_TYPE_CDDM)) {
1752                 DerivedMesh *tdm;
1753                 tdm= navmesh_dm_createNavMeshForVisualization(finaldm);
1754                 if (finaldm != tdm) {
1755                         finaldm->release(finaldm);
1756                         finaldm= tdm;
1757                 }
1758         }
1759 #endif /* WITH_GAMEENGINE */
1760
1761         {
1762                 /* calculating normals can re-calculate tessfaces in some cases */
1763 #if 0
1764                 int num_tessface = finaldm->getNumTessFaces(finaldm);
1765 #endif
1766                 /* --------------------------------------------------------------------- */
1767                 /* First calculate the polygon and vertex normals, re-tessellation
1768                  * copies these into the tessface's normal layer */
1769
1770
1771                 /* comment because this causes a bug when deform is applied after a
1772                  * bug when applied after a subsurf modifier (SubSurf -> Cast) for eg,
1773                  * it also looks like this isn't even needed since code above recalc's
1774                  * normals - campbell */
1775 #if 0
1776                 finaldm->calcNormals(finaldm);
1777 #endif
1778
1779                 /* Re-tessellation is necessary to push render data (uvs, textures, colors)
1780                  * from loops and polys onto the tessfaces. This may be currently be
1781                  * redundant in cases where the render mode doesn't use these inputs, but
1782                  * ideally eventually tessellation would happen on-demand, and this is one
1783                  * of the primary places it would be needed. */
1784 #if 0
1785                 if (num_tessface == 0 && finaldm->getNumTessFaces(finaldm) == 0)
1786 #else
1787                 if (finaldm->getNumTessFaces(finaldm) == 0) /* || !CustomData_has_layer(&finaldm->faceData, CD_POLYINDEX)) */
1788 #endif
1789                 {
1790                         finaldm->recalcTessellation(finaldm);
1791                 }
1792                 /* Even if tessellation is not needed, some modifiers migh have modified CD layers
1793                  * (like mloopcol or mloopuv), hence we have to update those. */
1794                 else if (finaldm->dirty & DM_DIRTY_TESS_CDLAYERS) {
1795                         /* A tessellation already exists, it should always have a CD_POLYINDEX. */
1796                         BLI_assert(CustomData_has_layer(&finaldm->faceData, CD_POLYINDEX));
1797                         DM_update_tessface_data(finaldm);
1798                 }
1799                 /* Need to watch this, it can cause issues, see bug [#29338]             */
1800                 /* take care with this block, we really need testing frameworks          */
1801                 /* --------------------------------------------------------------------- */
1802
1803                 /* without this, drawing ngon tri's faces will show ugly tessellated face
1804                  * normals and will also have to calculate normals on the fly, try avoid
1805                  * this where possible since calculating polygon normals isn't fast,
1806                  * note that this isn't a problem for subsurf (only quads) or editmode
1807                  * which deals with drawing differently.
1808                  *
1809                  * Never calc vertex normals because other code ensures these are up to date.
1810                  */
1811                 if ((finaldm->type == DM_TYPE_CDDM) && (CustomData_has_layer(&finaldm->faceData, CD_NORMAL) == FALSE)) {
1812                         CDDM_calc_normals_mapping_ex(finaldm, TRUE);
1813                 }
1814         }
1815
1816         *final_r = finaldm;
1817
1818         if (orcodm)
1819                 orcodm->release(orcodm);
1820         if (clothorcodm)
1821                 clothorcodm->release(clothorcodm);
1822
1823         if (deformedVerts && deformedVerts != inputVertexCos)
1824                 MEM_freeN(deformedVerts);
1825
1826         BLI_linklist_free(datamasks, NULL);
1827 }
1828
1829 float (*editbmesh_get_vertex_cos(BMEditMesh *em, int *numVerts_r))[3]
1830 {
1831         int i, numVerts = *numVerts_r = em->bm->totvert;
1832         float (*cos)[3];
1833         BMIter iter;
1834         BMVert *eve;
1835
1836         cos = MEM_mallocN(sizeof(float)*3*numVerts, "vertexcos");
1837
1838         eve = BM_iter_new(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
1839         for (i=0; eve; eve=BM_iter_step(&iter), i++) {
1840                 copy_v3_v3(cos[i], eve->co);
1841         }
1842
1843         return cos;
1844 }
1845
1846 int editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
1847 {
1848         ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1849         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1850
1851         if (!modifier_isEnabled(scene, md, required_mode)) return 0;
1852         if ((mti->flags & eModifierTypeFlag_RequiresOriginalData) && dm) {
1853                 modifier_setError(md, "%s", TIP_("Modifier requires original data, bad stack position."));
1854                 return 0;
1855         }
1856         
1857         return 1;
1858 }
1859
1860 static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, DerivedMesh **cage_r,
1861                                                                         DerivedMesh **final_r,
1862                                                                         CustomDataMask dataMask)
1863 {
1864         ModifierData *md;
1865         float (*deformedVerts)[3] = NULL;
1866         CustomDataMask mask;
1867         DerivedMesh *dm, *orcodm = NULL;
1868         int i, numVerts = 0, cageIndex = modifiers_getCageIndex(scene, ob, NULL, 1);
1869         LinkNode *datamasks, *curr;
1870         int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
1871
1872         modifiers_clearErrors(ob);
1873
1874         if (cage_r && cageIndex == -1) {
1875                 *cage_r = getEditDerivedBMesh(em, ob, NULL);
1876         }
1877
1878         dm = NULL;
1879         md = modifiers_getVirtualModifierList(ob);
1880
1881         datamasks = modifiers_calcDataMasks(scene, ob, md, dataMask, required_mode);
1882
1883         curr = datamasks;
1884         for (i = 0; md; i++, md = md->next, curr = curr->next) {
1885                 ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1886
1887                 md->scene= scene;
1888                 
1889                 if (!editbmesh_modifier_is_enabled(scene, md, dm))
1890                         continue;
1891
1892                 /* add an orco layer if needed by this modifier */
1893                 if (dm && mti->requiredDataMask) {
1894                         mask = mti->requiredDataMask(ob, md);
1895                         if (mask & CD_MASK_ORCO)
1896                                 add_orco_dm(ob, em, dm, orcodm, CD_ORCO);
1897                 }
1898
1899                 /* How to apply modifier depends on (a) what we already have as
1900                  * a result of previous modifiers (could be a DerivedMesh or just
1901                  * deformed vertices) and (b) what type the modifier is.
1902                  */
1903
1904                 if (mti->type == eModifierTypeType_OnlyDeform) {
1905                         /* No existing verts to deform, need to build them. */
1906                         if (!deformedVerts) {
1907                                 if (dm) {
1908                                         /* Deforming a derived mesh, read the vertex locations
1909                                          * out of the mesh and deform them. Once done with this
1910                                          * run of deformers verts will be written back.
1911                                          */
1912                                         numVerts = dm->getNumVerts(dm);
1913                                         deformedVerts =
1914                                                 MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
1915                                         dm->getVertCos(dm, deformedVerts);
1916                                 }
1917                                 else {
1918                                         deformedVerts = editbmesh_get_vertex_cos(em, &numVerts);
1919                                 }
1920                         }
1921
1922                         if (mti->deformVertsEM)
1923                                 mti->deformVertsEM(md, ob, em, dm, deformedVerts, numVerts);
1924                         else mti->deformVerts(md, ob, dm, deformedVerts, numVerts, 0, 0);
1925                 }
1926                 else {
1927                         DerivedMesh *ndm;
1928
1929                         /* apply vertex coordinates or build a DerivedMesh as necessary */
1930                         if (dm) {
1931                                 if (deformedVerts) {
1932                                         DerivedMesh *tdm = CDDM_copy(dm);
1933                                         if (!(cage_r && dm == *cage_r)) dm->release(dm);
1934                                         dm = tdm;
1935
1936                                         CDDM_apply_vert_coords(dm, deformedVerts);
1937                                         CDDM_calc_normals(dm);
1938                                 }
1939                                 else if (cage_r && dm == *cage_r) {
1940                                         /* dm may be changed by this modifier, so we need to copy it
1941                                          */
1942                                         dm = CDDM_copy(dm);
1943                                 }
1944
1945                         }
1946                         else {
1947                                 dm = CDDM_from_BMEditMesh(em, ob->data, FALSE, FALSE);
1948
1949                                 if (deformedVerts) {
1950                                         CDDM_apply_vert_coords(dm, deformedVerts);
1951                                         CDDM_calc_normals(dm);
1952                                 }
1953                         }
1954
1955                         /* create an orco derivedmesh in parallel */
1956                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link);
1957                         if (mask & CD_MASK_ORCO) {
1958                                 if (!orcodm)
1959                                         orcodm= create_orco_dm(ob, ob->data, em, CD_ORCO);
1960
1961                                 mask &= ~CD_MASK_ORCO;
1962                                 DM_set_only_copy(orcodm, mask | CD_MASK_ORIGINDEX);
1963
1964                                 if (mti->applyModifierEM)
1965                                         ndm = mti->applyModifierEM(md, ob, em, orcodm);
1966                                 else
1967                                         ndm = mti->applyModifier(md, ob, orcodm, 0, 0);
1968
1969                                 if (ndm) {
1970                                         /* if the modifier returned a new dm, release the old one */
1971                                         if (orcodm && orcodm != ndm) orcodm->release(orcodm);
1972                                         orcodm = ndm;
1973                                 }
1974                         }
1975
1976                         /* set the DerivedMesh to only copy needed data */
1977                         mask= (CustomDataMask)GET_INT_FROM_POINTER(curr->link); /* CD_MASK_ORCO may have been cleared above */
1978
1979                         DM_set_only_copy(dm, mask | CD_MASK_ORIGINDEX);
1980
1981                         if (mask & CD_MASK_ORIGSPACE_MLOOP) {
1982                                 if (!CustomData_has_layer(&dm->loopData, CD_ORIGSPACE_MLOOP)) {
1983                                         DM_add_loop_layer(dm, CD_ORIGSPACE_MLOOP, CD_CALLOC, NULL);
1984                                         DM_init_origspace(dm);
1985                                 }
1986                         }
1987                         
1988                         if (mti->applyModifierEM)
1989                                 ndm = mti->applyModifierEM(md, ob, em, dm);
1990                         else
1991                                 ndm = mti->applyModifier(md, ob, dm, 0, 0);
1992
1993                         if (ndm) {
1994                                 if (dm && dm != ndm)
1995                                         dm->release(dm);
1996
1997                                 dm = ndm;
1998
1999                                 if (deformedVerts) {
2000                                         MEM_freeN(deformedVerts);
2001                                         deformedVerts = NULL;
2002                                 }
2003                         }
2004                 }
2005
2006                 if (cage_r && i == cageIndex) {
2007                         if (dm && deformedVerts) {
2008                                 *cage_r = CDDM_copy(dm);
2009                                 CDDM_apply_vert_coords(*cage_r, deformedVerts);
2010                         }
2011                         else if (dm) {
2012                                 *cage_r = dm;
2013                         }
2014                         else {
2015                                 *cage_r =
2016                                         getEditDerivedBMesh(em, ob,
2017                                                 deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
2018                         }
2019                 }
2020         }
2021
2022         BLI_linklist_free(datamasks, NULL);
2023
2024         /* Yay, we are done. If we have a DerivedMesh and deformed vertices need
2025          * to apply these back onto the DerivedMesh. If we have no DerivedMesh
2026          * then we need to build one.
2027          */
2028         if (dm && deformedVerts) {
2029                 *final_r = CDDM_copy(dm);
2030
2031                 if (!(cage_r && dm == *cage_r)) dm->release(dm);
2032
2033                 CDDM_apply_vert_coords(*final_r, deformedVerts);
2034                 CDDM_calc_normals(*final_r); /* was CDDM_calc_normals_mapping - campbell */
2035         }
2036         else if (dm) {
2037                 *final_r = dm;
2038                 (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
2039         }
2040         else if (!deformedVerts && cage_r && *cage_r) {
2041                 /* cage should already have up to date normals */
2042                 *final_r = *cage_r;
2043                 (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
2044         }
2045         else {
2046                 /* this is just a copy of the editmesh, no need to calc normals */
2047                 *final_r = getEditDerivedBMesh(em, ob, deformedVerts);
2048                 deformedVerts = NULL;
2049         }
2050
2051         /* --- */
2052         /* BMESH_ONLY, ensure tessface's used for drawing,
2053          * but don't recalculate if the last modifier in the stack gives us tessfaces
2054          * check if the derived meshes are DM_TYPE_EDITBMESH before calling, this isn't essential
2055          * but quiets annoying error messages since tessfaces wont be created. */
2056         if ((*final_r)->type != DM_TYPE_EDITBMESH) {
2057                 DM_ensure_tessface(*final_r);
2058         }
2059         if (cage_r) {
2060                 if ((*cage_r)->type != DM_TYPE_EDITBMESH) {
2061                         if (*cage_r != *final_r) {
2062                                 DM_ensure_tessface(*cage_r);
2063                         }
2064                 }
2065         }
2066         /* --- */
2067
2068         /* add an orco layer if needed */
2069         if (dataMask & CD_MASK_ORCO)
2070                 add_orco_dm(ob, em, *final_r, orcodm, CD_ORCO);
2071
2072         if (orcodm)
2073                 orcodm->release(orcodm);
2074
2075         if (deformedVerts)
2076                 MEM_freeN(deformedVerts);
2077 }
2078
2079 static void clear_mesh_caches(Object *ob)
2080 {
2081         Mesh *me= ob->data;
2082
2083                 /* also serves as signal to remake texspace */
2084         if (ob->bb) {
2085                 MEM_freeN(ob->bb);
2086                 ob->bb = NULL;
2087         }
2088         if (me->bb) {
2089                 MEM_freeN(me->bb);
2090                 me->bb = NULL;
2091         }
2092
2093         freedisplist(&ob->disp);
2094
2095         if (ob->derivedFinal) {
2096                 ob->derivedFinal->needsFree = 1;
2097                 ob->derivedFinal->release(ob->derivedFinal);
2098                 ob->derivedFinal= NULL;
2099         }
2100         if (ob->derivedDeform) {
2101                 ob->derivedDeform->needsFree = 1;
2102                 ob->derivedDeform->release(ob->derivedDeform);
2103                 ob->derivedDeform= NULL;
2104         }
2105
2106         if (ob->sculpt) {
2107                 object_sculpt_modifiers_changed(ob);
2108         }
2109 }
2110
2111 static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask,
2112                             int build_shapekey_layers)
2113 {
2114         Object *obact = scene->basact?scene->basact->object:NULL;
2115         int editing = paint_facesel_test(ob);
2116         /* weight paint and face select need original indices because of selection buffer drawing */
2117         int needMapping = (ob==obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT|OB_MODE_VERTEX_PAINT|OB_MODE_TEXTURE_PAINT)));
2118
2119         clear_mesh_caches(ob);
2120
2121         mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
2122                                                 &ob->derivedFinal, 0, 1,
2123                                                 needMapping, dataMask, -1, 1, build_shapekey_layers);
2124
2125         DM_set_object_boundbox (ob, ob->derivedFinal);
2126
2127         ob->derivedFinal->needsFree = 0;
2128         ob->derivedDeform->needsFree = 0;
2129         ob->lastDataMask = dataMask;
2130
2131         if ((ob->mode & OB_MODE_SCULPT) && ob->sculpt) {
2132                 /* create PBVH immediately (would be created on the fly too,
2133                    but this avoids waiting on first stroke) */
2134                 ob->sculpt->pbvh= ob->derivedFinal->getPBVH(ob, ob->derivedFinal);
2135         }
2136 }
2137
2138 static void editbmesh_build_data(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2139 {
2140         clear_mesh_caches(obedit);
2141
2142         if (em->derivedFinal) {
2143                 if (em->derivedFinal!=em->derivedCage) {
2144                         em->derivedFinal->needsFree = 1;
2145                         em->derivedFinal->release(em->derivedFinal);
2146                 }
2147                 em->derivedFinal = NULL;
2148         }
2149         if (em->derivedCage) {
2150                 em->derivedCage->needsFree = 1;
2151                 em->derivedCage->release(em->derivedCage);
2152                 em->derivedCage = NULL;
2153         }
2154
2155         editbmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
2156         DM_set_object_boundbox (obedit, em->derivedFinal);
2157
2158         em->lastDataMask = dataMask;
2159         em->derivedFinal->needsFree = 0;
2160         em->derivedCage->needsFree = 0;
2161 }
2162
2163 void makeDerivedMesh(Scene *scene, Object *ob, BMEditMesh *em,
2164                      CustomDataMask dataMask, int build_shapekey_layers)
2165 {
2166         if (em) {
2167                 editbmesh_build_data(scene, ob, em, dataMask);
2168         }
2169         else {
2170                 mesh_build_data(scene, ob, dataMask, build_shapekey_layers);
2171         }
2172 }
2173
2174 /***/
2175
2176 DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dataMask)
2177 {
2178         /* if there's no derived mesh or the last data mask used doesn't include
2179          * the data we need, rebuild the derived mesh
2180          */
2181         if (!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
2182                 mesh_build_data(scene, ob, dataMask, 0);
2183
2184         return ob->derivedFinal;
2185 }
2186
2187 DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask dataMask)
2188 {
2189         /* if there's no derived mesh or the last data mask used doesn't include
2190          * the data we need, rebuild the derived mesh
2191          */
2192         if (!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
2193                 mesh_build_data(scene, ob, dataMask, 0);
2194
2195         return ob->derivedDeform;
2196 }
2197
2198 DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask dataMask)
2199 {
2200         DerivedMesh *final;
2201         
2202         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0, 0);
2203
2204         return final;
2205 }
2206
2207 DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDataMask dataMask, int index)
2208 {
2209         DerivedMesh *final;
2210         
2211         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0, 0);
2212
2213         return final;
2214 }
2215
2216 DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask dataMask)
2217 {
2218         DerivedMesh *final;
2219
2220         mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0, 0);
2221
2222         return final;
2223 }
2224
2225 DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*vertCos)[3],
2226                                                                                    CustomDataMask dataMask)
2227 {
2228         DerivedMesh *final;
2229         
2230         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0, 0);
2231
2232         return final;
2233 }
2234
2235 DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*vertCos)[3],
2236                                                                                         CustomDataMask dataMask)
2237 {
2238         DerivedMesh *final;
2239         
2240         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0, 0);
2241
2242         return final;
2243 }
2244
2245 DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertCos)[3],
2246                                                                                         CustomDataMask dataMask)
2247 {
2248         DerivedMesh *final;
2249         
2250         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0, 0);
2251
2252         return final;
2253 }
2254
2255 DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
2256                                                                                                   float (*vertCos)[3],
2257                                                                                                   CustomDataMask dataMask)
2258 {
2259         DerivedMesh *final;
2260
2261         mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0, 0);
2262
2263         return final;
2264 }
2265
2266 /***/
2267
2268 DerivedMesh *editbmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, BMEditMesh *em, DerivedMesh **final_r,
2269                                                                                                  CustomDataMask dataMask)
2270 {
2271         /* if there's no derived mesh or the last data mask used doesn't include
2272          * the data we need, rebuild the derived mesh
2273          */
2274         if (!em->derivedCage ||
2275            (em->lastDataMask & dataMask) != dataMask)
2276                 editbmesh_build_data(scene, obedit, em, dataMask);
2277
2278         *final_r = em->derivedFinal;
2279         return em->derivedCage;
2280 }
2281
2282 DerivedMesh *editbmesh_get_derived_cage(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
2283 {
2284         /* if there's no derived mesh or the last data mask used doesn't include
2285          * the data we need, rebuild the derived mesh
2286          */
2287         if (!em->derivedCage ||
2288            (em->lastDataMask & dataMask) != dataMask)
2289                 editbmesh_build_data(scene, obedit, em, dataMask);
2290
2291         return em->derivedCage;
2292 }
2293
2294 DerivedMesh *editbmesh_get_derived_base(Object *obedit, BMEditMesh *em)
2295 {
2296         return getEditDerivedBMesh(em, obedit, NULL);
2297 }
2298
2299
2300 /* ********* For those who don't grasp derived stuff! (ton) :) *************** */
2301
2302 static void make_vertexcosnos__mapFunc(void *userData, int index, float *co, float *no_f, short *no_s)
2303 {
2304         float *vec = userData;
2305         
2306         vec+= 6*index;
2307
2308         /* check if we've been here before (normal should not be 0) */
2309         if (vec[3] || vec[4] || vec[5]) return;
2310
2311         copy_v3_v3(vec, co);
2312         vec+= 3;
2313         if (no_f) {
2314                 copy_v3_v3(vec, no_f);
2315         }
2316         else {
2317                 normal_short_to_float_v3(vec, no_s);
2318         }
2319 }
2320
2321 /* always returns original amount me->totvert of vertices and normals, but fully deformed and subsurfered */
2322 /* this is needed for all code using vertexgroups (no subsurf support) */
2323 /* it stores the normals as floats, but they can still be scaled as shorts (32767 = unit) */
2324 /* in use now by vertex/weight paint and particle generating */
2325
2326 float *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
2327 {
2328         Mesh *me= ob->data;
2329         DerivedMesh *dm;
2330         float *vertexcosnos;
2331         
2332         /* lets prevent crashing... */
2333         if (ob->type!=OB_MESH || me->totvert==0)
2334                 return NULL;
2335         
2336         dm= mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH|CD_MASK_ORIGINDEX);
2337         vertexcosnos= MEM_callocN(6*sizeof(float)*me->totvert, "vertexcosnos map");
2338         
2339         if (dm->foreachMappedVert) {
2340                 dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
2341         }
2342         else {
2343                 float *fp= vertexcosnos;
2344                 int a;
2345                 
2346                 for (a=0; a< me->totvert; a++, fp+=6) {
2347                         dm->getVertCo(dm, a, fp);
2348                         dm->getVertNo(dm, a, fp+3);
2349                 }
2350         }
2351         
2352         dm->release(dm);
2353         return vertexcosnos;
2354 }
2355
2356 /* ******************* GLSL ******************** */
2357
2358 typedef struct
2359 {
2360         float * precomputedFaceNormals;
2361         MTFace * mtface;        // texture coordinates
2362         MFace * mface;          // indices
2363         MVert * mvert;          // vertices & normals
2364         float (*orco)[3];
2365         float (*tangent)[4];    // destination
2366         int numTessFaces;
2367
2368 } SGLSLMeshToTangent;
2369
2370 // interface
2371 #include "mikktspace.h"
2372
2373 static int GetNumFaces(const SMikkTSpaceContext * pContext)
2374 {
2375         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2376         return pMesh->numTessFaces;
2377 }
2378
2379 static int GetNumVertsOfFace(const SMikkTSpaceContext * pContext, const int face_num)
2380 {
2381         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2382         return pMesh->mface[face_num].v4!=0 ? 4 : 3;
2383 }
2384
2385 static void GetPosition(const SMikkTSpaceContext * pContext, float fPos[], const int face_num, const int vert_index)
2386 {
2387         //assert(vert_index>=0 && vert_index<4);
2388         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2389         const float *co= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].co;
2390         copy_v3_v3(fPos, co);
2391 }
2392
2393 static void GetTextureCoordinate(const SMikkTSpaceContext * pContext, float fUV[], const int face_num, const int vert_index)
2394 {
2395         //assert(vert_index>=0 && vert_index<4);
2396         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2397
2398         if (pMesh->mtface!=NULL) {
2399                 float * uv = pMesh->mtface[face_num].uv[vert_index];
2400                 fUV[0]=uv[0]; fUV[1]=uv[1];
2401         }
2402         else {
2403                 const float *orco= pMesh->orco[(&pMesh->mface[face_num].v1)[vert_index]];
2404                 map_to_sphere( &fUV[0], &fUV[1], orco[0], orco[1], orco[2]);
2405         }
2406 }
2407
2408 static void GetNormal(const SMikkTSpaceContext * pContext, float fNorm[], const int face_num, const int vert_index)
2409 {
2410         //assert(vert_index>=0 && vert_index<4);
2411         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2412
2413         const int smoothnormal = (pMesh->mface[face_num].flag & ME_SMOOTH);
2414         if (!smoothnormal) {    // flat
2415                 if (pMesh->precomputedFaceNormals) {
2416                         copy_v3_v3(fNorm, &pMesh->precomputedFaceNormals[3*face_num]);
2417                 }
2418                 else {
2419                         MFace *mf= &pMesh->mface[face_num];
2420                         float *p0= pMesh->mvert[mf->v1].co;
2421                         float *p1= pMesh->mvert[mf->v2].co;
2422                         float *p2= pMesh->mvert[mf->v3].co;
2423
2424                         if (mf->v4) {
2425                                 float *p3 = pMesh->mvert[mf->v4].co;
2426                                 normal_quad_v3(fNorm, p0, p1, p2, p3);
2427                         }
2428                         else {
2429                                 normal_tri_v3(fNorm, p0, p1, p2);
2430                         }
2431                 }
2432         }
2433         else {
2434                 const short *no= pMesh->mvert[(&pMesh->mface[face_num].v1)[vert_index]].no;
2435                 normal_short_to_float_v3(fNorm, no);
2436         }
2437 }
2438 static void SetTSpace(const SMikkTSpaceContext * pContext, const float fvTangent[], const float fSign, const int face_num, const int iVert)
2439 {
2440         //assert(vert_index>=0 && vert_index<4);
2441         SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
2442         float * pRes = pMesh->tangent[4*face_num+iVert];
2443         copy_v3_v3(pRes, fvTangent);
2444         pRes[3]=fSign;
2445 }
2446
2447
2448 void DM_add_tangent_layer(DerivedMesh *dm)
2449 {
2450         /* mesh vars */
2451         MTFace *mtface, *tf;
2452         MFace *mface, *mf;
2453         MVert *mvert, *v1, *v2, *v3, *v4;
2454         MemArena *arena= NULL;
2455         VertexTangent **vtangents= NULL;
2456         float (*orco)[3]= NULL, (*tangent)[4];
2457         float *uv1, *uv2, *uv3, *uv4, *vtang;
2458         float fno[3], tang[3], uv[4][2];
2459         int i, j, len, mf_vi[4], totvert, totface, iCalcNewMethod;
2460         float *nors;
2461
2462         if (CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
2463                 return;
2464
2465         nors = dm->getTessFaceDataArray(dm, CD_NORMAL);
2466
2467         /* check we have all the needed layers */
2468         totvert= dm->getNumVerts(dm);
2469         totface= dm->getNumTessFaces(dm);
2470
2471         mvert= dm->getVertArray(dm);
2472         mface= dm->getTessFaceArray(dm);
2473         mtface= dm->getTessFaceDataArray(dm, CD_MTFACE);
2474
2475         if (!mtface) {
2476                 orco= dm->getVertDataArray(dm, CD_ORCO);
2477                 if (!orco)
2478                         return;
2479         }
2480         
2481         /* create tangent layer */
2482         DM_add_tessface_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
2483         tangent= DM_get_tessface_data_layer(dm, CD_TANGENT);
2484         
2485         /* allocate some space */
2486         arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "tangent layer arena");
2487         BLI_memarena_use_calloc(arena);
2488         vtangents= MEM_callocN(sizeof(VertexTangent*)*totvert, "VertexTangent");
2489
2490         // new computation method
2491         iCalcNewMethod = 1;
2492         if (iCalcNewMethod != 0) {
2493                 SGLSLMeshToTangent mesh2tangent= {0};
2494                 SMikkTSpaceContext sContext= {0};
2495                 SMikkTSpaceInterface sInterface= {0};
2496
2497                 mesh2tangent.precomputedFaceNormals = nors;
2498                 mesh2tangent.mtface = mtface;
2499                 mesh2tangent.mface = mface;
2500                 mesh2tangent.mvert = mvert;
2501                 mesh2tangent.orco = orco;
2502                 mesh2tangent.tangent = tangent;
2503                 mesh2tangent.numTessFaces = totface;
2504
2505                 sContext.m_pUserData = &mesh2tangent;
2506                 sContext.m_pInterface = &sInterface;
2507                 sInterface.m_getNumFaces = GetNumFaces;
2508                 sInterface.m_getNumVerticesOfFace = GetNumVertsOfFace;
2509                 sInterface.m_getPosition = GetPosition;
2510                 sInterface.m_getTexCoord = GetTextureCoordinate;
2511                 sInterface.m_getNormal = GetNormal;
2512                 sInterface.m_setTSpaceBasic = SetTSpace;
2513
2514                 // 0 if failed
2515                 iCalcNewMethod = genTangSpaceDefault(&sContext);
2516         }
2517
2518         if (!iCalcNewMethod) {
2519                 /* sum tangents at connected vertices */
2520                 for (i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++) {
2521                         v1= &mvert[mf->v1];
2522                         v2= &mvert[mf->v2];
2523                         v3= &mvert[mf->v3];
2524
2525                         if (mf->v4) {
2526                                 v4= &mvert[mf->v4];
2527                                 normal_quad_v3( fno,v4->co, v3->co, v2->co, v1->co);
2528                         }
2529                         else {
2530                                 v4= NULL;
2531                                 normal_tri_v3( fno,v3->co, v2->co, v1->co);
2532                         }
2533                 
2534                         if (mtface) {
2535                                 uv1= tf->uv[0];
2536                                 uv2= tf->uv[1];
2537                                 uv3= tf->uv[2];
2538                                 uv4= tf->uv[3];
2539                         }
2540                         else {
2541                                 uv1= uv[0]; uv2= uv[1]; uv3= uv[2]; uv4= uv[3];
2542                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2543                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2544                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2545                                 if (v4)
2546                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2547                         }
2548                 
2549                         tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, fno, tang);
2550                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2551                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v2], tang, uv2);
2552                         sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2553                 
2554                         if (mf->v4) {
2555                                 v4= &mvert[mf->v4];
2556                         
2557                                 tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, fno, tang);
2558                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v1], tang, uv1);
2559                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v3], tang, uv3);
2560                                 sum_or_add_vertex_tangent(arena, &vtangents[mf->v4], tang, uv4);
2561                         }
2562                 }
2563         
2564                 /* write tangent to layer */
2565                 for (i=0, tf=mtface, mf=mface; i < totface; mf++, tf++, i++, tangent+=4) {
2566                         len= (mf->v4)? 4 : 3; 
2567
2568                         if (mtface == NULL) {
2569                                 map_to_sphere( &uv[0][0], &uv[0][1],orco[mf->v1][0], orco[mf->v1][1], orco[mf->v1][2]);
2570                                 map_to_sphere( &uv[1][0], &uv[1][1],orco[mf->v2][0], orco[mf->v2][1], orco[mf->v2][2]);
2571                                 map_to_sphere( &uv[2][0], &uv[2][1],orco[mf->v3][0], orco[mf->v3][1], orco[mf->v3][2]);
2572                                 if (len==4)
2573                                         map_to_sphere( &uv[3][0], &uv[3][1],orco[mf->v4][0], orco[mf->v4][1], orco[mf->v4][2]);
2574                         }
2575                 
2576                         mf_vi[0]= mf->v1;
2577                         mf_vi[1]= mf->v2;
2578                         mf_vi[2]= mf->v3;
2579                         mf_vi[3]= mf->v4;
2580                 
2581                         for (j=0; j<len; j++) {
2582                                 vtang= find_vertex_tangent(vtangents[mf_vi[j]], mtface ? tf->uv[j] : uv[j]);
2583                                 normalize_v3_v3(tangent[j], vtang);
2584                                 ((float *) tangent[j])[3]=1.0f;
2585                         }
2586                 }
2587         }
2588         
2589         BLI_memarena_free(arena);
2590         MEM_freeN(vtangents);
2591 }
2592
2593 void DM_calc_auto_bump_scale(DerivedMesh *dm)
2594 {
2595         /* int totvert= dm->getNumVerts(dm); */ /* UNUSED */
2596         int totface= dm->getNumTessFaces(dm);
2597
2598         MVert * mvert = dm->getVertArray(dm);
2599         MFace * mface = dm->getTessFaceArray(dm);
2600         MTFace * mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
2601
2602         if (mtface) {
2603                 double dsum = 0.0;
2604                 int nr_accumulated = 0;
2605                 int f;
2606
2607                 for ( f=0; f < totface; f++ ) {
2608                         {
2609                                 float * verts[4], * tex_coords[4];
2610                                 const int nr_verts = mface[f].v4!=0 ? 4 : 3;
2611                                 int i, is_degenerate;
2612
2613                                 verts[0]=mvert[mface[f].v1].co; verts[1]=mvert[mface[f].v2].co; verts[2]=mvert[mface[f].v3].co;
2614                                 tex_coords[0]=mtface[f].uv[0]; tex_coords[1]=mtface[f].uv[1]; tex_coords[2]=mtface[f].uv[2];
2615                                 if (nr_verts==4) {
2616                                         verts[3]=mvert[mface[f].v4].co;
2617                                         tex_coords[3]=mtface[f].uv[3];
2618                                 }
2619
2620                                 // discard degenerate faces
2621                                 is_degenerate = 0;
2622                                 if (    equals_v3v3(verts[0], verts[1]) || equals_v3v3(verts[0], verts[2]) || equals_v3v3(verts[1], verts[2]) ||
2623                                         equals_v2v2(tex_coords[0], tex_coords[1]) || equals_v2v2(tex_coords[0], tex_coords[2]) || equals_v2v2(tex_coords[1], tex_coords[2]) )
2624                                 {
2625                                         is_degenerate = 1;
2626                                 }
2627
2628                                 // verify last vertex as well if this is a quad
2629                                 if (is_degenerate == 0 && nr_verts == 4) {
2630                                         if (equals_v3v3(verts[3], verts[0]) || equals_v3v3(verts[3], verts[1]) || equals_v3v3(verts[3], verts[2]) ||
2631                                             equals_v2v2(tex_coords[3], tex_coords[0]) || equals_v2v2(tex_coords[3], tex_coords[1]) || equals_v2v2(tex_coords[3], tex_coords[2]) )
2632                                         {
2633                                                 is_degenerate = 1;
2634                                         }
2635
2636                                         // verify the winding is consistent
2637                                         if (is_degenerate == 0) {
2638                                                 float prev_edge[2];
2639                                                 int is_signed = 0;
2640                                                 sub_v2_v2v2(prev_edge, tex_coords[0], tex_coords[3]);
2641
2642                                                 i = 0;
2643                                                 while (is_degenerate == 0 && i < 4) {
2644                                                         float cur_edge[2], signed_area;
2645                                                         sub_v2_v2v2(cur_edge, tex_coords[(i+1)&0x3], tex_coords[i]);
2646                                                         signed_area = prev_edge[0]*cur_edge[1] - prev_edge[1]*cur_edge[0];
2647
2648                                                         if (i == 0 ) {
2649                                                                 is_signed = (signed_area < 0.0f) ? 1 : 0;
2650                                                         }
2651                                                         else if ((is_signed != 0) != (signed_area < 0.0f)) {
2652                                                                 is_degenerate = 1;
2653                                                         }
2654
2655                                                         if (is_degenerate == 0) {
2656                                                                 copy_v2_v2(prev_edge, cur_edge);
2657                                                                 ++i;
2658                                                         }
2659                                                 }
2660                                         }
2661                                 }
2662
2663                                 // proceed if not a degenerate face
2664                                 if (is_degenerate == 0) {
2665                                         int nr_tris_to_pile=0;
2666                                         // quads split at shortest diagonal
2667                                         int offs = 0;           // initial triangulation is 0,1,2 and 0, 2, 3
2668                                         if (nr_verts == 4) {
2669                                                 float pos_len_diag0, pos_len_diag1;
2670                                                 float vtmp[3];
2671                                                 sub_v3_v3v3(vtmp, verts[2], verts[0]);
2672                                                 pos_len_diag0 = dot_v3v3(vtmp, vtmp);
2673                                                 sub_v3_v3v3(vtmp, verts[3], verts[1]);
2674                                                 pos_len_diag1 = dot_v3v3(vtmp, vtmp);
2675
2676                                                 if (pos_len_diag1<pos_len_diag0) {
2677                                                         offs=1;         // alter split
2678                                                 }
2679                                                 else if (pos_len_diag0==pos_len_diag1) { /* do UV check instead */
2680                                                         float tex_len_diag0, tex_len_diag1;
2681
2682                                                         sub_v2_v2v2(vtmp, tex_coords[2], tex_coords[0]);
2683                                                         tex_len_diag0 = dot_v2v2(vtmp, vtmp);
2684                                                         sub_v2_v2v2(vtmp, tex_coords[3], tex_coords[1]);
2685                                                         tex_len_diag1 = dot_v2v2(vtmp, vtmp);
2686
2687                                                         if (tex_len_diag1<tex_len_diag0) {
2688                                                                 offs=1; /* alter split */
2689                                                         }
2690                                                 }
2691                                         }
2692                                         nr_tris_to_pile = nr_verts - 2;
2693                                         if (nr_tris_to_pile==1 || nr_tris_to_pile==2) {
2694                                                 const int indices[] = {offs+0, offs+1, offs+2, offs+0, offs+2, (offs+3)&0x3 };
2695                                                 int t;
2696                                                 for ( t=0; t<nr_tris_to_pile; t++ )
2697                                                 {
2698                                                         float f2x_area_uv;
2699                                                         float * p0 = verts[indices[t*3+0]];
2700                                                         float * p1 = verts[indices[t*3+1]];
2701                                                         float * p2 = verts[indices[t*3+2]];
2702
2703                                                         float edge_t0[2], edge_t1[2];
2704                                                         sub_v2_v2v2(edge_t0, tex_coords[indices[t*3+1]], tex_coords[indices[t*3+0]]);
2705                                                         sub_v2_v2v2(edge_t1, tex_coords[indices[t*3+2]], tex_coords[indices[t*3+0]]);
2706
2707                                                         f2x_area_uv = fabsf(edge_t0[0]*edge_t1[1] - edge_t0[1]*edge_t1[0]);
2708                                                         if (f2x_area_uv>FLT_EPSILON) {
2709                                                                 float norm[3], v0[3], v1[3], f2x_surf_area, fsurf_ratio;
2710                                                                 sub_v3_v3v3(v0, p1, p0);
2711                                                                 sub_v3_v3v3(v1, p2, p0);
2712                                                                 cross_v3_v3v3(norm, v0, v1);
2713
2714                                                                 f2x_surf_area = len_v3(norm);
2715                                                                 fsurf_ratio = f2x_surf_area/f2x_area_uv;        // tri area divided by texture area
2716
2717                                                                 ++nr_accumulated;
2718                                                                 dsum += (double)(fsurf_ratio);
2719                                                         }
2720                                                 }
2721                                         }
2722                                 }
2723                         }
2724                 }
2725
2726                 // finalize
2727                 {
2728                         const float avg_area_ratio = (nr_accumulated>0) ? ((float)(dsum / nr_accumulated)) : 1.0f;
2729                         const float use_as_render_bump_scale = sqrtf(avg_area_ratio);           // use width of average surface ratio as your bump scale
2730                         dm->auto_bump_scale = use_as_render_bump_scale;
2731                 }
2732         }
2733         else {
2734                 dm->auto_bump_scale = 1.0f;
2735         }
2736 }
2737
2738 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
2739 {
2740         CustomData *vdata, *fdata, *tfdata = NULL;
2741         int a, b, layer;
2742
2743         /* From the layers requested by the GLSL shader, figure out which ones are
2744          * actually available for this derivedmesh, and retrieve the pointers */
2745
2746         memset(attribs, 0, sizeof(DMVertexAttribs));
2747
2748         vdata = &dm->vertData;
2749         fdata = tfdata = dm->getTessFaceDataLayout(dm);
2750         
2751         /* calc auto bump scale if necessary */
2752         if (dm->auto_bump_scale<=0.0f)
2753                 DM_calc_auto_bump_scale(dm);
2754
2755         /* add a tangent layer if necessary */
2756         for (b = 0; b < gattribs->totlayer; b++)
2757                 if (gattribs->layer[b].type == CD_TANGENT)
2758                         if (CustomData_get_layer_index(fdata, CD_TANGENT) == -1)
2759                                 DM_add_tangent_layer(dm);
2760
2761         for (b = 0; b < gattribs->totlayer; b++) {
2762                 if (gattribs->layer[b].type == CD_MTFACE) {
2763                         /* uv coordinates */
2764                         if (gattribs->layer[b].name[0])
2765                                 layer = CustomData_get_named_layer_index(tfdata, CD_MTFACE,
2766                                         gattribs->layer[b].name);
2767                         else
2768                                 layer = CustomData_get_active_layer_index(tfdata, CD_MTFACE);
2769
2770                         if (layer != -1) {
2771                                 a = attribs->tottface++;
2772
2773                                 attribs->tface[a].array = tfdata->layers[layer].data;
2774                                 attribs->tface[a].emOffset = tfdata->layers[layer].offset;
2775                                 attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2776                                 attribs->tface[a].glTexco = gattribs->layer[b].gltexco;
2777                         }
2778                         /* BMESH_TODO - BMESH ONLY, may need to get this working?, otherwise remove */
2779 #if 0
2780                         else {
2781                                 int player;
2782                                 CustomData *pdata = dm->getPolyDataLayout(dm);
2783                                 
2784                                 if (gattribs->layer[b].name[0])
2785                                         player = CustomData_get_named_layer_index(pdata, CD_MTEXPOLY,
2786                                                 gattribs->layer[b].name);
2787                                 else
2788                                         player = CustomData_get_active_layer_index(pdata, CD_MTEXPOLY);
2789                                 
2790                                 if (player != -1) {
2791                                         a = attribs->tottface++;
2792         
2793                                         attribs->tface[a].array = NULL;
2794                                         attribs->tface[a].emOffset = pdata->layers[layer].offset;
2795                                         attribs->tface[a].glIndex = gattribs->layer[b].glindex;
2796                                         attribs->tface[a].glTexco = gattribs->layer[b].gltexco;
2797                                         
2798                                 }
2799                         }
2800 #endif
2801                 }
2802                 else if (gattribs->layer[b].type == CD_MCOL) {
2803                         /* vertex colors */
2804                         if (gattribs->layer[b].name[0])
2805                                 layer = CustomData_get_named_layer_index(tfdata, CD_MCOL,
2806                                         gattribs->layer[b].name);
2807                         else
2808                                 layer = CustomData_get_active_layer_index(tfdata, CD_MCOL);
2809
2810                         if (layer != -1) {
2811                                 a = attribs->totmcol++;
2812
2813                                 attribs->mcol[a].array = tfdata->layers[layer].data;
2814                                 attribs->mcol[a].emOffset = tfdata->layers[layer].offset;
2815                                 attribs->mcol[a].glIndex = gattribs->layer[b].glindex;
2816                         }
2817                 }
2818                 else if (gattribs->layer[b].type == CD_TANGENT) {
2819                         /* tangents */
2820                         layer = CustomData_get_layer_index(fdata, CD_TANGENT);
2821
2822                         if (layer != -1) {
2823                                 attribs->tottang = 1;
2824
2825                                 attribs->tang.array = fdata->layers[layer].data;
2826                                 attribs->tang.emOffset = fdata->layers[layer].offset;
2827                                 attribs->tang.glIndex = gattribs->layer[b].glindex;
2828                         }
2829                 }
2830                 else if (gattribs->layer[b].type == CD_ORCO) {
2831                         /* original coordinates */
2832                         layer = CustomData_get_layer_index(vdata, CD_ORCO);
2833
2834                         if (layer != -1) {
2835                                 attribs->totorco = 1;
2836
2837                                 attribs->orco.array = vdata->layers[layer].data;
2838                                 attribs->orco.emOffset = vdata->layers[layer].offset;
2839                                 attribs->orco.glIndex = gattribs->layer[b].glindex;
2840                                 attribs->orco.glTexco = gattribs->layer[b].gltexco;
2841                         }
2842                 }
2843         }
2844 }
2845
2846 /* Set object's bounding box based on DerivedMesh min/max data */
2847 void DM_set_object_boundbox(Object *ob, DerivedMesh *dm)
2848 {
2849         float min[3], max[3];
2850
2851         INIT_MINMAX(min, max);
2852
2853         dm->getMinMax(dm, min, max);
2854
2855         if (!ob->bb)
2856                 ob->bb= MEM_callocN(sizeof(BoundBox), "DM-BoundBox");
2857
2858         boundbox_set_from_min_max(ob->bb, min, max);
2859 }
2860
2861 /* --- NAVMESH (begin) --- */
2862 #ifdef WITH_GAMEENGINE
2863
2864 /* BMESH_TODO, navmesh is not working right currently
2865  * All tools set this as MPoly data, but derived mesh currently draws from MFace (tessface)
2866  *
2867  * Proposed solution, rather then copy CD_RECAST into the MFace array,
2868  * use ORIGINDEX to get the original poly index and then get the CD_RECAST
2869  * data from the original me->mpoly layer. - campbell
2870  */
2871
2872
2873 BLI_INLINE int navmesh_bit(int a, int b)
2874 {
2875         return (a & (1 << b)) >> b;
2876 }
2877
2878 BLI_INLINE void navmesh_intToCol(int i, float col[3])
2879 {
2880         int     r = navmesh_bit(i, 0) + navmesh_bit(i, 3) * 2 + 1;
2881         int     g = navmesh_bit(i, 1) + navmesh_bit(i, 4) * 2 + 1;
2882         int     b = navmesh_bit(i, 2) + navmesh_bit(i, 5) * 2 + 1;
2883         col[0] = 1 - r*63.0f/255.0f;
2884         col[1] = 1 - g*63.0f/255.0f;
2885         col[2] = 1 - b*63.0f/255.0f;
2886 }
2887
2888 static void navmesh_drawColored(DerivedMesh *dm)
2889 {
2890         int a, glmode;
2891         MVert *mvert = (MVert *)CustomData_get_layer(&dm->vertData, CD_MVERT);
2892         MFace *mface = (MFace *)CustomData_get_layer(&dm->faceData, CD_MFACE);
2893         int *polygonIdx = (int *)CustomData_get_layer(&dm->faceData, CD_RECAST);
2894         float col[3];
2895
2896         if (!polygonIdx)
2897                 return;
2898
2899 #if 0
2900         //UI_ThemeColor(TH_WIRE);
2901         glDisable(GL_LIGHTING);
2902         glLineWidth(2.0);
2903         dm->drawEdges(dm, 0, 1);
2904         glLineWidth(1.0);
2905         glEnable(GL_LIGHTING);
2906 #endif
2907
2908         glDisable(GL_LIGHTING);
2909         /*  if (GPU_buffer_legacy(dm) ) */ { /* TODO - VBO draw code, not high priority - campbell */
2910                 DEBUG_VBO( "Using legacy code. drawNavMeshColored\n" );
2911                 //glShadeModel(GL_SMOOTH);
2912                 glBegin(glmode = GL_QUADS);
2913                 for (a = 0; a < dm->numTessFaceData; a++, mface++) {
2914                         int new_glmode = mface->v4?GL_QUADS:GL_TRIANGLES;
2915                         int pi = polygonIdx[a];
2916                         if (pi <= 0) {
2917                                 zero_v3(col);
2918                         }
2919                         else {
2920                                 navmesh_intToCol(pi, col);
2921                         }
2922
2923                         if (new_glmode != glmode) {
2924                                 glEnd();
2925                                 glBegin(glmode = new_glmode);
2926                         }
2927                         glColor3fv(col);
2928                         glVertex3fv(mvert[mface->v1].co);
2929                         glVertex3fv(mvert[mface->v2].co);
2930                         glVertex3fv(mvert[mface->v3].co);
2931                         if (mface->v4) {
2932                                 glVertex3fv(mvert[mface->v4].co);
2933                         }
2934                 }
2935                 glEnd();
2936         }
2937         glEnable(GL_LIGHTING);
2938 }
2939
2940 static void navmesh_DM_drawFacesTex(DerivedMesh *dm,
2941                         DMSetDrawOptionsTex setDrawOptions,
2942                         DMCompareDrawOptions compareDrawOptions,
2943                         void *userData)
2944 {
2945         (void) setDrawOptions;
2946         (void) compareDrawOptions;
2947         (void) userData;
2948
2949         navmesh_drawColored(dm);
2950 }
2951
2952 static void navmesh_DM_drawFacesSolid(DerivedMesh *dm,
2953                                       float (*partial_redraw_planes)[4],
2954                                       int UNUSED(fast), DMSetMaterial setMaterial)
2955 {
2956         (void) partial_redraw_planes;
2957         (void) setMaterial;
2958
2959         //drawFacesSolid_original(dm, partial_redraw_planes, fast, setMaterial);
2960         navmesh_drawColored(dm);
2961 }
2962
2963 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm)
2964 {
2965         DerivedMesh *result;
2966         int maxFaces = dm->getNumPolys(dm);
2967         int *recastData;
2968         int vertsPerPoly=0, nverts=0, ndtris=0, npolys=0;
2969         float* verts=NULL;
2970         unsigned short *dtris=NULL, *dmeshes=NULL, *polys=NULL;
2971         int *dtrisToPolysMap=NULL, *dtrisToTrisMap=NULL, *trisToFacesMap=NULL;
2972         int res;
2973
2974         result = CDDM_copy(dm);
2975         if (!CustomData_has_layer(&result->faceData, CD_RECAST)) {
2976                 int *sourceRecastData = (int*)CustomData_get_layer(&dm->faceData, CD_RECAST);
2977                 if (sourceRecastData) {
2978                         CustomData_add_layer_named(&result->faceData, CD_RECAST, CD_DUPLICATE,
2979                                                    sourceRecastData, maxFaces, "recastData");
2980                 }
2981         }
2982         recastData = (int*)CustomData_get_layer(&result->faceData, CD_RECAST);
2983
2984         /* note: This is not good design! - really should not be doing this */
2985         result->drawFacesTex =  navmesh_DM_drawFacesTex;
2986         result->drawFacesSolid = navmesh_DM_drawFacesSolid;
2987
2988
2989         /* process mesh */
2990         res  = buildNavMeshDataByDerivedMesh(dm, &vertsPerPoly, &nverts, &verts, &ndtris, &dtris,
2991                                              &npolys, &dmeshes, &polys, &dtrisToPolysMap, &dtrisToTrisMap,
2992                                              &trisToFacesMap);
2993         if (res) {
2994                 size_t polyIdx;
2995
2996                 /* invalidate concave polygon */
2997                 for (polyIdx=0; polyIdx<(size_t)npolys; polyIdx++) {
2998                         unsigned short* poly = &polys[polyIdx*2*vertsPerPoly];
2999                         if (!polyIsConvex(poly, vertsPerPoly, verts)) {
3000                                 /* set negative polygon idx to all faces */
3001                                 unsigned short *dmesh = &dmeshes[4*polyIdx];
3002                                 unsigned short tbase = dmesh[2];
3003                                 unsigned short tnum = dmesh[3];
3004                                 unsigned short ti;
3005
3006                                 for (ti=0; ti<tnum; ti++) {
3007                                         unsigned short triidx = dtrisToTrisMap[tbase+ti];
3008                                         unsigned short faceidx = trisToFacesMap[triidx];
3009                                         if (recastData[faceidx] > 0) {
3010                                                 recastData[faceidx] = -recastData[faceidx];
3011                                         }
3012                                 }
3013                         }
3014                 }
3015         }
3016         else {
3017                 printf("Error during creation polygon infos\n");
3018         }
3019
3020         /* clean up */
3021         if (verts!=NULL)
3022                 MEM_freeN(verts);
3023         if (dtris!=NULL)
3024                 MEM_freeN(dtris);
3025         if (dmeshes!=NULL)
3026                 MEM_freeN(dmeshes);
3027         if (polys!=NULL)
3028                 MEM_freeN(polys);
3029         if (dtrisToPolysMap!=NULL)
3030                 MEM_freeN(dtrisToPolysMap);
3031         if (dtrisToTrisMap!=NULL)
3032                 MEM_freeN(dtrisToTrisMap);
3033         if (trisToFacesMap!=NULL)
3034                 MEM_freeN(trisToFacesMap);
3035
3036         return result;
3037 }
3038
3039 #endif /* WITH_GAMEENGINE */
3040
3041 /* --- NAVMESH (end) --- */
3042
3043
3044 void DM_init_origspace(DerivedMesh *dm)
3045 {
3046         static float default_osf[4][2] = {{0, 0}, {1, 0}, {1, 1}, {0, 1}};
3047
3048         OrigSpaceLoop *lof_array = CustomData_get_layer(&dm->loopData, CD_ORIGSPACE_MLOOP);
3049         OrigSpaceLoop *lof;
3050         const int numpoly = dm->getNumPolys(dm);
3051         // const int numloop = dm->getNumLoops(dm);
3052         MPoly *mp = dm->getPolyArray(dm);
3053