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