Merge branch 'master' into blender2.8
[blender.git] / source / blender / editors / mesh / editmesh_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  * ***** END GPL LICENSE BLOCK *****
19  */
20
21 /** \file blender/editors/mesh/editmesh_undo.c
22  *  \ingroup edmesh
23  */
24
25 #include "MEM_guardedalloc.h"
26
27 #include "CLG_log.h"
28
29 #include "DNA_mesh_types.h"
30 #include "DNA_object_types.h"
31 #include "DNA_key_types.h"
32 #include "DNA_layer_types.h"
33
34 #include "BLI_listbase.h"
35 #include "BLI_array_utils.h"
36 #include "BLI_alloca.h"
37
38 #include "BKE_DerivedMesh.h"
39 #include "BKE_context.h"
40 #include "BKE_key.h"
41 #include "BKE_layer.h"
42 #include "BKE_mesh.h"
43 #include "BKE_editmesh.h"
44 #include "BKE_undo_system.h"
45
46 #include "DEG_depsgraph.h"
47
48 #include "ED_object.h"
49 #include "ED_mesh.h"
50 #include "ED_util.h"
51 #include "ED_undo.h"
52
53 #include "WM_types.h"
54 #include "WM_api.h"
55
56 #define USE_ARRAY_STORE
57
58 #ifdef USE_ARRAY_STORE
59 // #  define DEBUG_PRINT
60 // #  define DEBUG_TIME
61 #  ifdef DEBUG_TIME
62 #    include "PIL_time_utildefines.h"
63 #  endif
64
65 #  include "BLI_array_store.h"
66 #  include "BLI_array_store_utils.h"
67    /* check on best size later... */
68 #  define ARRAY_CHUNK_SIZE 256
69
70 #  define USE_ARRAY_STORE_THREAD
71 #endif
72
73 #ifdef USE_ARRAY_STORE_THREAD
74 #  include "BLI_task.h"
75 #endif
76
77 /** We only need this locally. */
78 static CLG_LogRef LOG = {"ed.undo.mesh"};
79
80 /* -------------------------------------------------------------------- */
81 /** \name Undo Conversion
82  * \{ */
83
84 #ifdef USE_ARRAY_STORE
85
86 /* Single linked list of layers stored per type */
87 typedef struct BArrayCustomData {
88         struct BArrayCustomData *next;
89         CustomDataType type;
90         int states_len;  /* number of layers for each type */
91         BArrayState *states[0];
92 } BArrayCustomData;
93
94 #endif
95
96 typedef struct UndoMesh {
97         Mesh me;
98         int selectmode;
99
100         /** \note
101          * this isn't a prefect solution, if you edit keys and change shapes this works well (fixing [#32442]),
102          * but editing shape keys, going into object mode, removing or changing their order,
103          * then go back into editmode and undo will give issues - where the old index will be out of sync
104          * with the new object index.
105          *
106          * There are a few ways this could be made to work but for now its a known limitation with mixing
107          * object and editmode operations - Campbell */
108         int shapenr;
109
110 #ifdef USE_ARRAY_STORE
111         /* NULL arrays are considered empty */
112         struct { /* most data is stored as 'custom' data */
113                 BArrayCustomData *vdata, *edata, *ldata, *pdata;
114                 BArrayState **keyblocks;
115                 BArrayState *mselect;
116         } store;
117 #endif  /* USE_ARRAY_STORE */
118
119         size_t undo_size;
120 } UndoMesh;
121
122
123 #ifdef USE_ARRAY_STORE
124
125 /** \name Array Store
126  * \{ */
127
128 static struct {
129         struct BArrayStore_AtSize bs_stride;
130         int users;
131
132         /* We could have the undo API pass in the previous state, for now store a local list */
133         ListBase local_links;
134
135 #ifdef USE_ARRAY_STORE_THREAD
136                 TaskPool *task_pool;
137 #endif
138
139 } um_arraystore = {{NULL}};
140
141 static void um_arraystore_cd_compact(
142         struct CustomData *cdata, const size_t data_len,
143         bool create,
144         const BArrayCustomData *bcd_reference,
145         BArrayCustomData **r_bcd_first)
146 {
147         if (data_len == 0) {
148                 if (create) {
149                         *r_bcd_first = NULL;
150                 }
151         }
152
153         const BArrayCustomData *bcd_reference_current = bcd_reference;
154         BArrayCustomData *bcd = NULL, *bcd_first = NULL, *bcd_prev = NULL;
155         for (int layer_start = 0, layer_end; layer_start < cdata->totlayer; layer_start = layer_end) {
156                 const CustomDataType type = cdata->layers[layer_start].type;
157
158                 layer_end = layer_start + 1;
159                 while ((layer_end < cdata->totlayer) &&
160                        (type == cdata->layers[layer_end].type))
161                 {
162                         layer_end++;
163                 }
164
165                 const int stride = CustomData_sizeof(type);
166                 BArrayStore *bs = create ? BLI_array_store_at_size_ensure(&um_arraystore.bs_stride, stride, ARRAY_CHUNK_SIZE) : NULL;
167                 const int layer_len = layer_end - layer_start;
168
169                 if (create) {
170                         if (bcd_reference_current && (bcd_reference_current->type == type)) {
171                                 /* common case, the reference is aligned */
172                         }
173                         else {
174                                 bcd_reference_current = NULL;
175
176                                 /* do a full lookup when un-alligned */
177                                 if (bcd_reference) {
178                                         const BArrayCustomData *bcd_iter = bcd_reference;
179                                         while (bcd_iter) {
180                                                 if (bcd_iter->type == type) {
181                                                         bcd_reference_current = bcd_iter;
182                                                         break;
183                                                 }
184                                                 bcd_iter = bcd_iter->next;
185                                         }
186                                 }
187                         }
188                 }
189
190                 if (create) {
191                         bcd = MEM_callocN(sizeof(BArrayCustomData) + (layer_len * sizeof(BArrayState *)), __func__);
192                         bcd->next = NULL;
193                         bcd->type = type;
194                         bcd->states_len = layer_end - layer_start;
195
196                         if (bcd_prev) {
197                                 bcd_prev->next = bcd;
198                                 bcd_prev = bcd;
199                         }
200                         else {
201                                 bcd_first = bcd;
202                                 bcd_prev  = bcd;
203                         }
204                 }
205
206                 CustomDataLayer *layer = &cdata->layers[layer_start];
207                 for (int i = 0; i < layer_len; i++, layer++) {
208                         if (create) {
209                                 if (layer->data) {
210                                         BArrayState *state_reference =
211                                                 (bcd_reference_current && i < bcd_reference_current->states_len) ?
212                                                  bcd_reference_current->states[i] : NULL;
213                                         bcd->states[i] = BLI_array_store_state_add(
214                                                 bs, layer->data, (size_t)data_len * stride, state_reference);
215                                 }
216                                 else {
217                                         bcd->states[i] = NULL;
218                                 }
219                         }
220
221                         if (layer->data) {
222                                 MEM_freeN(layer->data);
223                                 layer->data = NULL;
224                         }
225                 }
226
227                 if (create) {
228                         if (bcd_reference_current) {
229                                 bcd_reference_current = bcd_reference_current->next;
230                         }
231                 }
232         }
233
234         if (create) {
235                 *r_bcd_first = bcd_first;
236         }
237 }
238
239 /**
240  * \note There is no room for data going out of sync here.
241  * The layers and the states are stored together so this can be kept working.
242  */
243 static void um_arraystore_cd_expand(
244         const BArrayCustomData *bcd, struct CustomData *cdata, const size_t data_len)
245 {
246         CustomDataLayer *layer = cdata->layers;
247         while (bcd) {
248                 const int stride = CustomData_sizeof(bcd->type);
249                 for (int i = 0; i < bcd->states_len; i++) {
250                         BLI_assert(bcd->type == layer->type);
251                         if (bcd->states[i]) {
252                                 size_t state_len;
253                                 layer->data = BLI_array_store_state_data_get_alloc(bcd->states[i], &state_len);
254                                 BLI_assert(stride * data_len == state_len);
255                                 UNUSED_VARS_NDEBUG(stride, data_len);
256                         }
257                         else {
258                                 layer->data = NULL;
259                         }
260                         layer++;
261                 }
262                 bcd = bcd->next;
263         }
264 }
265
266 static void um_arraystore_cd_free(BArrayCustomData *bcd)
267 {
268         while (bcd) {
269                 BArrayCustomData *bcd_next = bcd->next;
270                 const int stride = CustomData_sizeof(bcd->type);
271                 BArrayStore *bs = BLI_array_store_at_size_get(&um_arraystore.bs_stride, stride);
272                 for (int i = 0; i < bcd->states_len; i++) {
273                         if (bcd->states[i]) {
274                                 BLI_array_store_state_remove(bs, bcd->states[i]);
275                         }
276                 }
277                 MEM_freeN(bcd);
278                 bcd = bcd_next;
279         }
280 }
281
282 /**
283  * \param create: When false, only free the arrays.
284  * This is done since when reading from an undo state, they must be temporarily expanded.
285  * then discarded afterwards, having this argument avoids having 2x code paths.
286  */
287 static void um_arraystore_compact_ex(
288         UndoMesh *um, const UndoMesh *um_ref,
289         bool create)
290 {
291         Mesh *me = &um->me;
292
293         um_arraystore_cd_compact(&me->vdata, me->totvert, create, um_ref ? um_ref->store.vdata : NULL, &um->store.vdata);
294         um_arraystore_cd_compact(&me->edata, me->totedge, create, um_ref ? um_ref->store.edata : NULL, &um->store.edata);
295         um_arraystore_cd_compact(&me->ldata, me->totloop, create, um_ref ? um_ref->store.ldata : NULL, &um->store.ldata);
296         um_arraystore_cd_compact(&me->pdata, me->totpoly, create, um_ref ? um_ref->store.pdata : NULL, &um->store.pdata);
297
298         if (me->key && me->key->totkey) {
299                 const size_t stride = me->key->elemsize;
300                 BArrayStore *bs = create ? BLI_array_store_at_size_ensure(&um_arraystore.bs_stride, stride, ARRAY_CHUNK_SIZE) : NULL;
301                 if (create) {
302                         um->store.keyblocks = MEM_mallocN(me->key->totkey * sizeof(*um->store.keyblocks), __func__);
303                 }
304                 KeyBlock *keyblock = me->key->block.first;
305                 for (int i = 0; i < me->key->totkey; i++, keyblock = keyblock->next) {
306                         if (create) {
307                                 BArrayState *state_reference =
308                                         (um_ref && um_ref->me.key && (i < um_ref->me.key->totkey)) ?
309                                          um_ref->store.keyblocks[i] : NULL;
310                                 um->store.keyblocks[i] = BLI_array_store_state_add(
311                                         bs, keyblock->data, (size_t)keyblock->totelem * stride,
312                                         state_reference);
313                         }
314
315                         if (keyblock->data) {
316                                 MEM_freeN(keyblock->data);
317                                 keyblock->data = NULL;
318                         }
319                 }
320         }
321
322         if (me->mselect && me->totselect) {
323                 BLI_assert(create == (um->store.mselect == NULL));
324                 if (create) {
325                         BArrayState *state_reference = um_ref ? um_ref->store.mselect : NULL;
326                         const size_t stride = sizeof(*me->mselect);
327                         BArrayStore *bs = BLI_array_store_at_size_ensure(&um_arraystore.bs_stride, stride, ARRAY_CHUNK_SIZE);
328                         um->store.mselect = BLI_array_store_state_add(
329                                 bs, me->mselect, (size_t)me->totselect * stride, state_reference);
330                 }
331
332                 /* keep me->totselect for validation */
333                 MEM_freeN(me->mselect);
334                 me->mselect = NULL;
335         }
336
337         if (create) {
338                 um_arraystore.users += 1;
339         }
340
341         BKE_mesh_update_customdata_pointers(me, false);
342 }
343
344 /**
345  * Move data from allocated arrays to de-duplicated states and clear arrays.
346  */
347 static void um_arraystore_compact(UndoMesh *um, const UndoMesh *um_ref)
348 {
349         um_arraystore_compact_ex(um, um_ref, true);
350 }
351
352 static void um_arraystore_compact_with_info(UndoMesh *um, const UndoMesh *um_ref)
353 {
354 #ifdef DEBUG_PRINT
355         size_t size_expanded_prev, size_compacted_prev;
356         BLI_array_store_at_size_calc_memory_usage(&um_arraystore.bs_stride, &size_expanded_prev, &size_compacted_prev);
357 #endif
358
359 #ifdef DEBUG_TIME
360         TIMEIT_START(mesh_undo_compact);
361 #endif
362
363         um_arraystore_compact(um, um_ref);
364
365 #ifdef DEBUG_TIME
366         TIMEIT_END(mesh_undo_compact);
367 #endif
368
369 #ifdef DEBUG_PRINT
370         {
371                 size_t size_expanded, size_compacted;
372                 BLI_array_store_at_size_calc_memory_usage(&um_arraystore.bs_stride, &size_expanded, &size_compacted);
373
374                 const double percent_total = size_expanded ?
375                         (((double)size_compacted / (double)size_expanded) * 100.0) : -1.0;
376
377                 size_t size_expanded_step = size_expanded - size_expanded_prev;
378                 size_t size_compacted_step = size_compacted - size_compacted_prev;
379                 const double percent_step = size_expanded_step ?
380                         (((double)size_compacted_step / (double)size_expanded_step) * 100.0) : -1.0;
381
382                 printf("overall memory use: %.8f%% of expanded size\n", percent_total);
383                 printf("step memory use:    %.8f%% of expanded size\n", percent_step);
384         }
385 #endif
386 }
387
388 #ifdef USE_ARRAY_STORE_THREAD
389
390 struct UMArrayData {
391         UndoMesh *um;
392         const UndoMesh *um_ref;  /* can be NULL */
393 };
394 static void um_arraystore_compact_cb(TaskPool *__restrict UNUSED(pool),
395                                      void *taskdata,
396                                      int UNUSED(threadid))
397 {
398         struct UMArrayData *um_data = taskdata;
399         um_arraystore_compact_with_info(um_data->um, um_data->um_ref);
400 }
401
402 #endif  /* USE_ARRAY_STORE_THREAD */
403
404 /**
405  * Remove data we only expanded for temporary use.
406  */
407 static void um_arraystore_expand_clear(UndoMesh *um)
408 {
409         um_arraystore_compact_ex(um, NULL, false);
410 }
411
412 static void um_arraystore_expand(UndoMesh *um)
413 {
414         Mesh *me = &um->me;
415
416         um_arraystore_cd_expand(um->store.vdata, &me->vdata, me->totvert);
417         um_arraystore_cd_expand(um->store.edata, &me->edata, me->totedge);
418         um_arraystore_cd_expand(um->store.ldata, &me->ldata, me->totloop);
419         um_arraystore_cd_expand(um->store.pdata, &me->pdata, me->totpoly);
420
421         if (um->store.keyblocks) {
422                 const size_t stride = me->key->elemsize;
423                 KeyBlock *keyblock = me->key->block.first;
424                 for (int i = 0; i < me->key->totkey; i++, keyblock = keyblock->next) {
425                         BArrayState *state = um->store.keyblocks[i];
426                         size_t state_len;
427                         keyblock->data = BLI_array_store_state_data_get_alloc(state, &state_len);
428                         BLI_assert(keyblock->totelem == (state_len / stride));
429                         UNUSED_VARS_NDEBUG(stride);
430                 }
431         }
432
433         if (um->store.mselect) {
434                 const size_t stride = sizeof(*me->mselect);
435                 BArrayState *state = um->store.mselect;
436                 size_t state_len;
437                 me->mselect = BLI_array_store_state_data_get_alloc(state, &state_len);
438                 BLI_assert(me->totselect == (state_len / stride));
439                 UNUSED_VARS_NDEBUG(stride);
440         }
441
442         /* not essential, but prevents accidental dangling pointer access */
443         BKE_mesh_update_customdata_pointers(me, false);
444 }
445
446 static void um_arraystore_free(UndoMesh *um)
447 {
448         Mesh *me = &um->me;
449
450         um_arraystore_cd_free(um->store.vdata);
451         um_arraystore_cd_free(um->store.edata);
452         um_arraystore_cd_free(um->store.ldata);
453         um_arraystore_cd_free(um->store.pdata);
454
455         if (um->store.keyblocks) {
456                 const size_t stride = me->key->elemsize;
457                 BArrayStore *bs = BLI_array_store_at_size_get(&um_arraystore.bs_stride, stride);
458                 for (int i = 0; i < me->key->totkey; i++) {
459                         BArrayState *state = um->store.keyblocks[i];
460                         BLI_array_store_state_remove(bs, state);
461                 }
462                 MEM_freeN(um->store.keyblocks);
463                 um->store.keyblocks = NULL;
464         }
465
466         if (um->store.mselect) {
467                 const size_t stride = sizeof(*me->mselect);
468                 BArrayStore *bs = BLI_array_store_at_size_get(&um_arraystore.bs_stride, stride);
469                 BArrayState *state = um->store.mselect;
470                 BLI_array_store_state_remove(bs, state);
471                 um->store.mselect = NULL;
472         }
473
474         um_arraystore.users -= 1;
475
476         BLI_assert(um_arraystore.users >= 0);
477
478         if (um_arraystore.users == 0) {
479 #ifdef DEBUG_PRINT
480                 printf("mesh undo store: freeing all data!\n");
481 #endif
482                 BLI_array_store_at_size_clear(&um_arraystore.bs_stride);
483
484 #ifdef USE_ARRAY_STORE_THREAD
485                 BLI_task_pool_free(um_arraystore.task_pool);
486                 um_arraystore.task_pool = NULL;
487 #endif
488         }
489
490 }
491
492 /** \} */
493
494 #endif  /* USE_ARRAY_STORE */
495
496
497 /* for callbacks */
498 /* undo simply makes copies of a bmesh */
499 static void *undomesh_from_editmesh(UndoMesh *um, BMEditMesh *em, Key *key)
500 {
501         BLI_assert(BLI_array_is_zeroed(um, 1));
502 #ifdef USE_ARRAY_STORE_THREAD
503         /* changes this waits is low, but must have finished */
504         if (um_arraystore.task_pool) {
505                 BLI_task_pool_work_and_wait(um_arraystore.task_pool);
506         }
507 #endif
508         /* make sure shape keys work */
509         um->me.key = key ? BKE_key_copy_nolib(key) : NULL;
510
511         /* BM_mesh_validate(em->bm); */ /* for troubleshooting */
512
513         BM_mesh_bm_to_me(
514                 NULL, em->bm, &um->me, (&(struct BMeshToMeshParams){
515                     /* Undo code should not be manipulating 'G_MAIN->object' hooks/vertex-parent. */
516                     .calc_object_remap = false,
517                     .cd_mask_extra = CD_MASK_SHAPE_KEYINDEX,
518                 }));
519
520         um->selectmode = em->selectmode;
521         um->shapenr = em->bm->shapenr;
522
523 #ifdef USE_ARRAY_STORE
524         {
525                 /* We could be more clever here,
526                  * the previous undo state may be from a separate mesh. */
527                 const UndoMesh *um_ref = um_arraystore.local_links.last ?
528                                          ((LinkData *)um_arraystore.local_links.last)->data : NULL;
529
530                 /* add oursrlves */
531                 BLI_addtail(&um_arraystore.local_links, BLI_genericNodeN(um));
532
533 #ifdef USE_ARRAY_STORE_THREAD
534                 if (um_arraystore.task_pool == NULL) {
535                         TaskScheduler *scheduler = BLI_task_scheduler_get();
536                         um_arraystore.task_pool = BLI_task_pool_create_background(scheduler, NULL);
537                 }
538
539                 struct UMArrayData *um_data = MEM_mallocN(sizeof(*um_data), __func__);
540                 um_data->um = um;
541                 um_data->um_ref = um_ref;
542
543                 BLI_task_pool_push(
544                         um_arraystore.task_pool,
545                         um_arraystore_compact_cb, um_data, true, TASK_PRIORITY_LOW);
546 #else
547                 um_arraystore_compact_with_info(um, um_ref);
548 #endif
549         }
550 #endif
551
552         return um;
553 }
554
555 static void undomesh_to_editmesh(UndoMesh *um, BMEditMesh *em, Mesh *obmesh)
556 {
557         BMEditMesh *em_tmp;
558         Object *ob = em->ob;
559         BMesh *bm;
560         Key *key = obmesh->key;
561
562 #ifdef USE_ARRAY_STORE
563 #ifdef USE_ARRAY_STORE_THREAD
564         /* changes this waits is low, but must have finished */
565         BLI_task_pool_work_and_wait(um_arraystore.task_pool);
566 #endif
567
568 #ifdef DEBUG_TIME
569         TIMEIT_START(mesh_undo_expand);
570 #endif
571
572         um_arraystore_expand(um);
573
574 #ifdef DEBUG_TIME
575         TIMEIT_END(mesh_undo_expand);
576 #endif
577 #endif  /* USE_ARRAY_STORE */
578
579         const BMAllocTemplate allocsize = BMALLOC_TEMPLATE_FROM_ME(&um->me);
580
581         em->bm->shapenr = um->shapenr;
582
583         EDBM_mesh_free(em);
584
585         bm = BM_mesh_create(
586                 &allocsize,
587                 &((struct BMeshCreateParams){.use_toolflags = true,}));
588
589         BM_mesh_bm_from_me(
590                 bm, &um->me, (&(struct BMeshFromMeshParams){
591                     .calc_face_normal = true, .active_shapekey = um->shapenr,
592                 }));
593
594         em_tmp = BKE_editmesh_create(bm, true);
595         *em = *em_tmp;
596
597         em->selectmode = um->selectmode;
598         bm->selectmode = um->selectmode;
599         em->ob = ob;
600
601         /* T35170: Restore the active key on the RealMesh. Otherwise 'fake' offset propagation happens
602          *         if the active is a basis for any other. */
603         if (key && (key->type == KEY_RELATIVE)) {
604                 /* Since we can't add, remove or reorder keyblocks in editmode, it's safe to assume
605                  * shapenr from restored bmesh and keyblock indices are in sync. */
606                 const int kb_act_idx = ob->shapenr - 1;
607
608                 /* If it is, let's patch the current mesh key block to its restored value.
609                  * Else, the offsets won't be computed and it won't matter. */
610                 if (BKE_keyblock_is_basis(key, kb_act_idx)) {
611                         KeyBlock *kb_act = BLI_findlink(&key->block, kb_act_idx);
612
613                         if (kb_act->totelem != um->me.totvert) {
614                                 /* The current mesh has some extra/missing verts compared to the undo, adjust. */
615                                 MEM_SAFE_FREE(kb_act->data);
616                                 kb_act->data = MEM_mallocN((size_t)(key->elemsize * bm->totvert), __func__);
617                                 kb_act->totelem = um->me.totvert;
618                         }
619
620                         BKE_keyblock_update_from_mesh(&um->me, kb_act);
621                 }
622         }
623
624         ob->shapenr = um->shapenr;
625
626         MEM_freeN(em_tmp);
627
628 #ifdef USE_ARRAY_STORE
629         um_arraystore_expand_clear(um);
630 #endif
631 }
632
633 static void undomesh_free_data(UndoMesh *um)
634 {
635         Mesh *me = &um->me;
636
637 #ifdef USE_ARRAY_STORE
638
639 #ifdef USE_ARRAY_STORE_THREAD
640         /* changes this waits is low, but must have finished */
641         BLI_task_pool_work_and_wait(um_arraystore.task_pool);
642 #endif
643
644         /* we need to expand so any allocations in custom-data are freed with the mesh */
645         um_arraystore_expand(um);
646
647         {
648                 LinkData *link = BLI_findptr(&um_arraystore.local_links, um, offsetof(LinkData, data));
649                 BLI_remlink(&um_arraystore.local_links, link);
650                 MEM_freeN(link);
651         }
652         um_arraystore_free(um);
653 #endif
654
655         if (me->key) {
656                 BKE_key_free(me->key);
657                 MEM_freeN(me->key);
658         }
659
660         BKE_mesh_free(me);
661 }
662
663 static Object *editmesh_object_from_context(bContext *C)
664 {
665         Object *obedit = CTX_data_edit_object(C);
666         if (obedit && obedit->type == OB_MESH) {
667                 Mesh *me = obedit->data;
668                 if (me->edit_btmesh != NULL) {
669                         return obedit;
670                 }
671         }
672         return NULL;
673 }
674
675 /** \} */
676
677 /* -------------------------------------------------------------------- */
678 /** \name Implements ED Undo System
679  *
680  * \note This is similar for all edit-mode types.
681  * \{ */
682
683 typedef struct MeshUndoStep_Elem {
684         struct MeshUndoStep_Elem *next, *prev;
685         UndoRefID_Object obedit_ref;
686         UndoMesh data;
687 } MeshUndoStep_Elem;
688
689 typedef struct MeshUndoStep {
690         UndoStep step;
691         struct UndoIDPtrMap *id_map;
692         MeshUndoStep_Elem *elems;
693         uint               elems_len;
694 } MeshUndoStep;
695
696 static bool mesh_undosys_poll(bContext *C)
697 {
698         return editmesh_object_from_context(C) != NULL;
699 }
700
701 static bool mesh_undosys_step_encode(struct bContext *C, UndoStep *us_p)
702 {
703         MeshUndoStep *us = (MeshUndoStep *)us_p;
704
705         ViewLayer *view_layer = CTX_data_view_layer(C);
706         uint objects_len = 0;
707         Object **objects = BKE_view_layer_array_from_objects_in_edit_mode_unique_data(view_layer, &objects_len);
708
709         us->elems = MEM_callocN(sizeof(*us->elems) * objects_len, __func__);
710         us->elems_len = objects_len;
711
712         for (uint i = 0; i < objects_len; i++) {
713                 Object *ob = objects[i];
714                 MeshUndoStep_Elem *elem = &us->elems[i];
715
716                 elem->obedit_ref.ptr = ob;
717                 Mesh *me = elem->obedit_ref.ptr->data;
718                 undomesh_from_editmesh(&elem->data, me->edit_btmesh, me->key);
719                 us->step.data_size += elem->data.undo_size;
720         }
721         MEM_freeN(objects);
722         return true;
723 }
724
725 static void mesh_undosys_step_decode(struct bContext *C, UndoStep *us_p, int UNUSED(dir))
726 {
727         /* TODO(campbell): undo_system: use low-level API to set mode. */
728         ED_object_mode_set(C, OB_MODE_EDIT);
729         BLI_assert(mesh_undosys_poll(C));
730
731         MeshUndoStep *us = (MeshUndoStep *)us_p;
732
733         for (uint i = 0; i < us->elems_len; i++) {
734                 MeshUndoStep_Elem *elem = &us->elems[i];
735                 Object *obedit = elem->obedit_ref.ptr;
736                 Mesh *me = obedit->data;
737                 if (me->edit_btmesh == NULL) {
738                         /* Should never fail, may not crash but can give odd behavior. */
739                         CLOG_ERROR(&LOG, "name='%s', failed to enter edit-mode for object '%s', undo state invalid",
740                                    us_p->name, obedit->id.name);
741                         continue;
742                 }
743                 BMEditMesh *em = me->edit_btmesh;
744                 undomesh_to_editmesh(&elem->data, em, obedit->data);
745                 DEG_id_tag_update(&obedit->id, OB_RECALC_DATA);
746         }
747
748         /* The first element is always active */
749         ED_undo_object_set_active_or_warn(CTX_data_view_layer(C), us->elems[0].obedit_ref.ptr, us_p->name, &LOG);
750
751         WM_event_add_notifier(C, NC_GEOM | ND_DATA, NULL);
752 }
753
754 static void mesh_undosys_step_free(UndoStep *us_p)
755 {
756         MeshUndoStep *us = (MeshUndoStep *)us_p;
757
758         for (uint i = 0; i < us->elems_len; i++) {
759                 MeshUndoStep_Elem *elem = &us->elems[i];
760                 undomesh_free_data(&elem->data);
761         }
762         MEM_freeN(us->elems);
763
764         if (us->id_map != NULL) {
765                 BKE_undosys_ID_map_destroy(us->id_map);
766         }
767 }
768
769 static void mesh_undosys_foreach_ID_ref(
770         UndoStep *us_p, UndoTypeForEachIDRefFn foreach_ID_ref_fn, void *user_data)
771 {
772         MeshUndoStep *us = (MeshUndoStep *)us_p;
773
774         for (uint i = 0; i < us->elems_len; i++) {
775                 MeshUndoStep_Elem *elem = &us->elems[i];
776                 foreach_ID_ref_fn(user_data, ((UndoRefID *)&elem->obedit_ref));
777         }
778
779         if (us->id_map != NULL) {
780                 BKE_undosys_ID_map_foreach_ID_ref(us->id_map, foreach_ID_ref_fn, user_data);
781         }
782 }
783
784 /* Export for ED_undo_sys. */
785 void ED_mesh_undosys_type(UndoType *ut)
786 {
787         ut->name = "Edit Mesh";
788         ut->poll = mesh_undosys_poll;
789         ut->step_encode = mesh_undosys_step_encode;
790         ut->step_decode = mesh_undosys_step_decode;
791         ut->step_free = mesh_undosys_step_free;
792
793         ut->step_foreach_ID_ref = mesh_undosys_foreach_ID_ref;
794
795         ut->mode = BKE_UNDOTYPE_MODE_STORE;
796         ut->use_context = true;
797
798         ut->step_size = sizeof(MeshUndoStep);
799 }
800
801 /** \} */