Merging r48829 through r48861 from trunk into soc-2011-tomato
[blender.git] / source / blender / blenloader / intern / readfile.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
28 /** \file blender/blenloader/intern/readfile.c
29  *  \ingroup blenloader
30  */
31
32
33 #include "zlib.h"
34
35 #include <limits.h>
36 #include <stdio.h> // for printf fopen fwrite fclose sprintf FILE
37 #include <stdlib.h> // for getenv atoi
38 #include <stddef.h> // for offsetof
39 #include <fcntl.h> // for open
40 #include <string.h> // for strrchr strncmp strstr
41 #include <math.h> // for fabs
42 #include <stdarg.h> /* for va_start/end */
43
44 #ifndef WIN32
45 #  include <unistd.h> // for read close
46 #else
47 #  include <io.h> // for open close read
48 #  include "winsock2.h"
49 #  include "BLI_winstuff.h"
50 #endif
51
52 /* allow readfile to use deprecated functionality */
53 #define DNA_DEPRECATED_ALLOW
54
55 #include "DNA_anim_types.h"
56 #include "DNA_armature_types.h"
57 #include "DNA_actuator_types.h"
58 #include "DNA_brush_types.h"
59 #include "DNA_camera_types.h"
60 #include "DNA_cloth_types.h"
61 #include "DNA_controller_types.h"
62 #include "DNA_constraint_types.h"
63 #include "DNA_dynamicpaint_types.h"
64 #include "DNA_effect_types.h"
65 #include "DNA_fileglobal_types.h"
66 #include "DNA_genfile.h"
67 #include "DNA_group_types.h"
68 #include "DNA_gpencil_types.h"
69 #include "DNA_ipo_types.h"
70 #include "DNA_key_types.h"
71 #include "DNA_lattice_types.h"
72 #include "DNA_lamp_types.h"
73 #include "DNA_meta_types.h"
74 #include "DNA_material_types.h"
75 #include "DNA_mesh_types.h"
76 #include "DNA_meshdata_types.h"
77 #include "DNA_nla_types.h"
78 #include "DNA_node_types.h"
79 #include "DNA_object_fluidsim.h" // NT
80 #include "DNA_object_types.h"
81 #include "DNA_packedFile_types.h"
82 #include "DNA_particle_types.h"
83 #include "DNA_property_types.h"
84 #include "DNA_text_types.h"
85 #include "DNA_view3d_types.h"
86 #include "DNA_screen_types.h"
87 #include "DNA_sensor_types.h"
88 #include "DNA_sdna_types.h"
89 #include "DNA_scene_types.h"
90 #include "DNA_sequence_types.h"
91 #include "DNA_smoke_types.h"
92 #include "DNA_speaker_types.h"
93 #include "DNA_sound_types.h"
94 #include "DNA_space_types.h"
95 #include "DNA_vfont_types.h"
96 #include "DNA_world_types.h"
97 #include "DNA_movieclip_types.h"
98 #include "DNA_mask_types.h"
99
100 #include "MEM_guardedalloc.h"
101
102 #include "BLI_utildefines.h"
103 #include "BLI_blenlib.h"
104 #include "BLI_math.h"
105 #include "BLI_edgehash.h"
106
107 #include "BKE_anim.h"
108 #include "BKE_action.h"
109 #include "BKE_armature.h"
110 #include "BKE_brush.h"
111 #include "BKE_colortools.h"
112 #include "BKE_constraint.h"
113 #include "BKE_context.h"
114 #include "BKE_curve.h"
115 #include "BKE_deform.h"
116 #include "BKE_effect.h"
117 #include "BKE_fcurve.h"
118 #include "BKE_global.h" // for G
119 #include "BKE_group.h"
120 #include "BKE_image.h"
121 #include "BKE_lattice.h"
122 #include "BKE_library.h" // for which_libbase
123 #include "BKE_idcode.h"
124 #include "BKE_material.h"
125 #include "BKE_main.h" // for Main
126 #include "BKE_mesh.h" // for ME_ defines (patching)
127 #include "BKE_modifier.h"
128 #include "BKE_multires.h"
129 #include "BKE_node.h" // for tree type defines
130 #include "BKE_ocean.h"
131 #include "BKE_object.h"
132 #include "BKE_paint.h"
133 #include "BKE_particle.h"
134 #include "BKE_pointcache.h"
135 #include "BKE_property.h" // for get_ob_property
136 #include "BKE_report.h"
137 #include "BKE_sca.h" // for init_actuator
138 #include "BKE_scene.h"
139 #include "BKE_screen.h"
140 #include "BKE_sequencer.h"
141 #include "BKE_text.h" // for txt_extended_ascii_as_utf8
142 #include "BKE_tracking.h"
143 #include "BKE_utildefines.h" // SWITCH_INT DATA ENDB DNA1 O_BINARY GLOB USER TEST REND
144 #include "BKE_sound.h"
145
146 #include "IMB_imbuf.h"  // for proxy / timecode versioning stuff
147
148 #include "NOD_socket.h"
149
150 #include "BLO_readfile.h"
151 #include "BLO_undofile.h"
152
153 #include "RE_engine.h"
154
155 #include "readfile.h"
156
157 #include "PIL_time.h"
158
159 #include <errno.h>
160
161 /*
162  * Remark: still a weak point is the newaddress() function, that doesnt solve reading from
163  * multiple files at the same time
164  *
165  * (added remark: oh, i thought that was solved? will look at that... (ton)
166  *
167  * READ
168  * - Existing Library (Main) push or free
169  * - allocate new Main
170  * - load file
171  * - read SDNA
172  * - for each LibBlock
173  *     - read LibBlock
174  *     - if a Library
175  *         - make a new Main
176  *         - attach ID's to it
177  *     - else
178  *         - read associated 'direct data'
179  *         - link direct data (internal and to LibBlock)
180  * - read FileGlobal
181  * - read USER data, only when indicated (file is ~/X.XX/startup.blend)
182  * - free file
183  * - per Library (per Main)
184  *     - read file
185  *     - read SDNA
186  *     - find LibBlocks and attach IDs to Main
187  *         - if external LibBlock
188  *             - search all Main's
189  *                 - or it's already read,
190  *                 - or not read yet
191  *                 - or make new Main
192  *     - per LibBlock
193  *         - read recursive
194  *         - read associated direct data
195  *         - link direct data (internal and to LibBlock)
196  *     - free file
197  * - per Library with unread LibBlocks
198  *     - read file
199  *     - read SDNA
200  *     - per LibBlock
201  *                - read recursive
202  *                - read associated direct data
203  *                - link direct data (internal and to LibBlock)
204  *         - free file
205  * - join all Mains
206  * - link all LibBlocks and indirect pointers to libblocks
207  * - initialize FileGlobal and copy pointers to Global
208 */
209
210 /* also occurs in library.c */
211 /* GS reads the memory pointed at in a specific ordering. There are,
212  * however two definitions for it. I have jotted them down here, both,
213  * but I think the first one is actually used. The thing is that
214  * big-endian systems might read this the wrong way round. OTOH, we
215  * constructed the IDs that are read out with this macro explicitly as
216  * well. I expect we'll sort it out soon... */
217
218 /* from blendef: */
219 #define GS(a)   (*((short *)(a)))
220
221 /* from misc_util: flip the bytes from x  */
222 /*  #define GS(x) (((unsigned char *)(x))[0] << 8 | ((unsigned char *)(x))[1]) */
223
224 // only used here in readfile.c
225 #define SWITCH_LONGINT(a) { \
226         char s_i, *p_i; \
227         p_i= (char *)&(a);  \
228         s_i=p_i[0]; p_i[0]=p_i[7]; p_i[7]=s_i; \
229         s_i=p_i[1]; p_i[1]=p_i[6]; p_i[6]=s_i; \
230         s_i=p_i[2]; p_i[2]=p_i[5]; p_i[5]=s_i; \
231         s_i=p_i[3]; p_i[3]=p_i[4]; p_i[4]=s_i; \
232 } (void)0
233
234 /***/
235
236 typedef struct OldNew {
237         void *old, *newp;
238         int nr;
239 } OldNew;
240
241 typedef struct OldNewMap {
242         OldNew *entries;
243         int nentries, entriessize;
244         int sorted;
245         int lasthit;
246 } OldNewMap;
247
248
249 /* local prototypes */
250 static void *read_struct(FileData *fd, BHead *bh, const char *blockname);
251 static void direct_link_modifiers(FileData *fd, ListBase *lb);
252 static void convert_tface_mt(FileData *fd, Main *main);
253
254 /* this function ensures that reports are printed,
255  * in the case of libraray linking errors this is important!
256  *
257  * bit kludge but better then doubling up on prints,
258  * we could alternatively have a versions of a report function which foces printing - campbell
259  */
260 static void BKE_reportf_wrap(ReportList *reports, ReportType type, const char *format, ...)
261 {
262         char fixed_buf[1024]; /* should be long enough */
263         
264         va_list args;
265         
266         va_start(args, format);
267         vsnprintf(fixed_buf, sizeof(fixed_buf), format, args);
268         va_end(args);
269         
270         fixed_buf[sizeof(fixed_buf) - 1] = '\0';
271         
272         BKE_report(reports, type, fixed_buf);
273         
274         if (G.background == 0) {
275                 printf("%s\n", fixed_buf);
276         }
277 }
278
279 static OldNewMap *oldnewmap_new(void) 
280 {
281         OldNewMap *onm= MEM_callocN(sizeof(*onm), "OldNewMap");
282         
283         onm->entriessize = 1024;
284         onm->entries = MEM_mallocN(sizeof(*onm->entries)*onm->entriessize, "OldNewMap.entries");
285         
286         return onm;
287 }
288
289 static int verg_oldnewmap(const void *v1, const void *v2)
290 {
291         const struct OldNew *x1=v1, *x2=v2;
292         
293         if (x1->old > x2->old) return 1;
294         else if (x1->old < x2->old) return -1;
295         return 0;
296 }
297
298
299 static void oldnewmap_sort(FileData *fd) 
300 {
301         qsort(fd->libmap->entries, fd->libmap->nentries, sizeof(OldNew), verg_oldnewmap);
302         fd->libmap->sorted = 1;
303 }
304
305 /* nr is zero for data, and ID code for libdata */
306 static void oldnewmap_insert(OldNewMap *onm, void *oldaddr, void *newaddr, int nr) 
307 {
308         OldNew *entry;
309         
310         if (oldaddr==NULL || newaddr==NULL) return;
311         
312         if (onm->nentries == onm->entriessize) {
313                 int osize = onm->entriessize;
314                 OldNew *oentries = onm->entries;
315                 
316                 onm->entriessize *= 2;
317                 onm->entries = MEM_mallocN(sizeof(*onm->entries)*onm->entriessize, "OldNewMap.entries");
318                 
319                 memcpy(onm->entries, oentries, sizeof(*oentries)*osize);
320                 MEM_freeN(oentries);
321         }
322
323         entry = &onm->entries[onm->nentries++];
324         entry->old = oldaddr;
325         entry->newp = newaddr;
326         entry->nr = nr;
327 }
328
329 void blo_do_versions_oldnewmap_insert(OldNewMap *onm, void *oldaddr, void *newaddr, int nr)
330 {
331         oldnewmap_insert(onm, oldaddr, newaddr, nr);
332 }
333
334 static void *oldnewmap_lookup_and_inc(OldNewMap *onm, void *addr) 
335 {
336         int i;
337         
338         if (addr == NULL) return NULL;
339         
340         if (onm->lasthit < onm->nentries-1) {
341                 OldNew *entry = &onm->entries[++onm->lasthit];
342                 
343                 if (entry->old == addr) {
344                         entry->nr++;
345                         return entry->newp;
346                 }
347         }
348         
349         for (i = 0; i < onm->nentries; i++) {
350                 OldNew *entry = &onm->entries[i];
351                 
352                 if (entry->old == addr) {
353                         onm->lasthit = i;
354                         
355                         entry->nr++;
356                         return entry->newp;
357                 }
358         }
359         
360         return NULL;
361 }
362
363 /* for libdata, nr has ID code, no increment */
364 static void *oldnewmap_liblookup(OldNewMap *onm, void *addr, void *lib) 
365 {
366         int i;
367         
368         if (addr == NULL) return NULL;
369         
370         /* lasthit works fine for non-libdata, linking there is done in same sequence as writing */
371         if (onm->sorted) {
372                 OldNew entry_s, *entry;
373                 
374                 entry_s.old = addr;
375                 
376                 entry = bsearch(&entry_s, onm->entries, onm->nentries, sizeof(OldNew), verg_oldnewmap);
377                 if (entry) {
378                         ID *id = entry->newp;
379                         
380                         if (id && (!lib || id->lib)) {
381                                 return entry->newp;
382                         }
383                 }
384         }
385         
386         for (i = 0; i < onm->nentries; i++) {
387                 OldNew *entry = &onm->entries[i];
388                 
389                 if (entry->old == addr) {
390                         ID *id = entry->newp;
391                         
392                         if (id && (!lib || id->lib)) {
393                                 return entry->newp;
394                         }
395                 }
396         }
397
398         return NULL;
399 }
400
401 static void oldnewmap_free_unused(OldNewMap *onm) 
402 {
403         int i;
404
405         for (i = 0; i < onm->nentries; i++) {
406                 OldNew *entry = &onm->entries[i];
407                 if (entry->nr == 0) {
408                         MEM_freeN(entry->newp);
409                         entry->newp = NULL;
410                 }
411         }
412 }
413
414 static void oldnewmap_clear(OldNewMap *onm) 
415 {
416         onm->nentries = 0;
417         onm->lasthit = 0;
418 }
419
420 static void oldnewmap_free(OldNewMap *onm) 
421 {
422         MEM_freeN(onm->entries);
423         MEM_freeN(onm);
424 }
425
426 /***/
427
428 static void read_libraries(FileData *basefd, ListBase *mainlist);
429
430 /* ************ help functions ***************** */
431
432 static void add_main_to_main(Main *mainvar, Main *from)
433 {
434         ListBase *lbarray[MAX_LIBARRAY], *fromarray[MAX_LIBARRAY];
435         int a;
436         
437         set_listbasepointers(mainvar, lbarray);
438         a = set_listbasepointers(from, fromarray);
439         while (a--) {
440                 BLI_movelisttolist(lbarray[a], fromarray[a]);
441         }
442 }
443
444 void blo_join_main(ListBase *mainlist)
445 {
446         Main *tojoin, *mainl;
447         
448         mainl = mainlist->first;
449         while ((tojoin = mainl->next)) {
450                 add_main_to_main(mainl, tojoin);
451                 BLI_remlink(mainlist, tojoin);
452                 MEM_freeN(tojoin);
453         }
454 }
455
456 static void split_libdata(ListBase *lb, Main *first)
457 {
458         ListBase *lbn;
459         ID *id, *idnext;
460         Main *mainvar;
461         
462         id = lb->first;
463         while (id) {
464                 idnext = id->next;
465                 if (id->lib) {
466                         mainvar = first;
467                         while (mainvar) {
468                                 if (mainvar->curlib == id->lib) {
469                                         lbn= which_libbase(mainvar, GS(id->name));
470                                         BLI_remlink(lb, id);
471                                         BLI_addtail(lbn, id);
472                                         break;
473                                 }
474                                 mainvar = mainvar->next;
475                         }
476                         if (mainvar == NULL) printf("error split_libdata\n");
477                 }
478                 id = idnext;
479         }
480 }
481
482 void blo_split_main(ListBase *mainlist, Main *main)
483 {
484         ListBase *lbarray[MAX_LIBARRAY];
485         Library *lib;
486         int i;
487         
488         mainlist->first = mainlist->last = main;
489         main->next = NULL;
490         
491         if (main->library.first == NULL)
492                 return;
493         
494         for (lib = main->library.first; lib; lib = lib->id.next) {
495                 Main *libmain = MEM_callocN(sizeof(Main), "libmain");
496                 libmain->curlib = lib;
497                 BLI_addtail(mainlist, libmain);
498         }
499         
500         i = set_listbasepointers(main, lbarray);
501         while (i--)
502                 split_libdata(lbarray[i], main->next);
503 }
504
505 /* removes things like /blah/blah/../../blah/ etc, then writes in *name the full path */
506 static void cleanup_path(const char *relabase, char *name)
507 {
508         char filename[FILE_MAXFILE];
509         
510         BLI_splitdirstring(name, filename);
511         BLI_cleanup_dir(relabase, name);
512         strcat(name, filename);
513 }
514
515 static void read_file_version(FileData *fd, Main *main)
516 {
517         BHead *bhead;
518         
519         for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead)) {
520                 if (bhead->code == GLOB) {
521                         FileGlobal *fg= read_struct(fd, bhead, "Global");
522                         if (fg) {
523                                 main->subversionfile= fg->subversion;
524                                 main->minversionfile= fg->minversion;
525                                 main->minsubversionfile= fg->minsubversion;
526                                 MEM_freeN(fg);
527                         }
528                         else if (bhead->code == ENDB)
529                                 break;
530                 }
531         }
532 }
533
534
535 static Main *blo_find_main(FileData *fd, const char *filepath, const char *relabase)
536 {
537         ListBase *mainlist = fd->mainlist;
538         Main *m;
539         Library *lib;
540         char name1[FILE_MAX];
541         
542         BLI_strncpy(name1, filepath, sizeof(name1));
543         cleanup_path(relabase, name1);
544 //      printf("blo_find_main: original in  %s\n", name);
545 //      printf("blo_find_main: converted to %s\n", name1);
546         
547         for (m = mainlist->first; m; m = m->next) {
548                 char *libname = (m->curlib) ? m->curlib->filepath : m->name;
549                 
550                 if (BLI_path_cmp(name1, libname) == 0) {
551                         if (G.debug & G_DEBUG) printf("blo_find_main: found library %s\n", libname);
552                         return m;
553                 }
554         }
555         
556         m = MEM_callocN(sizeof(Main), "find_main");
557         BLI_addtail(mainlist, m);
558         
559         lib = BKE_libblock_alloc(&m->library, ID_LI, "lib");
560         BLI_strncpy(lib->name, filepath, sizeof(lib->name));
561         BLI_strncpy(lib->filepath, name1, sizeof(lib->filepath));
562         
563         m->curlib = lib;
564         
565         read_file_version(fd, m);
566         
567         if (G.debug & G_DEBUG) printf("blo_find_main: added new lib %s\n", filepath);
568         return m;
569 }
570
571
572 /* ************ FILE PARSING ****************** */
573
574 static void switch_endian_bh4(BHead4 *bhead)
575 {
576         /* the ID_.. codes */
577         if ((bhead->code & 0xFFFF)==0) bhead->code >>= 16;
578         
579         if (bhead->code != ENDB) {
580                 SWITCH_INT(bhead->len);
581                 SWITCH_INT(bhead->SDNAnr);
582                 SWITCH_INT(bhead->nr);
583         }
584 }
585
586 static void switch_endian_bh8(BHead8 *bhead)
587 {
588         /* the ID_.. codes */
589         if ((bhead->code & 0xFFFF)==0) bhead->code >>= 16;
590         
591         if (bhead->code != ENDB) {
592                 SWITCH_INT(bhead->len);
593                 SWITCH_INT(bhead->SDNAnr);
594                 SWITCH_INT(bhead->nr);
595         }
596 }
597
598 static void bh4_from_bh8(BHead *bhead, BHead8 *bhead8, int do_endian_swap)
599 {
600         BHead4 *bhead4 = (BHead4 *) bhead;
601 #if defined(WIN32) && !defined(FREE_WINDOWS)
602         __int64 old;
603 #else
604         long long old;
605 #endif
606
607         bhead4->code = bhead8->code;
608         bhead4->len = bhead8->len;
609
610         if (bhead4->code != ENDB) {
611                 /* perform a endian swap on 64bit pointers, otherwise the pointer might map to zero
612                  * 0x0000000000000000000012345678 would become 0x12345678000000000000000000000000
613                  */
614                 if (do_endian_swap) {
615                         SWITCH_LONGINT(bhead8->old);
616                 }
617                 
618                 /* this patch is to avoid a long long being read from not-eight aligned positions
619                  * is necessary on any modern 64bit architecture) */
620                 memcpy(&old, &bhead8->old, 8);
621                 bhead4->old = (int) (old >> 3);
622                 
623                 bhead4->SDNAnr = bhead8->SDNAnr;
624                 bhead4->nr = bhead8->nr;
625         }
626 }
627
628 static void bh8_from_bh4(BHead *bhead, BHead4 *bhead4)
629 {
630         BHead8 *bhead8 = (BHead8 *) bhead;
631         
632         bhead8->code = bhead4->code;
633         bhead8->len = bhead4->len;
634         
635         if (bhead8->code != ENDB) {
636                 bhead8->old = bhead4->old;
637                 bhead8->SDNAnr = bhead4->SDNAnr;
638                 bhead8->nr= bhead4->nr;
639         }
640 }
641
642 static BHeadN *get_bhead(FileData *fd)
643 {
644         BHeadN *new_bhead = NULL;
645         int readsize;
646         
647         if (fd) {
648                 if (!fd->eof) {
649                         /* initializing to zero isn't strictly needed but shuts valgrind up
650                          * since uninitialized memory gets compared */
651                         BHead8 bhead8 = {0};
652                         BHead4 bhead4 = {0};
653                         BHead  bhead = {0};
654                         
655                         /* First read the bhead structure.
656                          * Depending on the platform the file was written on this can
657                          * be a big or little endian BHead4 or BHead8 structure.
658                          *
659                          * As usual 'ENDB' (the last *partial* bhead of the file)
660                          * needs some special handling. We don't want to EOF just yet.
661                          */
662                         if (fd->flags & FD_FLAGS_FILE_POINTSIZE_IS_4) {
663                                 bhead4.code = DATA;
664                                 readsize = fd->read(fd, &bhead4, sizeof(bhead4));
665                                 
666                                 if (readsize == sizeof(bhead4) || bhead4.code == ENDB) {
667                                         if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
668                                                 switch_endian_bh4(&bhead4);
669                                         }
670                                         
671                                         if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) {
672                                                 bh8_from_bh4(&bhead, &bhead4);
673                                         }
674                                         else {
675                                                 memcpy(&bhead, &bhead4, sizeof(bhead));
676                                         }
677                                 }
678                                 else {
679                                         fd->eof = 1;
680                                         bhead.len= 0;
681                                 }
682                         }
683                         else {
684                                 bhead8.code = DATA;
685                                 readsize = fd->read(fd, &bhead8, sizeof(bhead8));
686                                 
687                                 if (readsize == sizeof(bhead8) || bhead8.code == ENDB) {
688                                         if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
689                                                 switch_endian_bh8(&bhead8);
690                                         }
691                                         
692                                         if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) {
693                                                 bh4_from_bh8(&bhead, &bhead8, (fd->flags & FD_FLAGS_SWITCH_ENDIAN));
694                                         }
695                                         else {
696                                                 memcpy(&bhead, &bhead8, sizeof(bhead));
697                                         }
698                                 }
699                                 else {
700                                         fd->eof = 1;
701                                         bhead.len= 0;
702                                 }
703                         }
704                         
705                         /* make sure people are not trying to pass bad blend files */
706                         if (bhead.len < 0) fd->eof = 1;
707                         
708                         /* bhead now contains the (converted) bhead structure. Now read
709                          * the associated data and put everything in a BHeadN (creative naming !)
710                          */
711                         if (!fd->eof) {
712                                 new_bhead = MEM_mallocN(sizeof(BHeadN) + bhead.len, "new_bhead");
713                                 if (new_bhead) {
714                                         new_bhead->next = new_bhead->prev = NULL;
715                                         new_bhead->bhead = bhead;
716                                         
717                                         readsize = fd->read(fd, new_bhead + 1, bhead.len);
718                                         
719                                         if (readsize != bhead.len) {
720                                                 fd->eof = 1;
721                                                 MEM_freeN(new_bhead);
722                                                 new_bhead = NULL;
723                                         }
724                                 }
725                                 else {
726                                         fd->eof = 1;
727                                 }
728                         }
729                 }
730         }
731
732         /* We've read a new block. Now add it to the list
733          * of blocks.
734          */
735         if (new_bhead) {
736                 BLI_addtail(&fd->listbase, new_bhead);
737         }
738         
739         return(new_bhead);
740 }
741
742 BHead *blo_firstbhead(FileData *fd)
743 {
744         BHeadN *new_bhead;
745         BHead *bhead = NULL;
746         
747         /* Rewind the file
748          * Read in a new block if necessary
749          */
750         new_bhead = fd->listbase.first;
751         if (new_bhead == NULL) {
752                 new_bhead = get_bhead(fd);
753         }
754         
755         if (new_bhead) {
756                 bhead = &new_bhead->bhead;
757         }
758         
759         return(bhead);
760 }
761
762 BHead *blo_prevbhead(FileData *UNUSED(fd), BHead *thisblock)
763 {
764         BHeadN *bheadn = (BHeadN *) (((char *) thisblock) - GET_INT_FROM_POINTER( &((BHeadN*)0)->bhead) );
765         BHeadN *prev = bheadn->prev;
766         
767         return (prev) ? &prev->bhead : NULL;
768 }
769
770 BHead *blo_nextbhead(FileData *fd, BHead *thisblock)
771 {
772         BHeadN *new_bhead = NULL;
773         BHead *bhead = NULL;
774         
775         if (thisblock) {
776                 // bhead is actually a sub part of BHeadN
777                 // We calculate the BHeadN pointer from the BHead pointer below
778                 new_bhead = (BHeadN *) (((char *) thisblock) - GET_INT_FROM_POINTER( &((BHeadN*)0)->bhead) );
779                 
780                 // get the next BHeadN. If it doesn't exist we read in the next one
781                 new_bhead = new_bhead->next;
782                 if (new_bhead == NULL) {
783                         new_bhead = get_bhead(fd);
784                 }
785         }
786         
787         if (new_bhead) {
788                 // here we do the reverse:
789                 // go from the BHeadN pointer to the BHead pointer
790                 bhead = &new_bhead->bhead;
791         }
792         
793         return(bhead);
794 }
795
796 static void decode_blender_header(FileData *fd)
797 {
798         char header[SIZEOFBLENDERHEADER], num[4];
799         int readsize;
800         
801         /* read in the header data */
802         readsize = fd->read(fd, header, sizeof(header));
803         
804         if (readsize == sizeof(header)) {
805                 if (strncmp(header, "BLENDER", 7) == 0) {
806                         int remove_this_endian_test = 1;
807                         
808                         fd->flags |= FD_FLAGS_FILE_OK;
809                         
810                         /* what size are pointers in the file ? */
811                         if (header[7]=='_') {
812                                 fd->flags |= FD_FLAGS_FILE_POINTSIZE_IS_4;
813                                 if (sizeof(void *) != 4) {
814                                         fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
815                                 }
816                         }
817                         else {
818                                 if (sizeof(void *) != 8) {
819                                         fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
820                                 }
821                         }
822                         
823                         /* is the file saved in a different endian
824                          * than we need ?
825                          */
826                         if (((((char*)&remove_this_endian_test)[0]==1)?L_ENDIAN:B_ENDIAN) != ((header[8]=='v')?L_ENDIAN:B_ENDIAN)) {
827                                 fd->flags |= FD_FLAGS_SWITCH_ENDIAN;
828                         }
829                         
830                         /* get the version number */
831                         memcpy(num, header + 9, 3);
832                         num[3] = 0;
833                         fd->fileversion = atoi(num);
834                 }
835         }
836 }
837
838 static int read_file_dna(FileData *fd)
839 {
840         BHead *bhead;
841         
842         for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead)) {
843                 if (bhead->code == DNA1) {
844                         int do_endian_swap = (fd->flags & FD_FLAGS_SWITCH_ENDIAN) ? 1 : 0;
845                         
846                         fd->filesdna = DNA_sdna_from_data(&bhead[1], bhead->len, do_endian_swap);
847                         if (fd->filesdna) {
848                                 fd->compflags = DNA_struct_get_compareflags(fd->filesdna, fd->memsdna);
849                                 /* used to retrieve ID names from (bhead+1) */
850                                 fd->id_name_offs = DNA_elem_offset(fd->filesdna, "ID", "char", "name[]");
851                         }
852                         
853                         return 1;
854                 }
855                 else if (bhead->code == ENDB)
856                         break;
857         }
858         
859         return 0;
860 }
861
862 static int fd_read_from_file(FileData *filedata, void *buffer, unsigned int size)
863 {
864         int readsize = read(filedata->filedes, buffer, size);
865         
866         if (readsize < 0) {
867                 readsize = EOF;
868         }
869         else {
870                 filedata->seek += readsize;
871         }
872         
873         return readsize;
874 }
875
876 static int fd_read_gzip_from_file(FileData *filedata, void *buffer, unsigned int size)
877 {
878         int readsize = gzread(filedata->gzfiledes, buffer, size);
879         
880         if (readsize < 0) {
881                 readsize = EOF;
882         }
883         else {
884                 filedata->seek += readsize;
885         }
886         
887         return (readsize);
888 }
889
890 static int fd_read_from_memory(FileData *filedata, void *buffer, unsigned int size)
891 {
892         /* don't read more bytes then there are available in the buffer */
893         int readsize = (int)MIN2(size, (unsigned int)(filedata->buffersize - filedata->seek));
894         
895         memcpy(buffer, filedata->buffer + filedata->seek, readsize);
896         filedata->seek += readsize;
897         
898         return (readsize);
899 }
900
901 static int fd_read_from_memfile(FileData *filedata, void *buffer, unsigned int size)
902 {
903         static unsigned int seek = (1<<30);     /* the current position */
904         static unsigned int offset = 0;         /* size of previous chunks */
905         static MemFileChunk *chunk = NULL;
906         unsigned int chunkoffset, readsize, totread;
907         
908         if (size == 0) return 0;
909         
910         if (seek != (unsigned int)filedata->seek) {
911                 chunk = filedata->memfile->chunks.first;
912                 seek = 0;
913                 
914                 while (chunk) {
915                         if (seek + chunk->size > (unsigned) filedata->seek) break;
916                         seek += chunk->size;
917                         chunk = chunk->next;
918                 }
919                 offset = seek;
920                 seek = filedata->seek;
921         }
922         
923         if (chunk) {
924                 totread = 0;
925                 
926                 do {
927                         /* first check if it's on the end if current chunk */
928                         if (seek-offset == chunk->size) {
929                                 offset += chunk->size;
930                                 chunk = chunk->next;
931                         }
932                         
933                         /* debug, should never happen */
934                         if (chunk == NULL) {
935                                 printf("illegal read, chunk zero\n");
936                                 return 0;
937                         }
938                         
939                         chunkoffset = seek-offset;
940                         readsize = size-totread;
941                         
942                         /* data can be spread over multiple chunks, so clamp size
943                          * to within this chunk, and then it will read further in
944                          * the next chunk */
945                         if (chunkoffset+readsize > chunk->size)
946                                 readsize= chunk->size-chunkoffset;
947                         
948                         memcpy((char*)buffer + totread, chunk->buf + chunkoffset, readsize);
949                         totread += readsize;
950                         filedata->seek += readsize;
951                         seek += readsize;
952                 } while (totread < size);
953                 
954                 return totread;
955         }
956         
957         return 0;
958 }
959
960 static FileData *filedata_new(void)
961 {
962         FileData *fd = MEM_callocN(sizeof(FileData), "FileData");
963         
964         fd->filedes = -1;
965         fd->gzfiledes = NULL;
966         
967                 /* XXX, this doesn't need to be done all the time,
968                  * but it keeps us re-entrant,  remove once we have
969                  * a lib that provides a nice lock. - zr
970                  */
971         fd->memsdna = DNA_sdna_from_data(DNAstr,  DNAlen,  0);
972         
973         fd->datamap = oldnewmap_new();
974         fd->globmap = oldnewmap_new();
975         fd->libmap = oldnewmap_new();
976         
977         return fd;
978 }
979
980 static FileData *blo_decode_and_check(FileData *fd, ReportList *reports)
981 {
982         decode_blender_header(fd);
983         
984         if (fd->flags & FD_FLAGS_FILE_OK) {
985                 if (!read_file_dna(fd)) {
986                         BKE_reportf(reports, RPT_ERROR, "Failed to read blend file: \"%s\", incomplete", fd->relabase);
987                         blo_freefiledata(fd);
988                         fd = NULL;
989                 }
990         } 
991         else {
992                 BKE_reportf(reports, RPT_ERROR, "Failed to read blend file: \"%s\", not a blend file", fd->relabase);
993                 blo_freefiledata(fd);
994                 fd = NULL;
995         }
996         
997         return fd;
998 }
999
1000 /* cannot be called with relative paths anymore! */
1001 /* on each new library added, it now checks for the current FileData and expands relativeness */
1002 FileData *blo_openblenderfile(const char *filepath, ReportList *reports)
1003 {
1004         gzFile gzfile;
1005         errno = 0;
1006         gzfile = BLI_gzopen(filepath, "rb");
1007         
1008         if (gzfile == (gzFile)Z_NULL) {
1009                 BKE_reportf(reports, RPT_ERROR, "Unable to open \"%s\": %s.", filepath, errno ? strerror(errno) : "Unknown error reading file");
1010                 return NULL;
1011         }
1012         else {
1013                 FileData *fd = filedata_new();
1014                 fd->gzfiledes = gzfile;
1015                 fd->read = fd_read_gzip_from_file;
1016                 
1017                 /* needed for library_append and read_libraries */
1018                 BLI_strncpy(fd->relabase, filepath, sizeof(fd->relabase));
1019                 
1020                 return blo_decode_and_check(fd, reports);
1021         }
1022 }
1023
1024 FileData *blo_openblendermemory(void *mem, int memsize, ReportList *reports)
1025 {
1026         if (!mem || memsize<SIZEOFBLENDERHEADER) {
1027                 BKE_report(reports, RPT_ERROR, (mem)? "Unable to read": "Unable to open");
1028                 return NULL;
1029         }
1030         else {
1031                 FileData *fd = filedata_new();
1032                 fd->buffer = mem;
1033                 fd->buffersize = memsize;
1034                 fd->read = fd_read_from_memory;
1035                 fd->flags |= FD_FLAGS_NOT_MY_BUFFER;
1036                 
1037                 return blo_decode_and_check(fd, reports);
1038         }
1039 }
1040
1041 FileData *blo_openblendermemfile(MemFile *memfile, ReportList *reports)
1042 {
1043         if (!memfile) {
1044                 BKE_report(reports, RPT_ERROR, "Unable to open blend <memory>");
1045                 return NULL;
1046         }
1047         else {
1048                 FileData *fd = filedata_new();
1049                 fd->memfile = memfile;
1050                 
1051                 fd->read = fd_read_from_memfile;
1052                 fd->flags |= FD_FLAGS_NOT_MY_BUFFER;
1053                 
1054                 return blo_decode_and_check(fd, reports);
1055         }
1056 }
1057
1058
1059 void blo_freefiledata(FileData *fd)
1060 {
1061         if (fd) {
1062                 if (fd->filedes != -1) {
1063                         close(fd->filedes);
1064                 }
1065                 
1066                 if (fd->gzfiledes != NULL) {
1067                         gzclose(fd->gzfiledes);
1068                 }
1069                 
1070                 if (fd->buffer && !(fd->flags & FD_FLAGS_NOT_MY_BUFFER)) {
1071                         MEM_freeN(fd->buffer);
1072                         fd->buffer = NULL;
1073                 }
1074                 
1075                 // Free all BHeadN data blocks
1076                 BLI_freelistN(&fd->listbase);
1077                 
1078                 if (fd->memsdna)
1079                         DNA_sdna_free(fd->memsdna);
1080                 if (fd->filesdna)
1081                         DNA_sdna_free(fd->filesdna);
1082                 if (fd->compflags)
1083                         MEM_freeN(fd->compflags);
1084                 
1085                 if (fd->datamap)
1086                         oldnewmap_free(fd->datamap);
1087                 if (fd->globmap)
1088                         oldnewmap_free(fd->globmap);
1089                 if (fd->imamap)
1090                         oldnewmap_free(fd->imamap);
1091                 if (fd->movieclipmap)
1092                         oldnewmap_free(fd->movieclipmap);
1093 #ifdef USE_MANGO_MASK_CACHE_HACK
1094                 if (fd->maskmap)
1095                         oldnewmap_free(fd->maskmap);
1096 #endif
1097                 if (fd->libmap && !(fd->flags & FD_FLAGS_NOT_MY_LIBMAP))
1098                         oldnewmap_free(fd->libmap);
1099                 if (fd->bheadmap)
1100                         MEM_freeN(fd->bheadmap);
1101                 
1102                 MEM_freeN(fd);
1103         }
1104 }
1105
1106 /* ************ DIV ****************** */
1107
1108 int BLO_has_bfile_extension(const char *str)
1109 {
1110         return (BLI_testextensie(str, ".ble") || 
1111                 BLI_testextensie(str, ".blend") || 
1112                 BLI_testextensie(str, ".blend.gz"));
1113 }
1114
1115 int BLO_is_a_library(const char *path, char *dir, char *group)
1116 {
1117         /* return ok when a blenderfile, in dir is the filename,
1118          * in group the type of libdata
1119          */
1120         int len;
1121         char *fd;
1122         
1123         strcpy(dir, path);
1124         len = strlen(dir);
1125         if (len < 7) return 0;
1126         if ((dir[len - 1] != '/') && (dir[len - 1] != '\\')) return 0;
1127         
1128         group[0] = '\0';
1129         dir[len - 1] = '\0';
1130
1131         /* Find the last slash */
1132         fd = BLI_last_slash(dir);
1133
1134         if (fd == NULL) return 0;
1135         *fd = 0;
1136         if (BLO_has_bfile_extension(fd+1)) {
1137                 /* the last part of the dir is a .blend file, no group follows */
1138                 *fd = '/'; /* put back the removed slash separating the dir and the .blend file name */
1139         }
1140         else {          
1141                 char *gp = fd + 1; // in case we have a .blend file, gp points to the group
1142                 
1143                 /* Find the last slash */
1144                 fd = BLI_last_slash(dir);
1145                 if (!fd || !BLO_has_bfile_extension(fd+1)) return 0;
1146                 
1147                 /* now we know that we are in a blend file and it is safe to 
1148                  * assume that gp actually points to a group */
1149                 if (strcmp("Screen", gp) != 0)
1150                         BLI_strncpy(group, gp, GROUP_MAX);
1151         }
1152         return 1;
1153 }
1154
1155 /* ************** OLD POINTERS ******************* */
1156
1157 static void *newdataadr(FileData *fd, void *adr)                /* only direct databocks */
1158 {
1159         return oldnewmap_lookup_and_inc(fd->datamap, adr);
1160 }
1161
1162 static void *newglobadr(FileData *fd, void *adr)                /* direct datablocks with global linking */
1163 {
1164         return oldnewmap_lookup_and_inc(fd->globmap, adr);
1165 }
1166
1167 static void *newimaadr(FileData *fd, void *adr)         /* used to restore image data after undo */
1168 {
1169         if (fd->imamap && adr)
1170                 return oldnewmap_lookup_and_inc(fd->imamap, adr);
1171         return NULL;
1172 }
1173
1174 static void *newmclipadr(FileData *fd, void *adr)              /* used to restore movie clip data after undo */
1175 {
1176         if (fd->movieclipmap && adr)
1177                 return oldnewmap_lookup_and_inc(fd->movieclipmap, adr);
1178         return NULL;
1179 }
1180
1181 #ifdef USE_MANGO_MASK_CACHE_HACK
1182 static void *newmaskadr(FileData *fd, void *adr)              /* used to restore mask data after undo */
1183 {
1184         if (fd->maskmap && adr)
1185                 return oldnewmap_lookup_and_inc(fd->maskmap, adr);
1186         return NULL;
1187 }
1188 #endif
1189
1190
1191 static void *newlibadr(FileData *fd, void *lib, void *adr)              /* only lib data */
1192 {
1193         return oldnewmap_liblookup(fd->libmap, adr, lib);
1194 }
1195
1196 void *blo_do_versions_newlibadr(FileData *fd, void *lib, void *adr)             /* only lib data */
1197 {
1198         return newlibadr(fd, lib, adr);
1199 }
1200
1201 static void *newlibadr_us(FileData *fd, void *lib, void *adr)   /* increases user number */
1202 {
1203         ID *id = newlibadr(fd, lib, adr);
1204         
1205         if (id)
1206                 id->us++;
1207         
1208         return id;
1209 }
1210
1211 void *blo_do_versions_newlibadr_us(FileData *fd, void *lib, void *adr)  /* increases user number */
1212 {
1213         return newlibadr_us(fd, lib, adr);
1214 }
1215
1216 static void change_idid_adr_fd(FileData *fd, void *old, void *new)
1217 {
1218         int i;
1219         
1220         for (i = 0; i < fd->libmap->nentries; i++) {
1221                 OldNew *entry = &fd->libmap->entries[i];
1222                 
1223                 if (old==entry->newp && entry->nr==ID_ID) {
1224                         entry->newp = new;
1225                         if (new) entry->nr = GS( ((ID *)new)->name );
1226                 }
1227         }
1228 }
1229
1230 static void change_idid_adr(ListBase *mainlist, FileData *basefd, void *old, void *new)
1231 {
1232         Main *mainptr;
1233         
1234         for (mainptr = mainlist->first; mainptr; mainptr = mainptr->next) {
1235                 FileData *fd;
1236                 
1237                 if (mainptr->curlib)
1238                         fd = mainptr->curlib->filedata;
1239                 else
1240                         fd = basefd;
1241                 
1242                 if (fd) {
1243                         change_idid_adr_fd(fd, old, new);
1244                 }
1245         }
1246 }
1247
1248 /* lib linked proxy objects point to our local data, we need
1249  * to clear that pointer before reading the undo memfile since
1250  * the object might be removed, it is set again in reading
1251  * if the local object still exists */
1252 void blo_clear_proxy_pointers_from_lib(Main *oldmain)
1253 {
1254         Object *ob = oldmain->object.first;
1255         
1256         for (; ob; ob= ob->id.next) {
1257                 if (ob->id.lib)
1258                         ob->proxy_from = NULL;
1259         }
1260 }
1261
1262 void blo_make_image_pointer_map(FileData *fd, Main *oldmain)
1263 {
1264         Image *ima = oldmain->image.first;
1265         Scene *sce = oldmain->scene.first;
1266         int a;
1267         
1268         fd->imamap = oldnewmap_new();
1269         
1270         for (; ima; ima = ima->id.next) {
1271                 Link *ibuf = ima->ibufs.first;
1272                 for (; ibuf; ibuf = ibuf->next)
1273                         oldnewmap_insert(fd->imamap, ibuf, ibuf, 0);
1274                 if (ima->gputexture)
1275                         oldnewmap_insert(fd->imamap, ima->gputexture, ima->gputexture, 0);
1276                 for (a=0; a < IMA_MAX_RENDER_SLOT; a++)
1277                         if (ima->renders[a])
1278                                 oldnewmap_insert(fd->imamap, ima->renders[a], ima->renders[a], 0);
1279         }
1280         for (; sce; sce = sce->id.next) {
1281                 if (sce->nodetree) {
1282                         bNode *node;
1283                         for (node = sce->nodetree->nodes.first; node; node = node->next)
1284                                 oldnewmap_insert(fd->imamap, node->preview, node->preview, 0);
1285                 }
1286         }
1287 }
1288
1289 /* set old main image ibufs to zero if it has been restored */
1290 /* this works because freeing old main only happens after this call */
1291 void blo_end_image_pointer_map(FileData *fd, Main *oldmain)
1292 {
1293         OldNew *entry = fd->imamap->entries;
1294         Image *ima = oldmain->image.first;
1295         Scene *sce = oldmain->scene.first;
1296         int i;
1297         
1298         /* used entries were restored, so we put them to zero */
1299         for (i = 0; i < fd->imamap->nentries; i++, entry++) {
1300                 if (entry->nr > 0)
1301                         entry->newp = NULL;
1302         }
1303         
1304         for (; ima; ima = ima->id.next) {
1305                 Link *ibuf, *next;
1306                 
1307                 /* this mirrors direct_link_image */
1308                 for (ibuf = ima->ibufs.first; ibuf; ibuf = next) {
1309                         next = ibuf->next;
1310                         if (NULL == newimaadr(fd, ibuf)) {      /* so was restored */
1311                                 BLI_remlink(&ima->ibufs, ibuf);
1312                                 ima->bindcode = 0;
1313                                 ima->gputexture = NULL;
1314                         }
1315                 }
1316                 for (i = 0; i < IMA_MAX_RENDER_SLOT; i++)
1317                         ima->renders[i] = newimaadr(fd, ima->renders[i]);
1318                 
1319                 ima->gputexture = newimaadr(fd, ima->gputexture);
1320         }
1321         for (; sce; sce = sce->id.next) {
1322                 if (sce->nodetree) {
1323                         bNode *node;
1324                         for (node = sce->nodetree->nodes.first; node; node = node->next)
1325                                 node->preview = newimaadr(fd, node->preview);
1326                 }
1327         }
1328 }
1329
1330 void blo_make_movieclip_pointer_map(FileData *fd, Main *oldmain)
1331 {
1332         MovieClip *clip = oldmain->movieclip.first;
1333         Scene *sce = oldmain->scene.first;
1334         
1335         fd->movieclipmap = oldnewmap_new();
1336         
1337         for (; clip; clip = clip->id.next) {
1338                 if (clip->cache)
1339                         oldnewmap_insert(fd->movieclipmap, clip->cache, clip->cache, 0);
1340                 
1341                 if (clip->tracking.camera.intrinsics)
1342                         oldnewmap_insert(fd->movieclipmap, clip->tracking.camera.intrinsics, clip->tracking.camera.intrinsics, 0);
1343         }
1344         
1345         for (; sce; sce = sce->id.next) {
1346                 if (sce->nodetree) {
1347                         bNode *node;
1348                         for (node = sce->nodetree->nodes.first; node; node= node->next)
1349                                 if (node->type == CMP_NODE_MOVIEDISTORTION)
1350                                         oldnewmap_insert(fd->movieclipmap, node->storage, node->storage, 0);
1351                 }
1352         }
1353 }
1354
1355 /* set old main movie clips caches to zero if it has been restored */
1356 /* this works because freeing old main only happens after this call */
1357 void blo_end_movieclip_pointer_map(FileData *fd, Main *oldmain)
1358 {
1359         OldNew *entry = fd->movieclipmap->entries;
1360         MovieClip *clip = oldmain->movieclip.first;
1361         Scene *sce = oldmain->scene.first;
1362         int i;
1363         
1364         /* used entries were restored, so we put them to zero */
1365         for (i=0; i < fd->movieclipmap->nentries; i++, entry++) {
1366                 if (entry->nr > 0)
1367                         entry->newp = NULL;
1368         }
1369         
1370         for (; clip; clip = clip->id.next) {
1371                 clip->cache = newmclipadr(fd, clip->cache);
1372                 clip->tracking.camera.intrinsics = newmclipadr(fd, clip->tracking.camera.intrinsics);
1373         }
1374         
1375         for (; sce; sce = sce->id.next) {
1376                 if (sce->nodetree) {
1377                         bNode *node;
1378                         for (node = sce->nodetree->nodes.first; node; node = node->next)
1379                                 if (node->type == CMP_NODE_MOVIEDISTORTION)
1380                                         node->storage = newmclipadr(fd, node->storage);
1381                 }
1382         }
1383 }
1384
1385 #ifdef USE_MANGO_MASK_CACHE_HACK
1386 void blo_make_mask_pointer_map(FileData *fd, Main *oldmain)
1387 {
1388         Mask *mask;
1389
1390         fd->maskmap = oldnewmap_new();
1391
1392         for (mask = oldmain->mask.first; mask; mask = mask->id.next) {
1393                 if (mask->raster_cache)
1394                         oldnewmap_insert(fd->maskmap, mask->raster_cache, mask->raster_cache, 0);
1395         }
1396 }
1397
1398 /* set old main mask caches to zero if it has been restored */
1399 /* this works because freeing old main only happens after this call */
1400 void blo_end_mask_pointer_map(FileData *fd, Main *oldmain)
1401 {
1402         OldNew *entry = fd->maskmap->entries;
1403         Mask *mask;
1404         int i;
1405
1406         /* used entries were restored, so we put them to zero */
1407         for (i = 0; i < fd->maskmap->nentries; i++, entry++) {
1408                 if (entry->nr > 0)
1409                         entry->newp = NULL;
1410         }
1411
1412         for (mask = oldmain->mask.first; mask; mask = mask->id.next) {
1413                 mask->raster_cache = newmclipadr(fd, mask->raster_cache);
1414         }
1415 }
1416 #endif
1417
1418 /* undo file support: add all library pointers in lookup */
1419 void blo_add_library_pointer_map(ListBase *mainlist, FileData *fd)
1420 {
1421         Main *ptr = mainlist->first;
1422         ListBase *lbarray[MAX_LIBARRAY];
1423         
1424         for (ptr = ptr->next; ptr; ptr = ptr->next) {
1425                 int i = set_listbasepointers(ptr, lbarray);
1426                 while (i--) {
1427                         ID *id;
1428                         for (id = lbarray[i]->first; id; id = id->next)
1429                                 oldnewmap_insert(fd->libmap, id, id, GS(id->name));
1430                 }
1431         }
1432 }
1433
1434
1435 /* ********** END OLD POINTERS ****************** */
1436 /* ********** READ FILE ****************** */
1437
1438 static void switch_endian_structs(struct SDNA *filesdna, BHead *bhead)
1439 {
1440         int blocksize, nblocks;
1441         char *data;
1442         
1443         data = (char *)(bhead+1);
1444         blocksize = filesdna->typelens[ filesdna->structs[bhead->SDNAnr][0] ];
1445         
1446         nblocks = bhead->nr;
1447         while (nblocks--) {
1448                 DNA_struct_switch_endian(filesdna, bhead->SDNAnr, data);
1449                 
1450                 data += blocksize;
1451         }
1452 }
1453
1454 static void *read_struct(FileData *fd, BHead *bh, const char *blockname)
1455 {
1456         void *temp = NULL;
1457         
1458         if (bh->len) {
1459                 /* switch is based on file dna */
1460                 if (bh->SDNAnr && (fd->flags & FD_FLAGS_SWITCH_ENDIAN))
1461                         switch_endian_structs(fd->filesdna, bh);
1462                 
1463                 if (fd->compflags[bh->SDNAnr]) {        /* flag==0: doesn't exist anymore */
1464                         if (fd->compflags[bh->SDNAnr] == 2) {
1465                                 temp = DNA_struct_reconstruct(fd->memsdna, fd->filesdna, fd->compflags, bh->SDNAnr, bh->nr, (bh+1));
1466                         }
1467                         else {
1468                                 temp = MEM_mallocN(bh->len, blockname);
1469                                 memcpy(temp, (bh+1), bh->len);
1470                         }
1471                 }
1472         }
1473
1474         return temp;
1475 }
1476
1477 static void link_list(FileData *fd, ListBase *lb)               /* only direct data */
1478 {
1479         Link *ln, *prev;
1480         
1481         if (lb->first == NULL) return;
1482         
1483         lb->first = newdataadr(fd, lb->first);
1484         ln = lb->first;
1485         prev = NULL;
1486         while (ln) {
1487                 ln->next = newdataadr(fd, ln->next);
1488                 ln->prev = prev;
1489                 prev = ln;
1490                 ln = ln->next;
1491         }
1492         lb->last = prev;
1493 }
1494
1495 static void link_glob_list(FileData *fd, ListBase *lb)          /* for glob data */
1496 {
1497         Link *ln, *prev;
1498         void *poin;
1499
1500         if (lb->first == NULL) return;
1501         poin = newdataadr(fd, lb->first);
1502         if (lb->first) {
1503                 oldnewmap_insert(fd->globmap, lb->first, poin, 0);
1504         }
1505         lb->first = poin;
1506         
1507         ln = lb->first;
1508         prev = NULL;
1509         while (ln) {
1510                 poin = newdataadr(fd, ln->next);
1511                 if (ln->next) {
1512                         oldnewmap_insert(fd->globmap, ln->next, poin, 0);
1513                 }
1514                 ln->next = poin;
1515                 ln->prev = prev;
1516                 prev = ln;
1517                 ln = ln->next;
1518         }
1519         lb->last = prev;
1520 }
1521
1522 static void test_pointer_array(FileData *fd, void **mat)
1523 {
1524 #if defined(WIN32) && !defined(FREE_WINDOWS)
1525         __int64 *lpoin, *lmat;
1526 #else
1527         long long *lpoin, *lmat;
1528 #endif
1529         int *ipoin, *imat;
1530         size_t len;
1531
1532                 /* manually convert the pointer array in
1533                  * the old dna format to a pointer array in
1534                  * the new dna format.
1535                  */
1536         if (*mat) {
1537                 len = MEM_allocN_len(*mat)/fd->filesdna->pointerlen;
1538                         
1539                 if (fd->filesdna->pointerlen==8 && fd->memsdna->pointerlen==4) {
1540                         ipoin=imat= MEM_mallocN(len * 4, "newmatar");
1541                         lpoin= *mat;
1542                         
1543                         while (len-- > 0) {
1544                                 if ((fd->flags & FD_FLAGS_SWITCH_ENDIAN))
1545                                         SWITCH_LONGINT(*lpoin);
1546                                 *ipoin = (int)((*lpoin) >> 3);
1547                                 ipoin++;
1548                                 lpoin++;
1549                         }
1550                         MEM_freeN(*mat);
1551                         *mat = imat;
1552                 }
1553                 
1554                 if (fd->filesdna->pointerlen==4 && fd->memsdna->pointerlen==8) {
1555                         lpoin = lmat = MEM_mallocN(len * 8, "newmatar");
1556                         ipoin = *mat;
1557                         
1558                         while (len-- > 0) {
1559                                 *lpoin = *ipoin;
1560                                 ipoin++;
1561                                 lpoin++;
1562                         }
1563                         MEM_freeN(*mat);
1564                         *mat= lmat;
1565                 }
1566         }
1567 }
1568
1569 /* ************ READ ID Properties *************** */
1570
1571 static void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, FileData *fd);
1572 static void IDP_LibLinkProperty(IDProperty *prop, int switch_endian, FileData *fd);
1573
1574 static void IDP_DirectLinkIDPArray(IDProperty *prop, int switch_endian, FileData *fd)
1575 {
1576         IDProperty *array;
1577         int i;
1578         
1579         /* since we didn't save the extra buffer, set totallen to len */
1580         prop->totallen = prop->len;
1581         prop->data.pointer = newdataadr(fd, prop->data.pointer);
1582
1583         array = (IDProperty *)prop->data.pointer;
1584         
1585         /* note!, idp-arrays didn't exist in 2.4x, so the pointer will be cleared
1586          * theres not really anything we can do to correct this, at least don't crash */
1587         if (array == NULL) {
1588                 prop->len = 0;
1589                 prop->totallen = 0;
1590         }
1591         
1592         
1593         for (i = 0; i < prop->len; i++)
1594                 IDP_DirectLinkProperty(&array[i], switch_endian, fd);
1595 }
1596
1597 static void IDP_DirectLinkArray(IDProperty *prop, int switch_endian, FileData *fd)
1598 {
1599         IDProperty **array;
1600         int i;
1601         
1602         /* since we didn't save the extra buffer, set totallen to len */
1603         prop->totallen = prop->len;
1604         prop->data.pointer = newdataadr(fd, prop->data.pointer);
1605         
1606         if (prop->subtype == IDP_GROUP) {
1607                 test_pointer_array(fd, prop->data.pointer);
1608                 array = prop->data.pointer;
1609                 
1610                 for (i = 0; i < prop->len; i++)
1611                         IDP_DirectLinkProperty(array[i], switch_endian, fd);
1612         }
1613         else if (prop->subtype == IDP_DOUBLE) {
1614                 if (switch_endian) {
1615                         for (i = 0; i < prop->len; i++) {
1616                                 SWITCH_LONGINT(((double *)prop->data.pointer)[i]);
1617                         }
1618                 }
1619         }
1620         else {
1621                 if (switch_endian) {
1622                         for (i = 0; i < prop->len; i++) {
1623                                 SWITCH_INT(((int *)prop->data.pointer)[i]);
1624                         }
1625                 }
1626         }
1627 }
1628
1629 static void IDP_DirectLinkString(IDProperty *prop, FileData *fd)
1630 {
1631         /*since we didn't save the extra string buffer, set totallen to len.*/
1632         prop->totallen = prop->len;
1633         prop->data.pointer = newdataadr(fd, prop->data.pointer);
1634 }
1635
1636 static void IDP_DirectLinkGroup(IDProperty *prop, int switch_endian, FileData *fd)
1637 {
1638         ListBase *lb = &prop->data.group;
1639         IDProperty *loop;
1640         
1641         link_list(fd, lb);
1642         
1643         /*Link child id properties now*/
1644         for (loop=prop->data.group.first; loop; loop=loop->next) {
1645                 IDP_DirectLinkProperty(loop, switch_endian, fd);
1646         }
1647 }
1648
1649 static void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, FileData *fd)
1650 {
1651         switch (prop->type) {
1652                 case IDP_GROUP:
1653                         IDP_DirectLinkGroup(prop, switch_endian, fd);
1654                         break;
1655                 case IDP_STRING:
1656                         IDP_DirectLinkString(prop, fd);
1657                         break;
1658                 case IDP_ARRAY:
1659                         IDP_DirectLinkArray(prop, switch_endian, fd);
1660                         break;
1661                 case IDP_IDPARRAY:
1662                         IDP_DirectLinkIDPArray(prop, switch_endian, fd);
1663                         break;
1664                 case IDP_DOUBLE:
1665                         /* erg, stupid doubles.  since I'm storing them
1666                          * in the same field as int val; val2 in the
1667                          * IDPropertyData struct, they have to deal with
1668                          * endianness specifically
1669                          *
1670                          * in theory, val and val2 would've already been swapped
1671                          * if switch_endian is true, so we have to first unswap
1672                          * them then reswap them as a single 64-bit entity.
1673                          */
1674                         
1675                         if (switch_endian) {
1676                                 SWITCH_INT(prop->data.val);
1677                                 SWITCH_INT(prop->data.val2);
1678                                 SWITCH_LONGINT(prop->data.val);
1679                         }
1680                         
1681                         break;
1682         }
1683 }
1684
1685 /* stub function */
1686 static void IDP_LibLinkProperty(IDProperty *UNUSED(prop), int UNUSED(switch_endian), FileData *UNUSED(fd))
1687 {
1688 }
1689
1690 /* ************ READ CurveMapping *************** */
1691
1692 /* cuma itself has been read! */
1693 static void direct_link_curvemapping(FileData *fd, CurveMapping *cumap)
1694 {
1695         int a;
1696         
1697         /* flag seems to be able to hang? Maybe old files... not bad to clear anyway */
1698         cumap->flag &= ~CUMA_PREMULLED;
1699         
1700         for (a = 0; a < CM_TOT; a++) {
1701                 cumap->cm[a].curve = newdataadr(fd, cumap->cm[a].curve);
1702                 cumap->cm[a].table = NULL;
1703                 cumap->cm[a].premultable = NULL;
1704         }
1705 }
1706
1707 /* ************ READ Brush *************** */
1708 /* library brush linking after fileread */
1709 static void lib_link_brush(FileData *fd, Main *main)
1710 {
1711         Brush *brush;
1712         
1713         /* only link ID pointers */
1714         for (brush = main->brush.first; brush; brush = brush->id.next) {
1715                 if (brush->id.flag & LIB_NEEDLINK) {
1716                         brush->id.flag -= LIB_NEEDLINK;
1717                         
1718                         brush->mtex.tex = newlibadr_us(fd, brush->id.lib, brush->mtex.tex);
1719                         brush->clone.image = newlibadr_us(fd, brush->id.lib, brush->clone.image);
1720                 }
1721         }
1722 }
1723
1724 static void direct_link_brush(FileData *fd, Brush *brush)
1725 {
1726         /* brush itself has been read */
1727
1728         /* fallof curve */
1729         brush->curve = newdataadr(fd, brush->curve);
1730         if (brush->curve)
1731                 direct_link_curvemapping(fd, brush->curve);
1732         else
1733                 BKE_brush_curve_preset(brush, CURVE_PRESET_SHARP);
1734
1735         brush->preview = NULL;
1736         brush->icon_imbuf = NULL;
1737 }
1738
1739 static void direct_link_script(FileData *UNUSED(fd), Script *script)
1740 {
1741         script->id.us = 1;
1742         SCRIPT_SET_NULL(script);
1743 }
1744
1745
1746 /* ************ READ PACKEDFILE *************** */
1747
1748 static PackedFile *direct_link_packedfile(FileData *fd, PackedFile *oldpf)
1749 {
1750         PackedFile *pf = newdataadr(fd, oldpf);
1751         
1752         if (pf) {
1753                 pf->data = newdataadr(fd, pf->data);
1754         }
1755         
1756         return pf;
1757 }
1758
1759 /* ************ READ IMAGE PREVIEW *************** */
1760
1761 static PreviewImage *direct_link_preview_image(FileData *fd, PreviewImage *old_prv)
1762 {
1763         PreviewImage *prv = newdataadr(fd, old_prv);
1764         
1765         if (prv) {
1766                 int i;
1767                 for (i = 0; i < NUM_ICON_SIZES; ++i) {
1768                         if (prv->rect[i]) {
1769                                 prv->rect[i] = newdataadr(fd, prv->rect[i]);
1770                         }
1771                 }
1772         }
1773         
1774         return prv;
1775 }
1776
1777 /* ************ READ ANIMATION STUFF ***************** */
1778
1779 /* Legacy Data Support (for Version Patching) ----------------------------- */
1780
1781 // XXX depreceated - old animation system
1782 static void lib_link_ipo(FileData *fd, Main *main)
1783 {
1784         Ipo *ipo;
1785         
1786         for (ipo = main->ipo.first; ipo; ipo = ipo->id.next) {
1787                 if (ipo->id.flag & LIB_NEEDLINK) {
1788                         IpoCurve *icu;
1789                         for (icu = ipo->curve.first; icu; icu = icu->next) {
1790                                 if (icu->driver)
1791                                         icu->driver->ob = newlibadr(fd, ipo->id.lib, icu->driver->ob);
1792                         }
1793                         ipo->id.flag -= LIB_NEEDLINK;
1794                 }
1795         }
1796 }
1797
1798 // XXX depreceated - old animation system
1799 static void direct_link_ipo(FileData *fd, Ipo *ipo)
1800 {
1801         IpoCurve *icu;
1802
1803         link_list(fd, &(ipo->curve));
1804         
1805         for (icu = ipo->curve.first; icu; icu = icu->next) {
1806                 icu->bezt = newdataadr(fd, icu->bezt);
1807                 icu->bp = newdataadr(fd, icu->bp);
1808                 icu->driver = newdataadr(fd, icu->driver);
1809         }
1810 }
1811
1812 // XXX depreceated - old animation system
1813 static void lib_link_nlastrips(FileData *fd, ID *id, ListBase *striplist)
1814 {
1815         bActionStrip *strip;
1816         bActionModifier *amod;
1817         
1818         for (strip=striplist->first; strip; strip=strip->next) {
1819                 strip->object = newlibadr(fd, id->lib, strip->object);
1820                 strip->act = newlibadr_us(fd, id->lib, strip->act);
1821                 strip->ipo = newlibadr(fd, id->lib, strip->ipo);
1822                 for (amod = strip->modifiers.first; amod; amod = amod->next)
1823                         amod->ob = newlibadr(fd, id->lib, amod->ob);
1824         }
1825 }
1826
1827 // XXX depreceated - old animation system
1828 static void direct_link_nlastrips(FileData *fd, ListBase *strips)
1829 {
1830         bActionStrip *strip;
1831         
1832         link_list(fd, strips);
1833         
1834         for (strip = strips->first; strip; strip = strip->next)
1835                 link_list(fd, &strip->modifiers);
1836 }
1837
1838 // XXX depreceated - old animation system
1839 static void lib_link_constraint_channels(FileData *fd, ID *id, ListBase *chanbase)
1840 {
1841         bConstraintChannel *chan;
1842
1843         for (chan=chanbase->first; chan; chan=chan->next) {
1844                 chan->ipo = newlibadr_us(fd, id->lib, chan->ipo);
1845         }
1846 }
1847
1848 /* Data Linking ----------------------------- */
1849
1850 static void lib_link_fmodifiers(FileData *fd, ID *id, ListBase *list)
1851 {
1852         FModifier *fcm;
1853         
1854         for (fcm = list->first; fcm; fcm = fcm->next) {
1855                 /* data for specific modifiers */
1856                 switch (fcm->type) {
1857                         case FMODIFIER_TYPE_PYTHON:
1858                         {
1859                                 FMod_Python *data = (FMod_Python *)fcm->data;
1860                                 data->script = newlibadr(fd, id->lib, data->script);
1861                         }
1862                                 break;
1863                 }
1864         }
1865 }
1866
1867 static void lib_link_fcurves(FileData *fd, ID *id, ListBase *list) 
1868 {
1869         FCurve *fcu;
1870         
1871         if (list == NULL)
1872                 return;
1873         
1874         /* relink ID-block references... */
1875         for (fcu = list->first; fcu; fcu = fcu->next) {
1876                 /* driver data */
1877                 if (fcu->driver) {
1878                         ChannelDriver *driver = fcu->driver;
1879                         DriverVar *dvar;
1880                         
1881                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
1882                                 DRIVER_TARGETS_LOOPER(dvar)
1883                                 {       
1884                                         /* only relink if still used */
1885                                         if (tarIndex < dvar->num_targets)
1886                                                 dtar->id = newlibadr(fd, id->lib, dtar->id); 
1887                                         else
1888                                                 dtar->id = NULL;
1889                                 }
1890                                 DRIVER_TARGETS_LOOPER_END
1891                         }
1892                 }
1893                 
1894                 /* modifiers */
1895                 lib_link_fmodifiers(fd, id, &fcu->modifiers);
1896         }
1897 }
1898
1899
1900 /* NOTE: this assumes that link_list has already been called on the list */
1901 static void direct_link_fmodifiers(FileData *fd, ListBase *list)
1902 {
1903         FModifier *fcm;
1904         
1905         for (fcm = list->first; fcm; fcm = fcm->next) {
1906                 /* relink general data */
1907                 fcm->data  = newdataadr(fd, fcm->data);
1908                 fcm->edata = NULL;
1909                 
1910                 /* do relinking of data for specific types */
1911                 switch (fcm->type) {
1912                         case FMODIFIER_TYPE_GENERATOR:
1913                         {
1914                                 FMod_Generator *data = (FMod_Generator *)fcm->data;
1915                                 
1916                                 data->coefficients = newdataadr(fd, data->coefficients);
1917                                 
1918                                 if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
1919                                         unsigned int a;
1920                                         for (a = 0; a < data->arraysize; a++)
1921                                                 SWITCH_INT(data->coefficients[a]);
1922                                 }
1923                         }
1924                                 break;
1925                         case FMODIFIER_TYPE_ENVELOPE:
1926                         {
1927                                 FMod_Envelope *data=  (FMod_Envelope *)fcm->data;
1928                                 
1929                                 data->data= newdataadr(fd, data->data);
1930                         }
1931                                 break;
1932                         case FMODIFIER_TYPE_PYTHON:
1933                         {
1934                                 FMod_Python *data = (FMod_Python *)fcm->data;
1935                                 
1936                                 data->prop = newdataadr(fd, data->prop);
1937                                 IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
1938                         }
1939                                 break;
1940                 }
1941         }
1942 }
1943
1944 /* NOTE: this assumes that link_list has already been called on the list */
1945 static void direct_link_fcurves(FileData *fd, ListBase *list)
1946 {
1947         FCurve *fcu;
1948         
1949         /* link F-Curve data to F-Curve again (non ID-libs) */
1950         for (fcu = list->first; fcu; fcu = fcu->next) {
1951                 /* curve data */
1952                 fcu->bezt = newdataadr(fd, fcu->bezt);
1953                 fcu->fpt = newdataadr(fd, fcu->fpt);
1954                 
1955                 /* rna path */
1956                 fcu->rna_path = newdataadr(fd, fcu->rna_path);
1957                 
1958                 /* group */
1959                 fcu->grp = newdataadr(fd, fcu->grp);
1960                 
1961                 /* driver */
1962                 fcu->driver= newdataadr(fd, fcu->driver);
1963                 if (fcu->driver) {
1964                         ChannelDriver *driver= fcu->driver;
1965                         DriverVar *dvar;
1966                         
1967                         driver->expr_comp = NULL;
1968                         
1969                         /* relink variables, targets and their paths */
1970                         link_list(fd, &driver->variables);
1971                         for (dvar= driver->variables.first; dvar; dvar= dvar->next) {
1972                                 DRIVER_TARGETS_LOOPER(dvar)
1973                                 {
1974                                         /* only relink the targets being used */
1975                                         if (tarIndex < dvar->num_targets)
1976                                                 dtar->rna_path = newdataadr(fd, dtar->rna_path);
1977                                         else
1978                                                 dtar->rna_path = NULL;
1979                                 }
1980                                 DRIVER_TARGETS_LOOPER_END
1981                         }
1982                 }
1983                 
1984                 /* modifiers */
1985                 link_list(fd, &fcu->modifiers);
1986                 direct_link_fmodifiers(fd, &fcu->modifiers);
1987         }
1988 }
1989
1990
1991 static void lib_link_action(FileData *fd, Main *main)
1992 {
1993         bAction *act;
1994         bActionChannel *chan;
1995
1996         for (act = main->action.first; act; act = act->id.next) {
1997                 if (act->id.flag & LIB_NEEDLINK) {
1998                         act->id.flag -= LIB_NEEDLINK;
1999                         
2000 // XXX depreceated - old animation system <<<
2001                         for (chan=act->chanbase.first; chan; chan=chan->next) {
2002                                 chan->ipo = newlibadr_us(fd, act->id.lib, chan->ipo);
2003                                 lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
2004                         }
2005 // >>> XXX depreceated - old animation system
2006                         
2007                         lib_link_fcurves(fd, &act->id, &act->curves);
2008                 }
2009         }
2010 }
2011
2012 static void direct_link_action(FileData *fd, bAction *act)
2013 {
2014         bActionChannel *achan; // XXX depreceated - old animation system
2015         bActionGroup *agrp;
2016
2017         link_list(fd, &act->curves);
2018         link_list(fd, &act->chanbase); // XXX depreceated - old animation system
2019         link_list(fd, &act->groups);
2020         link_list(fd, &act->markers);
2021
2022 // XXX depreceated - old animation system <<<
2023         for (achan = act->chanbase.first; achan; achan=achan->next) {
2024                 achan->grp = newdataadr(fd, achan->grp);
2025                 
2026                 link_list(fd, &achan->constraintChannels);
2027         }
2028 // >>> XXX depreceated - old animation system
2029
2030         direct_link_fcurves(fd, &act->curves);
2031         
2032         for (agrp = act->groups.first; agrp; agrp= agrp->next) {
2033                 agrp->channels.first= newdataadr(fd, agrp->channels.first);
2034                 agrp->channels.last= newdataadr(fd, agrp->channels.last);
2035         }
2036 }
2037
2038 static void lib_link_nladata_strips(FileData *fd, ID *id, ListBase *list)
2039 {
2040         NlaStrip *strip;
2041         
2042         for (strip = list->first; strip; strip = strip->next) {
2043                 /* check strip's children */
2044                 lib_link_nladata_strips(fd, id, &strip->strips);
2045                 
2046                 /* check strip's F-Curves */
2047                 lib_link_fcurves(fd, id, &strip->fcurves);
2048                 
2049                 /* reassign the counted-reference to action */
2050                 strip->act = newlibadr_us(fd, id->lib, strip->act);
2051                 
2052                 /* fix action id-root (i.e. if it comes from a pre 2.57 .blend file) */
2053                 if ((strip->act) && (strip->act->idroot == 0))
2054                         strip->act->idroot = GS(id->name);
2055         }
2056 }
2057
2058 static void lib_link_nladata(FileData *fd, ID *id, ListBase *list)
2059 {
2060         NlaTrack *nlt;
2061         
2062         /* we only care about the NLA strips inside the tracks */
2063         for (nlt = list->first; nlt; nlt = nlt->next) {
2064                 lib_link_nladata_strips(fd, id, &nlt->strips);
2065         }
2066 }
2067
2068 /* This handles Animato NLA-Strips linking 
2069  * NOTE: this assumes that link_list has already been called on the list 
2070  */
2071 static void direct_link_nladata_strips(FileData *fd, ListBase *list)
2072 {
2073         NlaStrip *strip;
2074         
2075         for (strip = list->first; strip; strip = strip->next) {
2076                 /* strip's child strips */
2077                 link_list(fd, &strip->strips);
2078                 direct_link_nladata_strips(fd, &strip->strips);
2079                 
2080                 /* strip's F-Curves */
2081                 link_list(fd, &strip->fcurves);
2082                 direct_link_fcurves(fd, &strip->fcurves);
2083                 
2084                 /* strip's F-Modifiers */
2085                 link_list(fd, &strip->modifiers);
2086                 direct_link_fmodifiers(fd, &strip->modifiers);
2087         }
2088 }
2089
2090 /* NOTE: this assumes that link_list has already been called on the list */
2091 static void direct_link_nladata(FileData *fd, ListBase *list)
2092 {
2093         NlaTrack *nlt;
2094         
2095         for (nlt = list->first; nlt; nlt = nlt->next) {
2096                 /* relink list of strips */
2097                 link_list(fd, &nlt->strips);
2098                 
2099                 /* relink strip data */
2100                 direct_link_nladata_strips(fd, &nlt->strips);
2101         }
2102 }
2103
2104 /* ------- */
2105
2106 static void lib_link_keyingsets(FileData *fd, ID *id, ListBase *list)
2107 {
2108         KeyingSet *ks;
2109         KS_Path *ksp;
2110         
2111         /* here, we're only interested in the ID pointer stored in some of the paths */
2112         for (ks = list->first; ks; ks = ks->next) {
2113                 for (ksp = ks->paths.first; ksp; ksp = ksp->next) {
2114                         ksp->id= newlibadr(fd, id->lib, ksp->id); 
2115                 }
2116         }
2117 }
2118
2119 /* NOTE: this assumes that link_list has already been called on the list */
2120 static void direct_link_keyingsets(FileData *fd, ListBase *list)
2121 {
2122         KeyingSet *ks;
2123         KS_Path *ksp;
2124         
2125         /* link KeyingSet data to KeyingSet again (non ID-libs) */
2126         for (ks = list->first; ks; ks = ks->next) {
2127                 /* paths */
2128                 link_list(fd, &ks->paths);
2129                 
2130                 for (ksp = ks->paths.first; ksp; ksp = ksp->next) {
2131                         /* rna path */
2132                         ksp->rna_path= newdataadr(fd, ksp->rna_path);
2133                 }
2134         }
2135 }
2136
2137 /* ------- */
2138
2139 static void lib_link_animdata(FileData *fd, ID *id, AnimData *adt)
2140 {
2141         if (adt == NULL)
2142                 return;
2143         
2144         /* link action data */
2145         adt->action= newlibadr_us(fd, id->lib, adt->action);
2146         adt->tmpact= newlibadr_us(fd, id->lib, adt->tmpact);
2147         
2148         /* fix action id-roots (i.e. if they come from a pre 2.57 .blend file) */
2149         if ((adt->action) && (adt->action->idroot == 0))
2150                 adt->action->idroot = GS(id->name);
2151         if ((adt->tmpact) && (adt->tmpact->idroot == 0))
2152                 adt->tmpact->idroot = GS(id->name);
2153         
2154         /* link drivers */
2155         lib_link_fcurves(fd, id, &adt->drivers);
2156         
2157         /* overrides don't have lib-link for now, so no need to do anything */
2158         
2159         /* link NLA-data */
2160         lib_link_nladata(fd, id, &adt->nla_tracks);
2161 }
2162
2163 static void direct_link_animdata(FileData *fd, AnimData *adt)
2164 {
2165         /* NOTE: must have called newdataadr already before doing this... */
2166         if (adt == NULL)
2167                 return;
2168         
2169         /* link drivers */
2170         link_list(fd, &adt->drivers);
2171         direct_link_fcurves(fd, &adt->drivers);
2172         
2173         /* link overrides */
2174         // TODO...
2175         
2176         /* link NLA-data */
2177         link_list(fd, &adt->nla_tracks);
2178         direct_link_nladata(fd, &adt->nla_tracks);
2179         
2180         /* relink active strip - even though strictly speaking this should only be used
2181          * if we're in 'tweaking mode', we need to be able to have this loaded back for
2182          * undo, but also since users may not exit tweakmode before saving (#24535)
2183          */
2184         // TODO: it's not really nice that anyone should be able to save the file in this
2185         //              state, but it's going to be too hard to enforce this single case...
2186         adt->actstrip = newdataadr(fd, adt->actstrip);
2187 }       
2188
2189 /* ************ READ MOTION PATHS *************** */
2190
2191 /* direct data for cache */
2192 static void direct_link_motionpath(FileData *fd, bMotionPath *mpath)
2193 {
2194         /* sanity check */
2195         if (mpath == NULL)
2196                 return;
2197         
2198         /* relink points cache */
2199         mpath->points = newdataadr(fd, mpath->points);
2200 }
2201
2202 /* ************ READ NODE TREE *************** */
2203
2204 /* singe node tree (also used for material/scene trees), ntree is not NULL */
2205 static void lib_link_ntree(FileData *fd, ID *id, bNodeTree *ntree)
2206 {
2207         bNode *node;
2208         
2209         if (ntree->adt) lib_link_animdata(fd, &ntree->id, ntree->adt);
2210         
2211         ntree->gpd = newlibadr_us(fd, id->lib, ntree->gpd);
2212         
2213         for (node = ntree->nodes.first; node; node = node->next)
2214                 node->id = newlibadr_us(fd, id->lib, node->id);
2215 }
2216
2217 /* library ntree linking after fileread */
2218 static void lib_link_nodetree(FileData *fd, Main *main)
2219 {
2220         bNodeTree *ntree;
2221         
2222         /* only link ID pointers */
2223         for (ntree = main->nodetree.first; ntree; ntree = ntree->id.next) {
2224                 if (ntree->id.flag & LIB_NEEDLINK) {
2225                         ntree->id.flag -= LIB_NEEDLINK;
2226                         lib_link_ntree(fd, &ntree->id, ntree);
2227                 }
2228         }
2229 }
2230
2231 static void do_versions_socket_default_value(bNodeSocket *sock)
2232 {
2233         bNodeSocketValueFloat *valfloat;
2234         bNodeSocketValueVector *valvector;
2235         bNodeSocketValueRGBA *valrgba;
2236         
2237         if (sock->default_value)
2238                 return;
2239         
2240         switch (sock->type) {
2241                 case SOCK_FLOAT:
2242                         valfloat = sock->default_value = MEM_callocN(sizeof(bNodeSocketValueFloat), "default socket value");
2243                         valfloat->value = sock->ns.vec[0];
2244                         valfloat->min = sock->ns.min;
2245                         valfloat->max = sock->ns.max;
2246                         valfloat->subtype = PROP_NONE;
2247                         break;
2248                 case SOCK_VECTOR:
2249                         valvector = sock->default_value = MEM_callocN(sizeof(bNodeSocketValueVector), "default socket value");
2250                         copy_v3_v3(valvector->value, sock->ns.vec);
2251                         valvector->min = sock->ns.min;
2252                         valvector->max = sock->ns.max;
2253                         valvector->subtype = PROP_NONE;
2254                         break;
2255                 case SOCK_RGBA:
2256                         valrgba = sock->default_value = MEM_callocN(sizeof(bNodeSocketValueRGBA), "default socket value");
2257                         copy_v4_v4(valrgba->value, sock->ns.vec);
2258                         break;
2259         }
2260 }
2261
2262 void blo_do_versions_nodetree_default_value(bNodeTree *ntree)
2263 {
2264         bNode *node;
2265         bNodeSocket *sock;
2266         for (node=ntree->nodes.first; node; node=node->next) {
2267                 for (sock=node->inputs.first; sock; sock=sock->next)
2268                         do_versions_socket_default_value(sock);
2269                 for (sock=node->outputs.first; sock; sock=sock->next)
2270                         do_versions_socket_default_value(sock);
2271         }
2272         for (sock=ntree->inputs.first; sock; sock=sock->next)
2273                 do_versions_socket_default_value(sock);
2274         for (sock=ntree->outputs.first; sock; sock=sock->next)
2275                 do_versions_socket_default_value(sock);
2276 }
2277
2278 static void lib_nodetree_init_types_cb(void *UNUSED(data), ID *UNUSED(id), bNodeTree *ntree)
2279 {
2280         bNode *node;
2281         
2282         ntreeInitTypes(ntree);
2283         
2284         /* need to do this here instead of in do_versions, otherwise next function can crash */
2285         blo_do_versions_nodetree_default_value(ntree);
2286         
2287         /* XXX could be replaced by do_versions for new nodes */
2288         for (node=ntree->nodes.first; node; node=node->next)
2289                 node_verify_socket_templates(ntree, node);
2290 }
2291
2292 /* updates group node socket own_index so that
2293  * external links to/from the group node are preserved.
2294  */
2295 static void lib_node_do_versions_group_indices(bNode *gnode)
2296 {
2297         bNodeTree *ngroup = (bNodeTree*)gnode->id;
2298         bNode *intnode;
2299         bNodeSocket *sock, *gsock, *intsock;
2300         int found;
2301         
2302         for (sock=gnode->outputs.first; sock; sock=sock->next) {
2303                 int old_index = sock->to_index;
2304                 for (gsock=ngroup->outputs.first; gsock; gsock=gsock->next) {
2305                         if (gsock->link && gsock->link->fromsock->own_index == old_index) {
2306                                 sock->own_index = gsock->own_index;
2307                                 break;
2308                         }
2309                 }
2310         }
2311         for (sock=gnode->inputs.first; sock; sock=sock->next) {
2312                 int old_index = sock->to_index;
2313                 /* can't use break in double loop */
2314                 found = 0;
2315                 for (intnode=ngroup->nodes.first; intnode && !found; intnode=intnode->next) {
2316                         for (intsock=intnode->inputs.first; intsock; intsock=intsock->next) {
2317                                 if (intsock->own_index == old_index && intsock->link) {
2318                                         sock->own_index = intsock->link->fromsock->own_index;
2319                                         found = 1;
2320                                         break;
2321                                 }
2322                         }
2323                 }
2324         }
2325 }
2326
2327 /* updates external links for all group nodes in a tree */
2328 static void lib_nodetree_do_versions_group_indices_cb(void *UNUSED(data), ID *UNUSED(id), bNodeTree *ntree)
2329 {
2330         bNode *node;
2331         
2332         for (node = ntree->nodes.first; node; node = node->next) {
2333                 if (node->type == NODE_GROUP) {
2334                         bNodeTree *ngroup = (bNodeTree*)node->id;
2335                         if (ngroup && (ngroup->flag & NTREE_DO_VERSIONS_GROUP_EXPOSE))
2336                                 lib_node_do_versions_group_indices(node);
2337                 }
2338         }
2339 }
2340
2341 /* make an update call for the tree */
2342 static void lib_nodetree_do_versions_update_cb(void *UNUSED(data), ID *UNUSED(id), bNodeTree *ntree)
2343 {
2344         if (ntree->update)
2345                 ntreeUpdateTree(ntree);
2346 }
2347
2348 /* verify types for nodes and groups, all data has to be read */
2349 /* open = 0: appending/linking, open = 1: open new file (need to clean out dynamic
2350  * typedefs */
2351 static void lib_verify_nodetree(Main *main, int UNUSED(open))
2352 {
2353         bNodeTree *ntree;
2354         int i;
2355         bNodeTreeType *ntreetype;
2356         
2357         /* this crashes blender on undo/redo */
2358 #if 0
2359                 if (open == 1) {
2360                         reinit_nodesystem();
2361                 }
2362 #endif
2363         
2364         /* set node->typeinfo pointers */
2365         for (i = 0; i < NUM_NTREE_TYPES; ++i) {
2366                 ntreetype = ntreeGetType(i);
2367                 if (ntreetype && ntreetype->foreach_nodetree)
2368                         ntreetype->foreach_nodetree(main, NULL, lib_nodetree_init_types_cb);
2369         }
2370         for (ntree = main->nodetree.first; ntree; ntree = ntree->id.next)
2371                 lib_nodetree_init_types_cb(NULL, NULL, ntree);
2372         
2373         {
2374                 int has_old_groups = 0;
2375                 /* XXX this should actually be part of do_versions, but since we need
2376                  * finished library linking, it is not possible there. Instead in do_versions
2377                  * we have set the NTREE_DO_VERSIONS flag, so at this point we can do the
2378                  * actual group node updates.
2379                  */
2380                 for (ntree = main->nodetree.first; ntree; ntree = ntree->id.next) {
2381                         if (ntree->flag & NTREE_DO_VERSIONS_GROUP_EXPOSE) {
2382                                 /* this adds copies and links from all unlinked internal sockets to group inputs/outputs. */
2383                                 node_group_expose_all_sockets(ntree);
2384                                 has_old_groups = 1;
2385                         }
2386                 }
2387                 
2388                 if (has_old_groups) {
2389                         for (i = 0; i < NUM_NTREE_TYPES; ++i) {
2390                                 ntreetype = ntreeGetType(i);
2391                                 if (ntreetype && ntreetype->foreach_nodetree)
2392                                         ntreetype->foreach_nodetree(main, NULL, lib_nodetree_do_versions_group_indices_cb);
2393                         }
2394                 }
2395                 
2396                 for (ntree = main->nodetree.first; ntree; ntree = ntree->id.next)
2397                         ntree->flag &= ~NTREE_DO_VERSIONS_GROUP_EXPOSE;
2398         }
2399                 
2400         /* verify all group user nodes */
2401         for (ntree = main->nodetree.first; ntree; ntree = ntree->id.next) {
2402                 ntreeVerifyNodes(main, &ntree->id);
2403         }
2404         
2405         /* make update calls where necessary */
2406         {
2407                 for (ntree = main->nodetree.first; ntree; ntree = ntree->id.next)
2408                         if (ntree->update)
2409                                 ntreeUpdateTree(ntree);
2410                 
2411                 for (i = 0; i < NUM_NTREE_TYPES; i++) {
2412                         ntreetype = ntreeGetType(i);
2413                         if (ntreetype && ntreetype->foreach_nodetree)
2414                                 ntreetype->foreach_nodetree(main, NULL, lib_nodetree_do_versions_update_cb);
2415                 }
2416         }
2417 }
2418
2419 static void direct_link_node_socket(FileData *fd, bNodeSocket *sock)
2420 {
2421         sock->link = newdataadr(fd, sock->link);
2422         sock->storage = newdataadr(fd, sock->storage);
2423         sock->default_value = newdataadr(fd, sock->default_value);
2424         sock->cache = NULL;
2425 }
2426
2427 /* ntree itself has been read! */
2428 static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
2429 {
2430         /* note: writing and reading goes in sync, for speed */
2431         bNode *node;
2432         bNodeSocket *sock;
2433         bNodeLink *link;
2434         
2435         ntree->init = 0;                /* to set callbacks and force setting types */
2436         ntree->progress = NULL;
2437         ntree->execdata = NULL;
2438         
2439         ntree->adt = newdataadr(fd, ntree->adt);
2440         direct_link_animdata(fd, ntree->adt);
2441         
2442         link_list(fd, &ntree->nodes);
2443         for (node = ntree->nodes.first; node; node = node->next) {
2444                 node->typeinfo = NULL;
2445                 
2446                 link_list(fd, &node->inputs);
2447                 link_list(fd, &node->outputs);
2448                 
2449                 if (node->type == CMP_NODE_MOVIEDISTORTION) {
2450                         node->storage = newmclipadr(fd, node->storage);
2451                 }
2452                 else
2453                         node->storage = newdataadr(fd, node->storage);
2454                 
2455                 if (node->storage) {
2456                         /* could be handlerized at some point */
2457                         if (ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
2458                                 direct_link_curvemapping(fd, node->storage);
2459                         else if (ntree->type==NTREE_COMPOSIT) {
2460                                 if (ELEM4(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB, CMP_NODE_HUECORRECT))
2461                                         direct_link_curvemapping(fd, node->storage);
2462                                 else if (ELEM3(node->type, CMP_NODE_IMAGE, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
2463                                         ((ImageUser *)node->storage)->ok = 1;
2464                         }
2465                         else if ( ntree->type==NTREE_TEXTURE) {
2466                                 if (node->type==TEX_NODE_CURVE_RGB || node->type==TEX_NODE_CURVE_TIME)
2467                                         direct_link_curvemapping(fd, node->storage);
2468                                 else if (node->type==TEX_NODE_IMAGE)
2469                                         ((ImageUser *)node->storage)->ok = 1;
2470                         }
2471                 }
2472         }
2473         link_list(fd, &ntree->links);
2474         
2475         /* external sockets */
2476         link_list(fd, &ntree->inputs);
2477         link_list(fd, &ntree->outputs);
2478         
2479         /* and we connect the rest */
2480         for (node = ntree->nodes.first; node; node = node->next) {
2481                 node->parent = newdataadr(fd, node->parent);
2482                 node->preview = newimaadr(fd, node->preview);
2483                 node->lasty = 0;
2484                 
2485                 for (sock = node->inputs.first; sock; sock = sock->next)
2486                         direct_link_node_socket(fd, sock);
2487                 for (sock = node->outputs.first; sock; sock = sock->next)
2488                         direct_link_node_socket(fd, sock);
2489         }
2490         for (sock = ntree->inputs.first; sock; sock = sock->next)
2491                 direct_link_node_socket(fd, sock);
2492         for (sock = ntree->outputs.first; sock; sock = sock->next)
2493                 direct_link_node_socket(fd, sock);
2494         
2495         for (link = ntree->links.first; link; link= link->next) {
2496                 link->fromnode = newdataadr(fd, link->fromnode);
2497                 link->tonode = newdataadr(fd, link->tonode);
2498                 link->fromsock = newdataadr(fd, link->fromsock);
2499                 link->tosock = newdataadr(fd, link->tosock);
2500         }
2501         
2502         /* type verification is in lib-link */
2503 }
2504
2505 /* ************ READ ARMATURE ***************** */
2506
2507 /* temp struct used to transport needed info to lib_link_constraint_cb() */
2508 typedef struct tConstraintLinkData {
2509         FileData *fd;
2510         ID *id;
2511 } tConstraintLinkData;
2512 /* callback function used to relink constraint ID-links */
2513 static void lib_link_constraint_cb(bConstraint *UNUSED(con), ID **idpoin, short isReference, void *userdata)
2514 {
2515         tConstraintLinkData *cld= (tConstraintLinkData *)userdata;
2516         
2517         /* for reference types, we need to increment the usercounts on load... */
2518         if (isReference) {
2519                 /* reference type - with usercount */
2520                 *idpoin = newlibadr_us(cld->fd, cld->id->lib, *idpoin);
2521         }
2522         else {
2523                 /* target type - no usercount needed */
2524                 *idpoin = newlibadr(cld->fd, cld->id->lib, *idpoin);
2525         }
2526 }
2527
2528 static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
2529 {
2530         tConstraintLinkData cld;
2531         bConstraint *con;
2532         
2533         /* legacy fixes */
2534         for (con = conlist->first; con; con=con->next) {
2535                 /* patch for error introduced by changing constraints (dunno how) */
2536                 /* if con->data type changes, dna cannot resolve the pointer! (ton) */
2537                 if (con->data == NULL) {
2538                         con->type = CONSTRAINT_TYPE_NULL;
2539                 }
2540                 /* own ipo, all constraints have it */
2541                 con->ipo = newlibadr_us(fd, id->lib, con->ipo); // XXX depreceated - old animation system
2542         }
2543         
2544         /* relink all ID-blocks used by the constraints */
2545         cld.fd = fd;
2546         cld.id = id;
2547         
2548         id_loop_constraints(conlist, lib_link_constraint_cb, &cld);
2549 }
2550
2551 static void direct_link_constraints(FileData *fd, ListBase *lb)
2552 {
2553         bConstraint *con;
2554         
2555         link_list(fd, lb);
2556         for (con=lb->first; con; con=con->next) {
2557                 con->data = newdataadr(fd, con->data);
2558                 
2559                 switch (con->type) {
2560                         case CONSTRAINT_TYPE_PYTHON:
2561                         {
2562                                 bPythonConstraint *data= con->data;
2563                                 
2564                                 link_list(fd, &data->targets);
2565                                 
2566                                 data->prop = newdataadr(fd, data->prop);
2567                                 if (data->prop)
2568                                         IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2569                         }
2570                                 break;
2571                         case CONSTRAINT_TYPE_SPLINEIK:
2572                         {
2573                                 bSplineIKConstraint *data= con->data;
2574                                 
2575                                 data->points= newdataadr(fd, data->points);
2576                         }
2577                                 break;
2578                         case CONSTRAINT_TYPE_KINEMATIC:
2579                         {
2580                                 con->lin_error = 0.f;
2581                                 con->rot_error = 0.f;
2582                         }
2583                         case CONSTRAINT_TYPE_CHILDOF:
2584                         {
2585                                 /* XXX version patch, in older code this flag wasn't always set, and is inherent to type */
2586                                 if (con->ownspace == CONSTRAINT_SPACE_POSE)
2587                                         con->flag |= CONSTRAINT_SPACEONCE;
2588                         }
2589                                 break;
2590                 }
2591         }
2592 }
2593
2594 static void lib_link_pose(FileData *fd, Object *ob, bPose *pose)
2595 {
2596         bPoseChannel *pchan;
2597         bArmature *arm = ob->data;
2598         int rebuild;
2599         
2600         if (!pose || !arm)
2601                 return;
2602         
2603         
2604         /* always rebuild to match proxy or lib changes */
2605         rebuild = ob->proxy || (ob->id.lib==NULL && arm->id.lib);
2606         
2607         if (ob->proxy) {
2608                 /* sync proxy layer */
2609                 if (pose->proxy_layer)
2610                         arm->layer = pose->proxy_layer;
2611                 
2612                 /* sync proxy active bone */
2613                 if (pose->proxy_act_bone[0]) {
2614                         Bone *bone = BKE_armature_find_bone_name(arm, pose->proxy_act_bone);
2615                         if (bone)
2616                                 arm->act_bone = bone;
2617                 }
2618         }
2619         
2620         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
2621                 lib_link_constraints(fd, (ID *)ob, &pchan->constraints);
2622                 
2623                 /* hurms... loop in a loop, but yah... later... (ton) */
2624                 pchan->bone = BKE_armature_find_bone_name(arm, pchan->name);
2625                 
2626                 pchan->custom = newlibadr_us(fd, arm->id.lib, pchan->custom);
2627                 if (pchan->bone == NULL)
2628                         rebuild= 1;
2629                 else if (ob->id.lib==NULL && arm->id.lib) {
2630                         /* local pose selection copied to armature, bit hackish */
2631                         pchan->bone->flag &= ~BONE_SELECTED;
2632                         pchan->bone->flag |= pchan->selectflag;
2633                 }
2634         }
2635         
2636         if (rebuild) {
2637                 ob->recalc = (OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
2638                 pose->flag |= POSE_RECALC;
2639         }
2640 }
2641
2642 static void lib_link_armature(FileData *fd, Main *main)
2643 {
2644         bArmature *arm;
2645         
2646         for (arm = main->armature.first; arm; arm = arm->id.next) {
2647                 if (arm->id.flag & LIB_NEEDLINK) {
2648                         if (arm->adt) lib_link_animdata(fd, &arm->id, arm->adt);
2649                         arm->id.flag -= LIB_NEEDLINK;
2650                 }
2651         }
2652 }
2653
2654 static void direct_link_bones(FileData *fd, Bone* bone)
2655 {
2656         Bone *child;
2657         
2658         bone->parent = newdataadr(fd, bone->parent);
2659         bone->prop = newdataadr(fd, bone->prop);
2660         if (bone->prop)
2661                 IDP_DirectLinkProperty(bone->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2662                 
2663         bone->flag &= ~BONE_DRAW_ACTIVE;
2664         
2665         link_list(fd, &bone->childbase);
2666         
2667         for (child=bone->childbase.first; child; child=child->next)
2668                 direct_link_bones(fd, child);
2669 }
2670
2671 static void direct_link_armature(FileData *fd, bArmature *arm)
2672 {
2673         Bone *bone;
2674         
2675         link_list(fd, &arm->bonebase);
2676         arm->edbo = NULL;
2677         arm->sketch = NULL;
2678         
2679         arm->adt = newdataadr(fd, arm->adt);
2680         direct_link_animdata(fd, arm->adt);
2681         
2682         for (bone = arm->bonebase.first; bone; bone = bone->next) {
2683                 direct_link_bones(fd, bone);
2684         }
2685         
2686         arm->act_bone = newdataadr(fd, arm->act_bone);
2687         arm->act_edbone = NULL;
2688 }
2689
2690 /* ************ READ CAMERA ***************** */
2691
2692 static void lib_link_camera(FileData *fd, Main *main)
2693 {
2694         Camera *ca;
2695         
2696         for (ca = main->camera.first; ca; ca = ca->id.next) {
2697                 if (ca->id.flag & LIB_NEEDLINK) {
2698                         if (ca->adt) lib_link_animdata(fd, &ca->id, ca->adt);
2699                         
2700                         ca->ipo = newlibadr_us(fd, ca->id.lib, ca->ipo); // XXX depreceated - old animation system
2701                         
2702                         ca->dof_ob = newlibadr_us(fd, ca->id.lib, ca->dof_ob);
2703                         
2704                         ca->id.flag -= LIB_NEEDLINK;
2705                 }
2706         }
2707 }
2708
2709 static void direct_link_camera(FileData *fd, Camera *ca)
2710 {
2711         ca->adt = newdataadr(fd, ca->adt);
2712         direct_link_animdata(fd, ca->adt);
2713 }
2714
2715
2716 /* ************ READ LAMP ***************** */
2717
2718 static void lib_link_lamp(FileData *fd, Main *main)
2719 {
2720         Lamp *la;
2721         MTex *mtex;
2722         int a;
2723         
2724         for (la = main->lamp.first; la; la = la->id.next) {
2725                 if (la->id.flag & LIB_NEEDLINK) {
2726                         if (la->adt) lib_link_animdata(fd, &la->id, la->adt);
2727                         
2728                         for (a = 0; a < MAX_MTEX; a++) {
2729                                 mtex = la->mtex[a];
2730                                 if (mtex) {
2731                                         mtex->tex = newlibadr_us(fd, la->id.lib, mtex->tex);
2732                                         mtex->object = newlibadr(fd, la->id.lib, mtex->object);
2733                                 }
2734                         }
2735                         
2736                         la->ipo = newlibadr_us(fd, la->id.lib, la->ipo); // XXX depreceated - old animation system
2737                         
2738                         if (la->nodetree)
2739                                 lib_link_ntree(fd, &la->id, la->nodetree);
2740                         
2741                         la->id.flag -= LIB_NEEDLINK;
2742                 }
2743         }
2744 }
2745
2746 static void direct_link_lamp(FileData *fd, Lamp *la)
2747 {
2748         int a;
2749         
2750         la->adt = newdataadr(fd, la->adt);
2751         direct_link_animdata(fd, la->adt);
2752         
2753         for (a=0; a<MAX_MTEX; a++) {
2754                 la->mtex[a] = newdataadr(fd, la->mtex[a]);
2755         }
2756         
2757         la->curfalloff = newdataadr(fd, la->curfalloff);
2758         if (la->curfalloff)
2759                 direct_link_curvemapping(fd, la->curfalloff);
2760
2761         la->nodetree= newdataadr(fd, la->nodetree);
2762         if (la->nodetree)
2763                 direct_link_nodetree(fd, la->nodetree);
2764         
2765         la->preview = direct_link_preview_image(fd, la->preview);
2766 }
2767
2768 /* ************ READ keys ***************** */
2769
2770 static void lib_link_key(FileData *fd, Main *main)
2771 {
2772         Key *key;
2773         
2774         for (key = main->key.first; key; key = key->id.next) {
2775                 /*check if we need to generate unique ids for the shapekeys*/
2776                 if (!key->uidgen) {
2777                         KeyBlock *block;
2778                         
2779                         key->uidgen = 1;
2780                         for (block=key->block.first; block; block=block->next) {
2781                                 block->uid = key->uidgen++;
2782                         }
2783                 }
2784                 
2785                 if (key->id.flag & LIB_NEEDLINK) {
2786                         if (key->adt) lib_link_animdata(fd, &key->id, key->adt);
2787                         
2788                         key->ipo = newlibadr_us(fd, key->id.lib, key->ipo); // XXX depreceated - old animation system
2789                         key->from = newlibadr(fd, key->id.lib, key->from);
2790                         
2791                         key->id.flag -= LIB_NEEDLINK;
2792                 }
2793         }
2794 }
2795
2796 static void switch_endian_keyblock(Key *key, KeyBlock *kb)
2797 {
2798         int elemsize, a, b;
2799         char *data, *poin, *cp;
2800         
2801         elemsize = key->elemsize;
2802         data = kb->data;
2803         
2804         for (a = 0; a < kb->totelem; a++) {
2805                 cp = key->elemstr;
2806                 poin = data;
2807                 
2808                 while (cp[0]) {  /* cp[0] == amount */
2809                         switch (cp[1]) {  /* cp[1] = type */
2810                                 case IPO_FLOAT:
2811                                 case IPO_BPOINT:
2812                                 case IPO_BEZTRIPLE:
2813                                         b = cp[0];
2814                                         
2815                                         while (b--) {
2816                                                 SWITCH_INT((*poin));
2817                                                 poin += 4;
2818                                         }
2819                                         break;
2820                         }
2821                         
2822                         cp += 2;
2823                 }
2824                 data+= elemsize;
2825         }
2826 }
2827
2828 static void direct_link_key(FileData *fd, Key *key)
2829 {
2830         KeyBlock *kb;
2831         
2832         link_list(fd, &(key->block));
2833         
2834         key->adt = newdataadr(fd, key->adt);
2835         direct_link_animdata(fd, key->adt);
2836                 
2837         key->refkey= newdataadr(fd, key->refkey);
2838         
2839         for (kb = key->block.first; kb; kb = kb->next) {
2840                 kb->data = newdataadr(fd, kb->data);
2841                 
2842                 if (fd->flags & FD_FLAGS_SWITCH_ENDIAN)
2843                         switch_endian_keyblock(key, kb);
2844         }
2845 }
2846
2847 /* ************ READ mball ***************** */
2848
2849 static void lib_link_mball(FileData *fd, Main *main)
2850 {
2851         MetaBall *mb;
2852         int a;
2853         
2854         for (mb = main->mball.first; mb; mb = mb->id.next) {
2855                 if (mb->id.flag & LIB_NEEDLINK) {
2856                         if (mb->adt) lib_link_animdata(fd, &mb->id, mb->adt);
2857                         
2858                         for (a = 0; a < mb->totcol; a++) 
2859                                 mb->mat[a]= newlibadr_us(fd, mb->id.lib, mb->mat[a]);
2860                         
2861                         mb->ipo = newlibadr_us(fd, mb->id.lib, mb->ipo); // XXX depreceated - old animation system
2862                         
2863                         mb->id.flag -= LIB_NEEDLINK;
2864                 }
2865         }
2866 }
2867
2868 static void direct_link_mball(FileData *fd, MetaBall *mb)
2869 {
2870         mb->adt = newdataadr(fd, mb->adt);
2871         direct_link_animdata(fd, mb->adt);
2872         
2873         mb->mat = newdataadr(fd, mb->mat);
2874         test_pointer_array(fd, (void **)&mb->mat);
2875         
2876         link_list(fd, &(mb->elems));
2877         
2878         mb->disp.first = mb->disp.last = NULL;
2879         mb->editelems = NULL;
2880         mb->bb = NULL;
2881 /*      mb->edit_elems.first= mb->edit_elems.last= NULL;*/
2882         mb->lastelem = NULL;
2883 }
2884
2885 /* ************ READ WORLD ***************** */
2886
2887 static void lib_link_world(FileData *fd, Main *main)
2888 {
2889         World *wrld;
2890         MTex *mtex;
2891         int a;
2892         
2893         for (wrld = main->world.first; wrld; wrld = wrld->id.next) {
2894                 if (wrld->id.flag & LIB_NEEDLINK) {
2895                         if (wrld->adt) lib_link_animdata(fd, &wrld->id, wrld->adt);
2896                         
2897                         wrld->ipo = newlibadr_us(fd, wrld->id.lib, wrld->ipo); // XXX depreceated - old animation system
2898                         
2899                         for (a=0; a < MAX_MTEX; a++) {
2900                                 mtex = wrld->mtex[a];
2901                                 if (mtex) {
2902                                         mtex->tex = newlibadr_us(fd, wrld->id.lib, mtex->tex);
2903                                         mtex->object = newlibadr(fd, wrld->id.lib, mtex->object);
2904                                 }
2905                         }
2906                         
2907                         if (wrld->nodetree)
2908                                 lib_link_ntree(fd, &wrld->id, wrld->nodetree);
2909                         
2910                         wrld->id.flag -= LIB_NEEDLINK;
2911                 }
2912         }
2913 }
2914
2915 static void direct_link_world(FileData *fd, World *wrld)
2916 {
2917         int a;
2918         
2919         wrld->adt = newdataadr(fd, wrld->adt);
2920         direct_link_animdata(fd, wrld->adt);
2921         
2922         for (a = 0; a < MAX_MTEX; a++) {
2923                 wrld->mtex[a] = newdataadr(fd, wrld->mtex[a]);
2924         }
2925         
2926         wrld->nodetree = newdataadr(fd, wrld->nodetree);
2927         if (wrld->nodetree)
2928                 direct_link_nodetree(fd, wrld->nodetree);
2929         
2930         wrld->preview = direct_link_preview_image(fd, wrld->preview);
2931 }
2932
2933
2934 /* ************ READ VFONT ***************** */
2935
2936 static void lib_link_vfont(FileData *UNUSED(fd), Main *main)
2937 {
2938         VFont *vf;
2939         
2940         for (vf = main->vfont.first; vf; vf = vf->id.next) {
2941                 if (vf->id.flag & LIB_NEEDLINK) {
2942                         vf->id.flag -= LIB_NEEDLINK;
2943                 }
2944         }
2945 }
2946
2947 static void direct_link_vfont(FileData *fd, VFont *vf)
2948 {
2949         vf->data = NULL;
2950         vf->packedfile = direct_link_packedfile(fd, vf->packedfile);
2951 }
2952
2953 /* ************ READ TEXT ****************** */
2954
2955 static void lib_link_text(FileData *UNUSED(fd), Main *main)
2956 {
2957         Text *text;
2958         
2959         for (text = main->text.first; text; text = text->id.next) {
2960                 if (text->id.flag & LIB_NEEDLINK) {
2961                         text->id.flag -= LIB_NEEDLINK;
2962                 }
2963         }
2964 }
2965
2966 static void direct_link_text(FileData *fd, Text *text)
2967 {
2968         TextLine *ln;
2969         
2970         text->name = newdataadr(fd, text->name);
2971         
2972         text->undo_pos = -1;
2973         text->undo_len = TXT_INIT_UNDO;
2974         text->undo_buf = MEM_mallocN(text->undo_len, "undo buf");
2975         
2976         text->compiled = NULL;
2977         
2978 #if 0
2979         if (text->flags & TXT_ISEXT) {
2980                 BKE_text_reload(text);
2981                 }
2982                 else {
2983 #endif
2984         
2985         link_list(fd, &text->lines);
2986         link_list(fd, &text->markers);
2987         
2988         text->curl = newdataadr(fd, text->curl);
2989         text->sell = newdataadr(fd, text->sell);
2990         
2991         for (ln = text->lines.first; ln; ln = ln->next) {
2992                 ln->line = newdataadr(fd, ln->line);
2993                 ln->format = NULL;
2994                 
2995                 if (ln->len != (int) strlen(ln->line)) {
2996                         printf("Error loading text, line lengths differ\n");
2997                         ln->len = strlen(ln->line);
2998                 }
2999         }
3000         
3001         text->flags = (text->flags) & ~TXT_ISEXT;
3002         
3003         text->id.us = 1;
3004 }
3005
3006 /* ************ READ IMAGE ***************** */
3007
3008 static void lib_link_image(FileData *fd, Main *main)
3009 {
3010         Image *ima;
3011         
3012         for (ima = main->image.first; ima; ima = ima->id.next) {
3013                 if (ima->id.flag & LIB_NEEDLINK) {
3014                         if (ima->id.properties) IDP_LibLinkProperty(ima->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
3015                         
3016                         ima->id.flag -= LIB_NEEDLINK;
3017                 }
3018         }
3019 }
3020
3021 static void link_ibuf_list(FileData *fd, ListBase *lb)
3022 {
3023         Link *ln, *prev;
3024         
3025         if (lb->first == NULL) return;
3026         
3027         lb->first = newimaadr(fd, lb->first);
3028         ln = lb->first;
3029         prev = NULL;
3030         while (ln) {
3031                 ln->next = newimaadr(fd, ln->next);
3032                 ln->prev = prev;
3033                 prev = ln;
3034                 ln = ln->next;
3035         }
3036         lb->last = prev;
3037 }
3038
3039 static void direct_link_image(FileData *fd, Image *ima)
3040 {
3041         /* for undo system, pointers could be restored */
3042         if (fd->imamap)
3043                 link_ibuf_list(fd, &ima->ibufs);
3044         else
3045                 ima->ibufs.first = ima->ibufs.last = NULL;
3046         
3047         /* if not restored, we keep the binded opengl index */
3048         if (ima->ibufs.first == NULL) {
3049                 ima->bindcode = 0;
3050                 ima->gputexture = NULL;
3051         }
3052         
3053         ima->anim = NULL;
3054         ima->rr = NULL;
3055         ima->repbind = NULL;
3056         
3057         /* undo system, try to restore render buffers */
3058         if (fd->imamap) {
3059                 int a;
3060                 
3061                 for (a = 0; a < IMA_MAX_RENDER_SLOT; a++)
3062                         ima->renders[a] = newimaadr(fd, ima->renders[a]);
3063         }
3064         else {
3065                 memset(ima->renders, 0, sizeof(ima->renders));
3066                 ima->last_render_slot = ima->render_slot;
3067         }
3068         
3069         ima->packedfile = direct_link_packedfile(fd, ima->packedfile);
3070         ima->preview = direct_link_preview_image(fd, ima->preview);
3071         ima->ok = 1;
3072 }
3073
3074
3075 /* ************ READ CURVE ***************** */
3076
3077 static void lib_link_curve(FileData *fd, Main *main)
3078 {
3079         Curve *cu;
3080         int a;
3081         
3082         for (cu = main->curve.first; cu; cu = cu->id.next) {
3083                 if (cu->id.flag & LIB_NEEDLINK) {
3084                         if (cu->adt) lib_link_animdata(fd, &cu->id, cu->adt);
3085                         
3086                         for (a = 0; a < cu->totcol; a++) 
3087                                 cu->mat[a] = newlibadr_us(fd, cu->id.lib, cu->mat[a]);
3088                         
3089                         cu->bevobj = newlibadr(fd, cu->id.lib, cu->bevobj);
3090                         cu->taperobj = newlibadr(fd, cu->id.lib, cu->taperobj);
3091                         cu->textoncurve = newlibadr(fd, cu->id.lib, cu->textoncurve);
3092                         cu->vfont = newlibadr_us(fd, cu->id.lib, cu->vfont);
3093                         cu->vfontb = newlibadr_us(fd, cu->id.lib, cu->vfontb);                  
3094                         cu->vfonti = newlibadr_us(fd, cu->id.lib, cu->vfonti);
3095                         cu->vfontbi = newlibadr_us(fd, cu->id.lib, cu->vfontbi);
3096                         
3097                         cu->ipo = newlibadr_us(fd, cu->id.lib, cu->ipo); // XXX depreceated - old animation system
3098                         cu->key = newlibadr_us(fd, cu->id.lib, cu->key);
3099                         
3100                         cu->id.flag -= LIB_NEEDLINK;
3101                 }
3102         }
3103 }
3104
3105
3106 static void switch_endian_knots(Nurb *nu)
3107 {
3108         int len;
3109         
3110         if (nu->knotsu) {
3111                 len = KNOTSU(nu);
3112                 while (len--) {
3113                         SWITCH_INT(nu->knotsu[len]);
3114                 }
3115         }
3116         if (nu->knotsv) {
3117                 len = KNOTSV(nu);
3118                 while (len--) {
3119                         SWITCH_INT(nu->knotsv[len]);
3120                 }
3121         }
3122 }
3123
3124 static void direct_link_curve(FileData *fd, Curve *cu)
3125 {
3126         Nurb *nu;
3127         TextBox *tb;
3128         
3129         cu->adt= newdataadr(fd, cu->adt);
3130         direct_link_animdata(fd, cu->adt);
3131         
3132         cu->mat = newdataadr(fd, cu->mat);
3133         test_pointer_array(fd, (void **)&cu->mat);
3134         cu->str = newdataadr(fd, cu->str);
3135         cu->strinfo= newdataadr(fd, cu->strinfo);       
3136         cu->tb = newdataadr(fd, cu->tb);
3137
3138         if (cu->vfont == NULL) link_list(fd, &(cu->nurb));
3139         else {
3140                 cu->nurb.first=cu->nurb.last= NULL;
3141                 
3142                 tb = MEM_callocN(MAXTEXTBOX*sizeof(TextBox), "TextBoxread");
3143                 if (cu->tb) {
3144                         memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox));
3145                         MEM_freeN(cu->tb);
3146                         cu->tb = tb;                    
3147                 }
3148                 else {
3149                         cu->totbox = 1;
3150                         cu->actbox = 1;
3151                         cu->tb = tb;
3152                         cu->tb[0].w = cu->linewidth;
3153                 }               
3154                 if (cu->wordspace == 0.0f) cu->wordspace = 1.0f;
3155         }
3156
3157         cu->bev.first = cu->bev.last = NULL;
3158         cu->disp.first = cu->disp.last = NULL;
3159         cu->editnurb = NULL;
3160         cu->lastsel = NULL;
3161         cu->path = NULL;
3162         cu->editfont = NULL;
3163         
3164         for (nu = cu->nurb.first; nu; nu = nu->next) {
3165                 nu->bezt = newdataadr(fd, nu->bezt);
3166                 nu->bp = newdataadr(fd, nu->bp);
3167                 nu->knotsu = newdataadr(fd, nu->knotsu);
3168                 nu->knotsv = newdataadr(fd, nu->knotsv);
3169                 if (cu->vfont == NULL) nu->charidx= nu->mat_nr;
3170                 
3171                 if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
3172                         switch_endian_knots(nu);
3173                 }
3174         }
3175         cu->bb = NULL;
3176 }
3177
3178 /* ************ READ TEX ***************** */
3179
3180 static void lib_link_texture(FileData *fd, Main *main)
3181 {
3182         Tex *tex;
3183         
3184         for (tex = main->tex.first; tex; tex = tex->id.next) {
3185                 if (tex->id.flag & LIB_NEEDLINK) {
3186                         if (tex->adt) lib_link_animdata(fd, &tex->id, tex->adt);
3187                         
3188                         tex->ima = newlibadr_us(fd, tex->id.lib, tex->ima);
3189                         tex->ipo = newlibadr_us(fd, tex->id.lib, tex->ipo);
3190                         if (tex->env)
3191                                 tex->env->object = newlibadr(fd, tex->id.lib, tex->env->object);
3192                         if (tex->pd)
3193                                 tex->pd->object = newlibadr(fd, tex->id.lib, tex->pd->object);
3194                         if (tex->vd)
3195                                 tex->vd->object = newlibadr(fd, tex->id.lib, tex->vd->object);
3196                         if (tex->ot)
3197                                 tex->ot->object = newlibadr(fd, tex->id.lib, tex->ot->object);
3198                         
3199                         if (tex->nodetree)
3200                                 lib_link_ntree(fd, &tex->id, tex->nodetree);
3201                         
3202                         tex->id.flag -= LIB_NEEDLINK;
3203                 }
3204         }
3205 }
3206
3207 static void direct_link_texture(FileData *fd, Tex *tex)
3208 {
3209         tex->adt = newdataadr(fd, tex->adt);
3210         direct_link_animdata(fd, tex->adt);
3211
3212         tex->coba = newdataadr(fd, tex->coba);
3213         tex->env = newdataadr(fd, tex->env);
3214         if (tex->env) {
3215                 tex->env->ima = NULL;
3216                 memset(tex->env->cube, 0, 6*sizeof(void *));
3217                 tex->env->ok= 0;
3218         }
3219         tex->pd = newdataadr(fd, tex->pd);
3220         if (tex->pd) {
3221                 tex->pd->point_tree = NULL;
3222                 tex->pd->coba = newdataadr(fd, tex->pd->coba);
3223                 tex->pd->falloff_curve = newdataadr(fd, tex->pd->falloff_curve);
3224                 if (tex->pd->falloff_curve) {
3225                         direct_link_curvemapping(fd, tex->pd->falloff_curve);
3226                 }
3227         }
3228         
3229         tex->vd = newdataadr(fd, tex->vd);
3230         if (tex->vd) {
3231                 tex->vd->dataset = NULL;