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