88bbcca3a9419c87f6bf84f25ac7e6c443240184
[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_NULL:
1756                         break;
1757                 }
1758         }
1759 }
1760
1761 static void direct_link_constraints(FileData *fd, ListBase *lb)
1762 {
1763         bConstraint *cons;
1764
1765         link_list(fd, lb);
1766         for (cons=lb->first; cons; cons=cons->next) {
1767                 cons->data = newdataadr(fd, cons->data);
1768                 if (cons->type == CONSTRAINT_TYPE_PYTHON) {
1769                         bPythonConstraint *data= cons->data;
1770                         link_list(fd, &data->targets);
1771                         data->prop = newdataadr(fd, data->prop);
1772                         IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
1773                 }
1774         }
1775 }
1776
1777 static void lib_link_pose(FileData *fd, Object *ob, bPose *pose)
1778 {
1779         bPoseChannel *pchan;
1780         bArmature *arm= ob->data;
1781         int rebuild;
1782         
1783         if (!pose || !arm)
1784                 return;
1785         
1786         /* always rebuild to match proxy or lib changes */
1787         rebuild= ob->proxy || (ob->id.lib==NULL && arm->id.lib);
1788
1789         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
1790                 lib_link_constraints(fd, (ID *)ob, &pchan->constraints);
1791                 
1792                 /* hurms... loop in a loop, but yah... later... (ton) */
1793                 pchan->bone= get_named_bone(arm, pchan->name);
1794                 
1795                 pchan->custom= newlibadr(fd, arm->id.lib, pchan->custom);
1796                 if(pchan->bone==NULL)
1797                         rebuild= 1;
1798                 else if(ob->id.lib==NULL && arm->id.lib) {
1799                         /* local pose selection copied to armature, bit hackish */
1800                         pchan->bone->flag &= ~(BONE_SELECTED|BONE_ACTIVE);
1801                         pchan->bone->flag |= pchan->selectflag;
1802                 }
1803         }
1804         
1805         if(rebuild) {
1806                 ob->recalc= OB_RECALC;
1807                 pose->flag |= POSE_RECALC;
1808         }
1809 }
1810
1811 static void lib_link_armature(FileData *fd, Main *main)
1812 {
1813         bArmature *arm;
1814
1815         arm= main->armature.first;
1816
1817         while(arm) {
1818                 if(arm->id.flag & LIB_NEEDLINK) {
1819                         arm->id.flag -= LIB_NEEDLINK;
1820                 }
1821                 arm= arm->id.next;
1822         }
1823 }
1824
1825 static void lib_link_action(FileData *fd, Main *main)
1826 {
1827         bAction *act;
1828         bActionChannel *chan;
1829
1830         act= main->action.first;
1831         while(act) {
1832                 if(act->id.flag & LIB_NEEDLINK) {
1833                         act->id.flag -= LIB_NEEDLINK;
1834                         
1835                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1836                                 chan->ipo= newlibadr_us(fd, act->id.lib, chan->ipo);
1837                                 lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
1838                         }
1839                         
1840                 }
1841                 act= act->id.next;
1842         }
1843 }
1844
1845 static void direct_link_bones(FileData *fd, Bone* bone)
1846 {
1847         Bone    *child;
1848
1849         bone->parent= newdataadr(fd, bone->parent);
1850
1851         link_list(fd, &bone->childbase);
1852
1853         for (child=bone->childbase.first; child; child=child->next) {
1854                 direct_link_bones(fd, child);
1855         }
1856 }
1857
1858
1859 static void direct_link_action(FileData *fd, bAction *act)
1860 {
1861         bActionChannel *achan;
1862         bActionGroup *agrp;
1863
1864         link_list(fd, &act->chanbase);
1865         link_list(fd, &act->groups);
1866         link_list(fd, &act->markers);
1867
1868         for (achan = act->chanbase.first; achan; achan=achan->next) {
1869                 achan->grp= newdataadr(fd, achan->grp);
1870                 
1871                 link_list(fd, &achan->constraintChannels);
1872         }
1873                 
1874         for (agrp = act->groups.first; agrp; agrp= agrp->next) {
1875                 if (agrp->channels.first) {
1876                         agrp->channels.first= newdataadr(fd, agrp->channels.first);
1877                         agrp->channels.last= newdataadr(fd, agrp->channels.last);
1878                 }
1879         }
1880 }
1881
1882 static void direct_link_armature(FileData *fd, bArmature *arm)
1883 {
1884         Bone    *bone;
1885
1886         link_list(fd, &arm->bonebase);
1887
1888         bone=arm->bonebase.first;
1889         while (bone) {
1890                 direct_link_bones(fd, bone);
1891                 bone=bone->next;
1892         }
1893 }
1894
1895 /* ************ READ CAMERA ***************** */
1896
1897 static void lib_link_camera(FileData *fd, Main *main)
1898 {
1899         Camera *ca;
1900
1901         ca= main->camera.first;
1902         while(ca) {
1903                 if(ca->id.flag & LIB_NEEDLINK) {
1904
1905                         ca->ipo= newlibadr_us(fd, ca->id.lib, ca->ipo);
1906                         
1907                         ca->dof_ob= newlibadr_us(fd, ca->id.lib, ca->dof_ob);
1908                         
1909                         lib_link_scriptlink(fd, &ca->id, &ca->scriptlink);
1910
1911                         ca->id.flag -= LIB_NEEDLINK;
1912                 }
1913                 ca= ca->id.next;
1914         }
1915 }
1916
1917 static void direct_link_camera(FileData *fd, Camera *ca)
1918 {
1919         direct_link_scriptlink(fd, &ca->scriptlink);
1920 }
1921
1922
1923 /* ************ READ LAMP ***************** */
1924
1925 static void lib_link_lamp(FileData *fd, Main *main)
1926 {
1927         Lamp *la;
1928         MTex *mtex;
1929         int a;
1930
1931         la= main->lamp.first;
1932         while(la) {
1933                 if(la->id.flag & LIB_NEEDLINK) {
1934
1935                         for(a=0; a<MAX_MTEX; a++) {
1936                                 mtex= la->mtex[a];
1937                                 if(mtex) {
1938                                         mtex->tex= newlibadr_us(fd, la->id.lib, mtex->tex);
1939                                         mtex->object= newlibadr(fd, la->id.lib, mtex->object);
1940                                 }
1941                         }
1942
1943                         la->ipo= newlibadr_us(fd, la->id.lib, la->ipo);
1944
1945                         lib_link_scriptlink(fd, &la->id, &la->scriptlink);
1946
1947                         la->id.flag -= LIB_NEEDLINK;
1948                 }
1949                 la= la->id.next;
1950         }
1951 }
1952
1953 static void direct_link_lamp(FileData *fd, Lamp *la)
1954 {
1955         int a;
1956
1957         direct_link_scriptlink(fd, &la->scriptlink);
1958
1959         for(a=0; a<MAX_MTEX; a++) {
1960                 la->mtex[a]= newdataadr(fd, la->mtex[a]);
1961         }
1962         
1963         la->curfalloff= newdataadr(fd, la->curfalloff);
1964         if(la->curfalloff)
1965                 direct_link_curvemapping(fd, la->curfalloff);
1966         
1967         la->preview = direct_link_preview_image(fd, la->preview);
1968 }
1969
1970 /* ************ READ keys ***************** */
1971
1972 static void lib_link_key(FileData *fd, Main *main)
1973 {
1974         Key *key;
1975
1976         key= main->key.first;
1977         while(key) {
1978                 if(key->id.flag & LIB_NEEDLINK) {
1979
1980                         key->ipo= newlibadr_us(fd, key->id.lib, key->ipo);
1981                         key->from= newlibadr(fd, key->id.lib, key->from);
1982
1983                         key->id.flag -= LIB_NEEDLINK;
1984                 }
1985                 key= key->id.next;
1986         }
1987 }
1988
1989 static void switch_endian_keyblock(Key *key, KeyBlock *kb)
1990 {
1991         int elemsize, a, b;
1992         char *data, *poin, *cp;
1993
1994         elemsize= key->elemsize;
1995         data= kb->data;
1996
1997         for(a=0; a<kb->totelem; a++) {
1998
1999                 cp= key->elemstr;
2000                 poin= data;
2001
2002                 while( cp[0] ) {        /* cp[0]==amount */
2003
2004                         switch(cp[1]) {         /* cp[1]= type */
2005                         case IPO_FLOAT:
2006                         case IPO_BPOINT:
2007                         case IPO_BEZTRIPLE:
2008                                 b= cp[0];
2009                                 while(b--) {
2010                                         SWITCH_INT((*poin));
2011                                         poin+= 4;
2012                                 }
2013                                 break;
2014                         }
2015
2016                         cp+= 2;
2017
2018                 }
2019                 data+= elemsize;
2020         }
2021 }
2022
2023 static void direct_link_key(FileData *fd, Key *key)
2024 {
2025         KeyBlock *kb;
2026
2027         link_list(fd, &(key->block));
2028
2029         key->refkey= newdataadr(fd, key->refkey);
2030
2031         kb= key->block.first;
2032         while(kb) {
2033
2034                 kb->data= newdataadr(fd, kb->data);
2035
2036                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN)
2037                         switch_endian_keyblock(key, kb);
2038
2039                 kb= kb->next;
2040         }
2041 }
2042
2043 /* ************ READ mball ***************** */
2044
2045 static void lib_link_mball(FileData *fd, Main *main)
2046 {
2047         MetaBall *mb;
2048         int a;
2049
2050         mb= main->mball.first;
2051         while(mb) {
2052                 if(mb->id.flag & LIB_NEEDLINK) {
2053
2054                         for(a=0; a<mb->totcol; a++) mb->mat[a]= newlibadr_us(fd, mb->id.lib, mb->mat[a]);
2055
2056                         mb->ipo= newlibadr_us(fd, mb->id.lib, mb->ipo);
2057
2058                         mb->id.flag -= LIB_NEEDLINK;
2059                 }
2060                 mb= mb->id.next;
2061         }
2062 }
2063
2064 static void direct_link_mball(FileData *fd, MetaBall *mb)
2065 {
2066         mb->mat= newdataadr(fd, mb->mat);
2067         test_pointer_array(fd, (void **)&mb->mat);
2068
2069         link_list(fd, &(mb->elems));
2070
2071         mb->disp.first= mb->disp.last= 0;
2072
2073         mb->bb= 0;
2074 }
2075
2076 /* ************ READ WORLD ***************** */
2077
2078 static void lib_link_world(FileData *fd, Main *main)
2079 {
2080         World *wrld;
2081         MTex *mtex;
2082         int a;
2083
2084         wrld= main->world.first;
2085         while(wrld) {
2086                 if(wrld->id.flag & LIB_NEEDLINK) {
2087
2088                         wrld->ipo= newlibadr_us(fd, wrld->id.lib, wrld->ipo);
2089
2090                         for(a=0; a<MAX_MTEX; a++) {
2091                                 mtex= wrld->mtex[a];
2092                                 if(mtex) {
2093                                         mtex->tex= newlibadr_us(fd, wrld->id.lib, mtex->tex);
2094                                         mtex->object= newlibadr(fd, wrld->id.lib, mtex->object);
2095                                 }
2096                         }
2097
2098                         lib_link_scriptlink(fd, &wrld->id, &wrld->scriptlink);
2099
2100                         wrld->id.flag -= LIB_NEEDLINK;
2101                 }
2102                 wrld= wrld->id.next;
2103         }
2104 }
2105
2106 static void direct_link_world(FileData *fd, World *wrld)
2107 {
2108         int a;
2109
2110         direct_link_scriptlink(fd, &wrld->scriptlink);
2111
2112         for(a=0; a<MAX_MTEX; a++) {
2113                 wrld->mtex[a]= newdataadr(fd, wrld->mtex[a]);
2114         }
2115         wrld->preview = direct_link_preview_image(fd, wrld->preview);
2116 }
2117
2118
2119 /* ************ READ IPO ***************** */
2120
2121 static void lib_link_ipo(FileData *fd, Main *main)
2122 {
2123         Ipo *ipo;
2124
2125         ipo= main->ipo.first;
2126         while(ipo) {
2127                 if(ipo->id.flag & LIB_NEEDLINK) {
2128                         IpoCurve *icu;
2129                         for(icu= ipo->curve.first; icu; icu= icu->next) {
2130                                 if(icu->driver)
2131                                         icu->driver->ob= newlibadr(fd, ipo->id.lib, icu->driver->ob);
2132                         }
2133                         ipo->id.flag -= LIB_NEEDLINK;
2134                 }
2135                 ipo= ipo->id.next;
2136         }
2137 }
2138
2139 static void direct_link_ipo(FileData *fd, Ipo *ipo)
2140 {
2141         IpoCurve *icu;
2142
2143         link_list(fd, &(ipo->curve));
2144         icu= ipo->curve.first;
2145         while(icu) {
2146                 icu->bezt= newdataadr(fd, icu->bezt);
2147                 icu->bp= newdataadr(fd, icu->bp);
2148                 icu->driver= newdataadr(fd, icu->driver);
2149                 icu= icu->next;
2150         }
2151 }
2152
2153 /* ************ READ VFONT ***************** */
2154
2155 static void lib_link_vfont(FileData *fd, Main *main)
2156 {
2157         VFont *vf;
2158
2159         vf= main->vfont.first;
2160         while(vf) {
2161                 if(vf->id.flag & LIB_NEEDLINK) {
2162                         vf->id.flag -= LIB_NEEDLINK;
2163                 }
2164                 vf= vf->id.next;
2165         }
2166 }
2167
2168 static void direct_link_vfont(FileData *fd, VFont *vf)
2169 {
2170         vf->data= NULL;
2171         vf->packedfile= direct_link_packedfile(fd, vf->packedfile);
2172 }
2173
2174 /* ************ READ TEXT ****************** */
2175
2176 static void lib_link_text(FileData *fd, Main *main)
2177 {
2178         Text *text;
2179
2180         text= main->text.first;
2181         while(text) {
2182                 if(text->id.flag & LIB_NEEDLINK) {
2183                         text->id.flag -= LIB_NEEDLINK;
2184                 }
2185                 text= text->id.next;
2186         }
2187 }
2188
2189 static void direct_link_text(FileData *fd, Text *text)
2190 {
2191         TextLine *ln;
2192
2193         text->name= newdataadr(fd, text->name);
2194
2195         text->undo_pos= -1;
2196         text->undo_len= TXT_INIT_UNDO;
2197         text->undo_buf= MEM_mallocN(text->undo_len, "undo buf");
2198
2199         text->compiled= NULL;
2200
2201 /*
2202         if(text->flags & TXT_ISEXT) {
2203                 reopen_text(text);
2204         } else {
2205 */
2206
2207         link_list(fd, &text->lines);
2208
2209         text->curl= newdataadr(fd, text->curl);
2210         text->sell= newdataadr(fd, text->sell);
2211
2212         ln= text->lines.first;
2213         while(ln) {
2214                 ln->line= newdataadr(fd, ln->line);
2215                 ln->format= NULL;
2216                 
2217                 if (ln->len != (int) strlen(ln->line)) {
2218                         printf("Error loading text, line lengths differ\n");
2219                         ln->len = strlen(ln->line);
2220                 }
2221
2222                 ln= ln->next;
2223         }
2224
2225         text->flags = (text->flags|TXT_ISTMP) & ~TXT_ISEXT;
2226
2227         text->id.us= 1;
2228 }
2229
2230 /* ************ READ IMAGE ***************** */
2231
2232 static void lib_link_image(FileData *fd, Main *main)
2233 {
2234         Image *ima;
2235
2236         ima= main->image.first;
2237         while (ima) {
2238                 if(ima->id.flag & LIB_NEEDLINK) {
2239                         if (ima->id.properties) IDP_LibLinkProperty(ima->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2240
2241                         ima->id.flag -= LIB_NEEDLINK;
2242                 }
2243                 ima= ima->id.next;
2244         }
2245 }
2246
2247 static void link_ibuf_list(FileData *fd, ListBase *lb)
2248 {
2249         Link *ln, *prev;
2250         
2251         if(lb->first==NULL) return;
2252         
2253         lb->first= newimaadr(fd, lb->first);
2254         ln= lb->first;
2255         prev= NULL;
2256         while(ln) {
2257                 ln->next= newimaadr(fd, ln->next);
2258                 ln->prev= prev;
2259                 prev= ln;
2260                 ln= ln->next;
2261         }
2262         lb->last= prev;
2263 }
2264
2265 static void direct_link_image(FileData *fd, Image *ima)
2266 {
2267         /* for undo system, pointers could be restored */
2268         if(fd->imamap)
2269                 link_ibuf_list(fd, &ima->ibufs);
2270         else
2271                 ima->ibufs.first= ima->ibufs.last= NULL;
2272         
2273         /* if not restored, we keep the binded opengl index */
2274         if(ima->ibufs.first==NULL)
2275                 ima->bindcode= 0;
2276         
2277         ima->anim= NULL;
2278         ima->rr= NULL;
2279         ima->repbind= NULL;
2280         
2281         ima->packedfile = direct_link_packedfile(fd, ima->packedfile);
2282         ima->preview = direct_link_preview_image(fd, ima->preview);
2283         ima->ok= 1;
2284 }
2285
2286
2287 /* ************ READ CURVE ***************** */
2288
2289 static void lib_link_curve(FileData *fd, Main *main)
2290 {
2291         Curve *cu;
2292         int a;
2293
2294         cu= main->curve.first;
2295         while(cu) {
2296                 if(cu->id.flag & LIB_NEEDLINK) {
2297
2298                         for(a=0; a<cu->totcol; a++) cu->mat[a]= newlibadr_us(fd, cu->id.lib, cu->mat[a]);
2299
2300                         cu->bevobj= newlibadr(fd, cu->id.lib, cu->bevobj);
2301                         cu->taperobj= newlibadr(fd, cu->id.lib, cu->taperobj);
2302                         cu->textoncurve= newlibadr(fd, cu->id.lib, cu->textoncurve);
2303                         cu->vfont= newlibadr_us(fd, cu->id.lib, cu->vfont);
2304                         cu->vfontb= newlibadr_us(fd, cu->id.lib, cu->vfontb);                   
2305                         cu->vfonti= newlibadr_us(fd, cu->id.lib, cu->vfonti);
2306                         cu->vfontbi= newlibadr_us(fd, cu->id.lib, cu->vfontbi);
2307
2308                         cu->ipo= newlibadr_us(fd, cu->id.lib, cu->ipo);
2309                         cu->key= newlibadr_us(fd, cu->id.lib, cu->key);
2310
2311                         cu->id.flag -= LIB_NEEDLINK;
2312                 }
2313                 cu= cu->id.next;
2314         }
2315 }
2316
2317
2318 static void switch_endian_knots(Nurb *nu)
2319 {
2320         int len;
2321
2322         if(nu->knotsu) {
2323                 len= KNOTSU(nu);
2324                 while(len--) {
2325                         SWITCH_INT(nu->knotsu[len]);
2326                 }
2327         }
2328         if(nu->knotsv) {
2329                 len= KNOTSV(nu);
2330                 while(len--) {
2331                         SWITCH_INT(nu->knotsv[len]);
2332                 }
2333         }
2334 }
2335
2336 static void direct_link_curve(FileData *fd, Curve *cu)
2337 {
2338         Nurb *nu;
2339         TextBox *tb;
2340
2341         cu->mat= newdataadr(fd, cu->mat);
2342         test_pointer_array(fd, (void **)&cu->mat);
2343         cu->str= newdataadr(fd, cu->str);
2344         cu->strinfo= newdataadr(fd, cu->strinfo);       
2345         cu->tb= newdataadr(fd, cu->tb);
2346
2347         if(cu->vfont==0) link_list(fd, &(cu->nurb));
2348         else {
2349                 cu->nurb.first=cu->nurb.last= 0;
2350
2351                 tb= MEM_callocN(MAXTEXTBOX*sizeof(TextBox), "TextBoxread");
2352                 if (cu->tb) {
2353                         memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox));
2354                         MEM_freeN(cu->tb);
2355                         cu->tb= tb;                     
2356                 } else {
2357                         cu->totbox = 1;
2358                         cu->actbox = 1;
2359                         cu->tb = tb;
2360                         cu->tb[0].w = cu->linewidth;
2361                 }               
2362                 if (cu->wordspace == 0.0) cu->wordspace = 1.0;
2363         }
2364
2365         cu->bev.first=cu->bev.last= 0;
2366         cu->disp.first=cu->disp.last= 0;
2367         cu->path= 0;
2368
2369         nu= cu->nurb.first;
2370         while(nu) {
2371                 nu->bezt= newdataadr(fd, nu->bezt);
2372                 nu->bp= newdataadr(fd, nu->bp);
2373                 nu->knotsu= newdataadr(fd, nu->knotsu);
2374                 nu->knotsv= newdataadr(fd, nu->knotsv);
2375                 if (cu->vfont==0) nu->charidx= nu->mat_nr;
2376
2377                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2378                         switch_endian_knots(nu);
2379                 }
2380
2381                 nu= nu->next;
2382         }
2383         cu->bb= NULL;
2384 }
2385
2386 /* ************ READ TEX ***************** */
2387
2388 static void lib_link_texture(FileData *fd, Main *main)
2389 {
2390         Tex *tex;
2391
2392         tex= main->tex.first;
2393         while(tex) {
2394                 if(tex->id.flag & LIB_NEEDLINK) {
2395
2396                         tex->ima= newlibadr_us(fd, tex->id.lib, tex->ima);
2397                         tex->ipo= newlibadr_us(fd, tex->id.lib, tex->ipo);
2398                         if(tex->env) tex->env->object= newlibadr(fd, tex->id.lib, tex->env->object);
2399
2400                         tex->id.flag -= LIB_NEEDLINK;
2401                 }
2402                 tex= tex->id.next;
2403         }
2404 }
2405
2406 static void direct_link_texture(FileData *fd, Tex *tex)
2407 {
2408         tex->plugin= newdataadr(fd, tex->plugin);
2409         if(tex->plugin) {
2410                 tex->plugin->handle= 0;
2411                 open_plugin_tex(tex->plugin);
2412                 /* initialize data for this instance, if an initialization
2413                  * function exists.
2414                  */
2415                 if (tex->plugin->instance_init)
2416                         tex->plugin->instance_init((void *) tex->plugin->data);
2417         }
2418         tex->coba= newdataadr(fd, tex->coba);
2419         tex->env= newdataadr(fd, tex->env);
2420         if(tex->env) {
2421                 tex->env->ima= NULL;
2422                 memset(tex->env->cube, 0, 6*sizeof(void *));
2423                 tex->env->ok= 0;
2424         }
2425         tex->preview = direct_link_preview_image(fd, tex->preview);
2426
2427         tex->iuser.ok= 1;
2428 }
2429
2430
2431
2432 /* ************ READ MATERIAL ***************** */
2433
2434 static void lib_link_material(FileData *fd, Main *main)
2435 {
2436         Material *ma;
2437         MTex *mtex;
2438         int a;
2439
2440         ma= main->mat.first;
2441         while(ma) {
2442                 if(ma->id.flag & LIB_NEEDLINK) {
2443                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
2444                         of library blocks that implement this.*/
2445                         if (ma->id.properties) IDP_LibLinkProperty(ma->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2446
2447                         ma->ipo= newlibadr_us(fd, ma->id.lib, ma->ipo);
2448                         ma->group= newlibadr_us(fd, ma->id.lib, ma->group);
2449                         
2450                         for(a=0; a<MAX_MTEX; a++) {
2451                                 mtex= ma->mtex[a];
2452                                 if(mtex) {
2453                                         mtex->tex= newlibadr_us(fd, ma->id.lib, mtex->tex);
2454                                         mtex->object= newlibadr(fd, ma->id.lib, mtex->object);
2455                                 }
2456                         }
2457                         lib_link_scriptlink(fd, &ma->id, &ma->scriptlink);
2458                         
2459                         if(ma->nodetree)
2460                                 lib_link_ntree(fd, &ma->id, ma->nodetree);
2461                         
2462                         ma->id.flag -= LIB_NEEDLINK;
2463                 }
2464                 ma= ma->id.next;
2465         }
2466 }
2467
2468 static void direct_link_material(FileData *fd, Material *ma)
2469 {
2470         int a;
2471
2472         for(a=0; a<MAX_MTEX; a++) {
2473                 ma->mtex[a]= newdataadr(fd, ma->mtex[a]);
2474         }
2475
2476         ma->ramp_col= newdataadr(fd, ma->ramp_col);
2477         ma->ramp_spec= newdataadr(fd, ma->ramp_spec);
2478         
2479         direct_link_scriptlink(fd, &ma->scriptlink);
2480         
2481         ma->nodetree= newdataadr(fd, ma->nodetree);
2482         if(ma->nodetree)
2483                 direct_link_nodetree(fd, ma->nodetree);
2484
2485         ma->preview = direct_link_preview_image(fd, ma->preview);
2486 }
2487
2488 /* ************ READ PARTICLE SETTINGS ***************** */
2489
2490 static void lib_link_particlesettings(FileData *fd, Main *main)
2491 {
2492         ParticleSettings *part;
2493
2494         part= main->particle.first;
2495         while(part) {
2496                 if(part->id.flag & LIB_NEEDLINK) {
2497                         part->ipo= newlibadr_us(fd, part->id.lib, part->ipo);
2498                         part->dup_ob = newlibadr(fd, part->id.lib, part->dup_ob);
2499                         part->dup_group = newlibadr(fd, part->id.lib, part->dup_group);
2500                         part->eff_group = newlibadr(fd, part->id.lib, part->eff_group);
2501                         part->bb_ob = newlibadr(fd, part->id.lib, part->bb_ob);
2502                         part->id.flag -= LIB_NEEDLINK;
2503                 }
2504                 part= part->id.next;
2505         }
2506 }
2507
2508 static void direct_link_particlesettings(FileData *fd, ParticleSettings *part)
2509 {
2510         part->pd= newdataadr(fd, part->pd);
2511 }
2512
2513 static void lib_link_particlesystems(FileData *fd, ID *id, ListBase *particles)
2514 {
2515         ParticleSystem *psys;
2516         int a;
2517
2518         for(psys=particles->first; psys; psys=psys->next){
2519                 ParticleData *pa;
2520                 psys->part = newlibadr_us(fd, id->lib, psys->part);
2521                 psys->target_ob = newlibadr(fd, id->lib, psys->target_ob);
2522                 psys->keyed_ob = newlibadr(fd, id->lib, psys->keyed_ob);
2523
2524                 for(a=0,pa=psys->particles; a<psys->totpart; a++,pa++){
2525                         pa->stick_ob=newlibadr(fd, id->lib, pa->stick_ob);
2526                 }
2527         }
2528 }
2529 static void direct_link_particlesystems(FileData *fd, ListBase *particles)
2530 {
2531         ParticleSystem *psys;
2532         int a;
2533
2534         for(psys=particles->first; psys; psys=psys->next) {
2535                 psys->particles=newdataadr(fd,psys->particles);
2536                 if(psys->particles && psys->particles->hair){
2537                         ParticleData *pa = psys->particles;
2538                         for(a=0; a<psys->totpart; a++, pa++)
2539                                 pa->hair=newdataadr(fd,pa->hair);
2540                 }
2541                 if(psys->particles && psys->particles->keys){
2542                         ParticleData *pa = psys->particles;
2543                         for(a=0; a<psys->totpart; a++, pa++)
2544                                 pa->keys=newdataadr(fd,pa->keys);
2545                 }
2546                 psys->child=newdataadr(fd,psys->child);
2547                 psys->effectors.first=psys->effectors.last=0;
2548
2549                 psys->soft= newdataadr(fd, psys->soft);
2550                 if(psys->soft) {
2551                         SoftBody *sb = psys->soft;
2552                         sb->particles = psys;
2553                         sb->bpoint= NULL;       // init pointers so it gets rebuilt nicely
2554                         sb->bspring= NULL;
2555                         sb->scratch= NULL;
2556                 }
2557
2558                 psys->edit = 0;
2559                 psys->pathcache = 0;
2560                 psys->childcache = 0;
2561                 psys->reactevents.first = psys->reactevents.last = 0;
2562         }
2563         return;
2564 }
2565
2566 /* ************ READ MESH ***************** */
2567
2568 static void lib_link_mtface(FileData *fd, Mesh *me, MTFace *mtface, int totface)
2569 {
2570         MTFace *tf= mtface;
2571         int i;
2572
2573         for (i=0; i<totface; i++, tf++) {
2574                 tf->tpage= newlibadr(fd, me->id.lib, tf->tpage);
2575                 if(tf->tpage && tf->tpage->id.us==0)
2576                         tf->tpage->id.us= 1;
2577         }
2578 }
2579
2580 static void lib_link_customdata_mtface(FileData *fd, Mesh *me, CustomData *fdata, int totface)
2581 {
2582         int i;  
2583         for(i=0; i<fdata->totlayer; i++) {
2584                 CustomDataLayer *layer = &fdata->layers[i];
2585                 
2586                 if(layer->type == CD_MTFACE)
2587                         lib_link_mtface(fd, me, layer->data, totface);
2588         }
2589
2590 }
2591
2592 static void lib_link_mesh(FileData *fd, Main *main)
2593 {
2594         Mesh *me;
2595
2596         me= main->mesh.first;
2597         while(me) {
2598                 if(me->id.flag & LIB_NEEDLINK) {
2599                         int i;
2600
2601                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
2602                         of library blocks that implement this.*/
2603                         if (me->id.properties) IDP_LibLinkProperty(me->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2604
2605                         /* this check added for python created meshes */
2606                         if(me->mat) {
2607                                 for(i=0; i<me->totcol; i++) {
2608                                         me->mat[i]= newlibadr_us(fd, me->id.lib, me->mat[i]);
2609                                 }
2610                         }
2611                         else me->totcol= 0;
2612
2613                         me->ipo= newlibadr_us(fd, me->id.lib, me->ipo);
2614                         me->key= newlibadr_us(fd, me->id.lib, me->key);
2615                         me->texcomesh= newlibadr_us(fd, me->id.lib, me->texcomesh);
2616
2617                         lib_link_customdata_mtface(fd, me, &me->fdata, me->totface);
2618                         if(me->mr && me->mr->levels.first)
2619                                 lib_link_customdata_mtface(fd, me, &me->mr->fdata,
2620                                                            ((MultiresLevel*)me->mr->levels.first)->totface);
2621
2622                         me->id.flag -= LIB_NEEDLINK;
2623                 }
2624                 me= me->id.next;
2625         }
2626 }
2627
2628 static void direct_link_dverts(FileData *fd, int count, MDeformVert *mdverts)
2629 {
2630         int     i;
2631
2632         if (!mdverts)
2633                 return;
2634
2635         for (i=0; i<count; i++) {
2636                 mdverts[i].dw=newdataadr(fd, mdverts[i].dw);
2637                 if (!mdverts[i].dw)
2638                         mdverts[i].totweight=0;
2639         }
2640 }
2641
2642 static void direct_link_customdata(FileData *fd, CustomData *data, int count)
2643 {
2644         int i = 0;
2645
2646         data->layers= newdataadr(fd, data->layers);
2647
2648         while (i < data->totlayer) {
2649                 CustomDataLayer *layer = &data->layers[i];
2650
2651                 if (CustomData_verify_versions(data, i)) {
2652                         layer->data = newdataadr(fd, layer->data);
2653                         i++;
2654                 }
2655         }
2656 }
2657
2658 static void direct_link_mesh(FileData *fd, Mesh *mesh)
2659 {
2660         mesh->mat= newdataadr(fd, mesh->mat);
2661         test_pointer_array(fd, (void **)&mesh->mat);
2662
2663         mesh->mvert= newdataadr(fd, mesh->mvert);
2664         mesh->medge= newdataadr(fd, mesh->medge);
2665         mesh->mface= newdataadr(fd, mesh->mface);
2666         mesh->tface= newdataadr(fd, mesh->tface);
2667         mesh->mtface= newdataadr(fd, mesh->mtface);
2668         mesh->mcol= newdataadr(fd, mesh->mcol);
2669         mesh->msticky= newdataadr(fd, mesh->msticky);
2670         mesh->dvert= newdataadr(fd, mesh->dvert);
2671         
2672         /* Partial-mesh visibility (do this before using totvert, totface, or totedge!) */
2673         mesh->pv= newdataadr(fd, mesh->pv);
2674         if(mesh->pv) {
2675                 mesh->pv->vert_map= newdataadr(fd, mesh->pv->vert_map);
2676                 mesh->pv->edge_map= newdataadr(fd, mesh->pv->edge_map);
2677                 mesh->pv->old_faces= newdataadr(fd, mesh->pv->old_faces);
2678                 mesh->pv->old_edges= newdataadr(fd, mesh->pv->old_edges);
2679         }
2680
2681         /* normally direct_link_dverts should be called in direct_link_customdata,
2682            but for backwards compat in do_versions to work we do it here */
2683         direct_link_dverts(fd, mesh->pv ? mesh->pv->totvert : mesh->totvert, mesh->dvert);
2684
2685         direct_link_customdata(fd, &mesh->vdata, mesh->pv ? mesh->pv->totvert : mesh->totvert);
2686         direct_link_customdata(fd, &mesh->edata, mesh->pv ? mesh->pv->totedge : mesh->totedge);
2687         direct_link_customdata(fd, &mesh->fdata, mesh->pv ? mesh->pv->totface : mesh->totface);
2688
2689         mesh->bb= NULL;
2690         mesh->mselect = NULL;
2691
2692         /* Multires data */
2693         mesh->mr= newdataadr(fd, mesh->mr);
2694         if(mesh->mr) {
2695                 MultiresLevel *lvl;
2696                 
2697                 link_list(fd, &mesh->mr->levels);
2698                 lvl= mesh->mr->levels.first;
2699                 
2700                 direct_link_customdata(fd, &mesh->mr->vdata, lvl->totvert);
2701                 direct_link_dverts(fd, lvl->totvert, CustomData_get(&mesh->mr->vdata, 0, CD_MDEFORMVERT));
2702                 direct_link_customdata(fd, &mesh->mr->fdata, lvl->totface);
2703                 
2704                 if(mesh->mr->edge_flags)
2705                         mesh->mr->edge_flags= newdataadr(fd, mesh->mr->edge_flags);
2706                 if(mesh->mr->edge_creases)
2707                         mesh->mr->edge_creases= newdataadr(fd, mesh->mr->edge_creases);
2708                 
2709                 if(!mesh->mr->edge_flags)
2710                         mesh->mr->edge_flags= MEM_callocN(sizeof(short)*lvl->totedge, "Multires Edge Flags");
2711                 if(!mesh->mr->edge_creases)
2712                         mesh->mr->edge_creases= MEM_callocN(sizeof(char)*lvl->totedge, "Multires Edge Creases");
2713
2714                 mesh->mr->verts = newdataadr(fd, mesh->mr->verts);
2715                         
2716                 for(; lvl; lvl= lvl->next) {
2717                         lvl->verts= newdataadr(fd, lvl->verts);
2718                         lvl->faces= newdataadr(fd, lvl->faces);
2719                         lvl->edges= newdataadr(fd, lvl->edges);
2720                         lvl->colfaces= newdataadr(fd, lvl->colfaces);
2721                         lvl->edge_boundary_states= NULL;
2722                         lvl->vert_face_map = lvl->vert_edge_map = NULL;
2723                         lvl->map_mem= NULL;
2724                 }
2725         }
2726         
2727         if((fd->flags & FD_FLAGS_SWITCH_ENDIAN) && mesh->tface) {
2728                 TFace *tf= mesh->tface;
2729                 int i;
2730
2731                 for (i=0; i< (mesh->pv ? mesh->pv->totface : mesh->totface); i++, tf++) {
2732                         SWITCH_INT(tf->col[0]);
2733                         SWITCH_INT(tf->col[1]);
2734                         SWITCH_INT(tf->col[2]);
2735                         SWITCH_INT(tf->col[3]);
2736                 }
2737         }
2738 }
2739
2740 /* ************ READ LATTICE ***************** */
2741
2742 static void lib_link_latt(FileData *fd, Main *main)
2743 {
2744         Lattice *lt;
2745         
2746         lt= main->latt.first;
2747         while(lt) {
2748                 if(lt->id.flag & LIB_NEEDLINK) {
2749                         
2750                         lt->ipo= newlibadr_us(fd, lt->id.lib, lt->ipo);
2751                         lt->key= newlibadr_us(fd, lt->id.lib, lt->key);
2752                         
2753                         lt->id.flag -= LIB_NEEDLINK;
2754                 }
2755                 lt= lt->id.next;
2756         }
2757 }
2758
2759 static void direct_link_latt(FileData *fd, Lattice *lt)
2760 {
2761         lt->def= newdataadr(fd, lt->def);
2762         
2763         lt->dvert= newdataadr(fd, lt->dvert);
2764         direct_link_dverts(fd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
2765 }
2766
2767
2768 /* ************ READ OBJECT ***************** */
2769
2770 static void lib_link_modifiers__linkModifiers(void *userData, Object *ob,
2771                                               ID **idpoin)
2772 {
2773         FileData *fd = userData;
2774
2775         *idpoin = newlibadr(fd, ob->id.lib, *idpoin);
2776         /* hardcoded bad exception; non-object modifier data gets user count (texture, displace) */
2777         if(*idpoin && GS((*idpoin)->name)!=ID_OB)
2778                 (*idpoin)->us++;
2779 }
2780 static void lib_link_modifiers(FileData *fd, Object *ob)
2781 {
2782         modifiers_foreachIDLink(ob, lib_link_modifiers__linkModifiers, fd);
2783 }
2784
2785 static void lib_link_object(FileData *fd, Main *main)
2786 {
2787         Object *ob;
2788         PartEff *paf;
2789         bSensor *sens;
2790         bController *cont;
2791         bActuator *act;
2792         void *poin;
2793         int warn=0, a;
2794
2795         ob= main->object.first;
2796         while(ob) {
2797                 if(ob->id.flag & LIB_NEEDLINK) {
2798                         if (ob->id.properties) IDP_LibLinkProperty(ob->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2799
2800                         ob->parent= newlibadr(fd, ob->id.lib, ob->parent);
2801                         ob->track= newlibadr(fd, ob->id.lib, ob->track);
2802                         ob->ipo= newlibadr_us(fd, ob->id.lib, ob->ipo);
2803                         ob->action = newlibadr_us(fd, ob->id.lib, ob->action);
2804                         ob->poselib= newlibadr_us(fd, ob->id.lib, ob->poselib);
2805                         ob->dup_group= newlibadr_us(fd, ob->id.lib, ob->dup_group);
2806                         
2807                         ob->proxy= newlibadr_us(fd, ob->id.lib, ob->proxy);
2808                         if(ob->proxy) {
2809                                 /* paranoia check, actually a proxy_from pointer should never be written... */
2810                                 if(ob->proxy->id.lib==NULL) {
2811                                         ob->proxy->proxy_from= NULL;
2812                                         ob->proxy= NULL;
2813                                 }
2814                                 else {
2815                                         /* this triggers object_update to always use a copy */
2816                                         ob->proxy->proxy_from= ob;
2817                                         /* force proxy updates after load/undo, a bit weak */
2818                                         ob->recalc= ob->proxy->recalc= OB_RECALC;
2819                                 }
2820                         }
2821                         ob->proxy_group= newlibadr(fd, ob->id.lib, ob->proxy_group);
2822
2823                         poin= ob->data;
2824                         ob->data= newlibadr_us(fd, ob->id.lib, ob->data);
2825                            
2826                         if(ob->data==NULL && poin!=NULL) {
2827                                 ob->type= OB_EMPTY;
2828                                 warn= 1;
2829                                 if(ob->id.lib) printf("Can't find obdata of %s lib %s\n", ob->id.name+2, ob->id.lib->name);
2830                                 else printf("Object %s lost data.", ob->id.name+2);
2831                                 
2832                                 if(ob->pose) {
2833                                         free_pose_channels(ob->pose);
2834                                         MEM_freeN(ob->pose);
2835                                         ob->pose= NULL;
2836                                         ob->flag &= ~OB_POSEMODE;
2837                                 }
2838                         }
2839                         for(a=0; a<ob->totcol; a++) ob->mat[a]= newlibadr_us(fd, ob->id.lib, ob->mat[a]);
2840
2841                         ob->id.flag -= LIB_NEEDLINK;
2842                         /* if id.us==0 a new base will be created later on */
2843
2844                         /* WARNING! Also check expand_object(), should reflect the stuff below. */
2845                         lib_link_pose(fd, ob, ob->pose);
2846                         lib_link_constraints(fd, &ob->id, &ob->constraints);
2847                         lib_link_nlastrips(fd, &ob->id, &ob->nlastrips);
2848                         lib_link_constraint_channels(fd, &ob->id, &ob->constraintChannels);
2849
2850                         for(paf= ob->effect.first; paf; paf= paf->next) {
2851                                 if(paf->type==EFF_PARTICLE) {
2852                                         paf->group= newlibadr_us(fd, ob->id.lib, paf->group);
2853                                 }
2854                         }                               
2855
2856                         sens= ob->sensors.first;
2857                         while(sens) {
2858                                 if(ob->id.lib==NULL) {  // done in expand_main
2859                                         for(a=0; a<sens->totlinks; a++) {
2860                                                 sens->links[a]= newglobadr(fd, sens->links[a]);
2861                                         }
2862                                 }
2863                                 if(sens->type==SENS_TOUCH) {
2864                                         bTouchSensor *ts= sens->data;
2865                                         ts->ma= newlibadr(fd, ob->id.lib, ts->ma);
2866                                 }
2867                                 else if(sens->type==SENS_MESSAGE) {
2868                                         bMessageSensor *ms= sens->data;
2869                                         ms->fromObject=
2870                                             newlibadr(fd, ob->id.lib, ms->fromObject);
2871                                 }
2872                                 sens= sens->next;
2873                         }
2874
2875                         cont= ob->controllers.first;
2876                         while(cont) {
2877                                 if(ob->id.lib==NULL) {  // done in expand_main
2878                                         for(a=0; a<cont->totlinks; a++) {
2879                                                 cont->links[a]= newglobadr(fd, cont->links[a]);
2880                                         }
2881                                 }
2882                                 if(cont->type==CONT_PYTHON) {
2883                                         bPythonCont *pc= cont->data;
2884                                         pc->text= newlibadr(fd, ob->id.lib, pc->text);
2885                                 }
2886                                 cont->slinks= NULL;
2887                                 cont->totslinks= 0;
2888
2889                                 cont= cont->next;
2890                         }
2891
2892                         act= ob->actuators.first;
2893                         while(act) {
2894                                 if(act->type==ACT_SOUND) {
2895                                         bSoundActuator *sa= act->data;
2896                                         sa->sound= newlibadr_us(fd, ob->id.lib, sa->sound);
2897                                 }
2898                                 else if(act->type==ACT_CD) {
2899                                         /* bCDActuator *cda= act->data; */
2900                                 }
2901                                 else if(act->type==ACT_GAME) {
2902                                         /* bGameActuator *ga= act->data; */
2903                                 }
2904                                 else if(act->type==ACT_CAMERA) {
2905                                         bCameraActuator *ca= act->data;
2906                                         ca->ob= newlibadr(fd, ob->id.lib, ca->ob);
2907                                 }
2908                                         /* leave this one, it's obsolete but necessary to read for conversion */
2909                                 else if(act->type==ACT_ADD_OBJECT) {
2910                                         bAddObjectActuator *eoa= act->data;
2911                                         if(eoa) eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
2912                                 }
2913                                 else if(act->type==ACT_EDIT_OBJECT) {
2914                                         bEditObjectActuator *eoa= act->data;
2915                                         if(eoa==NULL) {
2916                                                 init_actuator(act);
2917                                         }
2918                                         else {
2919                                                 eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
2920                                                 eoa->me= newlibadr(fd, ob->id.lib, eoa->me);
2921                                         }
2922                                 }
2923                                 else if(act->type==ACT_SCENE) {
2924                                         bSceneActuator *sa= act->data;
2925                                         sa->camera= newlibadr(fd, ob->id.lib, sa->camera);
2926                                         sa->scene= newlibadr(fd, ob->id.lib, sa->scene);
2927                                 }
2928                                 else if(act->type==ACT_ACTION) {
2929                                         bActionActuator *aa= act->data;
2930                                         aa->act= newlibadr(fd, ob->id.lib, aa->act);
2931                                 }
2932                                 else if(act->type==ACT_PROPERTY) {
2933                                         bPropertyActuator *pa= act->data;
2934                                         pa->ob= newlibadr(fd, ob->id.lib, pa->ob);
2935                                 }
2936                                 else if(act->type==ACT_MESSAGE) {
2937                                         bMessageActuator *ma= act->data;
2938                                         ma->toObject= newlibadr(fd, ob->id.lib, ma->toObject);
2939                                 }
2940                                 act= act->next;
2941                         }
2942
2943                         if(ob->fluidsimSettings) {
2944                                 ob->fluidsimSettings->ipo = newlibadr_us(fd, ob->id.lib, ob->fluidsimSettings->ipo);
2945                         }
2946                         
2947                         /* texture field */
2948                         if(ob->pd)
2949                                 if(ob->pd->tex)
2950                                         ob->pd->tex=newlibadr_us(fd, ob->id.lib, ob->pd->tex);
2951
2952                         lib_link_scriptlink(fd, &ob->id, &ob->scriptlink);
2953                         lib_link_particlesystems(fd, &ob->id, &ob->particlesystem);
2954                         lib_link_modifiers(fd, ob);
2955                 }
2956                 ob= ob->id.next;
2957         }
2958
2959         if(warn) error("WARNING IN CONSOLE");
2960 }
2961
2962
2963 static void direct_link_pose(FileData *fd, bPose *pose) {
2964
2965         bPoseChannel *pchan;
2966
2967         if (!pose)
2968                 return;
2969
2970         link_list(fd, &pose->chanbase);
2971
2972         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
2973                 pchan->bone= NULL;
2974                 pchan->parent= newdataadr(fd, pchan->parent);
2975                 pchan->child= newdataadr(fd, pchan->child);
2976                 direct_link_constraints(fd, &pchan->constraints);
2977                 pchan->iktree.first= pchan->iktree.last= NULL;
2978                 pchan->path= NULL;
2979         }
2980 }
2981
2982 static void direct_link_modifiers(FileData *fd, ListBase *lb)
2983 {
2984         ModifierData *md;
2985
2986         link_list(fd, lb);
2987
2988         for (md=lb->first; md; md=md->next) {
2989                 md->error = NULL;
2990                 
2991                 /* if modifiers disappear, or for upward compatibility */
2992                 if(NULL==modifierType_getInfo(md->type))
2993                         md->type= eModifierType_None;
2994                         
2995                 if (md->type==eModifierType_Subsurf) {
2996                         SubsurfModifierData *smd = (SubsurfModifierData*) md;
2997
2998                         smd->emCache = smd->mCache = 0;
2999                 } else if (md->type==eModifierType_Hook) {
3000                         HookModifierData *hmd = (HookModifierData*) md;
3001
3002                         hmd->indexar= newdataadr(fd, hmd->indexar);
3003                         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
3004                                 int a;
3005                                 for(a=0; a<hmd->totindex; a++) {
3006                                         SWITCH_INT(hmd->indexar[a]);
3007                                 }
3008                         }
3009                 } else if (md->type==eModifierType_ParticleSystem) {
3010                         ParticleSystemModifierData *psmd = (ParticleSystemModifierData*) md;
3011
3012                         psmd->dm=0;
3013                         psmd->psys=newdataadr(fd, psmd->psys);
3014                         psmd->flag &= ~eParticleSystemFlag_psys_updated;
3015                 } else if (md->type==eModifierType_Explode) {
3016                         ExplodeModifierData *psmd = (ExplodeModifierData*) md;
3017
3018                         psmd->facepa=0;
3019                 }
3020                 else if (md->type==eModifierType_MeshDeform) {
3021                         MeshDeformModifierData *mmd = (MeshDeformModifierData*) md;
3022
3023                         mmd->bindweights= newdataadr(fd, mmd->bindweights);
3024                         mmd->bindcos= newdataadr(fd, mmd->bindcos);
3025                         mmd->dyngrid= newdataadr(fd, mmd->dyngrid);
3026                         mmd->dyninfluences= newdataadr(fd, mmd->dyninfluences);
3027                         mmd->dynverts= newdataadr(fd, mmd->dynverts);
3028
3029                         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
3030                                 int a;
3031
3032                                 if(mmd->bindweights)
3033                                         for(a=0; a<mmd->totcagevert*mmd->totvert; a++)
3034                                                 SWITCH_INT(mmd->bindweights[a])
3035                                 if(mmd->bindcos)
3036                                         for(a=0; a<mmd->totcagevert*3; a++)
3037                                                 SWITCH_INT(mmd->bindcos[a])
3038                                 if(mmd->dynverts)
3039                                         for(a=0; a<mmd->totvert; a++)
3040                                                 SWITCH_INT(mmd->dynverts[a])
3041                         }
3042                 }
3043         }
3044 }
3045
3046 static void direct_link_nlastrips(FileData *fd, ListBase *strips)
3047 {
3048         bActionStrip *strip;
3049         
3050         link_list(fd, strips);
3051         
3052         for(strip= strips->first; strip; strip= strip->next)
3053                 link_list(fd, &strip->modifiers);
3054 }
3055
3056 static void direct_link_object(FileData *fd, Object *ob)
3057 {
3058         PartEff *paf;
3059         bProperty *prop;
3060         bSensor *sens;
3061         bController *cont;
3062         bActuator *act;
3063         int a;
3064         
3065         /* weak weak... this was only meant as draw flag, now is used in give_base too */
3066         ob->flag &= ~OB_FROMGROUP;
3067
3068         ob->disp.first=ob->disp.last= NULL;
3069
3070         ob->pose= newdataadr(fd, ob->pose);
3071         direct_link_pose(fd, ob->pose);
3072
3073         link_list(fd, &ob->defbase);
3074         direct_link_nlastrips(fd, &ob->nlastrips);
3075         link_list(fd, &ob->constraintChannels);
3076
3077         direct_link_scriptlink(fd, &ob->scriptlink);
3078
3079         ob->mat= newdataadr(fd, ob->mat);
3080         test_pointer_array(fd, (void **)&ob->mat);
3081         
3082         /* do it here, below old data gets converted */
3083         direct_link_modifiers(fd, &ob->modifiers);
3084         
3085         link_list(fd, &ob->effect);
3086         paf= ob->effect.first;
3087         while(paf) {
3088                 if(paf->type==EFF_PARTICLE) {
3089                         paf->keys= NULL;
3090                 }
3091                 if(paf->type==EFF_WAVE) {
3092                         WaveEff *wav = (WaveEff*) paf;
3093                         PartEff *next = paf->next;
3094                         WaveModifierData *wmd = (WaveModifierData*) modifier_new(eModifierType_Wave);
3095
3096                         wmd->damp = wav->damp;
3097                         wmd->flag = wav->flag;
3098                         wmd->height = wav->height;
3099                         wmd->lifetime = wav->lifetime;
3100                         wmd->narrow = wav->narrow;
3101                         wmd->speed = wav->speed;
3102                         wmd->startx = wav->startx;
3103                         wmd->starty = wav->startx;
3104                         wmd->timeoffs = wav->timeoffs;
3105                         wmd->width = wav->width;
3106
3107                         BLI_addtail(&ob->modifiers, wmd);
3108
3109                         BLI_remlink(&ob->effect, paf);
3110                         MEM_freeN(paf);
3111
3112                         paf = next;
3113                         continue;
3114                 }
3115                 if(paf->type==EFF_BUILD) {
3116                         BuildEff *baf = (BuildEff*) paf;
3117                         PartEff *next = paf->next;
3118                         BuildModifierData *bmd = (BuildModifierData*) modifier_new(eModifierType_Build);
3119
3120                         bmd->start = baf->sfra;
3121                         bmd->length = baf->len;
3122                         bmd->randomize = 0;
3123                         bmd->seed = 1;
3124
3125                         BLI_addtail(&ob->modifiers, bmd);
3126
3127                         BLI_remlink(&ob->effect, paf);
3128                         MEM_freeN(paf);
3129
3130                         paf = next;
3131                         continue;
3132                 }
3133                 paf= paf->next;
3134         }
3135
3136         ob->pd= newdataadr(fd, ob->pd);
3137         ob->soft= newdataadr(fd, ob->soft);
3138         if(ob->soft) {
3139                 SoftBody *sb= ob->soft;         
3140                 
3141                 sb->bpoint= NULL;       // init pointers so it gets rebuilt nicely
3142                 sb->bspring= NULL;
3143                 sb->scratch= NULL;
3144
3145                 /* although not used anymore */
3146                 /* still have to be loaded to be compatible with old files */
3147                 sb->keys= newdataadr(fd, sb->keys);
3148                 test_pointer_array(fd, (void **)&sb->keys);
3149                 if(sb->keys) {
3150                         for(a=0; a<sb->totkey; a++) {
3151                                 sb->keys[a]= newdataadr(fd, sb->keys[a]);
3152                         }
3153                 }
3154         }
3155         ob->fluidsimSettings= newdataadr(fd, ob->fluidsimSettings); /* NT */
3156         if(ob->fluidsimSettings) {
3157                 // reinit mesh pointers
3158                 ob->fluidsimSettings->orgMesh = NULL; //ob->data;
3159                 ob->fluidsimSettings->meshSurface = NULL;
3160                 ob->fluidsimSettings->meshBB = NULL;
3161                 ob->fluidsimSettings->meshSurfNormals = NULL;
3162         }
3163
3164         link_list(fd, &ob->particlesystem);
3165         direct_link_particlesystems(fd,&ob->particlesystem);
3166         
3167         link_list(fd, &ob->prop);
3168         prop= ob->prop.first;
3169         while(prop) {
3170                 prop->poin= newdataadr(fd, prop->poin);
3171                 if(prop->poin==0) prop->poin= &prop->data;
3172                 prop= prop->next;
3173         }
3174
3175         link_list(fd, &ob->sensors);
3176         sens= ob->sensors.first;
3177         while(sens) {
3178                 sens->data= newdataadr(fd, sens->data);
3179                 sens->links= newdataadr(fd, sens->links);
3180                 test_pointer_array(fd, (void **)&sens->links);
3181                 sens= sens->next;
3182         }
3183
3184         direct_link_constraints(fd, &ob->constraints);
3185
3186         link_glob_list(fd, &ob->controllers);
3187         cont= ob->controllers.first;
3188         while(cont) {
3189                 cont->data= newdataadr(fd, cont->data);
3190                 cont->links= newdataadr(fd, cont->links);
3191                 test_pointer_array(fd, (void **)&cont->links);
3192                 cont= cont->next;
3193         }
3194
3195         link_glob_list(fd, &ob->actuators);
3196         act= ob->actuators.first;
3197         while(act) {
3198                 act->data= newdataadr(fd, act->data);
3199                 act= act->next;
3200         }
3201
3202         link_list(fd, &ob->hooks);
3203         while (ob->hooks.first) {
3204                 ObHook *hook = ob->hooks.first;
3205                 HookModifierData *hmd = (HookModifierData*) modifier_new(eModifierType_Hook);
3206
3207                 hook->indexar= newdataadr(fd, hook->indexar);
3208                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
3209                         int a;
3210                         for(a=0; a<hook->totindex; a++) {
3211                                 SWITCH_INT(hook->indexar[a]);
3212                         }
3213                 }
3214
3215                         /* Do conversion here because if we have loaded
3216                          * a hook we need to make sure it gets converted
3217                          * and free'd, regardless of version.
3218                          */
3219                 VECCOPY(hmd->cent, hook->cent);
3220                 hmd->falloff = hook->falloff;
3221                 hmd->force = hook->force;
3222                 hmd->indexar = hook->indexar;
3223                 hmd->object = hook->parent;
3224                 memcpy(hmd->parentinv, hook->parentinv, sizeof(hmd->parentinv));
3225                 hmd->totindex = hook->totindex;
3226
3227                 BLI_addhead(&ob->modifiers, hmd);
3228                 BLI_remlink(&ob->hooks, hook);
3229
3230                 MEM_freeN(hook);
3231         }
3232         
3233         ob->bb= NULL;
3234         ob->derivedDeform= NULL;
3235         ob->derivedFinal= NULL;
3236 }
3237
3238 /* ************ READ SCENE ***************** */
3239
3240 static void lib_link_scene(FileData *fd, Main *main)
3241 {
3242         Scene *sce;
3243         Base *base, *next;