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