Merge branch 'master' into blender2.8
[blender.git] / source / blender / blenloader / intern / writefile.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) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  *
22  * Contributor(s): Blender Foundation
23  *
24  * ***** END GPL LICENSE BLOCK *****
25  */
26
27 /** \file blender/blenloader/intern/writefile.c
28  *  \ingroup blenloader
29  */
30
31
32 /**
33  *
34  * FILE FORMAT
35  * ===========
36  *
37  * IFF-style structure  (but not IFF compatible!)
38  *
39  * start file:
40  * <pre>
41  *     BLENDER_V100    12 bytes  (versie 1.00)
42  *                     V = big endian, v = little endian
43  *                     _ = 4 byte pointer, - = 8 byte pointer
44  * </pre>
45  *
46  * datablocks: (also see struct #BHead).
47  * <pre>
48  *     <bh.code>           4 chars
49  *     <bh.len>            int,  len data after BHead
50  *     <bh.old>            void,  old pointer
51  *     <bh.SDNAnr>         int
52  *     <bh.nr>             int, in case of array: number of structs
53  *     data
54  *     ...
55  *     ...
56  * </pre>
57  *
58  * Almost all data in Blender are structures. Each struct saved
59  * gets a BHead header.  With BHead the struct can be linked again
60  * and compared with StructDNA .
61  *
62  *
63  * WRITE
64  * =====
65  *
66  * Preferred writing order: (not really a must, but why would you do it random?)
67  * Any case: direct data is ALWAYS after the lib block
68  *
69  * (Local file data)
70  * - for each LibBlock
71  *   - write LibBlock
72  *   - write associated direct data
73  * (External file data)
74  * - per library
75  *   - write library block
76  *   - per LibBlock
77  *     - write the ID of LibBlock
78  * - write #TEST (#RenderInfo struct. 128x128 blend file preview is optional).
79  * - write #GLOB (#FileGlobal struct) (some global vars).
80  * - write #DNA1 (#SDNA struct)
81  * - write #USER (#UserDef struct) if filename is ``~/.config/blender/X.XX/config/startup.blend``.
82  */
83
84
85 #include <math.h>
86 #include <fcntl.h>
87 #include <limits.h>
88 #include <stdio.h>
89 #include <string.h>
90 #include <stdlib.h>
91
92 #ifdef WIN32
93 #  include <zlib.h>  /* odd include order-issue */
94 #  include "winsock2.h"
95 #  include <io.h>
96 #  include "BLI_winstuff.h"
97 #else
98 #  include <unistd.h>  /* FreeBSD, for write() and close(). */
99 #endif
100
101 #include "BLI_utildefines.h"
102
103 /* allow writefile to use deprecated functionality (for forward compatibility code) */
104 #define DNA_DEPRECATED_ALLOW
105 /* Allow using DNA struct members that are marked as private for read/write.
106  * Note: Each header that uses this needs to define its own way of handling
107  * it. There's no generic implementation, direct use does nothing. */
108 #define DNA_PRIVATE_READ_WRITE_ALLOW
109
110 #include "DNA_anim_types.h"
111 #include "DNA_armature_types.h"
112 #include "DNA_brush_types.h"
113 #include "DNA_cachefile_types.h"
114 #include "DNA_camera_types.h"
115 #include "DNA_cloth_types.h"
116 #include "DNA_constraint_types.h"
117 #include "DNA_dynamicpaint_types.h"
118 #include "DNA_genfile.h"
119 #include "DNA_group_types.h"
120 #include "DNA_gpencil_types.h"
121 #include "DNA_fileglobal_types.h"
122 #include "DNA_key_types.h"
123 #include "DNA_lattice_types.h"
124 #include "DNA_lamp_types.h"
125 #include "DNA_layer_types.h"
126 #include "DNA_linestyle_types.h"
127 #include "DNA_meta_types.h"
128 #include "DNA_mesh_types.h"
129 #include "DNA_meshdata_types.h"
130 #include "DNA_material_types.h"
131 #include "DNA_node_types.h"
132 #include "DNA_object_types.h"
133 #include "DNA_object_force_types.h"
134 #include "DNA_packedFile_types.h"
135 #include "DNA_particle_types.h"
136 #include "DNA_lightprobe_types.h"
137 #include "DNA_rigidbody_types.h"
138 #include "DNA_scene_types.h"
139 #include "DNA_sdna_types.h"
140 #include "DNA_sequence_types.h"
141 #include "DNA_smoke_types.h"
142 #include "DNA_space_types.h"
143 #include "DNA_screen_types.h"
144 #include "DNA_speaker_types.h"
145 #include "DNA_sound_types.h"
146 #include "DNA_text_types.h"
147 #include "DNA_view3d_types.h"
148 #include "DNA_vfont_types.h"
149 #include "DNA_world_types.h"
150 #include "DNA_windowmanager_types.h"
151 #include "DNA_workspace_types.h"
152 #include "DNA_movieclip_types.h"
153 #include "DNA_mask_types.h"
154
155 #include "MEM_guardedalloc.h" // MEM_freeN
156 #include "BLI_bitmap.h"
157 #include "BLI_blenlib.h"
158 #include "BLI_linklist.h"
159 #include "BLI_mempool.h"
160
161 #include "BKE_action.h"
162 #include "BKE_blender_version.h"
163 #include "BKE_bpath.h"
164 #include "BKE_curve.h"
165 #include "BKE_collection.h"
166 #include "BKE_constraint.h"
167 #include "BKE_global.h" // for G
168 #include "BKE_idcode.h"
169 #include "BKE_layer.h"
170 #include "BKE_library.h" // for  set_listbasepointers
171 #include "BKE_library_override.h"
172 #include "BKE_main.h"
173 #include "BKE_node.h"
174 #include "BKE_report.h"
175 #include "BKE_sequencer.h"
176 #include "BKE_subsurf.h"
177 #include "BKE_modifier.h"
178 #include "BKE_fcurve.h"
179 #include "BKE_pointcache.h"
180 #include "BKE_mesh.h"
181 #include "BKE_workspace.h"
182
183 #ifdef USE_NODE_COMPAT_CUSTOMNODES
184 #include "NOD_socket.h"  /* for sock->default_value data */
185 #endif
186
187
188 #include "BLO_writefile.h"
189 #include "BLO_readfile.h"
190 #include "BLO_runtime.h"
191 #include "BLO_undofile.h"
192 #include "BLO_blend_defs.h"
193
194 #include "readfile.h"
195
196 /* for SDNA_TYPE_FROM_STRUCT() macro */
197 #include "dna_type_offsets.h"
198
199 #include <errno.h>
200
201 /* ********* my write, buffered writing with minimum size chunks ************ */
202
203 /* Use optimal allocation since blocks of this size are kept in memory for undo. */
204 #define MYWRITE_BUFFER_SIZE (MEM_SIZE_OPTIMAL(1 << 17))  /* 128kb */
205 #define MYWRITE_MAX_CHUNK   (MEM_SIZE_OPTIMAL(1 << 15))  /* ~32kb */
206
207 /** Use if we want to store how many bytes have been written to the file. */
208 // #define USE_WRITE_DATA_LEN
209
210 /* -------------------------------------------------------------------- */
211 /** \name Internal Write Wrapper's (Abstracts Compression)
212  * \{ */
213
214 typedef enum {
215         WW_WRAP_NONE = 1,
216         WW_WRAP_ZLIB,
217 } eWriteWrapType;
218
219 typedef struct WriteWrap WriteWrap;
220 struct WriteWrap {
221         /* callbacks */
222         bool   (*open)(WriteWrap *ww, const char *filepath);
223         bool   (*close)(WriteWrap *ww);
224         size_t (*write)(WriteWrap *ww, const char *data, size_t data_len);
225
226         /* internal */
227         union {
228                 int file_handle;
229                 gzFile gz_handle;
230         } _user_data;
231 };
232
233 /* none */
234 #define FILE_HANDLE(ww) \
235         (ww)->_user_data.file_handle
236
237 static bool ww_open_none(WriteWrap *ww, const char *filepath)
238 {
239         int file;
240
241         file = BLI_open(filepath, O_BINARY + O_WRONLY + O_CREAT + O_TRUNC, 0666);
242
243         if (file != -1) {
244                 FILE_HANDLE(ww) = file;
245                 return true;
246         }
247         else {
248                 return false;
249         }
250 }
251 static bool ww_close_none(WriteWrap *ww)
252 {
253         return (close(FILE_HANDLE(ww)) != -1);
254 }
255 static size_t ww_write_none(WriteWrap *ww, const char *buf, size_t buf_len)
256 {
257         return write(FILE_HANDLE(ww), buf, buf_len);
258 }
259 #undef FILE_HANDLE
260
261 /* zlib */
262 #define FILE_HANDLE(ww) \
263         (ww)->_user_data.gz_handle
264
265 static bool ww_open_zlib(WriteWrap *ww, const char *filepath)
266 {
267         gzFile file;
268
269         file = BLI_gzopen(filepath, "wb1");
270
271         if (file != Z_NULL) {
272                 FILE_HANDLE(ww) = file;
273                 return true;
274         }
275         else {
276                 return false;
277         }
278 }
279 static bool ww_close_zlib(WriteWrap *ww)
280 {
281         return (gzclose(FILE_HANDLE(ww)) == Z_OK);
282 }
283 static size_t ww_write_zlib(WriteWrap *ww, const char *buf, size_t buf_len)
284 {
285         return gzwrite(FILE_HANDLE(ww), buf, buf_len);
286 }
287 #undef FILE_HANDLE
288
289 /* --- end compression types --- */
290
291 static void ww_handle_init(eWriteWrapType ww_type, WriteWrap *r_ww)
292 {
293         memset(r_ww, 0, sizeof(*r_ww));
294
295         switch (ww_type) {
296                 case WW_WRAP_ZLIB:
297                 {
298                         r_ww->open  = ww_open_zlib;
299                         r_ww->close = ww_close_zlib;
300                         r_ww->write = ww_write_zlib;
301                         break;
302                 }
303                 default:
304                 {
305                         r_ww->open  = ww_open_none;
306                         r_ww->close = ww_close_none;
307                         r_ww->write = ww_write_none;
308                         break;
309                 }
310         }
311 }
312
313 /** \} */
314
315 /* -------------------------------------------------------------------- */
316 /** \name Write Data Type & Functions
317  * \{ */
318
319 typedef struct {
320         const struct SDNA *sdna;
321
322         /** Use for file and memory writing (fixed size of #MYWRITE_BUFFER_SIZE). */
323         uchar *buf;
324         /** Number of bytes used in #WriteData.buf (flushed when exceeded). */
325         int buf_used_len;
326
327 #ifdef USE_WRITE_DATA_LEN
328         /** Total number of bytes written. */
329         size_t write_len;
330 #endif
331
332         /** Set on unlikely case of an error (ignores further file writing).  */
333         bool error;
334
335         /** #MemFile writing (used for undo). */
336         struct {
337                 MemFile      *current;
338                 MemFile      *compare;
339                 /** Use to de-duplicate chunks when writing. */
340                 MemFileChunk *compare_chunk;
341         } mem;
342         /** When true, write to #WriteData.current, could also call 'is_undo'. */
343         bool use_memfile;
344
345         /**
346          * Wrap writing, so we can use zlib or
347          * other compression types later, see: G_FILE_COMPRESS
348          * Will be NULL for UNDO.
349          */
350         WriteWrap *ww;
351 } WriteData;
352
353 static WriteData *writedata_new(WriteWrap *ww)
354 {
355         WriteData *wd = MEM_callocN(sizeof(*wd), "writedata");
356
357         wd->sdna = DNA_sdna_current_get();
358
359         wd->ww = ww;
360
361         wd->buf = MEM_mallocN(MYWRITE_BUFFER_SIZE, "wd->buf");
362
363         return wd;
364 }
365
366 static void writedata_do_write(WriteData *wd, const void *mem, int memlen)
367 {
368         if ((wd == NULL) || wd->error || (mem == NULL) || memlen < 1) {
369                 return;
370         }
371
372         if (UNLIKELY(wd->error)) {
373                 return;
374         }
375
376         /* memory based save */
377         if (wd->use_memfile) {
378                 memfile_chunk_add(wd->mem.current, mem, memlen, &wd->mem.compare_chunk);
379         }
380         else {
381                 if (wd->ww->write(wd->ww, mem, memlen) != memlen) {
382                         wd->error = true;
383                 }
384         }
385 }
386
387 static void writedata_free(WriteData *wd)
388 {
389         MEM_freeN(wd->buf);
390         MEM_freeN(wd);
391 }
392
393 /** \} */
394
395 /* -------------------------------------------------------------------- */
396 /** \name Local Writing API 'mywrite'
397  * \{ */
398
399 /**
400  * Flush helps the de-duplicating memory for undo-save by logically segmenting data,
401  * so differences in one part of memory won't cause unrelated data to be duplicated.
402  */
403 static void mywrite_flush(WriteData *wd)
404 {
405         if (wd->buf_used_len) {
406                 writedata_do_write(wd, wd->buf, wd->buf_used_len);
407                 wd->buf_used_len = 0;
408         }
409 }
410
411 /**
412  * Low level WRITE(2) wrapper that buffers data
413  * \param adr Pointer to new chunk of data
414  * \param len Length of new chunk of data
415  */
416 static void mywrite(WriteData *wd, const void *adr, int len)
417 {
418         if (UNLIKELY(wd->error)) {
419                 return;
420         }
421
422         if (UNLIKELY(adr == NULL)) {
423                 BLI_assert(0);
424                 return;
425         }
426
427 #ifdef USE_WRITE_DATA_LEN
428         wd->write_len += len;
429 #endif
430
431         /* if we have a single big chunk, write existing data in
432          * buffer and write out big chunk in smaller pieces */
433         if (len > MYWRITE_MAX_CHUNK) {
434                 if (wd->buf_used_len) {
435                         writedata_do_write(wd, wd->buf, wd->buf_used_len);
436                         wd->buf_used_len = 0;
437                 }
438
439                 do {
440                         int writelen = MIN2(len, MYWRITE_MAX_CHUNK);
441                         writedata_do_write(wd, adr, writelen);
442                         adr = (const char *)adr + writelen;
443                         len -= writelen;
444                 } while (len > 0);
445
446                 return;
447         }
448
449         /* if data would overflow buffer, write out the buffer */
450         if (len + wd->buf_used_len > MYWRITE_BUFFER_SIZE - 1) {
451                 writedata_do_write(wd, wd->buf, wd->buf_used_len);
452                 wd->buf_used_len = 0;
453         }
454
455         /* append data at end of buffer */
456         memcpy(&wd->buf[wd->buf_used_len], adr, len);
457         wd->buf_used_len += len;
458 }
459
460 /**
461  * BeGiN initializer for mywrite
462  * \param ww: File write wrapper.
463  * \param compare Previous memory file (can be NULL).
464  * \param current The current memory file (can be NULL).
465  * \warning Talks to other functions with global parameters
466  */
467 static WriteData *mywrite_begin(WriteWrap *ww, MemFile *compare, MemFile *current)
468 {
469         WriteData *wd = writedata_new(ww);
470
471         if (current != NULL) {
472                 wd->mem.current = current;
473                 wd->mem.compare = compare;
474                 wd->mem.compare_chunk = compare ? compare->chunks.first : NULL;
475                 wd->use_memfile = true;
476         }
477
478         return wd;
479 }
480
481 /**
482  * END the mywrite wrapper
483  * \return 1 if write failed
484  * \return unknown global variable otherwise
485  * \warning Talks to other functions with global parameters
486  */
487 static bool mywrite_end(WriteData *wd)
488 {
489         if (wd->buf_used_len) {
490                 writedata_do_write(wd, wd->buf, wd->buf_used_len);
491                 wd->buf_used_len = 0;
492         }
493
494         const bool err = wd->error;
495         writedata_free(wd);
496
497         return err;
498 }
499
500 /** \} */
501
502 /* -------------------------------------------------------------------- */
503 /** \name Generic DNA File Writing
504  * \{ */
505
506 static void writestruct_at_address_nr(
507         WriteData *wd, int filecode, const int struct_nr, int nr,
508         const void *adr, const void *data)
509 {
510         BHead bh;
511         const short *sp;
512
513         BLI_assert(struct_nr > 0 && struct_nr < SDNA_TYPE_MAX);
514
515         if (adr == NULL || data == NULL || nr == 0) {
516                 return;
517         }
518
519         /* init BHead */
520         bh.code = filecode;
521         bh.old = adr;
522         bh.nr = nr;
523
524         bh.SDNAnr = struct_nr;
525         sp = wd->sdna->structs[bh.SDNAnr];
526
527         bh.len = nr * wd->sdna->typelens[sp[0]];
528
529         if (bh.len == 0) {
530                 return;
531         }
532
533         mywrite(wd, &bh, sizeof(BHead));
534         mywrite(wd, data, bh.len);
535 }
536
537 static void writestruct_at_address_id(
538         WriteData *wd, int filecode, const char *structname, int nr,
539         const void *adr, const void *data)
540 {
541         if (adr == NULL || data == NULL || nr == 0) {
542                 return;
543         }
544
545         const int SDNAnr = DNA_struct_find_nr(wd->sdna, structname);
546         if (UNLIKELY(SDNAnr == -1)) {
547                 printf("error: can't find SDNA code <%s>\n", structname);
548                 return;
549         }
550
551         writestruct_at_address_nr(wd, filecode, SDNAnr, nr, adr, data);
552 }
553
554 static void writestruct_nr(
555         WriteData *wd, int filecode, const int struct_nr, int nr,
556         const void *adr)
557 {
558         writestruct_at_address_nr(wd, filecode, struct_nr, nr, adr, adr);
559 }
560
561 static void writestruct_id(
562         WriteData *wd, int filecode, const char *structname, int nr,
563         const void *adr)
564 {
565         writestruct_at_address_id(wd, filecode, structname, nr, adr, adr);
566 }
567
568 static void writedata(WriteData *wd, int filecode, int len, const void *adr)  /* do not use for structs */
569 {
570         BHead bh;
571
572         if (adr == NULL || len == 0) {
573                 return;
574         }
575
576         /* align to 4 (writes uninitialized bytes in some cases) */
577         len = (len + 3) & ~3;
578
579         /* init BHead */
580         bh.code   = filecode;
581         bh.old    = adr;
582         bh.nr     = 1;
583         bh.SDNAnr = 0;
584         bh.len    = len;
585
586         mywrite(wd, &bh, sizeof(BHead));
587         mywrite(wd, adr, len);
588 }
589
590 /* use this to force writing of lists in same order as reading (using link_list) */
591 static void writelist_nr(WriteData *wd, int filecode, const int struct_nr, const ListBase *lb)
592 {
593         const Link *link = lb->first;
594
595         while (link) {
596                 writestruct_nr(wd, filecode, struct_nr, 1, link);
597                 link = link->next;
598         }
599 }
600
601 #if 0
602 static void writelist_id(WriteData *wd, int filecode, const char *structname, const ListBase *lb)
603 {
604         const Link *link = lb->first;
605         if (link) {
606
607                 const int struct_nr = DNA_struct_find_nr(wd->sdna, structname);
608                 if (struct_nr == -1) {
609                         printf("error: can't find SDNA code <%s>\n", structname);
610                         return;
611                 }
612
613                 while (link) {
614                         writestruct_nr(wd, filecode, struct_nr, 1, link);
615                         link = link->next;
616                 }
617         }
618 }
619 #endif
620
621 #define writestruct_at_address(wd, filecode, struct_id, nr, adr, data) \
622         writestruct_at_address_nr(wd, filecode, SDNA_TYPE_FROM_STRUCT(struct_id), nr, adr, data)
623
624 #define writestruct(wd, filecode, struct_id, nr, adr) \
625         writestruct_nr(wd, filecode, SDNA_TYPE_FROM_STRUCT(struct_id), nr, adr)
626
627 #define writelist(wd, filecode, struct_id, lb) \
628         writelist_nr(wd, filecode, SDNA_TYPE_FROM_STRUCT(struct_id), lb)
629
630 /** \} */
631
632 /* -------------------------------------------------------------------- */
633 /** \name Typed DNA File Writing
634  *
635  * These functions are used by blender's .blend system for file saving/loading.
636  * \{ */
637
638 void IDP_WriteProperty_OnlyData(const IDProperty *prop, void *wd);
639 void IDP_WriteProperty(const IDProperty *prop, void *wd);
640
641 static void IDP_WriteArray(const IDProperty *prop, void *wd)
642 {
643         /*REMEMBER to set totalen to len in the linking code!!*/
644         if (prop->data.pointer) {
645                 writedata(wd, DATA, MEM_allocN_len(prop->data.pointer), prop->data.pointer);
646
647                 if (prop->subtype == IDP_GROUP) {
648                         IDProperty **array = prop->data.pointer;
649                         int a;
650
651                         for (a = 0; a < prop->len; a++) {
652                                 IDP_WriteProperty(array[a], wd);
653                         }
654                 }
655         }
656 }
657
658 static void IDP_WriteIDPArray(const IDProperty *prop, void *wd)
659 {
660         /*REMEMBER to set totalen to len in the linking code!!*/
661         if (prop->data.pointer) {
662                 const IDProperty *array = prop->data.pointer;
663                 int a;
664
665                 writestruct(wd, DATA, IDProperty, prop->len, array);
666
667                 for (a = 0; a < prop->len; a++) {
668                         IDP_WriteProperty_OnlyData(&array[a], wd);
669                 }
670         }
671 }
672
673 static void IDP_WriteString(const IDProperty *prop, void *wd)
674 {
675         /*REMEMBER to set totalen to len in the linking code!!*/
676         writedata(wd, DATA, prop->len, prop->data.pointer);
677 }
678
679 static void IDP_WriteGroup(const IDProperty *prop, void *wd)
680 {
681         IDProperty *loop;
682
683         for (loop = prop->data.group.first; loop; loop = loop->next) {
684                 IDP_WriteProperty(loop, wd);
685         }
686 }
687
688 /* Functions to read/write ID Properties */
689 void IDP_WriteProperty_OnlyData(const IDProperty *prop, void *wd)
690 {
691         switch (prop->type) {
692                 case IDP_GROUP:
693                         IDP_WriteGroup(prop, wd);
694                         break;
695                 case IDP_STRING:
696                         IDP_WriteString(prop, wd);
697                         break;
698                 case IDP_ARRAY:
699                         IDP_WriteArray(prop, wd);
700                         break;
701                 case IDP_IDPARRAY:
702                         IDP_WriteIDPArray(prop, wd);
703                         break;
704         }
705 }
706
707 void IDP_WriteProperty(const IDProperty *prop, void *wd)
708 {
709         writestruct(wd, DATA, IDProperty, 1, prop);
710         IDP_WriteProperty_OnlyData(prop, wd);
711 }
712
713 static void write_iddata(void *wd, const ID *id)
714 {
715         /* ID_WM's id->properties are considered runtime only, and never written in .blend file. */
716         if (id->properties && !ELEM(GS(id->name), ID_WM)) {
717                 IDP_WriteProperty(id->properties, wd);
718         }
719
720         if (id->override_static) {
721                 writestruct(wd, DATA, IDOverrideStatic, 1, id->override_static);
722
723                 writelist(wd, DATA, IDOverrideStaticProperty, &id->override_static->properties);
724                 for (IDOverrideStaticProperty *op = id->override_static->properties.first; op; op = op->next) {
725                         writedata(wd, DATA, strlen(op->rna_path) + 1, op->rna_path);
726
727                         writelist(wd, DATA, IDOverrideStaticPropertyOperation, &op->operations);
728                         for (IDOverrideStaticPropertyOperation *opop = op->operations.first; opop; opop = opop->next) {
729                                 if (opop->subitem_reference_name) {
730                                         writedata(wd, DATA, strlen(opop->subitem_reference_name) + 1, opop->subitem_reference_name);
731                                 }
732                                 if (opop->subitem_local_name) {
733                                         writedata(wd, DATA, strlen(opop->subitem_local_name) + 1, opop->subitem_local_name);
734                                 }
735                         }
736                 }
737         }
738 }
739
740 static void write_previews(WriteData *wd, const PreviewImage *prv_orig)
741 {
742         /* Note we write previews also for undo steps. It takes up some memory,
743          * but not doing so would causes all previews to be re-rendered after
744          * undo which is too expensive. */
745         if (prv_orig) {
746                 PreviewImage prv = *prv_orig;
747
748                 /* don't write out large previews if not requested */
749                 if (!(U.flag & USER_SAVE_PREVIEWS)) {
750                         prv.w[1] = 0;
751                         prv.h[1] = 0;
752                         prv.rect[1] = NULL;
753                 }
754                 writestruct_at_address(wd, DATA, PreviewImage, 1, prv_orig, &prv);
755                 if (prv.rect[0]) {
756                         writedata(wd, DATA, prv.w[0] * prv.h[0] * sizeof(unsigned int), prv.rect[0]);
757                 }
758                 if (prv.rect[1]) {
759                         writedata(wd, DATA, prv.w[1] * prv.h[1] * sizeof(unsigned int), prv.rect[1]);
760                 }
761         }
762 }
763
764 static void write_fmodifiers(WriteData *wd, ListBase *fmodifiers)
765 {
766         FModifier *fcm;
767
768         /* Write all modifiers first (for faster reloading) */
769         writelist(wd, DATA, FModifier, fmodifiers);
770
771         /* Modifiers */
772         for (fcm = fmodifiers->first; fcm; fcm = fcm->next) {
773                 const FModifierTypeInfo *fmi = fmodifier_get_typeinfo(fcm);
774
775                 /* Write the specific data */
776                 if (fmi && fcm->data) {
777                         /* firstly, just write the plain fmi->data struct */
778                         writestruct_id(wd, DATA, fmi->structName, 1, fcm->data);
779
780                         /* do any modifier specific stuff */
781                         switch (fcm->type) {
782                                 case FMODIFIER_TYPE_GENERATOR:
783                                 {
784                                         FMod_Generator *data = fcm->data;
785
786                                         /* write coefficients array */
787                                         if (data->coefficients) {
788                                                 writedata(wd, DATA, sizeof(float) * (data->arraysize), data->coefficients);
789                                         }
790
791                                         break;
792                                 }
793                                 case FMODIFIER_TYPE_ENVELOPE:
794                                 {
795                                         FMod_Envelope *data = fcm->data;
796
797                                         /* write envelope data */
798                                         if (data->data) {
799                                                 writestruct(wd, DATA, FCM_EnvelopeData, data->totvert, data->data);
800                                         }
801
802                                         break;
803                                 }
804                                 case FMODIFIER_TYPE_PYTHON:
805                                 {
806                                         FMod_Python *data = fcm->data;
807
808                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
809                                          * of library blocks that implement this.*/
810                                         IDP_WriteProperty(data->prop, wd);
811
812                                         break;
813                                 }
814                         }
815                 }
816         }
817 }
818
819 static void write_fcurves(WriteData *wd, ListBase *fcurves)
820 {
821         FCurve *fcu;
822
823         writelist(wd, DATA, FCurve, fcurves);
824         for (fcu = fcurves->first; fcu; fcu = fcu->next) {
825                 /* curve data */
826                 if (fcu->bezt) {
827                         writestruct(wd, DATA, BezTriple, fcu->totvert, fcu->bezt);
828                 }
829                 if (fcu->fpt) {
830                         writestruct(wd, DATA, FPoint, fcu->totvert, fcu->fpt);
831                 }
832
833                 if (fcu->rna_path) {
834                         writedata(wd, DATA, strlen(fcu->rna_path) + 1, fcu->rna_path);
835                 }
836
837                 /* driver data */
838                 if (fcu->driver) {
839                         ChannelDriver *driver = fcu->driver;
840                         DriverVar *dvar;
841
842                         writestruct(wd, DATA, ChannelDriver, 1, driver);
843
844                         /* variables */
845                         writelist(wd, DATA, DriverVar, &driver->variables);
846                         for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
847                                 DRIVER_TARGETS_USED_LOOPER(dvar)
848                                 {
849                                         if (dtar->rna_path) {
850                                                 writedata(wd, DATA, strlen(dtar->rna_path) + 1, dtar->rna_path);
851                                         }
852                                 }
853                                 DRIVER_TARGETS_LOOPER_END
854                         }
855                 }
856
857                 /* write F-Modifiers */
858                 write_fmodifiers(wd, &fcu->modifiers);
859         }
860 }
861
862 static void write_action(WriteData *wd, bAction *act)
863 {
864         if (act->id.us > 0 || wd->use_memfile) {
865                 writestruct(wd, ID_AC, bAction, 1, act);
866                 write_iddata(wd, &act->id);
867
868                 write_fcurves(wd, &act->curves);
869
870                 for (bActionGroup *grp = act->groups.first; grp; grp = grp->next) {
871                         writestruct(wd, DATA, bActionGroup, 1, grp);
872                 }
873
874                 for (TimeMarker *marker = act->markers.first; marker; marker = marker->next) {
875                         writestruct(wd, DATA, TimeMarker, 1, marker);
876                 }
877         }
878 }
879
880 static void write_keyingsets(WriteData *wd, ListBase *list)
881 {
882         KeyingSet *ks;
883         KS_Path *ksp;
884
885         for (ks = list->first; ks; ks = ks->next) {
886                 /* KeyingSet */
887                 writestruct(wd, DATA, KeyingSet, 1, ks);
888
889                 /* Paths */
890                 for (ksp = ks->paths.first; ksp; ksp = ksp->next) {
891                         /* Path */
892                         writestruct(wd, DATA, KS_Path, 1, ksp);
893
894                         if (ksp->rna_path) {
895                                 writedata(wd, DATA, strlen(ksp->rna_path) + 1, ksp->rna_path);
896                         }
897                 }
898         }
899 }
900
901 static void write_nlastrips(WriteData *wd, ListBase *strips)
902 {
903         NlaStrip *strip;
904
905         writelist(wd, DATA, NlaStrip, strips);
906         for (strip = strips->first; strip; strip = strip->next) {
907                 /* write the strip's F-Curves and modifiers */
908                 write_fcurves(wd, &strip->fcurves);
909                 write_fmodifiers(wd, &strip->modifiers);
910
911                 /* write the strip's children */
912                 write_nlastrips(wd, &strip->strips);
913         }
914 }
915
916 static void write_nladata(WriteData *wd, ListBase *nlabase)
917 {
918         NlaTrack *nlt;
919
920         /* write all the tracks */
921         for (nlt = nlabase->first; nlt; nlt = nlt->next) {
922                 /* write the track first */
923                 writestruct(wd, DATA, NlaTrack, 1, nlt);
924
925                 /* write the track's strips */
926                 write_nlastrips(wd, &nlt->strips);
927         }
928 }
929
930 static void write_animdata(WriteData *wd, AnimData *adt)
931 {
932         AnimOverride *aor;
933
934         /* firstly, just write the AnimData block */
935         writestruct(wd, DATA, AnimData, 1, adt);
936
937         /* write drivers */
938         write_fcurves(wd, &adt->drivers);
939
940         /* write overrides */
941         // FIXME: are these needed?
942         for (aor = adt->overrides.first; aor; aor = aor->next) {
943                 /* overrides consist of base data + rna_path */
944                 writestruct(wd, DATA, AnimOverride, 1, aor);
945                 writedata(wd, DATA, strlen(aor->rna_path) + 1, aor->rna_path);
946         }
947
948         // TODO write the remaps (if they are needed)
949
950         /* write NLA data */
951         write_nladata(wd, &adt->nla_tracks);
952 }
953
954 static void write_curvemapping_curves(WriteData *wd, CurveMapping *cumap)
955 {
956         for (int a = 0; a < CM_TOT; a++) {
957                 writestruct(wd, DATA, CurveMapPoint, cumap->cm[a].totpoint, cumap->cm[a].curve);
958         }
959 }
960
961 static void write_curvemapping(WriteData *wd, CurveMapping *cumap)
962 {
963         writestruct(wd, DATA, CurveMapping, 1, cumap);
964
965         write_curvemapping_curves(wd, cumap);
966 }
967
968 static void write_node_socket(WriteData *wd, bNodeTree *UNUSED(ntree), bNode *node, bNodeSocket *sock)
969 {
970 #ifdef USE_NODE_COMPAT_CUSTOMNODES
971         /* forward compatibility code, so older blenders still open (not for undo) */
972         if (wd->use_memfile == false) {
973                 sock->stack_type = 1;
974
975                 if (node->type == NODE_GROUP) {
976                         bNodeTree *ngroup = (bNodeTree *)node->id;
977                         if (ngroup) {
978                                 /* for node groups: look up the deprecated groupsock pointer */
979                                 sock->groupsock = ntreeFindSocketInterface(ngroup, sock->in_out, sock->identifier);
980                                 BLI_assert(sock->groupsock != NULL);
981
982                                 /* node group sockets now use the generic identifier string to verify group nodes,
983                                  * old blender uses the own_index.
984                                  */
985                                 sock->own_index = sock->groupsock->own_index;
986                         }
987                 }
988         }
989 #endif
990
991         /* actual socket writing */
992         writestruct(wd, DATA, bNodeSocket, 1, sock);
993
994         if (sock->prop) {
995                 IDP_WriteProperty(sock->prop, wd);
996         }
997
998         if (sock->default_value) {
999                 writedata(wd, DATA, MEM_allocN_len(sock->default_value), sock->default_value);
1000         }
1001 }
1002 static void write_node_socket_interface(WriteData *wd, bNodeTree *UNUSED(ntree), bNodeSocket *sock)
1003 {
1004 #ifdef USE_NODE_COMPAT_CUSTOMNODES
1005         /* forward compatibility code, so older blenders still open */
1006         sock->stack_type = 1;
1007
1008         /* Reconstruct the deprecated default_value structs in socket interface DNA. */
1009         if (sock->default_value == NULL && sock->typeinfo) {
1010                 node_socket_init_default_value(sock);
1011         }
1012 #endif
1013
1014         /* actual socket writing */
1015         writestruct(wd, DATA, bNodeSocket, 1, sock);
1016
1017         if (sock->prop) {
1018                 IDP_WriteProperty(sock->prop, wd);
1019         }
1020
1021         if (sock->default_value) {
1022                 writedata(wd, DATA, MEM_allocN_len(sock->default_value), sock->default_value);
1023         }
1024 }
1025 /* this is only direct data, tree itself should have been written */
1026 static void write_nodetree_nolib(WriteData *wd, bNodeTree *ntree)
1027 {
1028         bNode *node;
1029         bNodeSocket *sock;
1030         bNodeLink *link;
1031
1032         /* for link_list() speed, we write per list */
1033
1034         if (ntree->adt) {
1035                 write_animdata(wd, ntree->adt);
1036         }
1037
1038         for (node = ntree->nodes.first; node; node = node->next) {
1039                 writestruct(wd, DATA, bNode, 1, node);
1040
1041                 if (node->prop) {
1042                         IDP_WriteProperty(node->prop, wd);
1043                 }
1044
1045                 for (sock = node->inputs.first; sock; sock = sock->next) {
1046                         write_node_socket(wd, ntree, node, sock);
1047                 }
1048                 for (sock = node->outputs.first; sock; sock = sock->next) {
1049                         write_node_socket(wd, ntree, node, sock);
1050                 }
1051
1052                 for (link = node->internal_links.first; link; link = link->next) {
1053                         writestruct(wd, DATA, bNodeLink, 1, link);
1054                 }
1055
1056                 if (node->storage) {
1057                         /* could be handlerized at some point, now only 1 exception still */
1058                         if ((ntree->type == NTREE_SHADER) &&
1059                             ELEM(node->type, SH_NODE_CURVE_VEC, SH_NODE_CURVE_RGB))
1060                         {
1061                                 write_curvemapping(wd, node->storage);
1062                         }
1063                         else if (ntree->type == NTREE_SHADER &&
1064                                  (node->type == SH_NODE_SCRIPT))
1065                         {
1066                                 NodeShaderScript *nss = (NodeShaderScript *)node->storage;
1067                                 if (nss->bytecode) {
1068                                         writedata(wd, DATA, strlen(nss->bytecode) + 1, nss->bytecode);
1069                                 }
1070                                 writestruct_id(wd, DATA, node->typeinfo->storagename, 1, node->storage);
1071                         }
1072                         else if ((ntree->type == NTREE_COMPOSIT) &&
1073                                  ELEM(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB, CMP_NODE_HUECORRECT))
1074                         {
1075                                 write_curvemapping(wd, node->storage);
1076                         }
1077                         else if ((ntree->type == NTREE_TEXTURE) &&
1078                                  (node->type == TEX_NODE_CURVE_RGB || node->type == TEX_NODE_CURVE_TIME))
1079                         {
1080                                 write_curvemapping(wd, node->storage);
1081                         }
1082                         else if ((ntree->type == NTREE_COMPOSIT) &&
1083                                  (node->type == CMP_NODE_MOVIEDISTORTION))
1084                         {
1085                                 /* pass */
1086                         }
1087                         else if ((ntree->type == NTREE_COMPOSIT) && (node->type == CMP_NODE_GLARE)) {
1088                                 /* Simple forward compat for fix for T50736.
1089                                  * Not ideal (there is no ideal solution here), but should do for now. */
1090                                 NodeGlare *ndg = node->storage;
1091                                 /* Not in undo case. */
1092                                 if (wd->use_memfile == false) {
1093                                         switch (ndg->type) {
1094                                                 case 2:  /* Grrrr! magic numbers :( */
1095                                                         ndg->angle = ndg->streaks;
1096                                                         break;
1097                                                 case 0:
1098                                                         ndg->angle = ndg->star_45;
1099                                                         break;
1100                                                 default:
1101                                                         break;
1102                                         }
1103                                 }
1104                                 writestruct_id(wd, DATA, node->typeinfo->storagename, 1, node->storage);
1105                         }
1106                         else {
1107                                 writestruct_id(wd, DATA, node->typeinfo->storagename, 1, node->storage);
1108                         }
1109                 }
1110
1111                 if (node->type == CMP_NODE_OUTPUT_FILE) {
1112                         /* inputs have own storage data */
1113                         for (sock = node->inputs.first; sock; sock = sock->next) {
1114                                 writestruct(wd, DATA, NodeImageMultiFileSocket, 1, sock->storage);
1115                         }
1116                 }
1117                 if (ELEM(node->type, CMP_NODE_IMAGE, CMP_NODE_R_LAYERS)) {
1118                         /* write extra socket info */
1119                         for (sock = node->outputs.first; sock; sock = sock->next) {
1120                                 writestruct(wd, DATA, NodeImageLayer, 1, sock->storage);
1121                         }
1122                 }
1123         }
1124
1125         for (link = ntree->links.first; link; link = link->next) {
1126                 writestruct(wd, DATA, bNodeLink, 1, link);
1127         }
1128
1129         for (sock = ntree->inputs.first; sock; sock = sock->next) {
1130                 write_node_socket_interface(wd, ntree, sock);
1131         }
1132         for (sock = ntree->outputs.first; sock; sock = sock->next) {
1133                 write_node_socket_interface(wd, ntree, sock);
1134         }
1135 }
1136
1137 /**
1138  * Take care using 'use_active_win', since we wont want the currently active window
1139  * to change which scene renders (currently only used for undo).
1140  */
1141 static void current_screen_compat(
1142         Main *mainvar, bool use_active_win,
1143         bScreen **r_screen, Scene **r_scene, ViewLayer **r_render_layer)
1144 {
1145         wmWindowManager *wm;
1146         wmWindow *window = NULL;
1147
1148         /* find a global current screen in the first open window, to have
1149          * a reasonable default for reading in older versions */
1150         wm = mainvar->wm.first;
1151
1152         if (wm) {
1153                 if (use_active_win) {
1154                         /* write the active window into the file, needed for multi-window undo T43424 */
1155                         for (window = wm->windows.first; window; window = window->next) {
1156                                 if (window->active) {
1157                                         break;
1158                                 }
1159                         }
1160
1161                         /* fallback */
1162                         if (window == NULL) {
1163                                 window = wm->windows.first;
1164                         }
1165                 }
1166                 else {
1167                         window = wm->windows.first;
1168                 }
1169         }
1170
1171         *r_screen = (window) ? BKE_workspace_active_screen_get(window->workspace_hook) : NULL;
1172         *r_scene = (window) ? window->scene : NULL;
1173         *r_render_layer = (window && *r_scene) ? BKE_view_layer_find(*r_scene, window->view_layer_name) : NULL;
1174 }
1175
1176 typedef struct RenderInfo {
1177         int sfra;
1178         int efra;
1179         char scene_name[MAX_ID_NAME - 2];
1180 } RenderInfo;
1181
1182 /* was for historic render-deamon feature,
1183  * now write because it can be easily extracted without
1184  * reading the whole blend file */
1185 static void write_renderinfo(WriteData *wd, Main *mainvar)
1186 {
1187         bScreen *curscreen;
1188         Scene *sce, *curscene = NULL;
1189         ViewLayer *render_layer;
1190         RenderInfo data;
1191
1192         /* XXX in future, handle multiple windows with multiple screens? */
1193         current_screen_compat(mainvar, false, &curscreen, &curscene, &render_layer);
1194
1195         for (sce = mainvar->scene.first; sce; sce = sce->id.next) {
1196                 if (sce->id.lib == NULL && (sce == curscene || (sce->r.scemode & R_BG_RENDER))) {
1197                         data.sfra = sce->r.sfra;
1198                         data.efra = sce->r.efra;
1199                         memset(data.scene_name, 0, sizeof(data.scene_name));
1200
1201                         BLI_strncpy(data.scene_name, sce->id.name + 2, sizeof(data.scene_name));
1202
1203                         writedata(wd, REND, sizeof(data), &data);
1204                 }
1205         }
1206 }
1207
1208 static void write_keymapitem(WriteData *wd, const wmKeyMapItem *kmi)
1209 {
1210         writestruct(wd, DATA, wmKeyMapItem, 1, kmi);
1211         if (kmi->properties) {
1212                 IDP_WriteProperty(kmi->properties, wd);
1213         }
1214 }
1215
1216 static void write_userdef(WriteData *wd, const UserDef *userdef)
1217 {
1218         writestruct(wd, USER, UserDef, 1, userdef);
1219
1220         for (const bTheme *btheme = userdef->themes.first; btheme; btheme = btheme->next) {
1221                 writestruct(wd, DATA, bTheme, 1, btheme);
1222         }
1223
1224         for (const wmKeyMap *keymap = userdef->user_keymaps.first; keymap; keymap = keymap->next) {
1225                 writestruct(wd, DATA, wmKeyMap, 1, keymap);
1226
1227                 for (const wmKeyMapDiffItem *kmdi = keymap->diff_items.first; kmdi; kmdi = kmdi->next) {
1228                         writestruct(wd, DATA, wmKeyMapDiffItem, 1, kmdi);
1229                         if (kmdi->remove_item) {
1230                                 write_keymapitem(wd, kmdi->remove_item);
1231                         }
1232                         if (kmdi->add_item) {
1233                                 write_keymapitem(wd, kmdi->add_item);
1234                         }
1235                 }
1236
1237                 for (const wmKeyMapItem *kmi = keymap->items.first; kmi; kmi = kmi->next) {
1238                         write_keymapitem(wd, kmi);
1239                 }
1240         }
1241
1242         for (const bUserMenu *um = userdef->user_menus.first; um; um = um->next) {
1243                 writestruct(wd, DATA, bUserMenu, 1, um);
1244                 for (const bUserMenuItem *umi = um->items.first; umi; umi = umi->next) {
1245                         if (umi->type == USER_MENU_TYPE_OPERATOR) {
1246                                 const bUserMenuItem_Op *umi_op = (const bUserMenuItem_Op *)umi;
1247                                 writestruct(wd, DATA, bUserMenuItem_Op, 1, umi_op);
1248                                 if (umi_op->prop) {
1249                                         IDP_WriteProperty(umi_op->prop, wd);
1250                                 }
1251                         }
1252                         else if (umi->type == USER_MENU_TYPE_MENU) {
1253                                 const bUserMenuItem_Menu *umi_mt = (const bUserMenuItem_Menu *)umi;
1254                                 writestruct(wd, DATA, bUserMenuItem_Menu, 1, umi_mt);
1255                         }
1256                         else if (umi->type == USER_MENU_TYPE_PROP) {
1257                                 const bUserMenuItem_Prop *umi_pr = (const bUserMenuItem_Prop *)umi;
1258                                 writestruct(wd, DATA, bUserMenuItem_Prop, 1, umi_pr);
1259                         }
1260                         else {
1261                                 writestruct(wd, DATA, bUserMenuItem, 1, umi);
1262                         }
1263                 }
1264         }
1265
1266         for (const bAddon *bext = userdef->addons.first; bext; bext = bext->next) {
1267                 writestruct(wd, DATA, bAddon, 1, bext);
1268                 if (bext->prop) {
1269                         IDP_WriteProperty(bext->prop, wd);
1270                 }
1271         }
1272
1273         for (const bPathCompare *path_cmp = userdef->autoexec_paths.first; path_cmp; path_cmp = path_cmp->next) {
1274                 writestruct(wd, DATA, bPathCompare, 1, path_cmp);
1275         }
1276
1277         for (const uiStyle *style = userdef->uistyles.first; style; style = style->next) {
1278                 writestruct(wd, DATA, uiStyle, 1, style);
1279         }
1280 }
1281
1282 static void write_boid_state(WriteData *wd, BoidState *state)
1283 {
1284         BoidRule *rule = state->rules.first;
1285
1286         writestruct(wd, DATA, BoidState, 1, state);
1287
1288         for (; rule; rule = rule->next) {
1289                 switch (rule->type) {
1290                         case eBoidRuleType_Goal:
1291                         case eBoidRuleType_Avoid:
1292                                 writestruct(wd, DATA, BoidRuleGoalAvoid, 1, rule);
1293                                 break;
1294                         case eBoidRuleType_AvoidCollision:
1295                                 writestruct(wd, DATA, BoidRuleAvoidCollision, 1, rule);
1296                                 break;
1297                         case eBoidRuleType_FollowLeader:
1298                                 writestruct(wd, DATA, BoidRuleFollowLeader, 1, rule);
1299                                 break;
1300                         case eBoidRuleType_AverageSpeed:
1301                                 writestruct(wd, DATA, BoidRuleAverageSpeed, 1, rule);
1302                                 break;
1303                         case eBoidRuleType_Fight:
1304                                 writestruct(wd, DATA, BoidRuleFight, 1, rule);
1305                                 break;
1306                         default:
1307                                 writestruct(wd, DATA, BoidRule, 1, rule);
1308                                 break;
1309                 }
1310         }
1311 #if 0
1312         BoidCondition *cond = state->conditions.first;
1313         for (; cond; cond = cond->next) {
1314                 writestruct(wd, DATA, BoidCondition, 1, cond);
1315         }
1316 #endif
1317 }
1318
1319 /* update this also to readfile.c */
1320 static const char *ptcache_data_struct[] = {
1321         "", // BPHYS_DATA_INDEX
1322         "", // BPHYS_DATA_LOCATION
1323         "", // BPHYS_DATA_VELOCITY
1324         "", // BPHYS_DATA_ROTATION
1325         "", // BPHYS_DATA_AVELOCITY / BPHYS_DATA_XCONST */
1326         "", // BPHYS_DATA_SIZE:
1327         "", // BPHYS_DATA_TIMES:
1328         "BoidData" // case BPHYS_DATA_BOIDS:
1329 };
1330 static const char *ptcache_extra_struct[] = {
1331         "",
1332         "ParticleSpring"
1333 };
1334 static void write_pointcaches(WriteData *wd, ListBase *ptcaches)
1335 {
1336         PointCache *cache = ptcaches->first;
1337         int i;
1338
1339         for (; cache; cache = cache->next) {
1340                 writestruct(wd, DATA, PointCache, 1, cache);
1341
1342                 if ((cache->flag & PTCACHE_DISK_CACHE) == 0) {
1343                         PTCacheMem *pm = cache->mem_cache.first;
1344
1345                         for (; pm; pm = pm->next) {
1346                                 PTCacheExtra *extra = pm->extradata.first;
1347
1348                                 writestruct(wd, DATA, PTCacheMem, 1, pm);
1349
1350                                 for (i = 0; i < BPHYS_TOT_DATA; i++) {
1351                                         if (pm->data[i] && pm->data_types & (1 << i)) {
1352                                                 if (ptcache_data_struct[i][0] == '\0') {
1353                                                         writedata(wd, DATA, MEM_allocN_len(pm->data[i]), pm->data[i]);
1354                                                 }
1355                                                 else {
1356                                                         writestruct_id(wd, DATA, ptcache_data_struct[i], pm->totpoint, pm->data[i]);
1357                                                 }
1358                                         }
1359                                 }
1360
1361                                 for (; extra; extra = extra->next) {
1362                                         if (ptcache_extra_struct[extra->type][0] == '\0') {
1363                                                 continue;
1364                                         }
1365                                         writestruct(wd, DATA, PTCacheExtra, 1, extra);
1366                                         writestruct_id(wd, DATA, ptcache_extra_struct[extra->type], extra->totdata, extra->data);
1367                                 }
1368                         }
1369                 }
1370         }
1371 }
1372
1373 static void write_particlesettings(WriteData *wd, ParticleSettings *part)
1374 {
1375         if (part->id.us > 0 || wd->use_memfile) {
1376                 /* write LibData */
1377                 writestruct(wd, ID_PA, ParticleSettings, 1, part);
1378                 write_iddata(wd, &part->id);
1379
1380                 if (part->adt) {
1381                         write_animdata(wd, part->adt);
1382                 }
1383                 writestruct(wd, DATA, PartDeflect, 1, part->pd);
1384                 writestruct(wd, DATA, PartDeflect, 1, part->pd2);
1385                 writestruct(wd, DATA, EffectorWeights, 1, part->effector_weights);
1386
1387                 if (part->clumpcurve) {
1388                         write_curvemapping(wd, part->clumpcurve);
1389                 }
1390                 if (part->roughcurve) {
1391                         write_curvemapping(wd, part->roughcurve);
1392                 }
1393                 if (part->twistcurve) {
1394                         write_curvemapping(wd, part->twistcurve);
1395                 }
1396
1397                 for (ParticleDupliWeight *dw = part->dupliweights.first; dw; dw = dw->next) {
1398                         /* update indices, but only if dw->ob is set (can be NULL after loading e.g.) */
1399                         if (dw->ob != NULL) {
1400                                 dw->index = 0;
1401                                 if (part->dup_group) { /* can be NULL if lining fails or set to None */
1402                                         FOREACH_COLLECTION_OBJECT_RECURSIVE_BEGIN(part->dup_group, object)
1403                                         {
1404                                                 if (object != dw->ob) {
1405                                                         dw->index++;
1406                                                 }
1407                                         }
1408                                         FOREACH_COLLECTION_OBJECT_RECURSIVE_END;
1409                                 }
1410                         }
1411                         writestruct(wd, DATA, ParticleDupliWeight, 1, dw);
1412                 }
1413
1414                 if (part->boids && part->phystype == PART_PHYS_BOIDS) {
1415                         writestruct(wd, DATA, BoidSettings, 1, part->boids);
1416
1417                         for (BoidState *state = part->boids->states.first; state; state = state->next) {
1418                                 write_boid_state(wd, state);
1419                         }
1420                 }
1421                 if (part->fluid && part->phystype == PART_PHYS_FLUID) {
1422                         writestruct(wd, DATA, SPHFluidSettings, 1, part->fluid);
1423                 }
1424
1425                 for (int a = 0; a < MAX_MTEX; a++) {
1426                         if (part->mtex[a]) {
1427                                 writestruct(wd, DATA, MTex, 1, part->mtex[a]);
1428                         }
1429                 }
1430         }
1431 }
1432
1433 static void write_particlesystems(WriteData *wd, ListBase *particles)
1434 {
1435         ParticleSystem *psys = particles->first;
1436         ParticleTarget *pt;
1437         int a;
1438
1439         for (; psys; psys = psys->next) {
1440                 writestruct(wd, DATA, ParticleSystem, 1, psys);
1441
1442                 if (psys->particles) {
1443                         writestruct(wd, DATA, ParticleData, psys->totpart, psys->particles);
1444
1445                         if (psys->particles->hair) {
1446                                 ParticleData *pa = psys->particles;
1447
1448                                 for (a = 0; a < psys->totpart; a++, pa++) {
1449                                         writestruct(wd, DATA, HairKey, pa->totkey, pa->hair);
1450                                 }
1451                         }
1452
1453                         if (psys->particles->boid &&
1454                             (psys->part->phystype == PART_PHYS_BOIDS))
1455                         {
1456                                 writestruct(wd, DATA, BoidParticle, psys->totpart, psys->particles->boid);
1457                         }
1458
1459                         if (psys->part->fluid &&
1460                             (psys->part->phystype == PART_PHYS_FLUID) &&
1461                             (psys->part->fluid->flag & SPH_VISCOELASTIC_SPRINGS))
1462                         {
1463                                 writestruct(wd, DATA, ParticleSpring, psys->tot_fluidsprings, psys->fluid_springs);
1464                         }
1465                 }
1466                 pt = psys->targets.first;
1467                 for (; pt; pt = pt->next) {
1468                         writestruct(wd, DATA, ParticleTarget, 1, pt);
1469                 }
1470
1471                 if (psys->child) {
1472                         writestruct(wd, DATA, ChildParticle, psys->totchild, psys->child);
1473                 }
1474
1475                 if (psys->clmd) {
1476                         writestruct(wd, DATA, ClothModifierData, 1, psys->clmd);
1477                         writestruct(wd, DATA, ClothSimSettings, 1, psys->clmd->sim_parms);
1478                         writestruct(wd, DATA, ClothCollSettings, 1, psys->clmd->coll_parms);
1479                 }
1480
1481                 write_pointcaches(wd, &psys->ptcaches);
1482         }
1483 }
1484
1485 static void write_motionpath(WriteData *wd, bMotionPath *mpath)
1486 {
1487         /* sanity checks */
1488         if (mpath == NULL) {
1489                 return;
1490         }
1491
1492         /* firstly, just write the motionpath struct */
1493         writestruct(wd, DATA, bMotionPath, 1, mpath);
1494
1495         /* now write the array of data */
1496         writestruct(wd, DATA, bMotionPathVert, mpath->length, mpath->points);
1497 }
1498
1499 static void write_constraints(WriteData *wd, ListBase *conlist)
1500 {
1501         bConstraint *con;
1502
1503         for (con = conlist->first; con; con = con->next) {
1504                 const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
1505
1506                 /* Write the specific data */
1507                 if (cti && con->data) {
1508                         /* firstly, just write the plain con->data struct */
1509                         writestruct_id(wd, DATA, cti->structName, 1, con->data);
1510
1511                         /* do any constraint specific stuff */
1512                         switch (con->type) {
1513                                 case CONSTRAINT_TYPE_PYTHON:
1514                                 {
1515                                         bPythonConstraint *data = con->data;
1516                                         bConstraintTarget *ct;
1517
1518                                         /* write targets */
1519                                         for (ct = data->targets.first; ct; ct = ct->next) {
1520                                                 writestruct(wd, DATA, bConstraintTarget, 1, ct);
1521                                         }
1522
1523                                         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1524                                          * of library blocks that implement this.*/
1525                                         IDP_WriteProperty(data->prop, wd);
1526
1527                                         break;
1528                                 }
1529                                 case CONSTRAINT_TYPE_SPLINEIK:
1530                                 {
1531                                         bSplineIKConstraint *data = con->data;
1532
1533                                         /* write points array */
1534                                         writedata(wd, DATA, sizeof(float) * (data->numpoints), data->points);
1535
1536                                         break;
1537                                 }
1538                         }
1539                 }
1540
1541                 /* Write the constraint */
1542                 writestruct(wd, DATA, bConstraint, 1, con);
1543         }
1544 }
1545
1546 static void write_pose(WriteData *wd, bPose *pose)
1547 {
1548         bPoseChannel *chan;
1549         bActionGroup *grp;
1550
1551         /* Write each channel */
1552         if (pose == NULL) {
1553                 return;
1554         }
1555
1556         /* Write channels */
1557         for (chan = pose->chanbase.first; chan; chan = chan->next) {
1558                 /* Write ID Properties -- and copy this comment EXACTLY for easy finding
1559                  * of library blocks that implement this.*/
1560                 if (chan->prop) {
1561                         IDP_WriteProperty(chan->prop, wd);
1562                 }
1563
1564                 write_constraints(wd, &chan->constraints);
1565
1566                 write_motionpath(wd, chan->mpath);
1567
1568                 /* prevent crashes with autosave,
1569                  * when a bone duplicated in editmode has not yet been assigned to its posechannel */
1570                 if (chan->bone) {
1571                         /* gets restored on read, for library armatures */
1572                         chan->selectflag = chan->bone->flag & BONE_SELECTED;
1573                 }
1574
1575                 writestruct(wd, DATA, bPoseChannel, 1, chan);
1576         }
1577
1578         /* Write groups */
1579         for (grp = pose->agroups.first; grp; grp = grp->next) {
1580                 writestruct(wd, DATA, bActionGroup, 1, grp);
1581         }
1582
1583         /* write IK param */
1584         if (pose->ikparam) {
1585                 const char *structname = BKE_pose_ikparam_get_name(pose);
1586                 if (structname) {
1587                         writestruct_id(wd, DATA, structname, 1, pose->ikparam);
1588                 }
1589         }
1590
1591         /* Write this pose */
1592         writestruct(wd, DATA, bPose, 1, pose);
1593
1594 }
1595
1596 static void write_defgroups(WriteData *wd, ListBase *defbase)
1597 {
1598         for (bDeformGroup *defgroup = defbase->first; defgroup; defgroup = defgroup->next) {
1599                 writestruct(wd, DATA, bDeformGroup, 1, defgroup);
1600         }
1601 }
1602
1603 static void write_fmaps(WriteData *wd, ListBase *fbase)
1604 {
1605         for (bFaceMap *fmap = fbase->first; fmap; fmap = fmap->next) {
1606                 writestruct(wd, DATA, bFaceMap, 1, fmap);
1607         }
1608 }
1609
1610 static void write_modifiers(WriteData *wd, ListBase *modbase)
1611 {
1612         ModifierData *md;
1613
1614         if (modbase == NULL) {
1615                 return;
1616         }
1617
1618         for (md = modbase->first; md; md = md->next) {
1619                 const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
1620                 if (mti == NULL) {
1621                         return;
1622                 }
1623
1624                 writestruct_id(wd, DATA, mti->structName, 1, md);
1625
1626                 if (md->type == eModifierType_Hook) {
1627                         HookModifierData *hmd = (HookModifierData *)md;
1628
1629                         if (hmd->curfalloff) {
1630                                 write_curvemapping(wd, hmd->curfalloff);
1631                         }
1632
1633                         writedata(wd, DATA, sizeof(int) * hmd->totindex, hmd->indexar);
1634                 }
1635                 else if (md->type == eModifierType_Cloth) {
1636                         ClothModifierData *clmd = (ClothModifierData *)md;
1637
1638                         writestruct(wd, DATA, ClothSimSettings, 1, clmd->sim_parms);
1639                         writestruct(wd, DATA, ClothCollSettings, 1, clmd->coll_parms);
1640                         writestruct(wd, DATA, EffectorWeights, 1, clmd->sim_parms->effector_weights);
1641                         write_pointcaches(wd, &clmd->ptcaches);
1642                 }
1643                 else if (md->type == eModifierType_Smoke) {
1644                         SmokeModifierData *smd = (SmokeModifierData *)md;
1645
1646                         if (smd->type & MOD_SMOKE_TYPE_DOMAIN) {
1647                                 writestruct(wd, DATA, SmokeDomainSettings, 1, smd->domain);
1648
1649                                 if (smd->domain) {
1650                                         write_pointcaches(wd, &(smd->domain->ptcaches[0]));
1651
1652                                         /* create fake pointcache so that old blender versions can read it */
1653                                         smd->domain->point_cache[1] = BKE_ptcache_add(&smd->domain->ptcaches[1]);
1654                                         smd->domain->point_cache[1]->flag |= PTCACHE_DISK_CACHE | PTCACHE_FAKE_SMOKE;
1655                                         smd->domain->point_cache[1]->step = 1;
1656
1657                                         write_pointcaches(wd, &(smd->domain->ptcaches[1]));
1658
1659                                         if (smd->domain->coba) {
1660                                                 writestruct(wd, DATA, ColorBand, 1, smd->domain->coba);
1661                                         }
1662
1663
1664                                         /* cleanup the fake pointcache */
1665                                         BKE_ptcache_free_list(&smd->domain->ptcaches[1]);
1666                                         smd->domain->point_cache[1] = NULL;
1667
1668                                         writestruct(wd, DATA, EffectorWeights, 1, smd->domain->effector_weights);
1669                                 }
1670                         }
1671                         else if (smd->type & MOD_SMOKE_TYPE_FLOW) {
1672                                 writestruct(wd, DATA, SmokeFlowSettings, 1, smd->flow);
1673                         }
1674                         else if (smd->type & MOD_SMOKE_TYPE_COLL) {
1675                                 writestruct(wd, DATA, SmokeCollSettings, 1, smd->coll);
1676                         }
1677                 }
1678                 else if (md->type == eModifierType_Fluidsim) {
1679                         FluidsimModifierData *fluidmd = (FluidsimModifierData *)md;
1680
1681                         writestruct(wd, DATA, FluidsimSettings, 1, fluidmd->fss);
1682                 }
1683                 else if (md->type == eModifierType_DynamicPaint) {
1684                         DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)md;
1685
1686                         if (pmd->canvas) {
1687                                 DynamicPaintSurface *surface;
1688                                 writestruct(wd, DATA, DynamicPaintCanvasSettings, 1, pmd->canvas);
1689
1690                                 /* write surfaces */
1691                                 for (surface = pmd->canvas->surfaces.first; surface; surface = surface->next) {
1692                                         writestruct(wd, DATA, DynamicPaintSurface, 1, surface);
1693                                 }
1694                                 /* write caches and effector weights */
1695                                 for (surface = pmd->canvas->surfaces.first; surface; surface = surface->next) {
1696                                         write_pointcaches(wd, &(surface->ptcaches));
1697
1698                                         writestruct(wd, DATA, EffectorWeights, 1, surface->effector_weights);
1699                                 }
1700                         }
1701                         if (pmd->brush) {
1702                                 writestruct(wd, DATA, DynamicPaintBrushSettings, 1, pmd->brush);
1703                                 writestruct(wd, DATA, ColorBand, 1, pmd->brush->paint_ramp);
1704                                 writestruct(wd, DATA, ColorBand, 1, pmd->brush->vel_ramp);
1705                         }
1706                 }
1707                 else if (md->type == eModifierType_Collision) {
1708
1709 #if 0
1710                         CollisionModifierData *collmd = (CollisionModifierData *)md;
1711                         // TODO: CollisionModifier should use pointcache
1712                         // + have proper reset events before enabling this
1713                         writestruct(wd, DATA, MVert, collmd->numverts, collmd->x);
1714                         writestruct(wd, DATA, MVert, collmd->numverts, collmd->xnew);
1715                         writestruct(wd, DATA, MFace, collmd->numfaces, collmd->mfaces);
1716 #endif
1717                 }
1718                 else if (md->type == eModifierType_MeshDeform) {
1719                         MeshDeformModifierData *mmd = (MeshDeformModifierData *)md;
1720                         int size = mmd->dyngridsize;
1721
1722                         writestruct(wd, DATA, MDefInfluence, mmd->totinfluence, mmd->bindinfluences);
1723                         writedata(wd, DATA, sizeof(int) * (mmd->totvert + 1), mmd->bindoffsets);
1724                         writedata(wd, DATA, sizeof(float) * 3 * mmd->totcagevert,
1725                                   mmd->bindcagecos);
1726                         writestruct(wd, DATA, MDefCell, size * size * size, mmd->dyngrid);
1727                         writestruct(wd, DATA, MDefInfluence, mmd->totinfluence, mmd->dyninfluences);
1728                         writedata(wd, DATA, sizeof(int) * mmd->totvert, mmd->dynverts);
1729                 }
1730                 else if (md->type == eModifierType_Warp) {
1731                         WarpModifierData *tmd = (WarpModifierData *)md;
1732                         if (tmd->curfalloff) {
1733                                 write_curvemapping(wd, tmd->curfalloff);
1734                         }
1735                 }
1736                 else if (md->type == eModifierType_WeightVGEdit) {
1737                         WeightVGEditModifierData *wmd = (WeightVGEditModifierData *)md;
1738
1739                         if (wmd->cmap_curve) {
1740                                 write_curvemapping(wd, wmd->cmap_curve);
1741                         }
1742                 }
1743                 else if (md->type == eModifierType_LaplacianDeform) {
1744                         LaplacianDeformModifierData *lmd = (LaplacianDeformModifierData *)md;
1745
1746                         writedata(wd, DATA, sizeof(float) * lmd->total_verts * 3, lmd->vertexco);
1747                 }
1748                 else if (md->type == eModifierType_CorrectiveSmooth) {
1749                         CorrectiveSmoothModifierData *csmd = (CorrectiveSmoothModifierData *)md;
1750
1751                         if (csmd->bind_coords) {
1752                                 writedata(wd, DATA, sizeof(float[3]) * csmd->bind_coords_num, csmd->bind_coords);
1753                         }
1754                 }
1755                 else if (md->type == eModifierType_SurfaceDeform) {
1756                         SurfaceDeformModifierData *smd = (SurfaceDeformModifierData *)md;
1757
1758                         writestruct(wd, DATA, SDefVert, smd->numverts, smd->verts);
1759
1760                         if (smd->verts) {
1761                                 for (int i = 0; i < smd->numverts; i++) {
1762                                         writestruct(wd, DATA, SDefBind, smd->verts[i].numbinds, smd->verts[i].binds);
1763
1764                                         if (smd->verts[i].binds) {
1765                                                 for (int j = 0; j < smd->verts[i].numbinds; j++) {
1766                                                         writedata(wd, DATA, sizeof(int) * smd->verts[i].binds[j].numverts, smd->verts[i].binds[j].vert_inds);
1767
1768                                                         if (smd->verts[i].binds[j].mode == MOD_SDEF_MODE_CENTROID ||
1769                                                             smd->verts[i].binds[j].mode == MOD_SDEF_MODE_LOOPTRI)
1770                                                         {
1771                                                                 writedata(wd, DATA, sizeof(float) * 3, smd->verts[i].binds[j].vert_weights);
1772                                                         }
1773                                                         else {
1774                                                                 writedata(wd, DATA, sizeof(float) * smd->verts[i].binds[j].numverts, smd->verts[i].binds[j].vert_weights);
1775                                                         }
1776                                                 }
1777                                         }
1778                                 }
1779                         }
1780                 }
1781         }
1782 }
1783
1784 static void write_object(WriteData *wd, Object *ob)
1785 {
1786         if (ob->id.us > 0 || wd->use_memfile) {
1787                 /* write LibData */
1788                 writestruct(wd, ID_OB, Object, 1, ob);
1789                 write_iddata(wd, &ob->id);
1790
1791                 if (ob->adt) {
1792                         write_animdata(wd, ob->adt);
1793                 }
1794
1795                 /* direct data */
1796                 writedata(wd, DATA, sizeof(void *) * ob->totcol, ob->mat);
1797                 writedata(wd, DATA, sizeof(char) * ob->totcol, ob->matbits);
1798                 /* write_effects(wd, &ob->effect); */ /* not used anymore */
1799
1800                 if (ob->type == OB_ARMATURE) {
1801                         bArmature *arm = ob->data;
1802                         if (arm && ob->pose && arm->act_bone) {
1803                                 BLI_strncpy(ob->pose->proxy_act_bone, arm->act_bone->name, sizeof(ob->pose->proxy_act_bone));
1804                         }
1805                 }
1806
1807                 write_pose(wd, ob->pose);
1808                 write_defgroups(wd, &ob->defbase);
1809                 write_fmaps(wd, &ob->fmaps);
1810                 write_constraints(wd, &ob->constraints);
1811                 write_motionpath(wd, ob->mpath);
1812
1813                 writestruct(wd, DATA, PartDeflect, 1, ob->pd);
1814                 if (ob->soft) {
1815                         /* Set deprecated pointers to prevent crashes of older Blenders */
1816                         ob->soft->pointcache = ob->soft->shared->pointcache;
1817                         ob->soft->ptcaches = ob->soft->shared->ptcaches;
1818                         writestruct(wd, DATA, SoftBody, 1, ob->soft);
1819                         writestruct(wd, DATA, SoftBody_Shared, 1, ob->soft->shared);
1820                         write_pointcaches(wd, &(ob->soft->shared->ptcaches));
1821                         writestruct(wd, DATA, EffectorWeights, 1, ob->soft->effector_weights);
1822                 }
1823
1824                 if (ob->rigidbody_object) {
1825                         /* TODO: if any extra data is added to handle duplis, will need separate function then */
1826                         writestruct(wd, DATA, RigidBodyOb, 1, ob->rigidbody_object);
1827                 }
1828                 if (ob->rigidbody_constraint) {
1829                         writestruct(wd, DATA, RigidBodyCon, 1, ob->rigidbody_constraint);
1830                 }
1831
1832                 if (ob->type == OB_EMPTY && ob->empty_drawtype == OB_EMPTY_IMAGE) {
1833                         writestruct(wd, DATA, ImageUser, 1, ob->iuser);
1834                 }
1835
1836                 write_particlesystems(wd, &ob->particlesystem);
1837                 write_modifiers(wd, &ob->modifiers);
1838
1839                 writelist(wd, DATA, LinkData, &ob->pc_ids);
1840                 writelist(wd, DATA, LodLevel, &ob->lodlevels);
1841
1842                 write_previews(wd, ob->preview);
1843         }
1844 }
1845
1846
1847 static void write_vfont(WriteData *wd, VFont *vf)
1848 {
1849         if (vf->id.us > 0 || wd->use_memfile) {
1850                 /* write LibData */
1851                 writestruct(wd, ID_VF, VFont, 1, vf);
1852                 write_iddata(wd, &vf->id);
1853
1854                 /* direct data */
1855                 if (vf->packedfile) {
1856                         PackedFile *pf = vf->packedfile;
1857                         writestruct(wd, DATA, PackedFile, 1, pf);
1858                         writedata(wd, DATA, pf->size, pf->data);
1859                 }
1860         }
1861 }
1862
1863
1864 static void write_key(WriteData *wd, Key *key)
1865 {
1866         if (key->id.us > 0 || wd->use_memfile) {
1867                 /* write LibData */
1868                 writestruct(wd, ID_KE, Key, 1, key);
1869                 write_iddata(wd, &key->id);
1870
1871                 if (key->adt) {
1872                         write_animdata(wd, key->adt);
1873                 }
1874
1875                 /* direct data */
1876                 for (KeyBlock *kb = key->block.first; kb; kb = kb->next) {
1877                         writestruct(wd, DATA, KeyBlock, 1, kb);
1878                         if (kb->data) {
1879                                 writedata(wd, DATA, kb->totelem * key->elemsize, kb->data);
1880                         }
1881                 }
1882         }
1883 }
1884
1885 static void write_camera(WriteData *wd, Camera *cam)
1886 {
1887         if (cam->id.us > 0 || wd->use_memfile) {
1888                 /* write LibData */
1889                 writestruct(wd, ID_CA, Camera, 1, cam);
1890                 write_iddata(wd, &cam->id);
1891
1892                 if (cam->adt) {
1893                         write_animdata(wd, cam->adt);
1894                 }
1895
1896                 for (CameraBGImage *bgpic = cam->bg_images.first; bgpic; bgpic = bgpic->next) {
1897                         writestruct(wd, DATA, CameraBGImage, 1, bgpic);
1898                 }
1899         }
1900 }
1901
1902 static void write_mball(WriteData *wd, MetaBall *mb)
1903 {
1904         if (mb->id.us > 0 || wd->use_memfile) {
1905                 /* write LibData */
1906                 writestruct(wd, ID_MB, MetaBall, 1, mb);
1907                 write_iddata(wd, &mb->id);
1908
1909                 /* direct data */
1910                 writedata(wd, DATA, sizeof(void *) * mb->totcol, mb->mat);
1911                 if (mb->adt) {
1912                         write_animdata(wd, mb->adt);
1913                 }
1914
1915                 for (MetaElem *ml = mb->elems.first; ml; ml = ml->next) {
1916                         writestruct(wd, DATA, MetaElem, 1, ml);
1917                 }
1918         }
1919 }
1920
1921 static void write_curve(WriteData *wd, Curve *cu)
1922 {
1923         if (cu->id.us > 0 || wd->use_memfile) {
1924                 /* write LibData */
1925                 writestruct(wd, ID_CU, Curve, 1, cu);
1926                 write_iddata(wd, &cu->id);
1927
1928                 /* direct data */
1929                 writedata(wd, DATA, sizeof(void *) * cu->totcol, cu->mat);
1930                 if (cu->adt) {
1931                         write_animdata(wd, cu->adt);
1932                 }
1933
1934                 if (cu->vfont) {
1935                         writedata(wd, DATA, cu->len + 1, cu->str);
1936                         writestruct(wd, DATA, CharInfo, cu->len_wchar + 1, cu->strinfo);
1937                         writestruct(wd, DATA, TextBox, cu->totbox, cu->tb);
1938                 }
1939                 else {
1940                         /* is also the order of reading */
1941                         for (Nurb *nu = cu->nurb.first; nu; nu = nu->next) {
1942                                 writestruct(wd, DATA, Nurb, 1, nu);
1943                         }
1944                         for (Nurb *nu = cu->nurb.first; nu; nu = nu->next) {
1945                                 if (nu->type == CU_BEZIER) {
1946                                         writestruct(wd, DATA, BezTriple, nu->pntsu, nu->bezt);
1947                                 }
1948                                 else {
1949                                         writestruct(wd, DATA, BPoint, nu->pntsu * nu->pntsv, nu->bp);
1950                                         if (nu->knotsu) {
1951                                                 writedata(wd, DATA, KNOTSU(nu) * sizeof(float), nu->knotsu);
1952                                         }
1953                                         if (nu->knotsv) {
1954                                                 writedata(wd, DATA, KNOTSV(nu) * sizeof(float), nu->knotsv);
1955                                         }
1956                                 }
1957                         }
1958                 }
1959         }
1960 }
1961
1962 static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
1963 {
1964         if (dvlist) {
1965
1966                 /* Write the dvert list */
1967                 writestruct(wd, DATA, MDeformVert, count, dvlist);
1968
1969                 /* Write deformation data for each dvert */
1970                 for (int i = 0; i < count; i++) {
1971                         if (dvlist[i].dw) {
1972                                 writestruct(wd, DATA, MDeformWeight, dvlist[i].totweight, dvlist[i].dw);
1973                         }
1974                 }
1975         }
1976 }
1977
1978 static void write_mdisps(WriteData *wd, int count, MDisps *mdlist, int external)
1979 {
1980         if (mdlist) {
1981                 int i;
1982
1983                 writestruct(wd, DATA, MDisps, count, mdlist);
1984                 for (i = 0; i < count; ++i) {
1985                         MDisps *md = &mdlist[i];
1986                         if (md->disps) {
1987                                 if (!external) {
1988                                         writedata(wd, DATA, sizeof(float) * 3 * md->totdisp, md->disps);
1989                                 }
1990                         }
1991
1992                         if (md->hidden) {
1993                                 writedata(wd, DATA, BLI_BITMAP_SIZE(md->totdisp), md->hidden);
1994                         }
1995                 }
1996         }
1997 }
1998
1999 static void write_grid_paint_mask(WriteData *wd, int count, GridPaintMask *grid_paint_mask)
2000 {
2001         if (grid_paint_mask) {
2002                 int i;
2003
2004                 writestruct(wd, DATA, GridPaintMask, count, grid_paint_mask);
2005                 for (i = 0; i < count; ++i) {
2006                         GridPaintMask *gpm = &grid_paint_mask[i];
2007                         if (gpm->data) {
2008                                 const int gridsize = BKE_ccg_gridsize(gpm->level);
2009                                 writedata(wd, DATA,
2010                                           sizeof(*gpm->data) * gridsize * gridsize,
2011                                           gpm->data);
2012                         }
2013                 }
2014         }
2015 }
2016
2017 static void write_customdata(
2018         WriteData *wd, ID *id, int count, CustomData *data, CustomDataLayer *layers,
2019         int partial_type, int partial_count)
2020 {
2021         int i;
2022
2023         /* write external customdata (not for undo) */
2024         if (data->external && (wd->use_memfile == false)) {
2025                 CustomData_external_write(data, id, CD_MASK_MESH, count, 0);
2026         }
2027
2028         writestruct_at_address(wd, DATA, CustomDataLayer, data->totlayer, data->layers, layers);
2029
2030         for (i = 0; i < data->totlayer; i++) {
2031                 CustomDataLayer *layer = &layers[i];
2032                 const char *structname;
2033                 int structnum, datasize;
2034
2035                 if (layer->type == CD_MDEFORMVERT) {
2036                         /* layer types that allocate own memory need special handling */
2037                         write_dverts(wd, count, layer->data);
2038                 }
2039                 else if (layer->type == CD_MDISPS) {
2040                         write_mdisps(wd, count, layer->data, layer->flag & CD_FLAG_EXTERNAL);
2041                 }
2042                 else if (layer->type == CD_PAINT_MASK) {
2043                         const float *layer_data = layer->data;
2044                         writedata(wd, DATA, sizeof(*layer_data) * count, layer_data);
2045                 }
2046                 else if (layer->type == CD_GRID_PAINT_MASK) {
2047                         write_grid_paint_mask(wd, count, layer->data);
2048                 }
2049                 else if (layer->type == CD_FACEMAP) {
2050                         const int *layer_data = layer->data;
2051                         writedata(wd, DATA, sizeof(*layer_data) * count, layer_data);
2052                 }
2053                 else {
2054                         CustomData_file_write_info(layer->type, &structname, &structnum);
2055                         if (structnum) {
2056                                 /* when using partial visibility, the MEdge and MFace layers
2057                                  * are smaller than the original, so their type and count is
2058                                  * passed to make this work */
2059                                 if (layer->type != partial_type) {
2060                                         datasize = structnum * count;
2061                                 }
2062                                 else {
2063                                         datasize = structnum * partial_count;
2064                                 }
2065
2066                                 writestruct_id(wd, DATA, structname, datasize, layer->data);
2067                         }
2068                         else {
2069                                 printf("%s error: layer '%s':%d - can't be written to file\n",
2070                                        __func__, structname, layer->type);
2071                         }
2072                 }
2073         }
2074
2075         if (data->external) {
2076                 writestruct(wd, DATA, CustomDataExternal, 1, data->external);
2077         }
2078 }
2079
2080 static void write_mesh(WriteData *wd, Mesh *mesh)
2081 {
2082         CustomDataLayer *vlayers = NULL, vlayers_buff[CD_TEMP_CHUNK_SIZE];
2083         CustomDataLayer *elayers = NULL, elayers_buff[CD_TEMP_CHUNK_SIZE];
2084         CustomDataLayer *flayers = NULL, flayers_buff[CD_TEMP_CHUNK_SIZE];
2085         CustomDataLayer *llayers = NULL, llayers_buff[CD_TEMP_CHUNK_SIZE];
2086         CustomDataLayer *players = NULL, players_buff[CD_TEMP_CHUNK_SIZE];
2087
2088         if (mesh->id.us > 0 || wd->use_memfile) {
2089                 /* write LibData */
2090                 {
2091                         /* write a copy of the mesh, don't modify in place because it is
2092                          * not thread safe for threaded renders that are reading this */
2093                         Mesh *old_mesh = mesh;
2094                         Mesh copy_mesh = *mesh;
2095                         mesh = &copy_mesh;
2096
2097                         /* cache only - don't write */
2098                         mesh->mface = NULL;
2099                         mesh->totface = 0;
2100                         memset(&mesh->fdata, 0, sizeof(mesh->fdata));
2101
2102                         /**
2103                          * Those calls:
2104                          *   - Reduce mesh->xdata.totlayer to number of layers to write.
2105                          *   - Fill xlayers with those layers to be written.
2106                          * Note that mesh->xdata is from now on invalid for Blender, but this is why the whole mesh is
2107                          * a temp local copy!
2108                          */
2109                         CustomData_file_write_prepare(&mesh->vdata, &vlayers, vlayers_buff, ARRAY_SIZE(vlayers_buff));
2110                         CustomData_file_write_prepare(&mesh->edata, &elayers, elayers_buff, ARRAY_SIZE(elayers_buff));
2111                         flayers = flayers_buff;
2112                         CustomData_file_write_prepare(&mesh->ldata, &llayers, llayers_buff, ARRAY_SIZE(llayers_buff));
2113                         CustomData_file_write_prepare(&mesh->pdata, &players, players_buff, ARRAY_SIZE(players_buff));
2114
2115                         writestruct_at_address(wd, ID_ME, Mesh, 1, old_mesh, mesh);
2116                         write_iddata(wd, &mesh->id);
2117
2118                         /* direct data */
2119                         if (mesh->adt) {
2120                                 write_animdata(wd, mesh->adt);
2121                         }
2122
2123                         writedata(wd, DATA, sizeof(void *) * mesh->totcol, mesh->mat);
2124                         writedata(wd, DATA, sizeof(MSelect) * mesh->totselect, mesh->mselect);
2125
2126                         write_customdata(wd, &mesh->id, mesh->totvert, &mesh->vdata, vlayers, -1, 0);
2127                         write_customdata(wd, &mesh->id, mesh->totedge, &mesh->edata, elayers, -1, 0);
2128                         /* fdata is really a dummy - written so slots align */
2129                         write_customdata(wd, &mesh->id, mesh->totface, &mesh->fdata, flayers, -1, 0);
2130                         write_customdata(wd, &mesh->id, mesh->totloop, &mesh->ldata, llayers, -1, 0);
2131                         write_customdata(wd, &mesh->id, mesh->totpoly, &mesh->pdata, players, -1, 0);
2132
2133                         /* restore pointer */
2134                         mesh = old_mesh;
2135                 }
2136         }
2137
2138         if (vlayers && vlayers != vlayers_buff) {
2139                 MEM_freeN(vlayers);
2140         }
2141         if (elayers && elayers != elayers_buff) {
2142                 MEM_freeN(elayers);
2143         }
2144         if (flayers && flayers != flayers_buff) {
2145                 MEM_freeN(flayers);
2146         }
2147         if (llayers && llayers != llayers_buff) {
2148                 MEM_freeN(llayers);
2149         }
2150         if (players && players != players_buff) {
2151                 MEM_freeN(players);
2152         }
2153 }
2154
2155 static void write_lattice(WriteData *wd, Lattice *lt)
2156 {
2157         if (lt->id.us > 0 || wd->use_memfile) {
2158                 /* write LibData */
2159                 writestruct(wd, ID_LT, Lattice, 1, lt);
2160                 write_iddata(wd, &lt->id);
2161
2162                 /* write animdata */
2163                 if (lt->adt) {
2164                         write_animdata(wd, lt->adt);
2165                 }
2166
2167                 /* direct data */
2168                 writestruct(wd, DATA, BPoint, lt->pntsu * lt->pntsv * lt->pntsw, lt->def);
2169
2170                 write_dverts(wd, lt->pntsu * lt->pntsv * lt->pntsw, lt->dvert);
2171         }
2172 }
2173
2174 static void write_image(WriteData *wd, Image *ima)
2175 {
2176         if (ima->id.us > 0 || wd->use_memfile) {
2177                 ImagePackedFile *imapf;
2178
2179                 /* Some trickery to keep forward compatibility of packed images. */
2180                 BLI_assert(ima->packedfile == NULL);
2181                 if (ima->packedfiles.first != NULL) {
2182                         imapf = ima->packedfiles.first;
2183                         ima->packedfile = imapf->packedfile;
2184                 }
2185
2186                 /* write LibData */
2187                 writestruct(wd, ID_IM, Image, 1, ima);
2188                 write_iddata(wd, &ima->id);
2189
2190                 for (imapf = ima->packedfiles.first; imapf; imapf = imapf->next) {
2191                         writestruct(wd, DATA, ImagePackedFile, 1, imapf);
2192                         if (imapf->packedfile) {
2193                                 PackedFile *pf = imapf->packedfile;
2194                                 writestruct(wd, DATA, PackedFile, 1, pf);
2195                                 writedata(wd, DATA, pf->size, pf->data);
2196                         }
2197                 }
2198
2199                 write_previews(wd, ima->preview);
2200
2201                 for (ImageView *iv = ima->views.first; iv; iv = iv->next) {
2202                         writestruct(wd, DATA, ImageView, 1, iv);
2203                 }
2204                 writestruct(wd, DATA, Stereo3dFormat, 1, ima->stereo3d_format);
2205
2206                 ima->packedfile = NULL;
2207
2208                 writelist(wd, DATA, RenderSlot, &ima->renderslots);
2209         }
2210 }
2211
2212 static void write_texture(WriteData *wd, Tex *tex)
2213 {
2214         if (tex->id.us > 0 || wd->use_memfile) {
2215                 /* write LibData */
2216                 writestruct(wd, ID_TE, Tex, 1, tex);
2217                 write_iddata(wd, &tex->id);
2218
2219                 if (tex->adt) {
2220                         write_animdata(wd, tex->adt);
2221                 }
2222
2223                 /* direct data */
2224                 if (tex->coba) {
2225                         writestruct(wd, DATA, ColorBand, 1, tex->coba);
2226                 }
2227
2228                 /* nodetree is integral part of texture, no libdata */
2229                 if (tex->nodetree) {
2230                         writestruct(wd, DATA, bNodeTree, 1, tex->nodetree);
2231                         write_nodetree_nolib(wd, tex->nodetree);
2232                 }
2233
2234                 write_previews(wd, tex->preview);
2235         }
2236 }
2237
2238 static void write_material(WriteData *wd, Material *ma)
2239 {
2240         if (ma->id.us > 0 || wd->use_memfile) {
2241                 /* write LibData */
2242                 writestruct(wd, ID_MA, Material, 1, ma);
2243                 write_iddata(wd, &ma->id);
2244
2245                 if (ma->adt) {
2246                         write_animdata(wd, ma->adt);
2247                 }
2248
2249                 /* nodetree is integral part of material, no libdata */
2250                 if (ma->nodetree) {
2251                         writestruct(wd, DATA, bNodeTree, 1, ma->nodetree);
2252                         write_nodetree_nolib(wd, ma->nodetree);
2253                 }
2254
2255                 write_previews(wd, ma->preview);
2256         }
2257 }
2258
2259 static void write_world(WriteData *wd, World *wrld)
2260 {
2261         if (wrld->id.us > 0 || wd->use_memfile) {
2262                 /* write LibData */
2263                 writestruct(wd, ID_WO, World, 1, wrld);
2264                 write_iddata(wd, &wrld->id);
2265
2266                 if (wrld->adt) {
2267                         write_animdata(wd, wrld->adt);
2268                 }
2269
2270                 /* nodetree is integral part of world, no libdata */
2271                 if (wrld->nodetree) {
2272                         writestruct(wd, DATA, bNodeTree, 1, wrld->nodetree);
2273                         write_nodetree_nolib(wd, wrld->nodetree);
2274                 }
2275
2276                 write_previews(wd, wrld->preview);
2277         }
2278 }
2279
2280 static void write_lamp(WriteData *wd, Lamp *la)
2281 {
2282         if (la->id.us > 0 || wd->use_memfile) {
2283                 /* write LibData */
2284                 writestruct(wd, ID_LA, Lamp, 1, la);
2285                 write_iddata(wd, &la->id);
2286
2287                 if (la->adt) {
2288                         write_animdata(wd, la->adt);
2289                 }
2290
2291                 if (la->curfalloff) {
2292                         write_curvemapping(wd, la->curfalloff);
2293                 }
2294
2295                 /* nodetree is integral part of lamps, no libdata */
2296                 if (la->nodetree) {
2297                         writestruct(wd, DATA, bNodeTree, 1, la->nodetree);
2298                         write_nodetree_nolib(wd, la->nodetree);
2299                 }
2300
2301                 write_previews(wd, la->preview);
2302         }
2303 }
2304
2305 static void write_collection_nolib(WriteData *wd, Collection *collection)
2306 {
2307         /* Shared function for collection datablocks and scene master collection. */
2308         write_previews(wd, collection->preview);
2309
2310         for (CollectionObject *cob = collection->gobject.first; cob; cob = cob->next) {
2311                 writestruct(wd, DATA, CollectionObject, 1, cob);
2312         }
2313
2314         for (CollectionChild *child = collection->children.first; child; child = child->next) {
2315                 writestruct(wd, DATA, CollectionChild, 1, child);
2316         }
2317 }
2318
2319 static void write_collection(WriteData *wd, Collection *collection)
2320 {
2321         if (collection->id.us > 0 || wd->use_memfile) {
2322                 /* write LibData */
2323                 writestruct(wd, ID_GR, Collection, 1, collection);
2324                 write_iddata(wd, &collection->id);
2325
2326                 write_collection_nolib(wd, collection);
2327         }
2328 }
2329
2330 static void write_sequence_modifiers(WriteData *wd, ListBase *modbase)
2331 {
2332         SequenceModifierData *smd;
2333
2334         for (smd = modbase->first; smd; smd = smd->next) {
2335                 const SequenceModifierTypeInfo *smti = BKE_sequence_modifier_type_info_get(smd->type);
2336
2337                 if (smti) {
2338                         writestruct_id(wd, DATA, smti->struct_name, 1, smd);
2339
2340                         if (smd->type == seqModifierType_Curves) {
2341                                 CurvesModifierData *cmd = (CurvesModifierData *)smd;
2342
2343                                 write_curvemapping(wd, &cmd->curve_mapping);
2344                         }
2345                         else if (smd->type == seqModifierType_HueCorrect) {
2346                                 HueCorrectModifierData *hcmd = (HueCorrectModifierData *)smd;
2347
2348                                 write_curvemapping(wd, &hcmd->curve_mapping);
2349                         }
2350                 }
2351                 else {
2352                         writestruct(wd, DATA, SequenceModifierData, 1, smd);
2353                 }
2354         }
2355 }
2356
2357 static void write_view_settings(WriteData *wd, ColorManagedViewSettings *view_settings)
2358 {
2359         if (view_settings->curve_mapping) {
2360                 write_curvemapping(wd, view_settings->curve_mapping);
2361         }
2362 }
2363
2364 static void write_paint(WriteData *wd, Paint *p)
2365 {
2366         if (p->cavity_curve) {
2367                 write_curvemapping(wd, p->cavity_curve);
2368         }
2369 }
2370
2371 static void write_layer_collections(WriteData *wd, ListBase *lb)
2372 {
2373         for (LayerCollection *lc = lb->first; lc; lc = lc->next) {
2374                 writestruct(wd, DATA, LayerCollection, 1, lc);
2375
2376                 write_layer_collections(wd, &lc->layer_collections);
2377         }
2378 }
2379
2380 static void write_view_layer(WriteData *wd, ViewLayer *view_layer)
2381 {
2382         writestruct(wd, DATA, ViewLayer, 1, view_layer);
2383         writelist(wd, DATA, Base, &view_layer->object_bases);
2384
2385         if (view_layer->id_properties) {
2386                 IDP_WriteProperty(view_layer->id_properties, wd);
2387         }
2388
2389         for (FreestyleModuleConfig *fmc = view_layer->freestyle_config.modules.first; fmc; fmc = fmc->next) {
2390                 writestruct(wd, DATA, FreestyleModuleConfig, 1, fmc);
2391         }
2392
2393         for (FreestyleLineSet *fls = view_layer->freestyle_config.linesets.first; fls; fls = fls->next) {
2394                 writestruct(wd, DATA, FreestyleLineSet, 1, fls);
2395         }
2396         write_layer_collections(wd, &view_layer->layer_collections);
2397 }
2398
2399 static void write_lightcache_texture(WriteData *wd, LightCacheTexture *tex)
2400 {
2401         if (tex->data) {
2402                 size_t data_size = tex->components * tex->tex_size[0] * tex->tex_size[1] * tex->tex_size[2];
2403                 if (tex->data_type == LIGHTCACHETEX_FLOAT) {
2404                         data_size *= sizeof(float);
2405                 }
2406                 else if (tex->data_type == LIGHTCACHETEX_UINT) {
2407                         data_size *= sizeof(unsigned int);
2408                 }
2409                 writedata(wd, DATA, data_size, tex->data);
2410         }
2411 }
2412
2413 static void write_lightcache(WriteData *wd, LightCache *cache)
2414 {
2415         write_lightcache_texture(wd, &cache->grid_tx);
2416         write_lightcache_texture(wd, &cache->cube_tx);
2417
2418         if (cache->cube_mips) {
2419                 writestruct(wd, DATA, LightCacheTexture, cache->mips_len, cache->cube_mips);
2420                 for (int i = 0; i < cache->mips_len; ++i) {
2421                         write_lightcache_texture(wd, &cache->cube_mips[i]);
2422                 }
2423         }
2424
2425         writestruct(wd, DATA, LightGridCache,    cache->grid_len, cache->grid_data);
2426         writestruct(wd, DATA, LightProbeCache,   cache->cube_len, cache->cube_data);
2427 }
2428
2429 static void write_scene(WriteData *wd, Scene *sce)
2430 {
2431         /* write LibData */
2432         writestruct(wd, ID_SCE, Scene, 1, sce);
2433         write_iddata(wd, &sce->id);
2434
2435         if (sce->adt) {
2436                 write_animdata(wd, sce->adt);
2437         }
2438         write_keyingsets(wd, &sce->keyingsets);
2439
2440         /* direct data */
2441         ToolSettings *tos = sce->toolsettings;
2442         writestruct(wd, DATA, ToolSettings, 1, tos);
2443         if (tos->vpaint) {
2444                 writestruct(wd, DATA, VPaint, 1, tos->vpaint);
2445                 write_paint(wd, &tos->vpaint->paint);
2446         }
2447         if (tos->wpaint) {
2448                 writestruct(wd, DATA, VPaint, 1, tos->wpaint);
2449                 write_paint(wd, &tos->wpaint->paint);
2450         }
2451         if (tos->sculpt) {
2452                 writestruct(wd, DATA, Sculpt, 1, tos->sculpt);
2453                 write_paint(wd, &tos->sculpt->paint);
2454         }
2455         if (tos->uvsculpt) {
2456                 writestruct(wd, DATA, UvSculpt, 1, tos->uvsculpt);
2457                 write_paint(wd, &tos->uvsculpt->paint);
2458         }
2459         /* write grease-pencil drawing brushes to file */
2460         writelist(wd, DATA, bGPDbrush, &tos->gp_brushes);
2461         for (bGPDbrush *brush = tos->gp_brushes.first; brush; brush = brush->next) {
2462                 if (brush->cur_sensitivity) {
2463                         write_curvemapping(wd, brush->cur_sensitivity);
2464                 }
2465                 if (brush->cur_strength) {
2466                         write_curvemapping(wd, brush->cur_strength);
2467                 }
2468                 if (brush->cur_jitter) {
2469                         write_curvemapping(wd, brush->cur_jitter);
2470                 }
2471         }
2472         /* write grease-pencil custom ipo curve to file */
2473         if (tos->gp_interpolate.custom_ipo) {
2474                 write_curvemapping(wd, tos->gp_interpolate.custom_ipo);
2475         }
2476
2477
2478         write_paint(wd, &tos->imapaint.paint);
2479
2480         Editing *ed = sce->ed;
2481         if (ed) {
2482                 Sequence *seq;
2483
2484                 writestruct(wd, DATA, Editing, 1, ed);
2485
2486                 /* reset write flags too */
2487
2488                 SEQ_BEGIN(ed, seq)
2489                 {
2490                         if (seq->strip) {
2491                                 seq->strip->done = false;
2492                         }
2493                         writestruct(wd, DATA, Sequence, 1, seq);
2494                 }
2495                 SEQ_END
2496
2497                 SEQ_BEGIN(ed, seq)
2498                 {
2499                         if (seq->strip && seq->strip->done == 0) {
2500                                 /* write strip with 'done' at 0 because readfile */
2501
2502                                 if (seq->effectdata) {
2503                                         switch (seq->type) {
2504                                                 case SEQ_TYPE_COLOR:
2505                                                         writestruct(wd, DATA, SolidColorVars, 1, seq->effectdata);
2506                                                         break;
2507                                                 case SEQ_TYPE_SPEED:
2508                                                         writestruct(wd, DATA, SpeedControlVars, 1, seq->effectdata);
2509                                                         break;
2510                                                 case SEQ_TYPE_WIPE:
2511                                                         writestruct(wd, DATA, WipeVars, 1, seq->effectdata);
2512                                                         break;
2513                                                 case SEQ_TYPE_GLOW:
2514                                                         writestruct(wd, DATA, GlowVars, 1, seq->effectdata);
2515                                                         break;
2516                                                 case SEQ_TYPE_TRANSFORM:
2517                                                         writestruct(wd, DATA, TransformVars, 1, seq->effectdata);
2518                                                         break;
2519                                                 case SEQ_TYPE_GAUSSIAN_BLUR:
2520                                                         writestruct(wd, DATA, GaussianBlurVars, 1, seq->effectdata);
2521                                                         break;
2522                                                 case SEQ_TYPE_TEXT:
2523                                                         writestruct(wd, DATA, TextVars, 1, seq->effectdata);
2524                                                         break;
2525                                                 case SEQ_TYPE_COLORMIX:
2526                                                         writestruct(wd, DATA, ColorMixVars, 1, seq->effectdata);
2527                                                         break;
2528                                         }
2529                                 }
2530
2531                                 writestruct(wd, DATA, Stereo3dFormat, 1, seq->stereo3d_format);
2532
2533                                 Strip *strip = seq->strip;
2534                                 writestruct(wd, DATA, Strip, 1, strip);
2535                                 if (seq->flag & SEQ_USE_CROP && strip->crop) {
2536                                         writestruct(wd, DATA, StripCrop, 1, strip->crop);
2537                                 }
2538                                 if (seq->flag & SEQ_USE_TRANSFORM && strip->transform) {
2539                                         writestruct(wd, DATA, StripTransform, 1, strip->transform);
2540                                 }
2541                                 if (seq->flag & SEQ_USE_PROXY && strip->proxy) {
2542                                         writestruct(wd, DATA, StripProxy, 1, strip->proxy);
2543                                 }
2544                                 if (seq->type == SEQ_TYPE_IMAGE) {
2545                                         writestruct(wd, DATA, StripElem,
2546                                                     MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem),
2547                                                     strip->stripdata);
2548                                 }
2549                                 else if (ELEM(seq->type, SEQ_TYPE_MOVIE, SEQ_TYPE_SOUND_RAM, SEQ_TYPE_SOUND_HD)) {
2550                                         writestruct(wd, DATA, StripElem, 1, strip->stripdata);
2551                                 }
2552
2553                                 strip->done = true;
2554                         }
2555
2556                         if (seq->prop) {
2557                                 IDP_WriteProperty(seq->prop, wd);
2558                         }
2559
2560                         write_sequence_modifiers(wd, &seq->modifiers);
2561                 }
2562                 SEQ_END
2563
2564                 /* new; meta stack too, even when its nasty restore code */
2565                 for (MetaStack *ms = ed->metastack.first; ms; ms = ms->next) {
2566                         writestruct(wd, DATA, MetaStack, 1, ms);
2567                 }
2568         }
2569
2570         if (sce->r.avicodecdata) {
2571                 writestruct(wd, DATA, AviCodecData, 1, sce->r.avicodecdata);
2572                 if (sce->r.avicodecdata->lpFormat) {
2573                         writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
2574                 }
2575                 if (sce->r.avicodecdata->lpParms) {
2576                         writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
2577                 }
2578         }
2579         if (sce->r.ffcodecdata.properties) {
2580                 IDP_WriteProperty(sce->r.ffcodecdata.properties, wd);
2581         }
2582
2583         /* writing dynamic list of TimeMarkers to the blend file */
2584         for (TimeMarker *marker = sce->markers.first; marker; marker = marker->next) {
2585                 writestruct(wd, DATA, TimeMarker, 1, marker);
2586         }
2587
2588         /* writing dynamic list of TransformOrientations to the blend file */
2589         for (TransformOrientation *ts = sce->transform_spaces.first; ts; ts = ts->next) {
2590                 writestruct(wd, DATA, TransformOrientation, 1, ts);
2591         }
2592
2593         /* writing MultiView to the blend file */
2594         for (SceneRenderView *srv = sce->r.views.first; srv; srv = srv->next) {
2595                 writestruct(wd, DATA, SceneRenderView, 1, srv);
2596         }
2597
2598         if (sce->nodetree) {
2599                 writestruct(wd, DATA, bNodeTree, 1, sce->nodetree);
2600                 write_nodetree_nolib(wd, sce->nodetree);
2601         }
2602
2603         write_view_settings(wd, &sce->view_settings);
2604
2605         /* writing RigidBodyWorld data to the blend file */
2606         if (sce->rigidbody_world) {
2607                 /* Set deprecated pointers to prevent crashes of older Blenders */
2608                 sce->rigidbody_world->pointcache = sce->rigidbody_world->shared->pointcache;
2609                 sce->rigidbody_world->ptcaches = sce->rigidbody_world->shared->ptcaches;
2610                 writestruct(wd, DATA, RigidBodyWorld, 1, sce->rigidbody_world);
2611
2612                 writestruct(wd, DATA, RigidBodyWorld_Shared, 1, sce->rigidbody_world->shared);
2613                 writestruct(wd, DATA, EffectorWeights, 1, sce->rigidbody_world->effector_weights);
2614                 write_pointcaches(wd, &(sce->rigidbody_world->shared->ptcaches));
2615         }
2616
2617         write_previews(wd, sce->preview);
2618         write_curvemapping_curves(wd, &sce->r.mblur_shutter_curve);
2619
2620         for (ViewLayer *view_layer = sce->view_layers.first; view_layer; view_layer = view_layer->next) {
2621                 write_view_layer(wd, view_layer);
2622         }
2623
2624         if (sce->master_collection) {
2625                 writestruct(wd, DATA, Collection, 1, sce->master_collection);
2626                 write_collection_nolib(wd, sce->master_collection);
2627         }
2628
2629         /* Eevee Lightcache */
2630         if (sce->eevee.light_cache && !wd->use_memfile) {
2631                 writestruct(wd, DATA, LightCache, 1, sce->eevee.light_cache);
2632                 write_lightcache(wd, sce->eevee.light_cache);
2633         }
2634
2635         /* Freed on doversion. */
2636         BLI_assert(sce->layer_properties == NULL);
2637 }
2638
2639 static void write_gpencil(WriteData *wd, bGPdata *gpd)
2640 {
2641         if (gpd->id.us > 0 || wd->use_memfile) {
2642                 /* write gpd data block to file */
2643                 writestruct(wd, ID_GD, bGPdata, 1, gpd);
2644                 write_iddata(wd, &gpd->id);
2645
2646                 if (gpd->adt) {
2647                         write_animdata(wd, gpd->adt);
2648                 }
2649
2650                 /* write grease-pencil layers to file */
2651                 writelist(wd, DATA, bGPDlayer, &gpd->layers);
2652                 for (bGPDlayer *gpl = gpd->layers.first; gpl; gpl = gpl->next) {
2653                         /* write this layer's frames to file */
2654                         writelist(wd, DATA, bGPDframe, &gpl->frames);
2655                         for (bGPDframe *gpf = gpl->frames.first; gpf; gpf = gpf->next) {
2656                                 /* write strokes */
2657                                 writelist(wd, DATA, bGPDstroke, &gpf->strokes);
2658                                 for (bGPDstroke *gps = gpf->strokes.first; gps; gps = gps->next) {
2659                                         writestruct(wd, DATA, bGPDspoint, gps->totpoints, gps->points);
2660                                 }
2661                         }
2662                 }
2663
2664                 /* write grease-pencil palettes */
2665                 writelist(wd, DATA, bGPDpalette, &gpd->palettes);
2666                 for (bGPDpalette *palette = gpd->palettes.first; palette; palette = palette->next) {
2667                         writelist(wd, DATA, bGPDpalettecolor, &palette->colors);
2668                 }
2669         }
2670 }
2671
2672 static void write_region(WriteData *wd, ARegion *ar, int spacetype)
2673 {
2674         writestruct(wd, DATA, ARegion, 1, ar);
2675
2676         if (ar->regiondata) {
2677                 if (ar->flag & RGN_FLAG_TEMP_REGIONDATA) {
2678                         return;
2679                 }
2680
2681                 switch (spacetype) {
2682                         case SPACE_VIEW3D:
2683                                 if (ar->regiontype == RGN_TYPE_WINDOW) {
2684                                         RegionView3D *rv3d = ar->regiondata;
2685                                         writestruct(wd, DATA, RegionView3D, 1, rv3d);
2686
2687                                         if (rv3d->localvd) {
2688                                                 writestruct(wd, DATA, RegionView3D, 1, rv3d->localvd);
2689                                         }
2690                                         if (rv3d->clipbb) {
2691                                                 writestruct(wd, DATA, BoundBox, 1, rv3d->clipbb);
2692                                         }
2693
2694                                 }
2695                                 else
2696                                         printf("regiondata write missing!\n");
2697                                 break;
2698                         default:
2699                                 printf("regiondata write missing!\n");
2700                 }
2701         }
2702 }
2703
2704 static void write_uilist(WriteData *wd, uiList *ui_list)
2705 {
2706         writestruct(wd, DATA, uiList, 1, ui_list);
2707
2708         if (ui_list->properties) {
2709                 IDP_WriteProperty(ui_list->properties, wd);
2710         }
2711 }
2712
2713 static void write_soops(WriteData *wd, SpaceOops *so)
2714 {
2715         BLI_mempool *ts = so->treestore;
2716
2717         if (ts) {
2718                 SpaceOops so_flat = *so;
2719
2720                 int elems = BLI_mempool_len(ts);
2721                 /* linearize mempool to array */
2722                 TreeStoreElem *data = elems ? BLI_mempool_as_arrayN(ts, "TreeStoreElem") : NULL;
2723
2724                 if (data) {
2725                         /* In this block we use the memory location of the treestore
2726                          * but _not_ its data, the addresses in this case are UUID's,
2727                          * since we can't rely on malloc giving us different values each time.
2728                          */
2729                         TreeStore ts_flat = {0};
2730
2731                         /* we know the treestore is at least as big as a pointer,
2732                          * so offsetting works to give us a UUID. */
2733                         void *data_addr = (void *)POINTER_OFFSET(ts, sizeof(void *));
2734
2735                         ts_flat.usedelem = elems;
2736                         ts_flat.totelem = elems;
2737                         ts_flat.data = data_addr;
2738
2739                         writestruct(wd, DATA, SpaceOops, 1, so);
2740
2741                         writestruct_at_address(wd, DATA, TreeStore, 1, ts, &ts_flat);
2742                         writestruct_at_address(wd, DATA, TreeStoreElem, elems, data_addr, data);
2743
2744                         MEM_freeN(data);
2745                 }
2746                 else {
2747                         so_flat.treestore = NULL;
2748                         writestruct_at_address(wd, DATA, SpaceOops, 1, so, &so_flat);
2749                 }
2750         }
2751         else {
2752                 writestruct(wd, DATA, SpaceOops, 1, so);
2753         }
2754 }
2755
2756 static void write_panel_list(WriteData *wd, ListBase *lb)
2757 {
2758         for (Panel *pa = lb->first; pa; pa = pa->next) {
2759                 writestruct(wd, DATA, Panel, 1, pa);
2760                 write_panel_list(wd, &pa->children);
2761         }
2762 }
2763
2764 static void write_area_regions(WriteData *wd, ScrArea *area)
2765 {
2766         for (ARegion *region = area->regionbase.first; region; region = region->next) {
2767                 write_region(wd, region, area->spacetype);
2768                 write_panel_list(wd, &region->panels);
2769
2770                 for (PanelCategoryStack *pc_act = region->panels_category_active.first; pc_act; pc_act = pc_act->next) {
2771                         writestruct(wd, DATA, PanelCategoryStack, 1, pc_act);
2772                 }
2773
2774                 for (uiList *ui_list = region->ui_lists.first; ui_list; ui_list = ui_list->next) {
2775                         write_uilist(wd, ui_list);
2776                 }
2777
2778                 for (uiPreview *ui_preview = region->ui_previews.first; ui_preview; ui_preview = ui_preview->next) {
2779                         writestruct(wd, DATA, uiPreview, 1, ui_preview);
2780                 }
2781         }
2782
2783         for (SpaceLink *sl = area->spacedata.first; sl; sl = sl->next) {
2784                 for (ARegion *region = sl->regionbase.first; region; region = region->next) {
2785                         write_region(wd, region, sl->spacetype);
2786                 }
2787
2788                 if (sl->spacetype == SPACE_VIEW3D) {
2789                         View3D *v3d = (View3D *)sl;
2790                         writestruct(wd, DATA, View3D, 1, v3d);
2791
2792                         if (v3d->localvd) {
2793                                 writestruct(wd, DATA, View3D, 1, v3d->localvd);
2794                         }
2795
2796                         if (v3d->fx_settings.ssao) {
2797                                 writestruct(wd, DATA, GPUSSAOSettings, 1, v3d->fx_settings.ssao);
2798                         }
2799                         if (v3d->fx_settings.dof) {
2800                                 writestruct(wd, DATA, GPUDOFSettings, 1, v3d->fx_settings.dof);
2801                         }
2802                 }
2803                 else if (sl->spacetype == SPACE_IPO) {
2804                         SpaceIpo *sipo = (SpaceIpo *)sl;
2805                         ListBase tmpGhosts = sipo->ghostCurves;
2806
2807                         /* temporarily disable ghost curves when saving */
2808                         sipo->ghostCurves.first = sipo->ghostCurves.last = NULL;
2809
2810                         writestruct(wd, DATA, SpaceIpo, 1, sl);
2811                         if (sipo->ads) {
2812                                 writestruct(wd, DATA, bDopeSheet, 1, sipo->ads);
2813                         }
2814
2815                         /* reenable ghost curves */
2816                         sipo->ghostCurves = tmpGhosts;
2817                 }
2818                 else if (sl->spacetype == SPACE_BUTS) {
2819                         writestruct(wd, DATA, SpaceButs, 1, sl);
2820                 }
2821                 else if (sl->spacetype == SPACE_FILE) {
2822                         SpaceFile *sfile = (SpaceFile *)sl;
2823
2824                         writestruct(wd, DATA, SpaceFile, 1, sl);
2825                         if (sfile->params) {
2826                                 writestruct(wd, DATA, FileSelectParams, 1, sfile->params);
2827                         }
2828                 }
2829                 else if (sl->spacetype == SPACE_SEQ) {
2830                         writestruct(wd, DATA, SpaceSeq, 1, sl);
2831                 }
2832                 else if (sl->spacetype == SPACE_OUTLINER) {
2833                         SpaceOops *so = (SpaceOops *)sl;
2834                         write_soops(wd, so);
2835                 }
2836                 else if (sl->spacetype == SPACE_IMAGE) {
2837                         writestruct(wd, DATA, SpaceImage, 1, sl);
2838                 }
2839                 else if (sl->spacetype == SPACE_TEXT) {
2840                         writestruct(wd, DATA, SpaceText, 1, sl);
2841                 }
2842                 else if (sl->spacetype == SPACE_SCRIPT) {
2843                         SpaceScript *scr = (SpaceScript *)sl;
2844                         scr->but_refs = NULL;
2845                         writestruct(wd, DATA, SpaceScript, 1, sl);
2846                 }
2847                 else if (sl->spacetype == SPACE_ACTION) {
2848                         writestruct(wd, DATA, SpaceAction, 1, sl);
2849                 }
2850                 else if (sl->spacetype == SPACE_NLA) {
2851                         SpaceNla *snla = (SpaceNla *)sl;
2852
2853                         writestruct(wd, DATA, SpaceNla, 1, snla);
2854                         if (snla->ads) {
2855                                 writestruct(wd, DATA, bDopeSheet, 1, snla->ads);
2856                         }
2857                 }
2858                 else if (sl->spacetype == SPACE_NODE) {
2859                         SpaceNode *snode = (SpaceNode *)sl;
2860                         bNodeTreePath *path;
2861                         writestruct(wd, DATA, SpaceNode, 1, snode);
2862
2863                         for (path = snode->treepath.first; path; path = path->next) {
2864                                 writestruct(wd, DATA, bNodeTreePath, 1, path);
2865                         }
2866                 }
2867                 else if (sl->spacetype == SPACE_CONSOLE) {
2868                         SpaceConsole *con = (SpaceConsole *)sl;
2869                         ConsoleLine *cl;
2870
2871                         for (cl = con->history.first; cl; cl = cl->next) {
2872                                 /* 'len_alloc' is invalid on write, set from 'len' on read */
2873                                 writestruct(wd, DATA, ConsoleLine, 1, cl);
2874                                 writedata(wd, DATA, cl->len + 1, cl->line);
2875                         }
2876                         writestruct(wd, DATA, SpaceConsole, 1, sl);
2877                 }
2878 #ifdef WITH_GLOBAL_AREA_WRITING
2879                 else if (sl->spacetype == SPACE_TOPBAR) {
2880                         writestruct(wd, DATA, SpaceTopBar, 1, sl);
2881                 }
2882                 else if (sl->spacetype == SPACE_STATUSBAR) {
2883                         writestruct(wd, DATA, SpaceStatusBar, 1, sl);
2884                 }
2885 #endif
2886                 else if (sl->spacetype == SPACE_USERPREF) {
2887                         writestruct(wd, DATA, SpaceUserPref, 1, sl);
2888                 }
2889                 else if (sl->spacetype == SPACE_CLIP) {
2890                         writestruct(wd, DATA, SpaceClip, 1, sl);
2891                 }
2892                 else if (sl->spacetype == SPACE_INFO) {
2893                         writestruct(wd, DATA, SpaceInfo, 1, sl);
2894                 }
2895         }
2896 }
2897
2898 static void write_area_map(WriteData *wd, ScrAreaMap *area_map)
2899 {
2900         writelist(wd, DATA, ScrVert, &area_map->vertbase);
2901         writelist(wd, DATA, ScrEdge, &area_map->edgebase);
2902         for (ScrArea *area = area_map->areabase.first; area; area = area->next) {
2903                 area->butspacetype = area->spacetype; /* Just for compatibility, will be reset below. */
2904
2905                 writestruct(wd, DATA, ScrArea, 1, area);
2906
2907 #ifdef WITH_GLOBAL_AREA_WRITING
2908                 writestruct(wd, DATA, ScrGlobalAreaData, 1, area->global);
2909 #endif
2910
2911                 write_area_regions(wd, area);
2912
2913                 area->butspacetype = SPACE_EMPTY; /* Unset again, was changed above. */
2914         }
2915 }
2916
2917 static void write_windowmanager(WriteData *wd, wmWindowManager *wm)
2918 {
2919         writestruct(wd, ID_WM, wmWindowManager, 1, wm);
2920         write_iddata(wd, &wm->id);
2921
2922         for (wmWindow *win = wm->windows.first; win; win = win->next) {
2923 #ifndef WITH_GLOBAL_AREA_WRITING
2924                 /* Don't write global areas yet, while we make changes to them. */
2925                 ScrAreaMap global_areas = win->global_areas;
2926                 memset(&win->global_areas, 0, sizeof(win->global_areas));
2927 #endif
2928
2929                 /* update deprecated screen member (for so loading in 2.7x uses the correct screen) */
2930                 win->screen = BKE_workspace_active_screen_get(win->workspace_hook);
2931
2932                 writestruct(wd, DATA, wmWindow, 1, win);
2933                 writestruct(wd, DATA, WorkSpaceInstanceHook, 1, win->workspace_hook);
2934                 writestruct(wd, DATA, Stereo3dFormat, 1, win->stereo3d_format);
2935
2936 #ifdef WITH_GLOBAL_AREA_WRITING
2937                 write_area_map(wd, &win->global_areas);
2938 #else
2939                 win->global_areas = global_areas;
2940 #endif
2941
2942                 /* data is written, clear deprecated data again */
2943                 win->screen = NULL;
2944         }
2945 }
2946
2947 static void write_screen(WriteData *wd, bScreen *sc)
2948 {
2949         /* write LibData */
2950         /* in 2.50+ files, the file identifier for screens is patched, forward compatibility */
2951         writestruct(wd, ID_SCRN, bScreen, 1, sc);
2952         write_iddata(wd, &sc->id);
2953
2954         write_previews(wd, sc->preview);
2955
2956         /* direct data */
2957         write_area_map(wd, AREAMAP_FROM_SCREEN(sc));
2958 }
2959
2960 static void write_bone(WriteData *wd, Bone *bone)
2961 {
2962         /* PATCH for upward compatibility after 2.37+ armature recode */
2963         bone->size[0] = bone->size[1] = bone->size[2] = 1.0f;
2964
2965         /* Write this bone */
2966         writestruct(wd, DATA, Bone, 1, bone);
2967
2968         /* Write ID Properties -- and copy this comment EXACTLY for easy finding
2969          * of library blocks that implement this.*/
2970         if (bone->prop) {
2971                 IDP_WriteProperty(bone->prop, wd);
2972         }
2973
2974         /* Write Children */
2975         for (Bone *cbone = bone->childbase.first; cbone; cbone = cbone->next) {
2976                 write_bone(wd, cbone);
2977         }
2978 }
2979
2980 static void write_armature(WriteData *wd, bArmature *arm)
2981 {
2982         if (arm->id.us > 0 || wd->use_memfile) {
2983                 writestruct(wd, ID_AR, bArmature, 1, arm);
2984                 write_iddata(wd, &arm->id);
2985
2986                 if (arm->adt) {
2987                         write_animdata(wd, arm->adt);
2988                 }
2989
2990                 /* Direct data */
2991                 for (Bone *bone = arm->bonebase.first; bone; bone = bone->next) {
2992                         write_bone(wd, bone);
2993                 }
2994         }
2995 }
2996
2997 static void write_text(WriteData *wd, Text *text)
2998 {
2999         if ((text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) {
3000                 text->flags &= ~TXT_ISEXT;
3001         }
3002
3003         /* write LibData */
3004         writestruct(wd, ID_TXT, Text, 1, text);
3005         write_iddata(wd, &text->id);
3006
3007         if (text->name) {
3008                 writedata(wd, DATA, strlen(text->name) + 1, text->name);
3009         }
3010
3011         if (!(text->flags & TXT_ISEXT)) {
3012                 /* now write the text data, in two steps for optimization in the readfunction */
3013                 for (TextLine *tmp = text->lines.first; tmp; tmp = tmp->next) {
3014                         writestruct(wd, DATA, TextLine, 1, tmp);
3015                 }
3016
3017                 for (TextLine *tmp = text->lines.first; tmp; tmp = tmp->next) {
3018                         writedata(wd, DATA, tmp->len + 1, tmp->line);
3019                 }
3020         }
3021 }
3022
3023 static void write_speaker(WriteData *wd, Speaker *spk)
3024 {
3025         if (spk->id.us > 0 || wd->use_memfile) {
3026                 /* write LibData */
3027                 writestruct(wd, ID_SPK, Speaker, 1, spk);
3028                 write_iddata(wd, &spk->id);
3029
3030                 if (spk->adt) {
3031                         write_animdata(wd, spk->adt);
3032                 }
3033         }
3034 }
3035
3036 static void write_sound(WriteData *wd, bSound *sound)
3037 {
3038         if (sound->id.us > 0 || wd->use_memfile) {
3039                 /* write LibData */
3040                 writestruct(wd, ID_SO, bSound, 1, sound);
3041                 write_iddata(wd, &sound->id);
3042
3043                 if (sound->packedfile) {
3044                         PackedFile *pf = sound->packedfile;
3045                         writestruct(wd, DATA, PackedFile, 1, pf);
3046                         writedata(wd, DATA, pf->size, pf->data);
3047                 }
3048         }
3049 }
3050
3051 static void write_probe(WriteData *wd, LightProbe *prb)
3052 {
3053         if (prb->id.us > 0 || wd->use_memfile) {
3054                 /* write LibData */
3055                 writestruct(wd, ID_LP, LightProbe, 1, prb);
3056                 write_iddata(wd, &prb->id);
3057
3058                 if (prb->adt) {
3059                         write_animdata(wd, prb->adt);
3060                 }
3061         }
3062 }
3063
3064 static void write_nodetree(WriteData *wd, bNodeTree *ntree)
3065 {
3066         if (ntree->id.us > 0 || wd->use_memfile) {
3067                 writestruct(wd, ID_NT, bNodeTree, 1, ntree);
3068                 /* Note that trees directly used by other IDs (materials etc.) are not 'real' ID, they cannot
3069                  * be linked, etc., so we write actual id data here only, for 'real' ID trees. */
3070                 write_iddata(wd, &ntree->id);
3071
3072                 write_nodetree_nolib(wd, ntree);
3073         }
3074 }
3075
3076 #ifdef USE_NODE_COMPAT_CUSTOMNODES
3077 static void customnodes_add_deprecated_data(Main *mainvar)
3078 {
3079         FOREACH_NODETREE(mainvar, ntree, id) {
3080                 bNodeLink *link, *last_link = ntree->links.last;
3081
3082                 /* only do this for node groups */
3083                 if (id != &ntree->id) {
3084                         continue;
3085                 }
3086
3087                 /* Forward compatibility for group nodes: add links to node tree interface sockets.
3088                  * These links are invalid by new rules (missing node pointer)!
3089                  * They will be removed again in customnodes_free_deprecated_data,
3090                  * cannot do this directly lest bNodeLink pointer mapping becomes ambiguous.
3091                  * When loading files with such links in a new Blender version
3092                  * they will be removed as well.
3093                  */
3094                 for (link = ntree->links.first; link; link = link->next) {
3095                         bNode *fromnode = link->fromnode, *tonode = link->tonode;
3096                         bNodeSocket *fromsock = link->fromsock, *tosock = link->tosock;
3097
3098                         /* check both sides of the link, to handle direct input-to-output links */
3099                         if (fromnode->type == NODE_GROUP_INPUT) {
3100                                 fromnode = NULL;
3101                                 fromsock = ntreeFindSocketInterface(ntree, SOCK_IN, fromsock->identifier);
3102                         }
3103                         /* only the active output node defines links */
3104                         if (tonode->type == NODE_GROUP_OUTPUT && (tonode->flag & NODE_DO_OUTPUT)) {
3105                                 tonode = NULL;
3106                                 tosock = ntreeFindSocketInterface(ntree, SOCK_OUT, tosock->identifier);
3107                         }
3108
3109                         if (!fromnode || !tonode) {
3110                            &nb