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