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