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