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