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