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