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