Sculpt Branch:
[blender.git] / source / blender / blenkernel / intern / multires.c
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software  Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2007 by Nicholas Bishop
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  */
29
30 #include "MEM_guardedalloc.h"
31
32 #include "DNA_key_types.h"
33 #include "DNA_mesh_types.h"
34 #include "DNA_meshdata_types.h"
35 #include "DNA_modifier_types.h"
36 #include "DNA_object_types.h"
37 #include "DNA_scene_types.h"
38 #include "DNA_view3d_types.h"
39
40 #include "BLI_math.h"
41 #include "BLI_blenlib.h"
42 #include "BLI_pbvh.h"
43
44 #include "BKE_cdderivedmesh.h"
45 #include "BKE_customdata.h"
46 #include "BKE_depsgraph.h"
47 #include "BKE_DerivedMesh.h"
48 #include "BKE_global.h"
49 #include "BKE_mesh.h"
50 #include "BKE_modifier.h"
51 #include "BKE_multires.h"
52 #include "BKE_object.h"
53 #include "BKE_subsurf.h"
54 #include "BKE_utildefines.h"
55
56 #include "CCGSubSurf.h"
57
58 #include <math.h>
59 #include <string.h>
60
61 /* MULTIRES MODIFIER */
62 static const int multires_max_levels = 13;
63 static const int multires_grid_tot[] = {0, 4, 9, 25, 81, 289, 1089, 4225, 16641, 66049, 263169, 1050625, 4198401, 16785409};
64 static const int multires_side_tot[] = {0, 2, 3, 5,  9,  17,  33,   65,   129,   257,   513,    1025,    2049,    4097};
65
66 static void multiresModifier_disp_run(DerivedMesh *dm, Mesh *me, int invert, int add, DMGridData **oldGridData, int totlvl);
67
68 MultiresModifierData *find_multires_modifier(Object *ob)
69 {
70         ModifierData *md;
71         MultiresModifierData *mmd = NULL;
72
73         for(md = ob->modifiers.first; md; md = md->next) {
74                 if(md->type == eModifierType_Multires) {
75                         mmd = (MultiresModifierData*)md;
76                         break;
77                 }
78         }
79
80         return mmd;
81 }
82
83 static int multires_get_level(Object *ob, MultiresModifierData *mmd, int render)
84 {
85         if(render)
86                 return mmd->renderlvl;
87         else if(ob->mode == OB_MODE_SCULPT)
88                 return mmd->sculptlvl;
89         else
90                 return mmd->lvl;
91 }
92
93 static void multires_set_tot_level(Object *ob, MultiresModifierData *mmd, int lvl)
94 {
95         mmd->totlvl = lvl;
96
97         if(ob->mode != OB_MODE_SCULPT) {
98                 mmd->lvl = MAX2(mmd->lvl, lvl);
99                 CLAMP(mmd->lvl, 0, mmd->totlvl);
100         }
101
102         mmd->sculptlvl = MAX2(mmd->sculptlvl, lvl);
103         CLAMP(mmd->sculptlvl, 0, mmd->totlvl);
104
105         mmd->renderlvl = MAX2(mmd->renderlvl, lvl);
106         CLAMP(mmd->renderlvl, 0, mmd->totlvl);
107 }
108
109 /* XXX */
110 #if 0
111 void multiresModifier_join(Object *ob)
112 {
113         Base *base = NULL;
114         int highest_lvl = 0;
115
116         /* First find the highest level of subdivision */
117         base = FIRSTBASE;
118         while(base) {
119                 if(TESTBASELIB_BGMODE(v3d, scene, base) && base->object->type==OB_MESH) {
120                         ModifierData *md;
121                         for(md = base->object->modifiers.first; md; md = md->next) {
122                                 if(md->type == eModifierType_Multires) {
123                                         int totlvl = ((MultiresModifierData*)md)->totlvl;
124                                         if(totlvl > highest_lvl)
125                                                 highest_lvl = totlvl;
126
127                                         /* Ensure that all updates are processed */
128                                         multires_force_update(base->object);
129                                 }
130                         }
131                 }
132                 base = base->next;
133         }
134
135         /* No multires meshes selected */
136         if(highest_lvl == 0)
137                 return;
138
139         /* Subdivide all the displacements to the highest level */
140         base = FIRSTBASE;
141         while(base) {
142                 if(TESTBASELIB_BGMODE(v3d, scene, base) && base->object->type==OB_MESH) {
143                         ModifierData *md = NULL;
144                         MultiresModifierData *mmd = NULL;
145
146                         for(md = base->object->modifiers.first; md; md = md->next) {
147                                 if(md->type == eModifierType_Multires)
148                                         mmd = (MultiresModifierData*)md;
149                         }
150
151                         /* If the object didn't have multires enabled, give it a new modifier */
152                         if(!mmd) {
153                                 md = base->object->modifiers.first;
154                                 
155                                 while(md && modifierType_getInfo(md->type)->type == eModifierTypeType_OnlyDeform)
156                                         md = md->next;
157                                 
158                                 mmd = (MultiresModifierData*)modifier_new(eModifierType_Multires);
159                                 BLI_insertlinkbefore(&base->object->modifiers, md, mmd);
160                                 modifier_unique_name(&base->object->modifiers, mmd);
161                         }
162
163                         if(mmd)
164                                 multiresModifier_subdivide(mmd, base->object, highest_lvl - mmd->totlvl, 0, 0);
165                 }
166                 base = base->next;
167         }
168 }
169 #endif
170
171 /* Returns 0 on success, 1 if the src's totvert doesn't match */
172 int multiresModifier_reshape(MultiresModifierData *mmd, Object *dst, Object *src)
173 {
174         /* XXX */
175 #if 0
176         Mesh *src_me = get_mesh(src);
177         DerivedMesh *mrdm = dst->derivedFinal;
178
179         if(mrdm && mrdm->getNumVerts(mrdm) == src_me->totvert) {
180                 MVert *mvert = CDDM_get_verts(mrdm);
181                 int i;
182
183                 for(i = 0; i < src_me->totvert; ++i)
184                         copy_v3_v3(mvert[i].co, src_me->mvert[i].co);
185                 mrdm->needsFree = 1;
186                 MultiresDM_mark_as_modified(mrdm);
187                 mrdm->release(mrdm);
188                 dst->derivedFinal = NULL;
189
190                 return 0;
191         }
192 #endif
193
194         return 1;
195 }
196
197 static void column_vectors_to_mat3(float mat[][3], float v1[3], float v2[3], float v3[3])
198 {
199         copy_v3_v3(mat[0], v1);
200         copy_v3_v3(mat[1], v2);
201         copy_v3_v3(mat[2], v3);
202 }
203
204 static void multires_copy_grid(float (*gridA)[3], float (*gridB)[3], int sizeA, int sizeB)
205 {
206         int x, y, j, skip;
207
208         if(sizeA > sizeB) {
209                 skip = (sizeA-1)/(sizeB-1);
210
211                 for(j = 0, y = 0; y < sizeB; y++)
212                         for(x = 0; x < sizeB; x++, j++)
213                                 copy_v3_v3(gridA[y*skip*sizeA + x*skip], gridB[j]);
214         }
215         else {
216                 skip = (sizeB-1)/(sizeA-1);
217
218                 for(j = 0, y = 0; y < sizeA; y++)
219                         for(x = 0; x < sizeA; x++, j++)
220                                 copy_v3_v3(gridA[j], gridB[y*skip*sizeB + x*skip]);
221         }
222 }
223
224 static void multires_copy_dm_grid(DMGridData *gridA, DMGridData *gridB, int sizeA, int sizeB)
225 {
226         int x, y, j, skip;
227
228         if(sizeA > sizeB) {
229                 skip = (sizeA-1)/(sizeB-1);
230
231                 for(j = 0, y = 0; y < sizeB; y++)
232                         for(x = 0; x < sizeB; x++, j++)
233                                 copy_v3_v3(gridA[y*skip*sizeA + x*skip].co, gridB[j].co);
234         }
235         else {
236                 skip = (sizeB-1)/(sizeA-1);
237
238                 for(j = 0, y = 0; y < sizeA; y++)
239                         for(x = 0; x < sizeA; x++, j++)
240                                 copy_v3_v3(gridA[j].co, gridB[y*skip*sizeB + x*skip].co);
241         }
242 }
243
244 /* direction=1 for delete higher, direction=0 for lower (not implemented yet) */
245 void multiresModifier_del_levels(struct MultiresModifierData *mmd, struct Object *ob, int direction)
246 {
247         Mesh *me = get_mesh(ob);
248         int lvl = multires_get_level(ob, mmd, 0);
249         int levels = mmd->totlvl - lvl;
250         MDisps *mdisps;
251
252         CustomData_external_read(&me->fdata, &me->id, CD_MASK_MDISPS, me->totface);
253         mdisps= CustomData_get_layer(&me->fdata, CD_MDISPS);
254
255         multires_force_update(ob);
256
257         if(mdisps && levels > 0 && direction == 1) {
258                 if(lvl > 0) {
259                         int nsize = multires_side_tot[lvl];
260                         int hsize = multires_side_tot[mmd->totlvl];
261                         int i;
262
263                         for(i = 0; i < me->totface; ++i) {
264                                 MDisps *mdisp= &mdisps[i];
265                                 float (*disps)[3], (*ndisps)[3], (*hdisps)[3];
266                                 int nvert = (me->mface[i].v4)? 4: 3;
267                                 int totdisp = multires_grid_tot[lvl]*nvert;
268                                 int S;
269
270                                 disps = MEM_callocN(sizeof(float) * 3 * totdisp, "multires disps");
271
272                                 ndisps = disps;
273                                 hdisps = mdisp->disps;
274
275                                 for(S = 0; S < nvert; S++) {
276                                         multires_copy_grid(ndisps, hdisps, nsize, hsize);
277
278                                         ndisps += nsize*nsize;
279                                         hdisps += hsize*hsize;
280                                 }
281
282                                 MEM_freeN(mdisp->disps);
283                                 mdisp->disps = disps;
284                                 mdisp->totdisp = totdisp;
285                         }
286                 }
287                 else {
288                         CustomData_external_remove(&me->fdata, &me->id, CD_MDISPS, me->totface);
289                         CustomData_free_layer_active(&me->fdata, CD_MDISPS, me->totface);
290                 }
291         }
292
293         multires_set_tot_level(ob, mmd, lvl);
294 }
295
296 static DerivedMesh *multires_dm_create_local(Object *ob, DerivedMesh *dm, int lvl, int totlvl, int simple)
297 {
298         MultiresModifierData mmd;
299
300         memset(&mmd, 0, sizeof(MultiresModifierData));
301         mmd.lvl = lvl;
302         mmd.sculptlvl = lvl;
303         mmd.renderlvl = lvl;
304         mmd.totlvl = totlvl;
305         mmd.simple = simple;
306
307         return multires_dm_create_from_derived(&mmd, 1, dm, ob, 0, 0);
308 }
309
310 static DerivedMesh *subsurf_dm_create_local(Object *ob, DerivedMesh *dm, int lvl, int simple, int optimal)
311 {
312         SubsurfModifierData smd;
313
314         memset(&smd, 0, sizeof(SubsurfModifierData));
315         smd.levels = smd.renderLevels = lvl;
316         smd.flags |= eSubsurfModifierFlag_SubsurfUv;
317         if(simple)
318                 smd.subdivType = ME_SIMPLE_SUBSURF;
319         if(optimal)
320                 smd.flags |= eSubsurfModifierFlag_ControlEdges;
321
322         return subsurf_make_derived_from_derived(dm, &smd, 0, NULL, 0, 0);
323 }
324
325 static void multires_reallocate_mdisps(Mesh *me, MDisps *mdisps, int lvl)
326 {
327         int i;
328
329         /* reallocate displacements to be filled in */
330         for(i = 0; i < me->totface; ++i) {
331                 int nvert = (me->mface[i].v4)? 4: 3;
332                 int totdisp = multires_grid_tot[lvl]*nvert;
333                 float (*disps)[3] = MEM_callocN(sizeof(float) * 3 * totdisp, "multires disps");
334
335                 if(mdisps[i].disps)
336                         MEM_freeN(mdisps[i].disps);
337
338                 mdisps[i].disps = disps;
339                 mdisps[i].totdisp = totdisp;
340         }
341 }
342
343 void multiresModifier_subdivide(MultiresModifierData *mmd, Object *ob, int updateblock, int simple)
344 {
345         Mesh *me = ob->data;
346         MDisps *mdisps;
347         int lvl= mmd->totlvl;
348         int totlvl= mmd->totlvl+1;
349
350         if(totlvl > multires_max_levels)
351                 return;
352
353         multires_force_update(ob);
354
355         mdisps = CustomData_get_layer(&me->fdata, CD_MDISPS);
356         if(!mdisps)
357                 mdisps = CustomData_add_layer(&me->fdata, CD_MDISPS, CD_DEFAULT, NULL, me->totface);
358
359         if(mdisps->disps && !updateblock && totlvl > 1) {
360                 /* upsample */
361                 DerivedMesh *lowdm, *cddm, *highdm;
362                 DMGridData **highGridData, **lowGridData, **subGridData;
363                 CCGSubSurf *ss;
364                 int i, numGrids, highGridSize, lowGridSize;
365
366                 /* create subsurf DM from original mesh at high level */
367                 cddm = CDDM_from_mesh(me, NULL);
368                 highdm = subsurf_dm_create_local(ob, cddm, totlvl, simple, 0);
369
370                 /* create multires DM from original mesh at low level */
371                 lowdm = multires_dm_create_local(ob, cddm, lvl, lvl, simple);
372                 cddm->release(cddm);
373
374                 /* copy subsurf grids and replace them with low displaced grids */
375                 numGrids = highdm->getNumGrids(highdm);
376                 highGridSize = highdm->getGridSize(highdm);
377                 highGridData = highdm->getGridData(highdm);
378                 lowGridSize = lowdm->getGridSize(lowdm);
379                 lowGridData = lowdm->getGridData(lowdm);
380
381                 subGridData = MEM_callocN(sizeof(float*)*numGrids, "subGridData*");
382
383                 for(i = 0; i < numGrids; ++i) {
384                         /* backup subsurf grids */
385                         subGridData[i] = MEM_callocN(sizeof(DMGridData)*highGridSize*highGridSize, "subGridData");
386                         memcpy(subGridData[i], highGridData[i], sizeof(DMGridData)*highGridSize*highGridSize);
387
388                         /* overwrite with current displaced grids */
389                         multires_copy_dm_grid(highGridData[i], lowGridData[i], highGridSize, lowGridSize);
390                 }
391
392                 /* low lower level dm no longer needed at this point */
393                 lowdm->release(lowdm);
394
395                 /* subsurf higher levels again with displaced data */
396                 ss= ((CCGDerivedMesh*)highdm)->ss;
397                 ccgSubSurf_updateFromFaces(ss, lvl, NULL, 0);
398                 ccgSubSurf_updateLevels(ss, lvl, NULL, 0);
399
400                 /* reallocate displacements */
401                 multires_reallocate_mdisps(me, mdisps, totlvl); 
402
403                 /* compute displacements */
404                 multiresModifier_disp_run(highdm, me, 1, 0, subGridData, totlvl);
405
406                 /* free */
407                 highdm->release(highdm);
408                 for(i = 0; i < numGrids; ++i)
409                         MEM_freeN(subGridData[i]);
410                 MEM_freeN(subGridData);
411         }
412         else {
413                 /* only reallocate, nothing to upsample */
414                 multires_reallocate_mdisps(me, mdisps, totlvl); 
415         }
416
417         multires_set_tot_level(ob, mmd, totlvl);
418 }
419
420 static void grid_tangent(int gridSize, int index, int x, int y, int axis, DMGridData **gridData, float t[3])
421 {
422         if(axis == 0) {
423                 if(x == gridSize - 1) {
424                         if(y == gridSize - 1)
425                                 sub_v3_v3v3(t, gridData[index][x + gridSize*(y - 1)].co, gridData[index][x - 1 + gridSize*(y - 1)].co);
426                         else
427                                 sub_v3_v3v3(t, gridData[index][x + gridSize*y].co, gridData[index][x - 1 + gridSize*y].co);
428                 }
429                 else
430                         sub_v3_v3v3(t, gridData[index][x + 1 + gridSize*y].co, gridData[index][x + gridSize*y].co);
431         }
432         else if(axis == 1) {
433                 if(y == gridSize - 1) {
434                         if(x == gridSize - 1)
435                                 sub_v3_v3v3(t, gridData[index][x - 1 + gridSize*y].co, gridData[index][x - 1 + gridSize*(y - 1)].co);
436                         else
437                                 sub_v3_v3v3(t, gridData[index][x + gridSize*y].co, gridData[index][x + gridSize*(y - 1)].co);
438                 }
439                 else
440                         sub_v3_v3v3(t, gridData[index][x + gridSize*(y + 1)].co, gridData[index][x + gridSize*y].co);
441         }
442 }
443
444 static void multiresModifier_disp_run(DerivedMesh *dm, Mesh *me, int invert, int add, DMGridData **oldGridData, int totlvl)
445 {
446         CCGDerivedMesh *ccgdm = (CCGDerivedMesh*)dm;
447         DMGridData **gridData, **subGridData;
448         MFace *mface = me->mface;
449         MDisps *mdisps = CustomData_get_layer(&me->fdata, CD_MDISPS);
450         int *gridOffset;
451         int i, numGrids, gridSize, dGridSize, dSkip;
452
453         numGrids = dm->getNumGrids(dm);
454         gridSize = dm->getGridSize(dm);
455         gridData = dm->getGridData(dm);
456         gridOffset = dm->getGridOffset(dm);
457         subGridData = (oldGridData)? oldGridData: gridData;
458
459         dGridSize = multires_side_tot[totlvl];
460         dSkip = (dGridSize-1)/(gridSize-1);
461
462         #pragma omp parallel for private(i) schedule(static)
463         for(i = 0; i < me->totface; ++i) {
464                 const int numVerts = mface[i].v4 ? 4 : 3;
465                 MDisps *mdisp = &mdisps[i];
466                 int S, x, y, gIndex = gridOffset[i];
467
468                 /* when adding new faces in edit mode, need to allocate disps */
469                 if(!mdisp->disps)
470                 #pragma omp critical
471                 {
472                         multires_reallocate_mdisps(me, mdisps, totlvl);
473                 }
474
475                 for(S = 0; S < numVerts; ++S, ++gIndex) {
476                         DMGridData *grid = gridData[gIndex];
477                         DMGridData *subgrid = subGridData[gIndex];
478                         float (*dispgrid)[3] = &mdisp->disps[S*dGridSize*dGridSize];
479
480                         for(y = 0; y < gridSize; y++) {
481                                 for(x = 0; x < gridSize; x++) {
482                                         float *co = grid[x + y*gridSize].co;
483                                         float *sco = subgrid[x + y*gridSize].co;
484                                         float *no = subgrid[x + y*gridSize].no;
485                                         float *data = dispgrid[dGridSize*y*dSkip + x*dSkip];
486                                         float mat[3][3], tx[3], ty[3], disp[3], d[3];
487
488                                         /* construct tangent space matrix */
489                                         grid_tangent(gridSize, gIndex, x, y, 0, subGridData, tx);
490                                         normalize_v3(tx);
491
492                                         grid_tangent(gridSize, gIndex, x, y, 1, subGridData, ty);
493                                         normalize_v3(ty);
494
495                                         //mul_v3_fl(tx, 1.0f/(gridSize-1));
496                                         //mul_v3_fl(ty, 1.0f/(gridSize-1));
497                                         //cross_v3_v3v3(no, tx, ty);
498
499                                         column_vectors_to_mat3(mat, tx, ty, no);
500
501                                         if(!invert) {
502                                                 /* convert to object space and add */
503                                                 mul_v3_m3v3(disp, mat, data);
504                                                 add_v3_v3v3(co, sco, disp);
505                                         }
506                                         else if(!add) {
507                                                 /* convert difference to tangent space */
508                                                 sub_v3_v3v3(disp, co, sco);
509                                                 invert_m3(mat);
510                                                 mul_v3_m3v3(data, mat, disp);
511                                         }
512                                         else {
513                                                 /* convert difference to tangent space */
514                                                 invert_m3(mat);
515                                                 mul_v3_m3v3(d, mat, co);
516                                                 add_v3_v3(data, d);
517                                         }
518                                 }
519                         }
520                 }
521         }
522
523         if(!invert) {
524                 ccgSubSurf_stitchFaces(ccgdm->ss, 0, NULL, 0);
525                 ccgSubSurf_updateNormals(ccgdm->ss, NULL, 0);
526         }
527 }
528
529 static void multiresModifier_update(DerivedMesh *dm)
530 {
531         CCGDerivedMesh *ccgdm= (CCGDerivedMesh*)dm;
532         Object *ob;
533         Mesh *me;
534         MDisps *mdisps;
535         MultiresModifierData *mmd;
536
537         ob = ccgdm->multires.ob;
538         me = ccgdm->multires.ob->data;
539         mmd = ccgdm->multires.mmd;
540         CustomData_external_read(&me->fdata, &me->id, CD_MASK_MDISPS, me->totface);
541         mdisps = CustomData_get_layer(&me->fdata, CD_MDISPS);
542
543         if(mdisps) {
544                 int lvl = ccgdm->multires.lvl;
545                 int totlvl = ccgdm->multires.totlvl;
546                 
547                 if(lvl < totlvl) {
548                         Mesh *me = ob->data;
549                         DerivedMesh *lowdm, *cddm, *highdm;
550                         DMGridData **highGridData, **lowGridData, **subGridData, **gridData, *diffGrid;
551                         CCGSubSurf *ss;
552                         int i, j, numGrids, highGridSize, lowGridSize;
553
554                         /* create subsurf DM from original mesh at high level */
555                         cddm = CDDM_from_mesh(me, NULL);
556                         highdm = subsurf_dm_create_local(ob, cddm, totlvl, mmd->simple, 0);
557
558                         /* create multires DM from original mesh and displacements */
559                         lowdm = multires_dm_create_local(ob, cddm, lvl, totlvl, mmd->simple);
560                         cddm->release(cddm);
561
562                         /* gather grid data */
563                         numGrids = highdm->getNumGrids(highdm);
564                         highGridSize = highdm->getGridSize(highdm);
565                         highGridData = highdm->getGridData(highdm);
566                         lowGridSize = lowdm->getGridSize(lowdm);
567                         lowGridData = lowdm->getGridData(lowdm);
568                         gridData = dm->getGridData(dm);
569
570                         subGridData = MEM_callocN(sizeof(DMGridData*)*numGrids, "subGridData*");
571                         diffGrid = MEM_callocN(sizeof(DMGridData)*lowGridSize*lowGridSize, "diff");
572
573                         for(i = 0; i < numGrids; ++i) {
574                                 /* backup subsurf grids */
575                                 subGridData[i] = MEM_callocN(sizeof(DMGridData)*highGridSize*highGridSize, "subGridData");
576                                 memcpy(subGridData[i], highGridData[i], sizeof(DMGridData)*highGridSize*highGridSize);
577
578                                 /* write difference of subsurf and displaced low level into high subsurf */
579                                 for(j = 0; j < lowGridSize*lowGridSize; ++j)
580                                         sub_v3_v3v3(diffGrid[j].co, gridData[i][j].co, lowGridData[i][j].co);
581
582                                 multires_copy_dm_grid(highGridData[i], diffGrid, highGridSize, lowGridSize);
583                         }
584
585                         /* lower level dm no longer needed at this point */
586                         MEM_freeN(diffGrid);
587                         lowdm->release(lowdm);
588
589                         /* subsurf higher levels again with difference of coordinates */
590                         ss= ((CCGDerivedMesh*)highdm)->ss;
591                         ccgSubSurf_updateFromFaces(ss, lvl, NULL, 0);
592                         ccgSubSurf_updateLevels(ss, lvl, NULL, 0);
593
594                         /* add to displacements */
595                         multiresModifier_disp_run(highdm, me, 1, 1, subGridData, mmd->totlvl);
596
597                         /* free */
598                         highdm->release(highdm);
599                         for(i = 0; i < numGrids; ++i)
600                                 MEM_freeN(subGridData[i]);
601                         MEM_freeN(subGridData);
602                 }
603                 else {
604                         DerivedMesh *cddm, *subdm;
605
606                         cddm = CDDM_from_mesh(me, NULL);
607                         subdm = subsurf_dm_create_local(ob, cddm, mmd->totlvl, mmd->simple, 0);
608                         cddm->release(cddm);
609
610                         multiresModifier_disp_run(dm, me, 1, 0, subdm->getGridData(subdm), mmd->totlvl);
611
612                         subdm->release(subdm);
613                 }
614         }
615 }
616
617 void multires_mark_as_modified(struct Object *ob)
618 {
619         if(ob && ob->derivedFinal) {
620                 CCGDerivedMesh *ccgdm = (CCGDerivedMesh*)ob->derivedFinal;
621                 ccgdm->multires.modified = 1;
622         }
623 }
624
625 void multires_force_update(Object *ob)
626 {
627         if(ob && ob->derivedFinal) {
628                 ob->derivedFinal->needsFree =1;
629                 ob->derivedFinal->release(ob->derivedFinal);
630                 ob->derivedFinal = NULL;
631         }
632 }
633
634 void multires_stitch_grids(Object *ob)
635 {
636         /* utility for smooth brush */
637         if(ob && ob->derivedFinal) {
638                 CCGDerivedMesh *ccgdm = (CCGDerivedMesh*)ob->derivedFinal;
639                 CCGFace **faces;
640                 int totface;
641
642                 if(ccgdm->pbvh) {
643                         BLI_pbvh_get_grid_updates(ccgdm->pbvh, 0, (void***)&faces, &totface);
644
645                         if(totface) {
646                                 ccgSubSurf_stitchFaces(ccgdm->ss, 0, faces, totface);
647                                 MEM_freeN(faces);
648                         }
649                 }
650         }
651 }
652
653 struct DerivedMesh *multires_dm_create_from_derived(MultiresModifierData *mmd, int local_mmd, DerivedMesh *dm, Object *ob,
654                                                     int useRenderParams, int isFinalCalc)
655 {
656         Mesh *me= ob->data;
657         DerivedMesh *result;
658         CCGDerivedMesh *ccgdm;
659         DMGridData **gridData, **subGridData;
660         int lvl= multires_get_level(ob, mmd, useRenderParams);
661         int i, gridSize, numGrids;
662
663         if(lvl == 0)
664                 return dm;
665
666         result = subsurf_dm_create_local(ob, dm, lvl,
667                 mmd->simple, mmd->flags & eMultiresModifierFlag_ControlEdges);
668
669         if(!local_mmd) {
670                 ccgdm = (CCGDerivedMesh*)result;
671
672                 ccgdm->multires.ob = ob;
673                 ccgdm->multires.mmd = mmd;
674                 ccgdm->multires.local_mmd = local_mmd;
675                 ccgdm->multires.lvl = lvl;
676                 ccgdm->multires.totlvl = mmd->totlvl;
677                 ccgdm->multires.modified = 0;
678                 ccgdm->multires.update = multiresModifier_update;
679         }
680
681         numGrids = result->getNumGrids(result);
682         gridSize = result->getGridSize(result);
683         gridData = result->getGridData(result);
684
685         subGridData = MEM_callocN(sizeof(DMGridData*)*numGrids, "subGridData*");
686
687         for(i = 0; i < numGrids; i++) {
688                 subGridData[i] = MEM_callocN(sizeof(DMGridData)*gridSize*gridSize, "subGridData");
689                 memcpy(subGridData[i], gridData[i], sizeof(DMGridData)*gridSize*gridSize);
690         }
691
692         CustomData_external_read(&me->fdata, &me->id, CD_MASK_MDISPS, me->totface);
693         multiresModifier_disp_run(result, ob->data, 0, 0, subGridData, mmd->totlvl);
694
695         for(i = 0; i < numGrids; i++)
696                 MEM_freeN(subGridData[i]);
697         MEM_freeN(subGridData);
698
699         return result;
700 }
701
702 /**** Old Multires code ****
703 ***************************/
704
705 #if 0
706 static void mdisp_copy_grid(float (*new)[3], int newstride, float (*old)[3], int oldstride, int xoff, int yoff, int xsize, int ysize)
707 {
708         int x, y;
709
710         for(y = 0; y < ysize; ++y)
711                 for(x = 0; x < xsize; ++x)
712                         copy_v3_v3(disps[x + y*side], mdisp->disps[(x + xoffs) + (y + yoffs)*oldside]);
713
714 }
715
716 static void mdisps_convert(MFace *mface, MDisps *mdisp, int lvl)
717 {
718         int side = multires_side_tot[lvl];
719         int nvert = (mface->v4)? 4: 3;
720         int totdisp = multires_grid_tot[lvl]*nvert;
721         int x, y;
722         float (*disps)[3];
723
724         disps = MEM_callocN(sizeof(float) * 3 * totdisp, "multires disps");
725
726
727
728 static const int multires_max_levels = 13;
729 static const int multires_grid_tot[] = {1, 4, 9, 25, 81, 289, 1089, 4225, 16641, 66049, 263169, 1050625, 4198401, 16785409};
730 static const int multires_side_tot[] = {1, 2, 3, 5,  9,  17,  33,   65,   129,   257,   513,    1025,    2049,    4097};
731
732 }
733 #endif
734
735 /* Does not actually free lvl itself */
736 static void multires_free_level(MultiresLevel *lvl)
737 {
738         if(lvl) {
739                 if(lvl->faces) MEM_freeN(lvl->faces);
740                 if(lvl->edges) MEM_freeN(lvl->edges);
741                 if(lvl->colfaces) MEM_freeN(lvl->colfaces);
742         }
743 }
744
745 void multires_free(Multires *mr)
746 {
747         if(mr) {
748                 MultiresLevel* lvl= mr->levels.first;
749
750                 /* Free the first-level data */
751                 if(lvl) {
752                         CustomData_free(&mr->vdata, lvl->totvert);
753                         CustomData_free(&mr->fdata, lvl->totface);
754                         if(mr->edge_flags)
755                                 MEM_freeN(mr->edge_flags);
756                         if(mr->edge_creases)
757                                 MEM_freeN(mr->edge_creases);
758                 }
759
760                 while(lvl) {
761                         multires_free_level(lvl);                       
762                         lvl= lvl->next;
763                 }
764
765                 MEM_freeN(mr->verts);
766
767                 BLI_freelistN(&mr->levels);
768
769                 MEM_freeN(mr);
770         }
771 }
772
773 static void create_old_vert_face_map(ListBase **map, IndexNode **mem, const MultiresFace *mface,
774                                      const int totvert, const int totface)
775 {
776         int i,j;
777         IndexNode *node = NULL;
778         
779         (*map) = MEM_callocN(sizeof(ListBase) * totvert, "vert face map");
780         (*mem) = MEM_callocN(sizeof(IndexNode) * totface*4, "vert face map mem");
781         node = *mem;
782         
783         /* Find the users */
784         for(i = 0; i < totface; ++i){
785                 for(j = 0; j < (mface[i].v[3]?4:3); ++j, ++node) {
786                         node->index = i;
787                         BLI_addtail(&(*map)[mface[i].v[j]], node);
788                 }
789         }
790 }
791
792 static void create_old_vert_edge_map(ListBase **map, IndexNode **mem, const MultiresEdge *medge,
793                                      const int totvert, const int totedge)
794 {
795         int i,j;
796         IndexNode *node = NULL;
797         
798         (*map) = MEM_callocN(sizeof(ListBase) * totvert, "vert edge map");
799         (*mem) = MEM_callocN(sizeof(IndexNode) * totedge*2, "vert edge map mem");
800         node = *mem;
801         
802         /* Find the users */
803         for(i = 0; i < totedge; ++i){
804                 for(j = 0; j < 2; ++j, ++node) {
805                         node->index = i;
806                         BLI_addtail(&(*map)[medge[i].v[j]], node);
807                 }
808         }
809 }
810
811 static MultiresFace *find_old_face(ListBase *map, MultiresFace *faces, int v1, int v2, int v3, int v4)
812 {
813         IndexNode *n1;
814         int v[4] = {v1, v2, v3, v4}, i, j;
815
816         for(n1 = map[v1].first; n1; n1 = n1->next) {
817                 int fnd[4] = {0, 0, 0, 0};
818
819                 for(i = 0; i < 4; ++i) {
820                         for(j = 0; j < 4; ++j) {
821                                 if(v[i] == faces[n1->index].v[j])
822                                         fnd[i] = 1;
823                         }
824                 }
825
826                 if(fnd[0] && fnd[1] && fnd[2] && fnd[3])
827                         return &faces[n1->index];
828         }
829
830         return NULL;
831 }
832
833 static MultiresEdge *find_old_edge(ListBase *map, MultiresEdge *edges, int v1, int v2)
834 {
835         IndexNode *n1, *n2;
836
837         for(n1 = map[v1].first; n1; n1 = n1->next) {
838                 for(n2 = map[v2].first; n2; n2 = n2->next) {
839                         if(n1->index == n2->index)
840                                 return &edges[n1->index];
841                 }
842         }
843
844         return NULL;
845 }
846
847 static void multires_load_old_edges(ListBase **emap, MultiresLevel *lvl, int *vvmap, int dst, int v1, int v2, int mov)
848 {
849         int emid = find_old_edge(emap[2], lvl->edges, v1, v2)->mid;
850         vvmap[dst + mov] = emid;
851
852         if(lvl->next->next) {
853                 multires_load_old_edges(emap + 1, lvl->next, vvmap, dst + mov, v1, emid, mov / 2);
854                 multires_load_old_edges(emap + 1, lvl->next, vvmap, dst + mov, v2, emid, -mov / 2);
855         }
856 }
857
858 static void multires_load_old_faces(ListBase **fmap, ListBase **emap, MultiresLevel *lvl, int *vvmap, int dst,
859                                     int v1, int v2, int v3, int v4, int st2, int st3)
860 {
861         int fmid;
862         int emid13, emid14, emid23, emid24;
863
864         if(lvl && lvl->next) {
865                 fmid = find_old_face(fmap[1], lvl->faces, v1, v2, v3, v4)->mid;
866                 vvmap[dst] = fmid;
867
868                 emid13 = find_old_edge(emap[1], lvl->edges, v1, v3)->mid;
869                 emid14 = find_old_edge(emap[1], lvl->edges, v1, v4)->mid;
870                 emid23 = find_old_edge(emap[1], lvl->edges, v2, v3)->mid;
871                 emid24 = find_old_edge(emap[1], lvl->edges, v2, v4)->mid;
872
873
874                 multires_load_old_faces(fmap + 1, emap + 1, lvl->next, vvmap, dst + st2 * st3 + st3,
875                                         fmid, v2, emid23, emid24, st2, st3 / 2);
876
877                 multires_load_old_faces(fmap + 1, emap + 1, lvl->next, vvmap, dst - st2 * st3 + st3,
878                                         emid14, emid24, fmid, v4, st2, st3 / 2);
879
880                 multires_load_old_faces(fmap + 1, emap + 1, lvl->next, vvmap, dst + st2 * st3 - st3,
881                                         emid13, emid23, v3, fmid, st2, st3 / 2);
882
883                 multires_load_old_faces(fmap + 1, emap + 1, lvl->next, vvmap, dst - st2 * st3 - st3,
884                                         v1, fmid, emid13, emid14, st2, st3 / 2);
885
886                 if(lvl->next->next) {
887                         multires_load_old_edges(emap, lvl->next, vvmap, dst, emid24, fmid, st3);
888                         multires_load_old_edges(emap, lvl->next, vvmap, dst, emid13, fmid, -st3);
889                         multires_load_old_edges(emap, lvl->next, vvmap, dst, emid14, fmid, -st2 * st3);
890                         multires_load_old_edges(emap, lvl->next, vvmap, dst, emid23, fmid, st2 * st3);
891                 }
892         }
893 }
894
895 /* Loads a multires object stored in the old Multires struct into the new format */
896 void multires_load_old(DerivedMesh *dm, Multires *mr)
897 {
898         MultiresLevel *lvl, *lvl1;
899         MVert *vsrc, *vdst;
900         int src, dst;
901         int totlvl = 2; // XXX MultiresDM_get_totlvl(dm);
902         int st = multires_side_tot[totlvl - 1] - 1;
903         int extedgelen = multires_side_tot[totlvl] - 2;
904         int *vvmap; // inorder for dst, map to src
905         int crossedgelen;
906         int i, j, s, x, totvert, tottri, totquad;
907
908         src = 0;
909         dst = 0;
910         vsrc = mr->verts;
911         vdst = CDDM_get_verts(dm);
912         totvert = dm->getNumVerts(dm);
913         vvmap = MEM_callocN(sizeof(int) * totvert, "multires vvmap");
914
915         lvl1 = mr->levels.first;
916         /* Load base verts */
917         for(i = 0; i < lvl1->totvert; ++i) {
918                 vvmap[totvert - lvl1->totvert + i] = src;
919                 ++src;
920         }
921
922         /* Original edges */
923         dst = totvert - lvl1->totvert - extedgelen * lvl1->totedge;
924         for(i = 0; i < lvl1->totedge; ++i) {
925                 int ldst = dst + extedgelen * i;
926                 int lsrc = src;
927                 lvl = lvl1->next;
928
929                 for(j = 2; j <= mr->level_count; ++j) {
930                         int base = multires_side_tot[totlvl - j + 1] - 2;
931                         int skip = multires_side_tot[totlvl - j + 2] - 1;
932                         int st = multires_side_tot[j - 1] - 1;
933
934                         for(x = 0; x < st; ++x)
935                                 vvmap[ldst + base + x * skip] = lsrc + st * i + x;
936
937                         lsrc += lvl->totvert - lvl->prev->totvert;
938                         lvl = lvl->next;
939                 }
940         }
941
942         /* Center points */
943         dst = 0;
944         for(i = 0; i < lvl1->totface; ++i) {
945                 int sides = lvl1->faces[i].v[3] ? 4 : 3;
946
947                 vvmap[dst] = src + lvl1->totedge + i;
948                 dst += 1 + sides * (st - 1) * st;
949         }
950
951
952         /* The rest is only for level 3 and up */
953         if(lvl1->next && lvl1->next->next) {
954                 ListBase **fmap, **emap;
955                 IndexNode **fmem, **emem;
956
957                 /* Face edge cross */
958                 tottri = totquad = 0;
959                 crossedgelen = multires_side_tot[totlvl - 1] - 2;
960                 dst = 0;
961                 for(i = 0; i < lvl1->totface; ++i) {
962                         int sides = lvl1->faces[i].v[3] ? 4 : 3;
963
964                         lvl = lvl1->next->next;
965                         ++dst;
966
967                         for(j = 3; j <= mr->level_count; ++j) {
968                                 int base = multires_side_tot[totlvl - j + 1] - 2;
969                                 int skip = multires_side_tot[totlvl - j + 2] - 1;
970                                 int st = pow(2, j - 2);
971                                 int st2 = pow(2, j - 3);
972                                 int lsrc = lvl->prev->totvert;
973
974                                 /* Skip exterior edge verts */
975                                 lsrc += lvl1->totedge * st;
976
977                                 /* Skip earlier face edge crosses */
978                                 lsrc += st2 * (tottri * 3 + totquad * 4);
979
980                                 for(s = 0; s < sides; ++s) {
981                                         for(x = 0; x < st2; ++x) {
982                                                 vvmap[dst + crossedgelen * (s + 1) - base - x * skip - 1] = lsrc;
983                                                 ++lsrc;
984                                         }
985                                 }
986
987                                 lvl = lvl->next;
988                         }
989
990                         dst += sides * (st - 1) * st;
991
992                         if(sides == 4) ++totquad;
993                         else ++tottri;
994
995                 }
996
997                 /* calculate vert to edge/face maps for each level (except the last) */
998                 fmap = MEM_callocN(sizeof(ListBase*) * (mr->level_count-1), "multires fmap");
999                 emap = MEM_callocN(sizeof(ListBase*) * (mr->level_count-1), "multires emap");
1000                 fmem = MEM_callocN(sizeof(IndexNode*) * (mr->level_count-1), "multires fmem");
1001                 emem = MEM_callocN(sizeof(IndexNode*) * (mr->level_count-1), "multires emem");
1002                 lvl = lvl1;
1003                 for(i = 0; i < mr->level_count - 1; ++i) {
1004                         create_old_vert_face_map(fmap + i, fmem + i, lvl->faces, lvl->totvert, lvl->totface);
1005                         create_old_vert_edge_map(emap + i, emem + i, lvl->edges, lvl->totvert, lvl->totedge);
1006                         lvl = lvl->next;
1007                 }
1008
1009                 /* Interior face verts */
1010                 lvl = lvl1->next->next;
1011                 dst = 0;
1012                 for(j = 0; j < lvl1->totface; ++j) {
1013                         int sides = lvl1->faces[j].v[3] ? 4 : 3;
1014                         int ldst = dst + 1 + sides * (st - 1);
1015
1016                         for(s = 0; s < sides; ++s) {
1017                                 int st2 = multires_side_tot[totlvl - 1] - 2;
1018                                 int st3 = multires_side_tot[totlvl - 2] - 2;
1019                                 int st4 = st3 == 0 ? 1 : (st3 + 1) / 2;
1020                                 int mid = ldst + st2 * st3 + st3;
1021                                 int cv = lvl1->faces[j].v[s];
1022                                 int nv = lvl1->faces[j].v[s == sides - 1 ? 0 : s + 1];
1023                                 int pv = lvl1->faces[j].v[s == 0 ? sides - 1 : s - 1];
1024
1025                                 multires_load_old_faces(fmap, emap, lvl1->next, vvmap, mid,
1026                                                         vvmap[dst], cv,
1027                                                         find_old_edge(emap[0], lvl1->edges, pv, cv)->mid,
1028                                                         find_old_edge(emap[0], lvl1->edges, cv, nv)->mid,
1029                                                         st2, st4);
1030
1031                                 ldst += (st - 1) * (st - 1);
1032                         }
1033
1034
1035                         dst = ldst;
1036                 }
1037
1038                 lvl = lvl->next;
1039
1040                 for(i = 0; i < mr->level_count - 1; ++i) {
1041                         MEM_freeN(fmap[i]);
1042                         MEM_freeN(fmem[i]);
1043                         MEM_freeN(emap[i]);
1044                         MEM_freeN(emem[i]);
1045                 }
1046
1047                 MEM_freeN(fmap);
1048                 MEM_freeN(emap);
1049                 MEM_freeN(fmem);
1050                 MEM_freeN(emem);
1051         }
1052
1053         /* Transfer verts */
1054         for(i = 0; i < totvert; ++i)
1055                 copy_v3_v3(vdst[i].co, vsrc[vvmap[i]].co);
1056
1057         MEM_freeN(vvmap);
1058 }
1059