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