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