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