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