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