fix for crash in recent ghost/do_versions
[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                 }
1699         }
1700 }
1701
1702 static void lib_link_fcurves(FileData *fd, ID *id, ListBase *list) 
1703 {
1704         FCurve *fcu;
1705         
1706         if (list == NULL)
1707                 return;
1708         
1709         /* relink ID-block references... */
1710         for (fcu= list->first; fcu; fcu= fcu->next) {
1711                 /* driver data */
1712                 if (fcu->driver) {
1713                         ChannelDriver *driver= fcu->driver;
1714                         DriverTarget *dtar;
1715                         
1716                         for (dtar= driver->targets.first; dtar; dtar= dtar->next)
1717                                 dtar->id= newlibadr(fd, id->lib, dtar->id); 
1718                 }
1719                 
1720                 /* modifiers */
1721                 lib_link_fmodifiers(fd, id, &fcu->modifiers);
1722         }
1723 }
1724
1725
1726 /* NOTE: this assumes that link_list has already been called on the list */
1727 static void direct_link_fmodifiers(FileData *fd, ListBase *list)
1728 {
1729         FModifier *fcm;
1730         
1731         for (fcm= list->first; fcm; fcm= fcm->next) {
1732                 /* relink general data */
1733                 fcm->data = newdataadr(fd, fcm->data);
1734                 fcm->edata= NULL;
1735                 
1736                 /* do relinking of data for specific types */
1737                 switch (fcm->type) {
1738                         case FMODIFIER_TYPE_GENERATOR:
1739                         {
1740                                 FMod_Generator *data= (FMod_Generator *)fcm->data;
1741                                 
1742                                 data->coefficients= newdataadr(fd, data->coefficients);
1743                         }
1744                                 break;
1745                         case FMODIFIER_TYPE_ENVELOPE:
1746                         {
1747                                 FMod_Envelope *data= (FMod_Envelope *)fcm->data;
1748                                 
1749                                 data->data= newdataadr(fd, data->data);
1750                         }
1751                                 break;
1752                         case FMODIFIER_TYPE_PYTHON:
1753                         {
1754                                 FMod_Python *data= (FMod_Python *)fcm->data;
1755                                 
1756                                 data->prop = newdataadr(fd, data->prop);
1757                                 IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
1758                         }
1759                                 break;
1760                 }
1761         }
1762 }
1763
1764 /* NOTE: this assumes that link_list has already been called on the list */
1765 static void direct_link_fcurves(FileData *fd, ListBase *list)
1766 {
1767         FCurve *fcu;
1768         
1769         /* link F-Curve data to F-Curve again (non ID-libs) */
1770         for (fcu= list->first; fcu; fcu= fcu->next) {
1771                 /* curve data */
1772                 fcu->bezt= newdataadr(fd, fcu->bezt);
1773                 fcu->fpt= newdataadr(fd, fcu->fpt);
1774                 
1775                 /* rna path */
1776                 fcu->rna_path= newdataadr(fd, fcu->rna_path);
1777                 
1778                 /* group */
1779                 fcu->grp= newdataadr(fd, fcu->grp);
1780                 
1781                 /* driver */
1782                 fcu->driver= newdataadr(fd, fcu->driver);
1783                 if (fcu->driver) {
1784                         ChannelDriver *driver= fcu->driver;
1785                         DriverTarget *dtar;
1786                         
1787                         /* relink targets and their paths */
1788                         link_list(fd, &driver->targets);
1789                         for (dtar= driver->targets.first; dtar; dtar= dtar->next)
1790                                 dtar->rna_path= newdataadr(fd, dtar->rna_path);
1791                 }
1792                 
1793                 /* modifiers */
1794                 link_list(fd, &fcu->modifiers);
1795                 direct_link_fmodifiers(fd, &fcu->modifiers);
1796         }
1797 }
1798
1799
1800 static void lib_link_action(FileData *fd, Main *main)
1801 {
1802         bAction *act;
1803         bActionChannel *chan;
1804
1805         for (act= main->action.first; act; act= act->id.next) {
1806                 if (act->id.flag & LIB_NEEDLINK) {
1807                         act->id.flag -= LIB_NEEDLINK;
1808                         
1809 // XXX depreceated - old animation system <<<
1810                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1811                                 chan->ipo= newlibadr_us(fd, act->id.lib, chan->ipo);
1812                                 lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
1813                         }
1814 // >>> XXX depreceated - old animation system
1815                         
1816                         lib_link_fcurves(fd, &act->id, &act->curves);
1817                 }
1818         }
1819 }
1820
1821 static void direct_link_action(FileData *fd, bAction *act)
1822 {
1823         bActionChannel *achan; // XXX depreceated - old animation system
1824         bActionGroup *agrp;
1825
1826         link_list(fd, &act->curves);
1827         link_list(fd, &act->chanbase); // XXX depreceated - old animation system
1828         link_list(fd, &act->groups);
1829         link_list(fd, &act->markers);
1830
1831 // XXX depreceated - old animation system <<<
1832         for (achan = act->chanbase.first; achan; achan=achan->next) {
1833                 achan->grp= newdataadr(fd, achan->grp);
1834                 
1835                 link_list(fd, &achan->constraintChannels);
1836         }
1837 // >>> XXX depreceated - old animation system
1838
1839         direct_link_fcurves(fd, &act->curves);
1840         
1841         for (agrp = act->groups.first; agrp; agrp= agrp->next) {
1842                 agrp->channels.first= newdataadr(fd, agrp->channels.first);
1843                 agrp->channels.last= newdataadr(fd, agrp->channels.last);
1844         }
1845 }
1846
1847 static void lib_link_nladata_strips(FileData *fd, ID *id, ListBase *list)
1848 {
1849         NlaStrip *strip;
1850         
1851         for (strip= list->first; strip; strip= strip->next) {
1852                 /* check strip's children */
1853                 lib_link_nladata_strips(fd, id, &strip->strips);
1854                 
1855                 /* check strip's F-Curves */
1856                 lib_link_fcurves(fd, id, &strip->fcurves);
1857                 
1858                 /* reassign the counted-reference to action */
1859                 strip->act = newlibadr_us(fd, id->lib, strip->act);
1860         }
1861 }
1862
1863 static void lib_link_nladata(FileData *fd, ID *id, ListBase *list)
1864 {
1865         NlaTrack *nlt;
1866         
1867         /* we only care about the NLA strips inside the tracks */
1868         for (nlt= list->first; nlt; nlt= nlt->next) {
1869                 lib_link_nladata_strips(fd, id, &nlt->strips);
1870         }
1871 }
1872
1873 /* This handles Animato NLA-Strips linking 
1874  * NOTE: this assumes that link_list has already been called on the list 
1875  */
1876 static void direct_link_nladata_strips(FileData *fd, ListBase *list)
1877 {
1878         NlaStrip *strip;
1879         
1880         for (strip= list->first; strip; strip= strip->next) {
1881                 /* strip's child strips */
1882                 link_list(fd, &strip->strips);
1883                 direct_link_nladata_strips(fd, &strip->strips);
1884                 
1885                 /* strip's F-Curves */
1886                 link_list(fd, &strip->fcurves);
1887                 direct_link_fcurves(fd, &strip->fcurves);
1888                 
1889                 /* strip's F-Modifiers */
1890                 link_list(fd, &strip->modifiers);
1891                 direct_link_fcurves(fd, &strip->modifiers);
1892         }
1893 }
1894
1895 /* NOTE: this assumes that link_list has already been called on the list */
1896 static void direct_link_nladata(FileData *fd, ListBase *list)
1897 {
1898         NlaTrack *nlt;
1899         
1900         for (nlt= list->first; nlt; nlt= nlt->next) {
1901                 /* relink list of strips */
1902                 link_list(fd, &nlt->strips);
1903                 
1904                 /* relink strip data */
1905                 direct_link_nladata_strips(fd, &nlt->strips);
1906         }
1907 }
1908
1909 /* ------- */
1910
1911 static void lib_link_keyingsets(FileData *fd, ID *id, ListBase *list)
1912 {
1913         KeyingSet *ks;
1914         KS_Path *ksp;
1915         
1916         /* here, we're only interested in the ID pointer stored in some of the paths */
1917         for (ks= list->first; ks; ks= ks->next) {
1918                 for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
1919                         ksp->id= newlibadr(fd, id->lib, ksp->id); 
1920                 }
1921         }
1922 }
1923
1924 /* NOTE: this assumes that link_list has already been called on the list */
1925 static void direct_link_keyingsets(FileData *fd, ListBase *list)
1926 {
1927         KeyingSet *ks;
1928         KS_Path *ksp;
1929         
1930         /* link KeyingSet data to KeyingSet again (non ID-libs) */
1931         for (ks= list->first; ks; ks= ks->next) {
1932                 /* paths */
1933                 link_list(fd, &ks->paths);
1934                 
1935                 for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
1936                         /* rna path */
1937                         ksp->rna_path= newdataadr(fd, ksp->rna_path);
1938                 }
1939         }
1940 }
1941
1942 /* ------- */
1943
1944 static void lib_link_animdata(FileData *fd, ID *id, AnimData *adt)
1945 {
1946         if (adt == NULL)
1947                 return;
1948         
1949         /* link action data */
1950         adt->action= newlibadr_us(fd, id->lib, adt->action);
1951         adt->tmpact= newlibadr_us(fd, id->lib, adt->tmpact);
1952         
1953         /* link drivers */
1954         lib_link_fcurves(fd, id, &adt->drivers);
1955         
1956         /* overrides don't have lib-link for now, so no need to do anything */
1957         
1958         /* link NLA-data */
1959         lib_link_nladata(fd, id, &adt->nla_tracks);
1960 }
1961
1962 static void direct_link_animdata(FileData *fd, AnimData *adt)
1963 {
1964         /* NOTE: must have called newdataadr already before doing this... */
1965         if (adt == NULL)
1966                 return;
1967         
1968         /* link drivers */
1969         link_list(fd, &adt->drivers);
1970         direct_link_fcurves(fd, &adt->drivers);
1971         
1972         /* link overrides */
1973         // TODO...
1974         
1975         /* link NLA-data */
1976         link_list(fd, &adt->nla_tracks);
1977         direct_link_nladata(fd, &adt->nla_tracks);
1978         
1979         /* clear temp pointers that may have been set... */
1980         // TODO: it's probably only a small cost to reload this anyway...
1981         adt->actstrip= NULL;
1982 }       
1983
1984 /* ************ READ MOTION PATHS *************** */
1985
1986 /* direct data for cache */
1987 static void direct_link_motionpath(FileData *fd, bMotionPath *mpath)
1988 {
1989         /* sanity check */
1990         if (mpath == NULL)
1991                 return;
1992         
1993         /* relink points cache */
1994         mpath->points= newdataadr(fd, mpath->points);
1995 }
1996
1997 /* ************ READ NODE TREE *************** */
1998
1999 /* singe node tree (also used for material/scene trees), ntree is not NULL */
2000 static void lib_link_ntree(FileData *fd, ID *id, bNodeTree *ntree)
2001 {
2002         bNode *node;
2003         
2004         if(ntree->adt) lib_link_animdata(fd, &ntree->id, ntree->adt);
2005         
2006         ntree->gpd= newlibadr_us(fd, id->lib, ntree->gpd);
2007         
2008         for(node= ntree->nodes.first; node; node= node->next)
2009                 node->id= newlibadr_us(fd, id->lib, node->id);
2010 }
2011
2012 /* library ntree linking after fileread */
2013 static void lib_link_nodetree(FileData *fd, Main *main)
2014 {
2015         bNodeTree *ntree;
2016         
2017         /* only link ID pointers */
2018         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
2019                 if(ntree->id.flag & LIB_NEEDLINK) {
2020                         ntree->id.flag -= LIB_NEEDLINK;
2021                         lib_link_ntree(fd, &ntree->id, ntree);
2022                 }
2023         }
2024 }
2025
2026 /* verify types for nodes and groups, all data has to be read */
2027 /* open = 0: appending/linking, open = 1: open new file (need to clean out dynamic
2028 * typedefs*/
2029 static void lib_verify_nodetree(Main *main, int open)
2030 {
2031         Scene *sce;
2032         Material *ma;
2033         Tex *tx;
2034         bNodeTree *ntree;
2035         
2036         /* this crashes blender on undo/redo
2037                 if(open==1) {
2038                         reinit_nodesystem();
2039                 }*/
2040         
2041         /* now create the own typeinfo structs an verify nodes */
2042         /* here we still assume no groups in groups */
2043         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
2044                 ntreeVerifyTypes(ntree);        /* internal nodes, no groups! */
2045                 ntreeMakeOwnType(ntree);        /* for group usage */
2046         }
2047         
2048         /* now verify all types in material trees, groups are set OK now */
2049         for(ma= main->mat.first; ma; ma= ma->id.next) {
2050                 if(ma->nodetree)
2051                         ntreeVerifyTypes(ma->nodetree);
2052         }
2053         /* and scene trees */
2054         for(sce= main->scene.first; sce; sce= sce->id.next) {
2055                 if(sce->nodetree)
2056                         ntreeVerifyTypes(sce->nodetree);
2057         }
2058         /* and texture trees */
2059         for(tx= main->tex.first; tx; tx= tx->id.next) {
2060                 if(tx->nodetree)
2061                         ntreeVerifyTypes(tx->nodetree);
2062         }
2063 }
2064
2065
2066
2067 /* ntree itself has been read! */
2068 static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
2069 {
2070         /* note: writing and reading goes in sync, for speed */
2071         bNode *node;
2072         bNodeSocket *sock;
2073         bNodeLink *link;
2074         
2075         ntree->init= 0;         /* to set callbacks and force setting types */
2076         ntree->owntype= NULL;
2077         ntree->timecursor= NULL;
2078         
2079         ntree->adt= newdataadr(fd, ntree->adt);
2080         direct_link_animdata(fd, ntree->adt);
2081         
2082         link_list(fd, &ntree->nodes);
2083         for(node= ntree->nodes.first; node; node= node->next) {
2084                 if(node->type == NODE_DYNAMIC) {
2085                         node->custom1= 0;
2086                         node->custom1= BSET(node->custom1, NODE_DYNAMIC_LOADED);
2087                         node->typeinfo= NULL;
2088                 }
2089                 
2090                 node->storage= newdataadr(fd, node->storage);
2091                 if(node->storage) {
2092                         
2093                         /* could be handlerized at some point */
2094                         if(ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
2095                                 direct_link_curvemapping(fd, node->storage);
2096                         else if(ntree->type==NTREE_COMPOSIT) {
2097                                 if( ELEM3(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB))
2098                                         direct_link_curvemapping(fd, node->storage);
2099                                 else if(ELEM3(node->type, CMP_NODE_IMAGE, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
2100                                         ((ImageUser *)node->storage)->ok= 1;
2101                         }
2102                         else if( ntree->type==NTREE_TEXTURE && (node->type==TEX_NODE_CURVE_RGB || node->type==TEX_NODE_CURVE_TIME) ) {
2103                                 direct_link_curvemapping(fd, node->storage);
2104                         }
2105                 }
2106                 link_list(fd, &node->inputs);
2107                 link_list(fd, &node->outputs);
2108         }
2109         link_list(fd, &ntree->links);
2110         
2111         /* and we connect the rest */
2112         for(node= ntree->nodes.first; node; node= node->next) {
2113                 node->preview= newimaadr(fd, node->preview);
2114                 node->lasty= 0;
2115                 for(sock= node->inputs.first; sock; sock= sock->next)
2116                         sock->link= newdataadr(fd, sock->link);
2117                 for(sock= node->outputs.first; sock; sock= sock->next)
2118                         sock->ns.data= NULL;
2119         }
2120         for(link= ntree->links.first; link; link= link->next) {
2121                 link->fromnode= newdataadr(fd, link->fromnode);
2122                 link->tonode= newdataadr(fd, link->tonode);
2123                 link->fromsock= newdataadr(fd, link->fromsock);
2124                 link->tosock= newdataadr(fd, link->tosock);
2125         }
2126         
2127         /* set selin and selout */
2128         for(node= ntree->nodes.first; node; node= node->next) {
2129                 for(sock= node->inputs.first; sock; sock= sock->next) {
2130                         if(sock->flag & SOCK_SEL) {
2131                                 ntree->selin= sock;
2132                                 break;
2133                         }
2134                 }
2135                 for(sock= node->outputs.first; sock; sock= sock->next) {
2136                         if(sock->flag & SOCK_SEL) {
2137                                 ntree->selout= sock;
2138                                 break;
2139                         }
2140                 }
2141         }
2142         
2143         /* type verification is in lib-link */
2144 }
2145
2146 /* ************ READ ARMATURE ***************** */
2147
2148 static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
2149 {
2150         bConstraint *con;
2151
2152         for (con = conlist->first; con; con=con->next) {
2153                 /* patch for error introduced by changing constraints (dunno how) */
2154                 /* if con->data type changes, dna cannot resolve the pointer! (ton) */
2155                 if(con->data==NULL) {
2156                         con->type= CONSTRAINT_TYPE_NULL;
2157                 }
2158                 /* own ipo, all constraints have it */
2159                 con->ipo= newlibadr_us(fd, id->lib, con->ipo); // XXX depreceated - old animation system
2160                 
2161                 switch (con->type) {
2162                 case CONSTRAINT_TYPE_PYTHON:
2163                         {
2164                                 bPythonConstraint *data= (bPythonConstraint*)con->data;
2165                                 bConstraintTarget *ct;
2166                                 
2167                                 for (ct= data->targets.first; ct; ct= ct->next)
2168                                         ct->tar = newlibadr(fd, id->lib, ct->tar);
2169                                         
2170                                 data->text = newlibadr(fd, id->lib, data->text);
2171                                 //IDP_LibLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2172                         }
2173                         break;
2174                 case CONSTRAINT_TYPE_ACTION:
2175                         {
2176                                 bActionConstraint *data;
2177                                 data= ((bActionConstraint*)con->data);
2178                                 data->tar = newlibadr(fd, id->lib, data->tar);
2179                                 data->act = newlibadr(fd, id->lib, data->act);
2180                         }
2181                         break;
2182                 case CONSTRAINT_TYPE_LOCLIKE:
2183                         {
2184                                 bLocateLikeConstraint *data;
2185                                 data= ((bLocateLikeConstraint*)con->data);
2186                                 data->tar = newlibadr(fd, id->lib, data->tar);
2187                         }
2188                         break;
2189                 case CONSTRAINT_TYPE_ROTLIKE:
2190                         {
2191                                 bRotateLikeConstraint *data;
2192                                 data= ((bRotateLikeConstraint*)con->data);
2193                                 data->tar = newlibadr(fd, id->lib, data->tar);
2194                         }
2195                         break;
2196                 case CONSTRAINT_TYPE_SIZELIKE:
2197                         {
2198                                 bSizeLikeConstraint *data;
2199                                 data= ((bSizeLikeConstraint*)con->data);
2200                                 data->tar = newlibadr(fd, id->lib, data->tar);
2201                         }
2202                         break;
2203                 case CONSTRAINT_TYPE_KINEMATIC:
2204                         {
2205                                 bKinematicConstraint *data;
2206                                 data = ((bKinematicConstraint*)con->data);
2207                                 data->tar = newlibadr(fd, id->lib, data->tar);
2208                                 data->poletar = newlibadr(fd, id->lib, data->poletar);
2209                                 con->lin_error = 0.f;
2210                                 con->rot_error = 0.f;
2211                         }
2212                         break;
2213                 case CONSTRAINT_TYPE_TRACKTO:
2214                         {
2215                                 bTrackToConstraint *data;
2216                                 data = ((bTrackToConstraint*)con->data);
2217                                 data->tar = newlibadr(fd, id->lib, data->tar);
2218                         }
2219                         break;
2220                 case CONSTRAINT_TYPE_MINMAX:
2221                         {
2222                                 bMinMaxConstraint *data;
2223                                 data = ((bMinMaxConstraint*)con->data);
2224                                 data->tar = newlibadr(fd, id->lib, data->tar);
2225                         }
2226                         break;
2227                 case CONSTRAINT_TYPE_LOCKTRACK:
2228                         {
2229                                 bLockTrackConstraint *data;
2230                                 data= ((bLockTrackConstraint*)con->data);
2231                                 data->tar = newlibadr(fd, id->lib, data->tar);
2232                         }
2233                         break;
2234                 case CONSTRAINT_TYPE_FOLLOWPATH:
2235                         {
2236                                 bFollowPathConstraint *data;
2237                                 data= ((bFollowPathConstraint*)con->data);
2238                                 data->tar = newlibadr(fd, id->lib, data->tar);
2239                         }
2240                         break;
2241                 case CONSTRAINT_TYPE_STRETCHTO:
2242                         {
2243                                 bStretchToConstraint *data;
2244                                 data= ((bStretchToConstraint*)con->data);
2245                                 data->tar = newlibadr(fd, id->lib, data->tar);
2246                         }
2247                         break;
2248                 case CONSTRAINT_TYPE_RIGIDBODYJOINT:
2249                         {
2250                                 bRigidBodyJointConstraint *data;
2251                                 data= ((bRigidBodyJointConstraint*)con->data);
2252                                 data->tar = newlibadr(fd, id->lib, data->tar);
2253                         }
2254                         break;
2255                 case CONSTRAINT_TYPE_CLAMPTO:
2256                         {
2257                                 bClampToConstraint *data;
2258                                 data= ((bClampToConstraint*)con->data);
2259                                 data->tar = newlibadr(fd, id->lib, data->tar);
2260                         }
2261                         break;
2262                 case CONSTRAINT_TYPE_CHILDOF:
2263                         {
2264                                 bChildOfConstraint *data;
2265                                 data= ((bChildOfConstraint*)con->data);
2266                                 data->tar = newlibadr(fd, id->lib, data->tar);
2267                         }
2268                         break;
2269                 case CONSTRAINT_TYPE_TRANSFORM:
2270                         {
2271                                 bTransformConstraint *data;
2272                                 data= ((bTransformConstraint*)con->data);
2273                                 data->tar = newlibadr(fd, id->lib, data->tar);
2274                         }
2275                         break;
2276                 case CONSTRAINT_TYPE_DISTLIMIT:
2277                         {
2278                                 bDistLimitConstraint *data;
2279                                 data= ((bDistLimitConstraint*)con->data);
2280                                 data->tar = newlibadr(fd, id->lib, data->tar);
2281                         }
2282                         break;
2283                 case CONSTRAINT_TYPE_SHRINKWRAP:
2284                         {
2285                                 bShrinkwrapConstraint *data;
2286                                 data= ((bShrinkwrapConstraint*)con->data);
2287                                 data->target = newlibadr(fd, id->lib, data->target);
2288                         }
2289                         break;
2290                 case CONSTRAINT_TYPE_DAMPTRACK:
2291                         {
2292                                 bDampTrackConstraint *data;
2293                                 data= ((bDampTrackConstraint*)con->data);
2294                                 data->tar = newlibadr(fd, id->lib, data->tar);
2295                         }
2296                         break;
2297                 case CONSTRAINT_TYPE_SPLINEIK:
2298                         {
2299                                 bSplineIKConstraint *data;
2300                                 data= ((bSplineIKConstraint*)con->data);
2301                                 data->tar = newlibadr(fd, id->lib, data->tar);
2302                         }
2303                         break;
2304                 case CONSTRAINT_TYPE_NULL:
2305                         break;
2306                 }
2307         }
2308 }
2309
2310 static void direct_link_constraints(FileData *fd, ListBase *lb)
2311 {
2312         bConstraint *cons;
2313
2314         link_list(fd, lb);
2315         for (cons=lb->first; cons; cons=cons->next) {
2316                 cons->data = newdataadr(fd, cons->data);
2317                 
2318                 if (cons->type == CONSTRAINT_TYPE_PYTHON) {
2319                         bPythonConstraint *data= cons->data;
2320                         
2321                         link_list(fd, &data->targets);
2322                         
2323                         data->prop = newdataadr(fd, data->prop);
2324                         if (data->prop)
2325                                 IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2326                 }
2327                 else if (cons->type == CONSTRAINT_TYPE_SPLINEIK) {
2328                         bSplineIKConstraint *data= cons->data;
2329                         
2330                         data->points= newdataadr(fd, data->points);
2331                 }
2332         }
2333 }
2334
2335 static void lib_link_pose(FileData *fd, Object *ob, bPose *pose)
2336 {
2337         bPoseChannel *pchan;
2338         bArmature *arm= ob->data;
2339         int rebuild;
2340         
2341         if (!pose || !arm)
2342                 return;
2343         
2344         /* always rebuild to match proxy or lib changes */
2345         rebuild= ob->proxy || (ob->id.lib==NULL && arm->id.lib);
2346
2347         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
2348                 lib_link_constraints(fd, (ID *)ob, &pchan->constraints);
2349                 
2350                 /* hurms... loop in a loop, but yah... later... (ton) */
2351                 pchan->bone= get_named_bone(arm, pchan->name);
2352                 
2353                 pchan->custom= newlibadr(fd, arm->id.lib, pchan->custom);
2354                 if(pchan->bone==NULL)
2355                         rebuild= 1;
2356                 else if(ob->id.lib==NULL && arm->id.lib) {
2357                         /* local pose selection copied to armature, bit hackish */
2358                         pchan->bone->flag &= ~BONE_SELECTED;
2359                         pchan->bone->flag |= pchan->selectflag;
2360                 }
2361         }
2362         
2363         if(rebuild) {
2364                 ob->recalc= OB_RECALC;
2365                 pose->flag |= POSE_RECALC;
2366         }
2367 }
2368
2369 static void lib_link_armature(FileData *fd, Main *main)
2370 {
2371         bArmature *arm;
2372
2373         arm= main->armature.first;
2374
2375         while(arm) {
2376                 if(arm->id.flag & LIB_NEEDLINK) {
2377                         if (arm->adt) lib_link_animdata(fd, &arm->id, arm->adt);
2378                         arm->id.flag -= LIB_NEEDLINK;
2379                 }
2380                 arm= arm->id.next;
2381         }
2382 }
2383
2384 static void direct_link_bones(FileData *fd, Bone* bone)
2385 {
2386         Bone    *child;
2387
2388         bone->parent= newdataadr(fd, bone->parent);
2389         bone->prop= newdataadr(fd, bone->prop);
2390         if(bone->prop)
2391                 IDP_DirectLinkProperty(bone->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2392                 
2393         bone->flag &= ~BONE_DRAW_ACTIVE;
2394
2395         link_list(fd, &bone->childbase);
2396
2397         for(child=bone->childbase.first; child; child=child->next)
2398                 direct_link_bones(fd, child);
2399 }
2400
2401 static void direct_link_armature(FileData *fd, bArmature *arm)
2402 {
2403         Bone    *bone;
2404
2405         link_list(fd, &arm->bonebase);
2406         arm->edbo= NULL;
2407         arm->sketch = NULL;
2408         
2409         arm->adt= newdataadr(fd, arm->adt);
2410         direct_link_animdata(fd, arm->adt);
2411         
2412         bone=arm->bonebase.first;
2413         while (bone) {
2414                 direct_link_bones(fd, bone);
2415                 bone=bone->next;
2416         }
2417
2418         arm->act_bone= newdataadr(fd, arm->act_bone);
2419         arm->act_edbone= NULL;
2420 }
2421
2422 /* ************ READ CAMERA ***************** */
2423
2424 static void lib_link_camera(FileData *fd, Main *main)
2425 {
2426         Camera *ca;
2427
2428         ca= main->camera.first;
2429         while(ca) {
2430                 if(ca->id.flag & LIB_NEEDLINK) {
2431                         if (ca->adt) lib_link_animdata(fd, &ca->id, ca->adt);
2432                         
2433                         ca->ipo= newlibadr_us(fd, ca->id.lib, ca->ipo); // XXX depreceated - old animation system
2434                         
2435                         ca->dof_ob= newlibadr_us(fd, ca->id.lib, ca->dof_ob);
2436                         
2437                         ca->id.flag -= LIB_NEEDLINK;
2438                 }
2439                 ca= ca->id.next;
2440         }
2441 }
2442
2443 static void direct_link_camera(FileData *fd, Camera *ca)
2444 {
2445         ca->adt= newdataadr(fd, ca->adt);
2446         direct_link_animdata(fd, ca->adt);
2447 }
2448
2449
2450 /* ************ READ LAMP ***************** */
2451
2452 static void lib_link_lamp(FileData *fd, Main *main)
2453 {
2454         Lamp *la;
2455         MTex *mtex;
2456         int a;
2457
2458         la= main->lamp.first;
2459         while(la) {
2460                 if(la->id.flag & LIB_NEEDLINK) {
2461                         if (la->adt) lib_link_animdata(fd, &la->id, la->adt);
2462                         
2463                         for(a=0; a<MAX_MTEX; a++) {
2464                                 mtex= la->mtex[a];
2465                                 if(mtex) {
2466                                         mtex->tex= newlibadr_us(fd, la->id.lib, mtex->tex);
2467                                         mtex->object= newlibadr(fd, la->id.lib, mtex->object);
2468                                 }
2469                         }
2470                         
2471                         la->ipo= newlibadr_us(fd, la->id.lib, la->ipo); // XXX depreceated - old animation system
2472                         
2473                         la->id.flag -= LIB_NEEDLINK;
2474                 }
2475                 la= la->id.next;
2476         }
2477 }
2478
2479 static void direct_link_lamp(FileData *fd, Lamp *la)
2480 {
2481         int a;
2482         
2483         la->adt= newdataadr(fd, la->adt);
2484         direct_link_animdata(fd, la->adt);
2485
2486         for(a=0; a<MAX_MTEX; a++) {
2487                 la->mtex[a]= newdataadr(fd, la->mtex[a]);
2488         }
2489         
2490         la->curfalloff= newdataadr(fd, la->curfalloff);
2491         if(la->curfalloff)
2492                 direct_link_curvemapping(fd, la->curfalloff);
2493         
2494         la->preview = direct_link_preview_image(fd, la->preview);
2495 }
2496
2497 /* ************ READ keys ***************** */
2498
2499 static void lib_link_key(FileData *fd, Main *main)
2500 {
2501         Key *key;
2502
2503         key= main->key.first;
2504         while(key) {
2505                 if(key->id.flag & LIB_NEEDLINK) {
2506                         if(key->adt) lib_link_animdata(fd, &key->id, key->adt);
2507                         
2508                         key->ipo= newlibadr_us(fd, key->id.lib, key->ipo); // XXX depreceated - old animation system
2509                         key->from= newlibadr(fd, key->id.lib, key->from);
2510
2511                         key->id.flag -= LIB_NEEDLINK;
2512                 }
2513                 key= key->id.next;
2514         }
2515 }
2516
2517 static void switch_endian_keyblock(Key *key, KeyBlock *kb)
2518 {
2519         int elemsize, a, b;
2520         char *data, *poin, *cp;
2521
2522         elemsize= key->elemsize;
2523         data= kb->data;
2524
2525         for(a=0; a<kb->totelem; a++) {
2526
2527                 cp= key->elemstr;
2528                 poin= data;
2529
2530                 while( cp[0] ) {        /* cp[0]==amount */
2531
2532                         switch(cp[1]) {         /* cp[1]= type */
2533                         case IPO_FLOAT:
2534                         case IPO_BPOINT:
2535                         case IPO_BEZTRIPLE:
2536                                 b= cp[0];
2537                                 while(b--) {
2538                                         SWITCH_INT((*poin));
2539                                         poin+= 4;
2540                                 }
2541                                 break;
2542                         }
2543
2544                         cp+= 2;
2545
2546                 }
2547                 data+= elemsize;
2548         }
2549 }
2550
2551 static void direct_link_key(FileData *fd, Key *key)
2552 {
2553         KeyBlock *kb;
2554
2555         link_list(fd, &(key->block));
2556
2557         key->adt= newdataadr(fd, key->adt);
2558         direct_link_animdata(fd, key->adt);
2559         
2560         key->refkey= newdataadr(fd, key->refkey);
2561
2562         kb= key->block.first;
2563         while(kb) {
2564
2565                 kb->data= newdataadr(fd, kb->data);
2566
2567                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN)
2568                         switch_endian_keyblock(key, kb);
2569
2570                 kb= kb->next;
2571         }
2572 }
2573
2574 /* ************ READ mball ***************** */
2575
2576 static void lib_link_mball(FileData *fd, Main *main)
2577 {
2578         MetaBall *mb;
2579         int a;
2580
2581         mb= main->mball.first;
2582         while(mb) {
2583                 if(mb->id.flag & LIB_NEEDLINK) {
2584                         if (mb->adt) lib_link_animdata(fd, &mb->id, mb->adt);
2585                         
2586                         for(a=0; a<mb->totcol; a++) mb->mat[a]= newlibadr_us(fd, mb->id.lib, mb->mat[a]);
2587
2588                         mb->ipo= newlibadr_us(fd, mb->id.lib, mb->ipo); // XXX depreceated - old animation system
2589
2590                         mb->id.flag -= LIB_NEEDLINK;
2591                 }
2592                 mb= mb->id.next;
2593         }
2594 }
2595
2596 static void direct_link_mball(FileData *fd, MetaBall *mb)
2597 {
2598         mb->adt= newdataadr(fd, mb->adt);
2599         direct_link_animdata(fd, mb->adt);
2600         
2601         mb->mat= newdataadr(fd, mb->mat);
2602         test_pointer_array(fd, (void **)&mb->mat);
2603
2604         link_list(fd, &(mb->elems));
2605
2606         mb->disp.first= mb->disp.last= NULL;
2607         mb->editelems= NULL;
2608         mb->bb= NULL;
2609 /*      mb->edit_elems.first= mb->edit_elems.last= NULL;*/
2610         mb->lastelem= NULL;
2611 }
2612
2613 /* ************ READ WORLD ***************** */
2614
2615 static void lib_link_world(FileData *fd, Main *main)
2616 {
2617         World *wrld;
2618         MTex *mtex;
2619         int a;
2620
2621         wrld= main->world.first;
2622         while(wrld) {
2623                 if(wrld->id.flag & LIB_NEEDLINK) {
2624                         if (wrld->adt) lib_link_animdata(fd, &wrld->id, wrld->adt);
2625                         
2626                         wrld->ipo= newlibadr_us(fd, wrld->id.lib, wrld->ipo); // XXX depreceated - old animation system
2627                         
2628                         for(a=0; a<MAX_MTEX; a++) {
2629                                 mtex= wrld->mtex[a];
2630                                 if(mtex) {
2631                                         mtex->tex= newlibadr_us(fd, wrld->id.lib, mtex->tex);
2632                                         mtex->object= newlibadr(fd, wrld->id.lib, mtex->object);
2633                                 }
2634                         }
2635                         
2636                         wrld->id.flag -= LIB_NEEDLINK;
2637                 }
2638                 wrld= wrld->id.next;
2639         }
2640 }
2641
2642 static void direct_link_world(FileData *fd, World *wrld)
2643 {
2644         int a;
2645
2646         wrld->adt= newdataadr(fd, wrld->adt);
2647         direct_link_animdata(fd, wrld->adt);
2648
2649         for(a=0; a<MAX_MTEX; a++) {
2650                 wrld->mtex[a]= newdataadr(fd, wrld->mtex[a]);
2651         }
2652         wrld->preview = direct_link_preview_image(fd, wrld->preview);
2653 }
2654
2655
2656 /* ************ READ VFONT ***************** */
2657
2658 static void lib_link_vfont(FileData *fd, Main *main)
2659 {
2660         VFont *vf;
2661
2662         vf= main->vfont.first;
2663         while(vf) {
2664                 if(vf->id.flag & LIB_NEEDLINK) {
2665                         vf->id.flag -= LIB_NEEDLINK;
2666                 }
2667                 vf= vf->id.next;
2668         }
2669 }
2670
2671 static void direct_link_vfont(FileData *fd, VFont *vf)
2672 {
2673         vf->data= NULL;
2674         vf->packedfile= direct_link_packedfile(fd, vf->packedfile);
2675 }
2676
2677 /* ************ READ TEXT ****************** */
2678
2679 static void lib_link_text(FileData *fd, Main *main)
2680 {
2681         Text *text;
2682
2683         text= main->text.first;
2684         while(text) {
2685                 if(text->id.flag & LIB_NEEDLINK) {
2686                         text->id.flag -= LIB_NEEDLINK;
2687                 }
2688                 text= text->id.next;
2689         }
2690 }
2691
2692 static void direct_link_text(FileData *fd, Text *text)
2693 {
2694         TextLine *ln;
2695
2696         text->name= newdataadr(fd, text->name);
2697
2698         text->undo_pos= -1;
2699         text->undo_len= TXT_INIT_UNDO;
2700         text->undo_buf= MEM_mallocN(text->undo_len, "undo buf");
2701
2702         text->compiled= NULL;
2703
2704 /*
2705         if(text->flags & TXT_ISEXT) {
2706                 reopen_text(text);
2707         } else {
2708 */
2709
2710         link_list(fd, &text->lines);
2711         link_list(fd, &text->markers);
2712
2713         text->curl= newdataadr(fd, text->curl);
2714         text->sell= newdataadr(fd, text->sell);
2715
2716         ln= text->lines.first;
2717         while(ln) {
2718                 ln->line= newdataadr(fd, ln->line);
2719                 ln->format= NULL;
2720                 
2721                 if (ln->len != (int) strlen(ln->line)) {
2722                         printf("Error loading text, line lengths differ\n");
2723                         ln->len = strlen(ln->line);
2724                 }
2725
2726                 ln= ln->next;
2727         }
2728
2729         text->flags = (text->flags) & ~TXT_ISEXT;
2730
2731         text->id.us= 1;
2732 }
2733
2734 /* ************ READ IMAGE ***************** */
2735
2736 static void lib_link_image(FileData *fd, Main *main)
2737 {
2738         Image *ima;
2739
2740         ima= main->image.first;
2741         while (ima) {
2742                 if(ima->id.flag & LIB_NEEDLINK) {
2743                         if (ima->id.properties) IDP_LibLinkProperty(ima->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2744
2745                         ima->id.flag -= LIB_NEEDLINK;
2746                 }
2747                 ima= ima->id.next;
2748         }
2749 }
2750
2751 static void link_ibuf_list(FileData *fd, ListBase *lb)
2752 {
2753         Link *ln, *prev;
2754         
2755         if(lb->first==NULL) return;
2756         
2757         lb->first= newimaadr(fd, lb->first);
2758         ln= lb->first;
2759         prev= NULL;
2760         while(ln) {
2761                 ln->next= newimaadr(fd, ln->next);
2762                 ln->prev= prev;
2763                 prev= ln;
2764                 ln= ln->next;
2765         }
2766         lb->last= prev;
2767 }
2768
2769 static void direct_link_image(FileData *fd, Image *ima)
2770 {
2771         /* for undo system, pointers could be restored */
2772         if(fd->imamap)
2773                 link_ibuf_list(fd, &ima->ibufs);
2774         else
2775                 ima->ibufs.first= ima->ibufs.last= NULL;
2776         
2777         /* if not restored, we keep the binded opengl index */
2778         if(ima->ibufs.first==NULL) {
2779                 ima->bindcode= 0;
2780                 ima->gputexture= NULL;
2781         }
2782         
2783         ima->anim= NULL;
2784         ima->rr= NULL;
2785         ima->repbind= NULL;
2786         ima->render_text= newdataadr(fd, ima->render_text);
2787         
2788         ima->packedfile = direct_link_packedfile(fd, ima->packedfile);
2789         ima->preview = direct_link_preview_image(fd, ima->preview);
2790         ima->ok= 1;
2791 }
2792
2793
2794 /* ************ READ CURVE ***************** */
2795
2796 static void lib_link_curve(FileData *fd, Main *main)
2797 {
2798         Curve *cu;
2799         int a;
2800
2801         cu= main->curve.first;
2802         while(cu) {
2803                 if(cu->id.flag & LIB_NEEDLINK) {
2804                         if(cu->adt) lib_link_animdata(fd, &cu->id, cu->adt);
2805
2806                         for(a=0; a<cu->totcol; a++) cu->mat[a]= newlibadr_us(fd, cu->id.lib, cu->mat[a]);
2807
2808                         cu->bevobj= newlibadr(fd, cu->id.lib, cu->bevobj);
2809                         cu->taperobj= newlibadr(fd, cu->id.lib, cu->taperobj);
2810                         cu->textoncurve= newlibadr(fd, cu->id.lib, cu->textoncurve);
2811                         cu->vfont= newlibadr_us(fd, cu->id.lib, cu->vfont);
2812                         cu->vfontb= newlibadr_us(fd, cu->id.lib, cu->vfontb);                   
2813                         cu->vfonti= newlibadr_us(fd, cu->id.lib, cu->vfonti);
2814                         cu->vfontbi= newlibadr_us(fd, cu->id.lib, cu->vfontbi);
2815
2816                         cu->ipo= newlibadr_us(fd, cu->id.lib, cu->ipo); // XXX depreceated - old animation system
2817                         cu->key= newlibadr_us(fd, cu->id.lib, cu->key);
2818
2819                         cu->id.flag -= LIB_NEEDLINK;
2820                 }
2821                 cu= cu->id.next;
2822         }
2823 }
2824
2825
2826 static void switch_endian_knots(Nurb *nu)
2827 {
2828         int len;
2829
2830         if(nu->knotsu) {
2831                 len= KNOTSU(nu);
2832                 while(len--) {
2833                         SWITCH_INT(nu->knotsu[len]);
2834                 }
2835         }
2836         if(nu->knotsv) {
2837                 len= KNOTSV(nu);
2838                 while(len--) {
2839                         SWITCH_INT(nu->knotsv[len]);
2840                 }
2841         }
2842 }
2843
2844 static void direct_link_curve(FileData *fd, Curve *cu)
2845 {
2846         Nurb *nu;
2847         TextBox *tb;
2848         
2849         cu->adt= newdataadr(fd, cu->adt);
2850         direct_link_animdata(fd, cu->adt);
2851         
2852         cu->mat= newdataadr(fd, cu->mat);
2853         test_pointer_array(fd, (void **)&cu->mat);
2854         cu->str= newdataadr(fd, cu->str);
2855         cu->strinfo= newdataadr(fd, cu->strinfo);       
2856         cu->tb= newdataadr(fd, cu->tb);
2857
2858         if(cu->vfont==0) link_list(fd, &(cu->nurb));
2859         else {
2860                 cu->nurb.first=cu->nurb.last= 0;
2861
2862                 tb= MEM_callocN(MAXTEXTBOX*sizeof(TextBox), "TextBoxread");
2863                 if (cu->tb) {
2864                         memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox));
2865                         MEM_freeN(cu->tb);
2866                         cu->tb= tb;                     
2867                 } else {
2868                         cu->totbox = 1;
2869                         cu->actbox = 1;
2870                         cu->tb = tb;
2871                         cu->tb[0].w = cu->linewidth;
2872                 }               
2873                 if (cu->wordspace == 0.0) cu->wordspace = 1.0;
2874         }
2875
2876         cu->bev.first=cu->bev.last= NULL;
2877         cu->disp.first=cu->disp.last= NULL;
2878         cu->editnurb= NULL;
2879         cu->lastselbp= NULL;
2880         cu->path= NULL;
2881         cu->editfont= NULL;
2882         
2883         nu= cu->nurb.first;
2884         while(nu) {
2885                 nu->bezt= newdataadr(fd, nu->bezt);
2886                 nu->bp= newdataadr(fd, nu->bp);
2887                 nu->knotsu= newdataadr(fd, nu->knotsu);
2888                 nu->knotsv= newdataadr(fd, nu->knotsv);
2889                 if (cu->vfont==0) nu->charidx= nu->mat_nr;
2890
2891                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2892                         switch_endian_knots(nu);
2893                 }
2894
2895                 nu= nu->next;
2896         }
2897         cu->bb= NULL;
2898 }
2899
2900 /* ************ READ TEX ***************** */
2901
2902 static void lib_link_texture(FileData *fd, Main *main)
2903 {
2904         Tex *tex;
2905
2906         tex= main->tex.first;
2907         while(tex) {
2908                 if(tex->id.flag & LIB_NEEDLINK) {
2909                         if(tex->adt) lib_link_animdata(fd, &tex->id, tex->adt);
2910
2911                         tex->ima= newlibadr_us(fd, tex->id.lib, tex->ima);
2912                         tex->ipo= newlibadr_us(fd, tex->id.lib, tex->ipo);
2913                         if(tex->env) tex->env->object= newlibadr(fd, tex->id.lib, tex->env->object);
2914                         if(tex->pd)
2915                                 tex->pd->object= newlibadr(fd, tex->id.lib, tex->pd->object);
2916                         if(tex->vd) tex->vd->object= newlibadr(fd, tex->id.lib, tex->vd->object);
2917
2918                         if(tex->nodetree)
2919                                 lib_link_ntree(fd, &tex->id, tex->nodetree);
2920                         
2921                         tex->id.flag -= LIB_NEEDLINK;
2922                 }
2923                 tex= tex->id.next;
2924         }
2925 }
2926
2927 static void direct_link_texture(FileData *fd, Tex *tex)
2928 {
2929         tex->adt= newdataadr(fd, tex->adt);
2930         direct_link_animdata(fd, tex->adt);
2931         
2932         tex->plugin= newdataadr(fd, tex->plugin);
2933         if(tex->plugin) {
2934                 tex->plugin->handle= 0;
2935                 open_plugin_tex(tex->plugin);
2936                 /* initialize data for this instance, if an initialization
2937                  * function exists.
2938                  */
2939                 if (tex->plugin->instance_init)
2940                         tex->plugin->instance_init((void *) tex->plugin->data);
2941         }
2942         tex->coba= newdataadr(fd, tex->coba);
2943         tex->env= newdataadr(fd, tex->env);
2944         if(tex->env) {
2945                 tex->env->ima= NULL;
2946                 memset(tex->env->cube, 0, 6*sizeof(void *));
2947                 tex->env->ok= 0;
2948         }
2949         tex->pd= newdataadr(fd, tex->pd);
2950         if(tex->pd) {
2951                 tex->pd->point_tree = NULL;
2952                 tex->pd->coba= newdataadr(fd, tex->pd->coba);
2953         }
2954         
2955         tex->vd= newdataadr(fd, tex->vd);
2956         if(tex->vd) {
2957                 tex->vd->dataset = NULL;
2958         }
2959         
2960         tex->nodetree= newdataadr(fd, tex->nodetree);
2961         if(tex->nodetree)
2962                 direct_link_nodetree(fd, tex->nodetree);
2963         
2964         tex->preview = direct_link_preview_image(fd, tex->preview);
2965
2966         tex->iuser.ok= 1;
2967 }
2968
2969
2970
2971 /* ************ READ MATERIAL ***************** */
2972
2973 static void lib_link_material(FileData *fd, Main *main)
2974 {
2975         Material *ma;
2976         MTex *mtex;
2977         int a;
2978
2979         ma= main->mat.first;
2980         while(ma) {
2981                 if(ma->id.flag & LIB_NEEDLINK) {
2982                         if(ma->adt) lib_link_animdata(fd, &ma->id, ma->adt);
2983
2984                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
2985                         of library blocks that implement this.*/
2986                         if (ma->id.properties) IDP_LibLinkProperty(ma->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2987
2988                         ma->ipo= newlibadr_us(fd, ma->id.lib, ma->ipo);
2989                         ma->group= newlibadr_us(fd, ma->id.lib, ma->group);
2990                         
2991                         for(a=0; a<MAX_MTEX; a++) {
2992                                 mtex= ma->mtex[a];
2993                                 if(mtex) {
2994                                         mtex->tex= newlibadr_us(fd, ma->id.lib, mtex->tex);
2995                                         mtex->object= newlibadr(fd, ma->id.lib, mtex->object);
2996                                 }
2997                         }
2998                         
2999                         if(ma->nodetree)
3000                                 lib_link_ntree(fd, &ma->id, ma->nodetree);
3001                         
3002                         ma->id.flag -= LIB_NEEDLINK;
3003                 }
3004                 ma= ma->id.next;
3005         }
3006 }
3007
3008 static void direct_link_material(FileData *fd, Material *ma)
3009 {
3010         int a;
3011
3012         ma->adt= newdataadr(fd, ma->adt);
3013         direct_link_animdata(fd, ma->adt);
3014         
3015         for(a=0; a<MAX_MTEX; a++) {
3016                 ma->mtex[a]= newdataadr(fd, ma->mtex[a]);
3017         }
3018
3019         ma->ramp_col= newdataadr(fd, ma->ramp_col);
3020         ma->ramp_spec= newdataadr(fd, ma->ramp_spec);
3021         
3022         ma->nodetree= newdataadr(fd, ma->nodetree);
3023         if(ma->nodetree)
3024                 direct_link_nodetree(fd, ma->nodetree);
3025
3026         ma->preview = direct_link_preview_image(fd, ma->preview);
3027         ma->gpumaterial.first = ma->gpumaterial.last = NULL;
3028 }
3029
3030 /* ************ READ PARTICLE SETTINGS ***************** */
3031
3032 static void direct_link_pointcache(FileData *fd, PointCache *cache)
3033 {
3034         if((cache->flag & PTCACHE_DISK_CACHE)==0) {
3035                 PTCacheMem *pm;
3036                 int i;
3037
3038                 link_list(fd, &cache->mem_cache);
3039
3040                 pm = cache->mem_cache.first;
3041
3042                 for(; pm; pm=pm->next) {
3043                         if(pm->index_array)
3044                                 pm->index_array = newdataadr(fd, pm->index_array);
3045                         
3046                         for(i=0; i<BPHYS_TOT_DATA; i++) {
3047                                 if(pm->data[i] && pm->data_types & (1<<i))
3048                                         pm->data[i] = newdataadr(fd, pm->data[i]);
3049                         }
3050                 }
3051         }
3052         else
3053                 cache->mem_cache.first = cache->mem_cache.last = NULL;
3054
3055         cache->flag &= ~PTCACHE_SIMULATION_VALID;
3056         cache->simframe= 0;
3057         cache->edit= NULL;
3058         cache->free_edit= NULL;
3059 }
3060
3061 static void direct_link_pointcache_list(FileData *fd, ListBase *ptcaches, PointCache **ocache)
3062 {
3063         PointCache *cache;
3064
3065         if(ptcaches->first) {
3066                 link_list(fd, ptcaches);
3067                 for(cache=ptcaches->first; cache; cache=cache->next)
3068                         direct_link_pointcache(fd, cache);
3069
3070                 *ocache = newdataadr(fd, *ocache);
3071         }
3072         else if(*ocache) {
3073                 /* old "single" caches need to be linked too */
3074                 *ocache = newdataadr(fd, *ocache);
3075                 direct_link_pointcache(fd, *ocache);
3076
3077                 ptcaches->first = ptcaches->last = *ocache;
3078         }
3079 }
3080
3081 void lib_link_partdeflect(FileData *fd, ID *id, PartDeflect *pd)
3082 {
3083         if(pd && pd->tex)
3084                 pd->tex=newlibadr_us(fd, id->lib, pd->tex);
3085 }
3086
3087 static void lib_link_particlesettings(FileData *fd, Main *main)
3088 {
3089         ParticleSettings *part;
3090         ParticleDupliWeight *dw;
3091
3092         part= main->particle.first;
3093         while(part) {
3094                 if(part->id.flag & LIB_NEEDLINK) {
3095                         if (part->adt) lib_link_animdata(fd, &part->id, part->adt);
3096                         part->ipo= newlibadr_us(fd, part->id.lib, part->ipo); // XXX depreceated - old animation system
3097                         
3098                         part->dup_ob = newlibadr(fd, part->id.lib, part->dup_ob);
3099                         part->dup_group = newlibadr(fd, part->id.lib, part->dup_group);
3100                         part->eff_group = newlibadr(fd, part->id.lib, part->eff_group);
3101                         part->bb_ob = newlibadr(fd, part->id.lib, part->bb_ob);
3102
3103                         lib_link_partdeflect(fd, &part->id, part->pd);
3104                         lib_link_partdeflect(fd, &part->id, part->pd2);
3105
3106                         if(part->effector_weights)
3107                                 part->effector_weights->group = newlibadr(fd, part->id.lib, part->effector_weights->group);
3108
3109                         dw = part->dupliweights.first;
3110                         for(; dw; dw=dw->next)
3111                                 dw->ob = newlibadr(fd, part->id.lib, dw->ob);
3112
3113                         if(part->boids) {
3114                                 BoidState *state = part->boids->states.first;
3115                                 BoidRule *rule;
3116                                 for(; state; state=state->next) {
3117                                         rule = state->rules.first;
3118                                 for(; rule; rule=rule->next)
3119                                         switch(rule->type) {
3120                                                 case eBoidRuleType_Goal:
3121                                                 case eBoidRuleType_Avoid:
3122                                                 {
3123                                                         BoidRuleGoalAvoid *brga = (BoidRuleGoalAvoid*)rule;
3124                                                         brga->ob = newlibadr(fd, part->id.lib, brga->ob);
3125                                                         break;
3126                                                 }
3127                                                 case eBoidRuleType_FollowLeader:
3128                                                 {
3129                                                         BoidRuleFollowLeader *brfl = (BoidRuleFollowLeader*)rule;
3130                                                         brfl->ob = newlibadr(fd, part->id.lib, brfl->ob);
3131                                                         break;
3132                                                 }
3133                                         }
3134                                 }
3135                         }
3136                         part->id.flag -= LIB_NEEDLINK;
3137                 }
3138                 part= part->id.next;
3139         }
3140 }
3141
3142 static void direct_link_partdeflect(PartDeflect *pd)
3143 {
3144         if(pd) pd->rng=NULL;
3145 }
3146
3147 static void direct_link_particlesettings(FileData *fd, ParticleSettings *part)
3148 {
3149         part->adt= newdataadr(fd, part->adt);
3150         part->pd= newdataadr(fd, part->pd);
3151         part->pd2= newdataadr(fd, part->pd2);
3152
3153         direct_link_partdeflect(part->pd);
3154         direct_link_partdeflect(part->pd2);
3155
3156         part->effector_weights = newdataadr(fd, part->effector_weights);
3157         if(!part->effector_weights)
3158                 part->effector_weights = BKE_add_effector_weights(part->eff_group);
3159
3160         link_list(fd, &part->dupliweights);
3161
3162         part->boids= newdataadr(fd, part->boids);
3163
3164         if(part->boids) {
3165                 BoidState *state;
3166                 link_list(fd, &part->boids->states);
3167                 
3168                 for(state=part->boids->states.first; state; state=state->next) {
3169                         link_list(fd, &state->rules);
3170                         link_list(fd, &state->conditions);
3171                         link_list(fd, &state->actions);
3172                 }
3173         }
3174 }
3175
3176 static void lib_link_particlesystems(FileData *fd, Object *ob, ID *id, ListBase *particles)
3177 {
3178         ParticleSystem *psys, *psysnext;
3179
3180         for(psys=particles->first; psys; psys=psysnext){
3181                 psysnext= psys->next;
3182                 
3183                 psys->part = newlibadr_us(fd, id->lib, psys->part);
3184                 if(psys->part) {
3185                         ParticleTarget *pt = psys->targets.first;
3186
3187                         for(; pt; pt=pt->next)
3188                                 pt->ob=newlibadr(fd, id->lib, pt->ob);
3189
3190                         psys->target_ob = newlibadr(fd, id->lib, psys->target_ob);
3191                 }
3192                 else {
3193                         /* particle modifier must be removed before particle system */
3194                         ParticleSystemModifierData *psmd= psys_get_modifier(ob,psys);
3195                         BLI_remlink(&ob->modifiers, psmd);
3196                         modifier_free((ModifierData *)psmd);
3197
3198                         BLI_remlink(particles, psys);
3199                         MEM_freeN(psys);
3200                 }
3201         }
3202 }
3203 static void direct_link_particlesystems(FileData *fd, ListBase *particles)
3204 {
3205         ParticleSystem *psys;
3206         ParticleData *pa;
3207         int a;
3208
3209         for(psys=particles->first; psys; psys=psys->next) {
3210                 psys->particles=newdataadr(fd,psys->particles);
3211                 
3212                 if(psys->particles && psys->particles->hair){
3213                         for(a=0,pa=psys->particles; a<psys->totpart; a++, pa++)
3214                                 pa->hair=newdataadr(fd,pa->hair);
3215                 }
3216                 
3217                 if(psys->particles && psys->particles->keys){
3218                         for(a=0,pa=psys->particles; a<psys->totpart; a++, pa++) {
3219                                 pa->keys= NULL;
3220                                 pa->totkey= 0;
3221                         }
3222
3223                         psys->flag &= ~PSYS_KEYED;
3224                 }
3225
3226                 if(psys->particles && psys->particles->boid) {
3227                         pa = psys->particles;
3228                         pa->boid = newdataadr(fd, pa->boid);
3229                         for(a=1,pa++; a<psys->totpart; a++, pa++)
3230                                 pa->boid = (pa-1)->boid + 1;
3231                 }
3232                 else {
3233                         for(a=0,pa=psys->particles; a<psys->totpart; a++, pa++)
3234                                 pa->boid = NULL;
3235                 }
3236
3237
3238                 psys->child = newdataadr(fd,psys->child);
3239                 psys->effectors = NULL;
3240
3241                 link_list(fd, &psys->targets);
3242
3243                 psys->edit = NULL;
3244                 psys->free_edit = NULL;
3245                 psys->pathcache = NULL;
3246                 psys->childcache = NULL;
3247                 psys->pathcachebufs.first = psys->pathcachebufs.last = NULL;
3248                 psys->childcachebufs.first = psys->childcachebufs.last = NULL;
3249                 psys->frand = NULL;
3250                 psys->pdd = NULL;
3251
3252                 direct_link_pointcache_list(fd, &psys->ptcaches, &psys->pointcache);
3253
3254                 if(psys->clmd) {
3255                         psys->clmd = newdataadr(fd, psys->clmd);
3256                         psys->clmd->clothObject = NULL;
3257                         
3258                         psys->clmd->sim_parms= newdataadr(fd, psys->clmd->sim_parms);
3259                         psys->clmd->coll_parms= newdataadr(fd, psys->clmd->coll_parms);
3260                         
3261                         if(psys->clmd->sim_parms) {
3262                                 if(psys->clmd->sim_parms->presets > 10)
3263                                         psys->clmd->sim_parms->presets = 0;
3264                         }
3265
3266                         psys->hair_in_dm = psys->hair_out_dm = NULL;
3267
3268                         psys->clmd->point_cache = psys->pointcache;
3269                 }