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