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