Merged changes in the trunk up to revision 55546.
[blender-staging.git] / source / blender / editors / sculpt_paint / sculpt_undo.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) 2006 by Nicholas Bishop
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  * Implements the Sculpt Mode tools
28  *
29  */
30
31 /** \file blender/editors/sculpt_paint/sculpt_undo.c
32  *  \ingroup edsculpt
33  */
34
35 #include <stddef.h>
36
37 #include "MEM_guardedalloc.h"
38
39 #include "BLI_math.h"
40 #include "BLI_utildefines.h"
41 #include "BLI_string.h"
42 #include "BLI_listbase.h"
43 #include "BLI_ghash.h"
44 #include "BLI_threads.h"
45
46 #include "DNA_meshdata_types.h"
47 #include "DNA_object_types.h"
48 #include "DNA_scene_types.h"
49 #include "DNA_mesh_types.h"
50
51 #include "BKE_ccg.h"
52 #include "BKE_cdderivedmesh.h"
53 #include "BKE_context.h"
54 #include "BKE_depsgraph.h"
55 #include "BKE_modifier.h"
56 #include "BKE_multires.h"
57 #include "BKE_paint.h"
58 #include "BKE_key.h"
59 #include "BKE_mesh.h"
60 #include "BKE_subsurf.h"
61
62 #include "WM_api.h"
63 #include "WM_types.h"
64
65 #include "GPU_buffers.h"
66
67 #include "ED_sculpt.h"
68 #include "bmesh.h"
69 #include "paint_intern.h"
70 #include "sculpt_intern.h"
71
72 /************************** Undo *************************/
73
74 static void update_cb(PBVHNode *node, void *rebuild)
75 {
76         BKE_pbvh_node_mark_update(node);
77         if (*((int *)rebuild))
78                 BKE_pbvh_node_mark_rebuild_draw(node);
79         BKE_pbvh_node_fully_hidden_set(node, 0);
80 }
81
82 static void sculpt_undo_restore_deformed(const SculptSession *ss,
83                                          SculptUndoNode *unode,
84                                          int uindex, int oindex,
85                                          float coord[3])
86 {
87         if (unode->orig_co) {
88                 swap_v3_v3(coord, unode->orig_co[uindex]);
89                 copy_v3_v3(unode->co[uindex], ss->deform_cos[oindex]);
90         }
91         else {
92                 swap_v3_v3(coord, unode->co[uindex]);
93         }
94 }
95
96 static int sculpt_undo_restore_coords(bContext *C, DerivedMesh *dm, SculptUndoNode *unode)
97 {
98         Scene *scene = CTX_data_scene(C);
99         Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
100         Object *ob = CTX_data_active_object(C);
101         SculptSession *ss = ob->sculpt;
102         MVert *mvert;
103         int *index, i, j;
104         
105         if (unode->maxvert) {
106                 /* regular mesh restore */
107
108                 if (ss->kb && strcmp(ss->kb->name, unode->shapeName)) {
109                         /* shape key has been changed before calling undo operator */
110
111                         Key *key = BKE_key_from_object(ob);
112                         KeyBlock *kb = key ? BKE_keyblock_find_name(key, unode->shapeName) : NULL;
113
114                         if (kb) {
115                                 ob->shapenr = BLI_findindex(&key->block, kb) + 1;
116
117                                 sculpt_update_mesh_elements(scene, sd, ob, 0, FALSE);
118                                 WM_event_add_notifier(C, NC_OBJECT | ND_DATA, ob);
119                         }
120                         else {
121                                 /* key has been removed -- skip this undo node */
122                                 return 0;
123                         }
124                 }
125
126                 index = unode->index;
127                 mvert = ss->mvert;
128
129                 if (ss->kb) {
130                         float (*vertCos)[3];
131                         vertCos = BKE_key_convert_to_vertcos(ob, ss->kb);
132
133                         for (i = 0; i < unode->totvert; i++) {
134                                 if (ss->modifiers_active) {
135                                         sculpt_undo_restore_deformed(ss, unode, i, index[i], vertCos[index[i]]);
136                                 }
137                                 else {
138                                         if (unode->orig_co) swap_v3_v3(vertCos[index[i]], unode->orig_co[i]);
139                                         else swap_v3_v3(vertCos[index[i]], unode->co[i]);
140                                 }
141                         }
142
143                         /* propagate new coords to keyblock */
144                         sculpt_vertcos_to_key(ob, ss->kb, vertCos);
145
146                         /* pbvh uses it's own mvert array, so coords should be */
147                         /* propagated to pbvh here */
148                         BKE_pbvh_apply_vertCos(ss->pbvh, vertCos);
149
150                         MEM_freeN(vertCos);
151                 }
152                 else {
153                         for (i = 0; i < unode->totvert; i++) {
154                                 if (ss->modifiers_active) {
155                                         sculpt_undo_restore_deformed(ss, unode, i, index[i], mvert[index[i]].co);
156                                 }
157                                 else {
158                                         if (unode->orig_co) swap_v3_v3(mvert[index[i]].co, unode->orig_co[i]);
159                                         else swap_v3_v3(mvert[index[i]].co, unode->co[i]);
160                                 }
161                                 mvert[index[i]].flag |= ME_VERT_PBVH_UPDATE;
162                         }
163                 }
164         }
165         else if (unode->maxgrid && dm->getGridData) {
166                 /* multires restore */
167                 CCGElem **grids, *grid;
168                 CCGKey key;
169                 float (*co)[3];
170                 int gridsize;
171
172                 grids = dm->getGridData(dm);
173                 gridsize = dm->getGridSize(dm);
174                 dm->getGridKey(dm, &key);
175
176                 co = unode->co;
177                 for (j = 0; j < unode->totgrid; j++) {
178                         grid = grids[unode->grids[j]];
179
180                         for (i = 0; i < gridsize * gridsize; i++, co++)
181                                 swap_v3_v3(CCG_elem_offset_co(&key, grid, i), co[0]);
182                 }
183         }
184
185         return 1;
186 }
187
188 static int sculpt_undo_restore_hidden(bContext *C, DerivedMesh *dm,
189                                       SculptUndoNode *unode)
190 {
191         Object *ob = CTX_data_active_object(C);
192         SculptSession *ss = ob->sculpt;
193         int i;
194
195         if (unode->maxvert) {
196                 MVert *mvert = ss->mvert;
197                 
198                 for (i = 0; i < unode->totvert; i++) {
199                         MVert *v = &mvert[unode->index[i]];
200                         int uval = BLI_BITMAP_GET(unode->vert_hidden, i);
201
202                         BLI_BITMAP_MODIFY(unode->vert_hidden, i,
203                                           v->flag & ME_HIDE);
204                         if (uval)
205                                 v->flag |= ME_HIDE;
206                         else
207                                 v->flag &= ~ME_HIDE;
208                         
209                         v->flag |= ME_VERT_PBVH_UPDATE;
210                 }
211         }
212         else if (unode->maxgrid && dm->getGridData) {
213                 BLI_bitmap *grid_hidden = dm->getGridHidden(dm);
214                 
215                 for (i = 0; i < unode->totgrid; i++) {
216                         SWAP(BLI_bitmap,
217                              unode->grid_hidden[i],
218                              grid_hidden[unode->grids[i]]);
219                         
220                 }
221         }
222
223         return 1;
224 }
225
226 static int sculpt_undo_restore_mask(bContext *C, DerivedMesh *dm, SculptUndoNode *unode)
227 {
228         Object *ob = CTX_data_active_object(C);
229         SculptSession *ss = ob->sculpt;
230         MVert *mvert;
231         float *vmask;
232         int *index, i, j;
233         
234         if (unode->maxvert) {
235                 /* regular mesh restore */
236
237                 index = unode->index;
238                 mvert = ss->mvert;
239                 vmask = ss->vmask;
240
241                 for (i = 0; i < unode->totvert; i++) {
242                         SWAP(float, vmask[index[i]], unode->mask[i]);
243                         mvert[index[i]].flag |= ME_VERT_PBVH_UPDATE;
244                 }
245         }
246         else if (unode->maxgrid && dm->getGridData) {
247                 /* multires restore */
248                 CCGElem **grids, *grid;
249                 CCGKey key;
250                 float *mask;
251                 int gridsize;
252
253                 grids = dm->getGridData(dm);
254                 gridsize = dm->getGridSize(dm);
255                 dm->getGridKey(dm, &key);
256
257                 mask = unode->mask;
258                 for (j = 0; j < unode->totgrid; j++) {
259                         grid = grids[unode->grids[j]];
260
261                         for (i = 0; i < gridsize * gridsize; i++, mask++)
262                                 SWAP(float, *CCG_elem_offset_mask(&key, grid, i), *mask);
263                 }
264         }
265
266         return 1;
267 }
268
269 static void sculpt_undo_bmesh_restore_generic(SculptUndoNode *unode,
270                                               Object *ob,
271                                               SculptSession *ss)
272 {
273         if (unode->applied) {
274                 BM_log_undo(ss->bm, ss->bm_log);
275                 unode->applied = FALSE;
276         }
277         else {
278                 BM_log_redo(ss->bm, ss->bm_log);
279                 unode->applied = TRUE;
280         }
281
282         /* A bit lame, but for now just recreate the PBVH. The alternative
283          * is to store changes to the PBVH in the undo stack. */
284         sculpt_pbvh_clear(ob);
285 }
286
287 /* Create empty sculpt BMesh and enable logging */
288 static void sculpt_undo_bmesh_enable(Object *ob,
289                                      SculptUndoNode *unode)
290 {
291         SculptSession *ss = ob->sculpt;
292         Mesh *me = ob->data;
293
294         sculpt_pbvh_clear(ob);
295
296         /* Create empty BMesh and enable logging */
297         ss->bm = BM_mesh_create(&bm_mesh_allocsize_default);
298         BM_data_layer_add(ss->bm, &ss->bm->vdata, CD_PAINT_MASK);
299         me->flag |= ME_SCULPT_DYNAMIC_TOPOLOGY;
300
301         /* Restore the BMLog using saved entries */
302         ss->bm_log = BM_log_from_existing_entries_create(ss->bm,
303                                                          unode->bm_entry);
304 }
305
306 static void sculpt_undo_bmesh_restore_begin(bContext *C,
307                                             SculptUndoNode *unode,
308                                             Object *ob,
309                                             SculptSession *ss)
310 {
311         if (unode->applied) {
312                 sculpt_dynamic_topology_disable(C, unode);
313                 unode->applied = FALSE;
314         }
315         else {
316                 sculpt_undo_bmesh_enable(ob, unode);
317
318                 /* Restore the mesh from the first log entry */
319                 BM_log_redo(ss->bm, ss->bm_log);
320
321                 unode->applied = TRUE;
322         }
323 }
324
325 static void sculpt_undo_bmesh_restore_end(bContext *C,
326                                           SculptUndoNode *unode,
327                                           Object *ob,
328                                           SculptSession *ss)
329 {
330         if (unode->applied) {
331                 sculpt_undo_bmesh_enable(ob, unode);
332
333                 /* Restore the mesh from the last log entry */
334                 BM_log_undo(ss->bm, ss->bm_log);
335
336                 unode->applied = FALSE;
337         }
338         else {
339                 /* Disable dynamic topology sculpting */
340                 sculpt_dynamic_topology_disable(C, NULL);
341                 unode->applied = TRUE;
342         }
343 }
344
345 /* Handle all dynamic-topology updates
346  *
347  * Returns TRUE if this was a dynamic-topology undo step, otherwise
348  * returns FALSE to indicate the non-dyntopo code should run. */
349 static int sculpt_undo_bmesh_restore(bContext *C,
350                                      SculptUndoNode *unode,
351                                      Object *ob,
352                                      SculptSession *ss)
353 {
354         switch (unode->type) {
355                 case SCULPT_UNDO_DYNTOPO_BEGIN:
356                         sculpt_undo_bmesh_restore_begin(C, unode, ob, ss);
357                         return TRUE;
358
359                 case SCULPT_UNDO_DYNTOPO_END:
360                         sculpt_undo_bmesh_restore_end(C, unode, ob, ss);
361                         return TRUE;
362
363                 default:
364                         if (ss->bm_log) {
365                                 sculpt_undo_bmesh_restore_generic(unode, ob, ss);
366                                 return TRUE;
367                         }
368                         break;
369         }
370
371         return FALSE;
372 }
373
374 static void sculpt_undo_restore(bContext *C, ListBase *lb)
375 {
376         Scene *scene = CTX_data_scene(C);
377         Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
378         Object *ob = CTX_data_active_object(C);
379         DerivedMesh *dm;
380         SculptSession *ss = ob->sculpt;
381         SculptUndoNode *unode;
382         int update = FALSE, rebuild = FALSE;
383         int need_mask = FALSE;
384
385         for (unode = lb->first; unode; unode = unode->next) {
386                 if (strcmp(unode->idname, ob->id.name) == 0) {
387                         if (unode->type == SCULPT_UNDO_MASK) {
388                                 /* is possible that we can't do the mask undo (below)
389                                  * because of the vertex count */
390                                 need_mask = TRUE;
391                                 break;
392                         }
393                 }
394         }
395
396         sculpt_update_mesh_elements(scene, sd, ob, 0, need_mask);
397
398         /* call _after_ sculpt_update_mesh_elements() which may update 'ob->derivedFinal' */
399         dm = mesh_get_derived_final(scene, ob, 0);
400
401         if (lb->first && sculpt_undo_bmesh_restore(C, lb->first, ob, ss))
402                 return;
403
404         for (unode = lb->first; unode; unode = unode->next) {
405                 if (!(strcmp(unode->idname, ob->id.name) == 0))
406                         continue;
407
408                 /* check if undo data matches current data well enough to
409                  * continue */
410                 if (unode->maxvert) {
411                         if (ss->totvert != unode->maxvert)
412                                 continue;
413                 }
414                 else if (unode->maxgrid && dm->getGridData) {
415                         if ((dm->getNumGrids(dm) != unode->maxgrid) ||
416                             (dm->getGridSize(dm) != unode->gridsize))
417                         {
418                                 continue;
419                         }
420                 }
421
422                 switch (unode->type) {
423                         case SCULPT_UNDO_COORDS:
424                                 if (sculpt_undo_restore_coords(C, dm, unode))
425                                         update = TRUE;
426                                 break;
427                         case SCULPT_UNDO_HIDDEN:
428                                 if (sculpt_undo_restore_hidden(C, dm, unode))
429                                         rebuild = TRUE;
430                                 break;
431                         case SCULPT_UNDO_MASK:
432                                 if (sculpt_undo_restore_mask(C, dm, unode))
433                                         update = TRUE;
434                                 break;
435
436                         case SCULPT_UNDO_DYNTOPO_BEGIN:
437                         case SCULPT_UNDO_DYNTOPO_END:
438                         case SCULPT_UNDO_DYNTOPO_SYMMETRIZE:
439                                 BLI_assert(!"Dynamic topology should've already been handled");
440                                 break;
441                 }
442         }
443
444         if (update || rebuild) {
445                 int tag_update = 0;
446                 /* we update all nodes still, should be more clever, but also
447                  * needs to work correct when exiting/entering sculpt mode and
448                  * the nodes get recreated, though in that case it could do all */
449                 BKE_pbvh_search_callback(ss->pbvh, NULL, NULL, update_cb, &rebuild);
450                 BKE_pbvh_update(ss->pbvh, PBVH_UpdateBB | PBVH_UpdateOriginalBB | PBVH_UpdateRedraw, NULL);
451
452                 if (sculpt_multires_active(scene, ob)) {
453                         if (rebuild)
454                                 multires_mark_as_modified(ob, MULTIRES_HIDDEN_MODIFIED);
455                         else
456                                 multires_mark_as_modified(ob, MULTIRES_COORDS_MODIFIED);
457                 }
458
459                 tag_update = ((Mesh *)ob->data)->id.us > 1;
460
461                 if (ss->modifiers_active) {
462                         Mesh *mesh = ob->data;
463                         BKE_mesh_calc_normals_tessface(mesh->mvert, mesh->totvert,
464                                                        mesh->mface, mesh->totface, NULL);
465
466                         free_sculptsession_deformMats(ss);
467                         tag_update |= 1;
468                 }
469
470                 if (tag_update)
471                         DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
472
473                 /* for non-PBVH drawing, need to recreate VBOs */
474                 GPU_drawobject_free(ob->derivedFinal);
475         }
476 }
477
478 static void sculpt_undo_free(ListBase *lb)
479 {
480         SculptUndoNode *unode;
481         int i;
482
483         for (unode = lb->first; unode; unode = unode->next) {
484                 if (unode->co)
485                         MEM_freeN(unode->co);
486                 if (unode->no)
487                         MEM_freeN(unode->no);
488                 if (unode->index)
489                         MEM_freeN(unode->index);
490                 if (unode->grids)
491                         MEM_freeN(unode->grids);
492                 if (unode->orig_co)
493                         MEM_freeN(unode->orig_co);
494                 if (unode->vert_hidden)
495                         MEM_freeN(unode->vert_hidden);
496                 if (unode->grid_hidden) {
497                         for (i = 0; i < unode->totgrid; i++) {
498                                 if (unode->grid_hidden[i])
499                                         MEM_freeN(unode->grid_hidden[i]);
500                         }
501                         MEM_freeN(unode->grid_hidden);
502                 }
503                 if (unode->mask)
504                         MEM_freeN(unode->mask);
505                 if (unode->bm_entry) {
506                         BM_log_entry_drop(unode->bm_entry);
507                 }
508                 if (unode->bm_enter_totvert)
509                         CustomData_free(&unode->bm_enter_vdata, unode->bm_enter_totvert);
510                 if (unode->bm_enter_totedge)
511                         CustomData_free(&unode->bm_enter_edata, unode->bm_enter_totedge);
512                 if (unode->bm_enter_totloop)
513                         CustomData_free(&unode->bm_enter_ldata, unode->bm_enter_totloop);
514                 if (unode->bm_enter_totpoly)
515                         CustomData_free(&unode->bm_enter_pdata, unode->bm_enter_totpoly);
516         }
517 }
518
519 SculptUndoNode *sculpt_undo_get_node(PBVHNode *node)
520 {
521         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_MESH);
522
523         if (!lb) {
524                 return NULL;
525         }
526
527         return BLI_findptr(lb, node, offsetof(SculptUndoNode, node));
528 }
529
530 static void sculpt_undo_alloc_and_store_hidden(PBVH *pbvh,
531                                                SculptUndoNode *unode)
532 {
533         PBVHNode *node = unode->node;
534         BLI_bitmap *grid_hidden;
535         int i, *grid_indices, totgrid;
536
537         grid_hidden = BKE_pbvh_grid_hidden(pbvh);
538
539         BKE_pbvh_node_get_grids(pbvh, node, &grid_indices, &totgrid,
540                                 NULL, NULL, NULL, NULL);
541                         
542         unode->grid_hidden = MEM_mapallocN(sizeof(BLI_bitmap) * totgrid,
543                                            "unode->grid_hidden");
544                 
545         for (i = 0; i < totgrid; i++) {
546                 if (grid_hidden[grid_indices[i]])
547                         unode->grid_hidden[i] = MEM_dupallocN(grid_hidden[grid_indices[i]]);
548                 else
549                         unode->grid_hidden[i] = NULL;
550         }
551 }
552
553 static SculptUndoNode *sculpt_undo_alloc_node(Object *ob, PBVHNode *node,
554                                               SculptUndoType type)
555 {
556         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_MESH);
557         SculptUndoNode *unode;
558         SculptSession *ss = ob->sculpt;
559         int totvert, allvert, totgrid, maxgrid, gridsize, *grids;
560         
561         unode = MEM_callocN(sizeof(SculptUndoNode), "SculptUndoNode");
562         BLI_strncpy(unode->idname, ob->id.name, sizeof(unode->idname));
563         unode->type = type;
564         unode->node = node;
565
566         if (node) {
567                 BKE_pbvh_node_num_verts(ss->pbvh, node, &totvert, &allvert);
568                 BKE_pbvh_node_get_grids(ss->pbvh, node, &grids, &totgrid,
569                                         &maxgrid, &gridsize, NULL, NULL);
570
571                 unode->totvert = totvert;
572         }
573         else
574                 maxgrid = 0;
575         
576         /* we will use this while sculpting, is mapalloc slow to access then? */
577
578         /* general TODO, fix count_alloc */
579         switch (type) {
580                 case SCULPT_UNDO_COORDS:
581                         unode->co = MEM_mapallocN(sizeof(float) * 3 * allvert, "SculptUndoNode.co");
582                         unode->no = MEM_mapallocN(sizeof(short) * 3 * allvert, "SculptUndoNode.no");
583                         undo_paint_push_count_alloc(UNDO_PAINT_MESH,
584                                                     (sizeof(float) * 3 +
585                                                      sizeof(short) * 3 +
586                                                      sizeof(int)) * allvert);
587                         break;
588                 case SCULPT_UNDO_HIDDEN:
589                         if (maxgrid)
590                                 sculpt_undo_alloc_and_store_hidden(ss->pbvh, unode);
591                         else
592                                 unode->vert_hidden = BLI_BITMAP_NEW(allvert, "SculptUndoNode.vert_hidden");
593                 
594                         break;
595                 case SCULPT_UNDO_MASK:
596                         unode->mask = MEM_mapallocN(sizeof(float) * allvert, "SculptUndoNode.mask");
597                         undo_paint_push_count_alloc(UNDO_PAINT_MESH, (sizeof(float) * sizeof(int)) * allvert);
598                         break;
599                 case SCULPT_UNDO_DYNTOPO_BEGIN:
600                 case SCULPT_UNDO_DYNTOPO_END:
601                 case SCULPT_UNDO_DYNTOPO_SYMMETRIZE:
602                         BLI_assert(!"Dynamic topology should've already been handled");
603                         break;
604         }
605         
606         BLI_addtail(lb, unode);
607
608         if (maxgrid) {
609                 /* multires */
610                 unode->maxgrid = maxgrid;
611                 unode->totgrid = totgrid;
612                 unode->gridsize = gridsize;
613                 unode->grids = MEM_mapallocN(sizeof(int) * totgrid, "SculptUndoNode.grids");
614         }
615         else {
616                 /* regular mesh */
617                 unode->maxvert = ss->totvert;
618                 unode->index = MEM_mapallocN(sizeof(int) * allvert, "SculptUndoNode.index");
619         }
620
621         if (ss->modifiers_active)
622                 unode->orig_co = MEM_callocN(allvert * sizeof(*unode->orig_co), "undoSculpt orig_cos");
623
624         return unode;
625 }
626
627 static void sculpt_undo_store_coords(Object *ob, SculptUndoNode *unode)
628 {
629         SculptSession *ss = ob->sculpt;
630         PBVHVertexIter vd;
631
632         BKE_pbvh_vertex_iter_begin(ss->pbvh, unode->node, vd, PBVH_ITER_ALL)
633         {
634                 copy_v3_v3(unode->co[vd.i], vd.co);
635                 if (vd.no) copy_v3_v3_short(unode->no[vd.i], vd.no);
636                 else normal_float_to_short_v3(unode->no[vd.i], vd.fno);
637
638                 if (ss->modifiers_active)
639                         copy_v3_v3(unode->orig_co[vd.i], ss->orig_cos[unode->index[vd.i]]);
640         }
641         BKE_pbvh_vertex_iter_end;
642 }
643
644 static void sculpt_undo_store_hidden(Object *ob, SculptUndoNode *unode)
645 {
646         PBVH *pbvh = ob->sculpt->pbvh;
647         PBVHNode *node = unode->node;
648
649         if (unode->grids) {
650                 /* already stored during allocation */
651         }
652         else {
653                 MVert *mvert;
654                 int *vert_indices, allvert;
655                 int i;
656                 
657                 BKE_pbvh_node_num_verts(pbvh, node, NULL, &allvert);
658                 BKE_pbvh_node_get_verts(pbvh, node, &vert_indices, &mvert);
659                 for (i = 0; i < allvert; i++) {
660                         BLI_BITMAP_MODIFY(unode->vert_hidden, i,
661                                           mvert[vert_indices[i]].flag & ME_HIDE);
662                 }
663         }
664 }
665
666 static void sculpt_undo_store_mask(Object *ob, SculptUndoNode *unode)
667 {
668         SculptSession *ss = ob->sculpt;
669         PBVHVertexIter vd;
670
671         BKE_pbvh_vertex_iter_begin(ss->pbvh, unode->node, vd, PBVH_ITER_ALL)
672         {
673                 unode->mask[vd.i] = *vd.mask;
674         }
675         BKE_pbvh_vertex_iter_end;
676 }
677
678 static SculptUndoNode *sculpt_undo_bmesh_push(Object *ob,
679                                               PBVHNode *node,
680                                               SculptUndoType type)
681 {
682         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_MESH);
683         SculptUndoNode *unode = lb->first;
684         SculptSession *ss = ob->sculpt;
685         PBVHVertexIter vd;
686
687         if (!lb->first) {
688                 unode = MEM_callocN(sizeof(*unode), AT);
689
690                 BLI_strncpy(unode->idname, ob->id.name, sizeof(unode->idname));
691                 unode->type = type;
692                 unode->applied = TRUE;
693
694                 if (type == SCULPT_UNDO_DYNTOPO_END) {
695                         unode->bm_entry = BM_log_entry_add(ss->bm_log);
696                         BM_log_before_all_removed(ss->bm, ss->bm_log);
697                 }
698                 else if (type == SCULPT_UNDO_DYNTOPO_BEGIN) {
699                         Mesh *me = ob->data;
700
701                         /* Store a copy of the mesh's current vertices, loops, and
702                          * polys. A full copy like this is needed because entering
703                          * dynamic-topology immediately does topological edits
704                          * (converting polys to triangles) that the BMLog can't
705                          * fully restore from */
706                         CustomData_copy(&me->vdata, &unode->bm_enter_vdata, CD_MASK_MESH,
707                                         CD_DUPLICATE, me->totvert);
708                         CustomData_copy(&me->edata, &unode->bm_enter_edata, CD_MASK_MESH,
709                                         CD_DUPLICATE, me->totedge);
710                         CustomData_copy(&me->ldata, &unode->bm_enter_ldata, CD_MASK_MESH,
711                                         CD_DUPLICATE, me->totloop);
712                         CustomData_copy(&me->pdata, &unode->bm_enter_pdata, CD_MASK_MESH,
713                                         CD_DUPLICATE, me->totpoly);
714                         unode->bm_enter_totvert = me->totvert;
715                         unode->bm_enter_totedge = me->totedge;
716                         unode->bm_enter_totloop = me->totloop;
717                         unode->bm_enter_totpoly = me->totpoly;
718
719                         unode->bm_entry = BM_log_entry_add(ss->bm_log);
720                         BM_log_all_added(ss->bm, ss->bm_log);
721                 }
722                 else {
723                         unode->bm_entry = BM_log_entry_add(ss->bm_log);
724                 }
725
726                 BLI_addtail(lb, unode);
727         }
728
729         if (node) {
730                 switch (type) {
731                         case SCULPT_UNDO_COORDS:
732                         case SCULPT_UNDO_HIDDEN:
733                         case SCULPT_UNDO_MASK:
734                                 /* Before any vertex values get modified, ensure their
735                                  * original positions are logged */
736                                 BKE_pbvh_vertex_iter_begin(ss->pbvh, node, vd, PBVH_ITER_ALL) {
737                                         BM_log_vert_before_modified(ss->bm, ss->bm_log, vd.bm_vert);
738                                 }
739                                 BKE_pbvh_vertex_iter_end;
740                                 break;
741
742                         case SCULPT_UNDO_DYNTOPO_BEGIN:
743                         case SCULPT_UNDO_DYNTOPO_END:
744                         case SCULPT_UNDO_DYNTOPO_SYMMETRIZE:
745                                 break;
746                 }
747         }
748
749         return unode;
750 }
751
752 SculptUndoNode *sculpt_undo_push_node(Object *ob, PBVHNode *node,
753                                       SculptUndoType type)
754 {
755         SculptSession *ss = ob->sculpt;
756         SculptUndoNode *unode;
757
758         /* list is manipulated by multiple threads, so we lock */
759         BLI_lock_thread(LOCK_CUSTOM1);
760
761         if (ss->bm ||
762             ELEM(type,
763                  SCULPT_UNDO_DYNTOPO_BEGIN,
764                  SCULPT_UNDO_DYNTOPO_END))
765         {
766                 /* Dynamic topology stores only one undo node per stroke,
767                  * regardless of the number of PBVH nodes modified */
768                 unode = sculpt_undo_bmesh_push(ob, node, type);
769                 BLI_unlock_thread(LOCK_CUSTOM1);
770                 return unode;
771         }
772         else if ((unode = sculpt_undo_get_node(node))) {
773                 BLI_unlock_thread(LOCK_CUSTOM1);
774                 return unode;
775         }
776
777         unode = sculpt_undo_alloc_node(ob, node, type);
778         
779         BLI_unlock_thread(LOCK_CUSTOM1);
780
781         /* copy threaded, hopefully this is the performance critical part */
782
783         if (unode->grids) {
784                 int totgrid, *grids;
785                 BKE_pbvh_node_get_grids(ss->pbvh, node, &grids, &totgrid,
786                                         NULL, NULL, NULL, NULL);
787                 memcpy(unode->grids, grids, sizeof(int) * totgrid);
788         }
789         else {
790                 int *vert_indices, allvert;
791                 BKE_pbvh_node_num_verts(ss->pbvh, node, NULL, &allvert);
792                 BKE_pbvh_node_get_verts(ss->pbvh, node, &vert_indices, NULL);
793                 memcpy(unode->index, vert_indices, sizeof(int) * unode->totvert);
794         }
795
796         switch (type) {
797                 case SCULPT_UNDO_COORDS:
798                         sculpt_undo_store_coords(ob, unode);
799                         break;
800                 case SCULPT_UNDO_HIDDEN:
801                         sculpt_undo_store_hidden(ob, unode);
802                         break;
803                 case SCULPT_UNDO_MASK:
804                         sculpt_undo_store_mask(ob, unode);
805                         break;
806                 case SCULPT_UNDO_DYNTOPO_BEGIN:
807                 case SCULPT_UNDO_DYNTOPO_END:
808                 case SCULPT_UNDO_DYNTOPO_SYMMETRIZE:
809                         BLI_assert(!"Dynamic topology should've already been handled");
810                         break;
811         }
812
813         /* store active shape key */
814         if (ss->kb) BLI_strncpy(unode->shapeName, ss->kb->name, sizeof(ss->kb->name));
815         else unode->shapeName[0] = '\0';
816
817         return unode;
818 }
819
820 void sculpt_undo_push_begin(const char *name)
821 {
822         undo_paint_push_begin(UNDO_PAINT_MESH, name,
823                               sculpt_undo_restore, sculpt_undo_free);
824 }
825
826 void sculpt_undo_push_end(void)
827 {
828         ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_MESH);
829         SculptUndoNode *unode;
830
831         /* we don't need normals in the undo stack */
832         for (unode = lb->first; unode; unode = unode->next) {
833                 if (unode->no) {
834                         MEM_freeN(unode->no);
835                         unode->no = NULL;
836                 }
837
838                 if (unode->node)
839                         BKE_pbvh_node_layer_disp_free(unode->node);
840         }
841
842         undo_paint_push_end(UNDO_PAINT_MESH);
843 }