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