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