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