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