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