Part 2 of 64 bits fixing; the files.
[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 any modern 64bit architecture) */
558                 memcpy(&old, &bhead8->old, 8);
559                 bhead4->old = (int) (old >> 3);
560
561                 bhead4->SDNAnr= bhead8->SDNAnr;
562                 bhead4->nr= bhead8->nr;
563         }
564 }
565
566 static void bh8_from_bh4(BHead *bhead, BHead4 *bhead4)
567 {
568         BHead8 *bhead8 = (BHead8 *) bhead;
569
570         bhead8->code= bhead4->code;
571         bhead8->len= bhead4->len;
572
573         if (bhead8->code != ENDB) {
574                 bhead8->old= bhead4->old;
575                 bhead8->SDNAnr= bhead4->SDNAnr;
576                 bhead8->nr= bhead4->nr;
577         }
578 }
579
580 static BHeadN *get_bhead(FileData *fd)
581 {
582         BHead8 bhead8;
583         BHead4 bhead4;
584         BHead  bhead;
585         BHeadN *new_bhead = 0;
586         int readsize;
587
588         if (fd) {
589                 if ( ! fd->eof) {
590
591                         // First read the bhead structure.
592                         // Depending on the platform the file was written on this can
593                         // be a big or little endian BHead4 or BHead8 structure.
594
595                         // As usual 'ENDB' (the last *partial* bhead of the file)
596                         // needs some special handling. We don't want to EOF just yet.
597
598                         if (fd->flags & FD_FLAGS_FILE_POINTSIZE_IS_4) {
599                                 bhead4.code = DATA;
600                                 readsize = fd->read(fd, &bhead4, sizeof(bhead4));
601
602                                 if (readsize == sizeof(bhead4) || bhead4.code == ENDB) {
603                                         if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
604                                                 switch_endian_bh4(&bhead4);
605                                         }
606
607                                         if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) {
608                                                 bh8_from_bh4(&bhead, &bhead4);
609                                         } else {
610                                                 memcpy(&bhead, &bhead4, sizeof(bhead));
611                                         }
612                                 } else {
613                                         fd->eof = 1;
614                                         bhead.len= 0;
615                                 }
616                         } else {
617                                 bhead8.code = DATA;
618                                 readsize = fd->read(fd, &bhead8, sizeof(bhead8));
619
620                                 if (readsize == sizeof(bhead8) || bhead8.code == ENDB) {
621                                         if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
622                                                 switch_endian_bh8(&bhead8);
623                                         }
624
625                                         if (fd->flags & FD_FLAGS_POINTSIZE_DIFFERS) {
626                                                 bh4_from_bh8(&bhead, &bhead8, (fd->flags & FD_FLAGS_SWITCH_ENDIAN));
627                                         } else {
628                                                 memcpy(&bhead, &bhead8, sizeof(bhead));
629                                         }
630                                 } else {
631                                         fd->eof = 1;
632                                         bhead.len= 0;
633                                 }
634                         }
635
636                         /* make sure people are not trying to pass bad blend files */
637                         if (bhead.len < 0) fd->eof = 1;
638
639                         // bhead now contains the (converted) bhead structure. Now read
640                         // the associated data and put everything in a BHeadN (creative naming !)
641
642                         if ( ! fd->eof) {
643                                 new_bhead = MEM_mallocN(sizeof(BHeadN) + bhead.len, "new_bhead");
644                                 if (new_bhead) {
645                                         new_bhead->next = new_bhead->prev = 0;
646                                         new_bhead->bhead = bhead;
647
648                                         readsize = fd->read(fd, new_bhead + 1, bhead.len);
649
650                                         if (readsize != bhead.len) {
651                                                 fd->eof = 1;
652                                                 MEM_freeN(new_bhead);
653                                                 new_bhead = 0;
654                                         }
655                                 } else {
656                                         fd->eof = 1;
657                                 }
658                         }
659                 }
660         }
661
662         // We've read a new block. Now add it to the list
663         // of blocks.
664
665         if (new_bhead) {
666                 BLI_addtail(&fd->listbase, new_bhead);
667         }
668
669         return(new_bhead);
670 }
671
672 BHead *blo_firstbhead(FileData *fd)
673 {
674         BHeadN *new_bhead;
675         BHead *bhead = 0;
676
677         // Rewind the file
678         // Read in a new block if necessary
679
680         new_bhead = fd->listbase.first;
681         if (new_bhead == 0) {
682                 new_bhead = get_bhead(fd);
683         }
684
685         if (new_bhead) {
686                 bhead = &new_bhead->bhead;
687         }
688
689         return(bhead);
690 }
691
692 BHead *blo_prevbhead(FileData *fd, BHead *thisblock)
693 {
694         BHeadN *bheadn= (BHeadN *) (((char *) thisblock) - (int) (&((BHeadN*)0)->bhead));
695         BHeadN *prev= bheadn->prev;
696
697         return prev?&prev->bhead:NULL;
698 }
699
700 BHead *blo_nextbhead(FileData *fd, BHead *thisblock)
701 {
702         BHeadN *new_bhead = 0;
703         BHead *bhead = 0;
704
705         if (thisblock) {
706                 // bhead is actually a sub part of BHeadN
707                 // We calculate the BHeadN pointer from the BHead pointer below
708                 new_bhead = (BHeadN *) (((char *) thisblock) - (int) (&((BHeadN*)0)->bhead));
709
710                 // get the next BHeadN. If it doesn't exist we read in the next one
711                 new_bhead = new_bhead->next;
712                 if (new_bhead == 0) {
713                         new_bhead = get_bhead(fd);
714                 }
715         }
716
717         if (new_bhead) {
718                 // here we do the reverse:
719                 // go from the BHeadN pointer to the BHead pointer
720                 bhead = &new_bhead->bhead;
721         }
722
723         return(bhead);
724 }
725
726 #if 0
727 static void get_blender_subversion(FileData *fd)
728 {
729         BHead *bhead;
730         
731         for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead)) {
732                 if (bhead->code==GLOB) {
733                         FileGlobal *fg= read_struct(fd, bhead, "Global");
734                         fd->filesubversion= fg->subversion;
735                         fd->fileminversion= fg->minversion;
736                         fd->fileminsubversion= fg->minsubversion;
737                         MEM_freeN(fg);
738                         return;
739                 } 
740                 else if (bhead->code==ENDB)
741                         break;
742         }
743 }
744 #endif
745
746 static void decode_blender_header(FileData *fd)
747 {
748         char header[SIZEOFBLENDERHEADER], num[4];
749         int readsize;
750
751         // read in the header data
752         readsize = fd->read(fd, header, sizeof(header));
753
754         if (readsize == sizeof(header)) {
755                 if(strncmp(header, "BLENDER", 7) == 0) {
756                         int remove_this_endian_test= 1;
757
758                         fd->flags |= FD_FLAGS_FILE_OK;
759
760                         // what size are pointers in the file ?
761                         if(header[7]=='_') {
762                                 fd->flags |= FD_FLAGS_FILE_POINTSIZE_IS_4;
763                                 if (sizeof(void *) != 4) {
764                                         fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
765                                 }
766                         } else {
767                                 if (sizeof(void *) != 8) {
768                                         fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
769                                 }
770                         }
771
772                         // is the file saved in a different endian
773                         // than we need ?
774                         if (((((char*)&remove_this_endian_test)[0]==1)?L_ENDIAN:B_ENDIAN) != ((header[8]=='v')?L_ENDIAN:B_ENDIAN)) {
775                                 fd->flags |= FD_FLAGS_SWITCH_ENDIAN;
776                         }
777
778                         // get the version number
779
780                         memcpy(num, header+9, 3);
781                         num[3] = 0;
782                         fd->fileversion = atoi(num);
783                 }
784         }
785 }
786
787 static int read_file_dna(FileData *fd)
788 {
789         BHead *bhead;
790
791         for (bhead= blo_firstbhead(fd); bhead; bhead= blo_nextbhead(fd, bhead)) {
792                 if (bhead->code==DNA1) {
793                         int do_endian_swap= (fd->flags&FD_FLAGS_SWITCH_ENDIAN)?1:0;
794
795                         fd->filesdna= dna_sdna_from_data(&bhead[1], bhead->len, do_endian_swap);
796                         if (fd->filesdna) {
797                                 
798                                 fd->compflags= dna_get_structDNA_compareflags(fd->filesdna, fd->memsdna);
799                                 /* used to retrieve ID names from (bhead+1) */
800                                 fd->id_name_offs= dna_elem_offset(fd->filesdna, "ID", "char", "name[]");
801                         }
802
803                         return 1;
804                 } else if (bhead->code==ENDB)
805                         break;
806         }
807
808         return 0;
809 }
810
811 static int fd_read_from_file(FileData *filedata, void *buffer, int size)
812 {
813         int readsize = read(filedata->filedes, buffer, size);
814
815         if (readsize < 0) {
816                 readsize = EOF;
817         } else {
818                 filedata->seek += readsize;
819         }
820
821         return (readsize);
822 }
823
824 static int fd_read_gzip_from_file(FileData *filedata, void *buffer, int size)
825 {
826         int readsize = gzread(filedata->gzfiledes, buffer, size);
827
828         if (readsize < 0) {
829                 readsize = EOF;
830         } else {
831                 filedata->seek += readsize;
832         }
833
834         return (readsize);
835 }
836
837 static int fd_read_from_memory(FileData *filedata, void *buffer, int size)
838 {
839                 // don't read more bytes then there are available in the buffer
840         int readsize = MIN2(size, filedata->buffersize - filedata->seek);
841
842         memcpy(buffer, filedata->buffer + filedata->seek, readsize);
843         filedata->seek += readsize;
844
845         return (readsize);
846 }
847
848 static int fd_read_from_memfile(FileData *filedata, void *buffer, int size)
849 {
850         static unsigned int seek= 1<<30;        /* the current position */
851         static unsigned int offset= 0;          /* size of previous chunks */
852         static MemFileChunk *chunk=NULL;
853         
854         if(size==0) return 0;
855         
856         if(seek != (unsigned int)filedata->seek) {
857                 chunk= filedata->memfile->chunks.first;
858                 seek= 0;
859                 
860                 while(chunk) {
861                         if(seek + chunk->size > (unsigned) filedata->seek) break;
862                         seek+= chunk->size;
863                         chunk= chunk->next;
864                 }
865                 offset= seek;
866                 seek= filedata->seek;
867         }
868         
869         if(chunk) {
870                 /* first check if it's on the end if current chunk */
871                 if( seek-offset == chunk->size) {
872                         offset+= chunk->size;
873                         chunk= chunk->next;
874                 }
875                 
876                 /* debug, should never happen */
877                 if(chunk==NULL) {
878                         printf("illegal read, chunk zero\n");
879                         return 0;
880                 }
881                 else if( (seek-offset)+size > chunk->size) {
882                         size= chunk->size - (seek-offset);
883                         printf("chunk too large, clipped to %d\n", size);
884                 }
885                 
886                 memcpy(buffer, chunk->buf + (seek-offset), size);
887                 filedata->seek += size;
888                 seek+= size;
889                 
890                 return (size);
891                 
892         }
893         return 0;
894 }
895
896 static FileData *filedata_new(void)
897 {
898         extern unsigned char DNAstr[];  /* DNA.c */
899         extern int DNAlen;
900         FileData *fd = MEM_callocN(sizeof(FileData), "FileData");
901
902         fd->filedes = -1;
903         fd->gzfiledes = NULL;
904
905                 /* XXX, this doesn't need to be done all the time,
906                  * but it keeps us reentrant,  remove once we have
907                  * a lib that provides a nice lock. - zr
908                  */
909         fd->memsdna = dna_sdna_from_data(DNAstr,  DNAlen,  0);
910
911         fd->datamap = oldnewmap_new();
912         fd->globmap = oldnewmap_new();
913         fd->libmap = oldnewmap_new();
914
915         return fd;
916 }
917
918 static FileData *blo_decode_and_check(FileData *fd, BlendReadError *error_r)
919 {
920         decode_blender_header(fd);
921
922         if (fd->flags & FD_FLAGS_FILE_OK) {
923                 if (!read_file_dna(fd)) {
924                         *error_r = BRE_INCOMPLETE;
925                         blo_freefiledata(fd);
926                         fd= NULL;
927                 }
928         } 
929         else {
930                 *error_r = BRE_NOT_A_BLEND;
931                 blo_freefiledata(fd);
932                 fd= NULL;
933         }
934
935         return fd;
936 }
937
938 /* cannot be called with relative paths anymore! */
939 /* on each new library added, it now checks for the current FileData and expands relativeness */
940 FileData *blo_openblenderfile(char *name, BlendReadError *error_r)
941 {
942         gzFile gzfile;
943         
944         gzfile= gzopen(name, "rb");
945
946         if (NULL == gzfile) {
947                 *error_r = BRE_UNABLE_TO_OPEN;
948                 return NULL;
949         } else {
950                 FileData *fd = filedata_new();
951                 fd->gzfiledes = gzfile;
952                 BLI_strncpy(fd->filename, name, sizeof(fd->filename));  // now only in use by library append
953                 fd->read = fd_read_gzip_from_file;
954
955                 return blo_decode_and_check(fd, error_r);
956         }
957 }
958
959 FileData *blo_openblendermemory(void *mem, int memsize, BlendReadError *error_r)
960 {
961         if (!mem || memsize<SIZEOFBLENDERHEADER) {
962                 *error_r = mem?BRE_UNABLE_TO_READ:BRE_UNABLE_TO_OPEN;
963                 return NULL;
964         } else {
965                 FileData *fd= filedata_new();
966                 fd->buffer= mem;
967                 fd->buffersize= memsize;
968                 fd->read= fd_read_from_memory;
969                 fd->flags|= FD_FLAGS_NOT_MY_BUFFER;
970
971                 return blo_decode_and_check(fd, error_r);
972         }
973 }
974
975 FileData *blo_openblendermemfile(MemFile *memfile, BlendReadError *error_r)
976 {
977         if (!memfile) {
978                 *error_r = BRE_UNABLE_TO_OPEN;
979                 return NULL;
980         } else {
981                 FileData *fd= filedata_new();
982                 fd->memfile= memfile;
983
984                 fd->read= fd_read_from_memfile;
985                 fd->flags|= FD_FLAGS_NOT_MY_BUFFER;
986
987                 return blo_decode_and_check(fd, error_r);
988         }
989 }
990
991
992 void blo_freefiledata(FileData *fd)
993 {
994         if (fd) {
995                 
996                 if (fd->filedes != -1) {
997                         close(fd->filedes);
998                 }
999
1000                 if (fd->gzfiledes != NULL)
1001                 {
1002                         gzclose(fd->gzfiledes);
1003                 }
1004
1005                 if (fd->buffer && !(fd->flags & FD_FLAGS_NOT_MY_BUFFER)) {
1006                         MEM_freeN(fd->buffer);
1007                         fd->buffer = 0;
1008                 }
1009
1010                 // Free all BHeadN data blocks
1011                 BLI_freelistN(&fd->listbase);
1012
1013                 if (fd->memsdna)
1014                         dna_freestructDNA(fd->memsdna);
1015                 if (fd->filesdna)
1016                         dna_freestructDNA(fd->filesdna);
1017                 if (fd->compflags)
1018                         MEM_freeN(fd->compflags);
1019
1020                 if (fd->datamap)
1021                         oldnewmap_free(fd->datamap);
1022                 if (fd->globmap)
1023                         oldnewmap_free(fd->globmap);
1024                 if (fd->imamap)
1025                         oldnewmap_free(fd->imamap);
1026                 if (fd->libmap && !(fd->flags & FD_FLAGS_NOT_MY_LIBMAP))
1027                         oldnewmap_free(fd->libmap);
1028
1029                 MEM_freeN(fd);
1030         }
1031 }
1032
1033 /* ************ DIV ****************** */
1034
1035 int BLO_has_bfile_extension(char *str)
1036 {
1037         return (BLI_testextensie(str, ".ble") || BLI_testextensie(str, ".blend")||BLI_testextensie(str, ".blend.gz"));
1038 }
1039
1040 /* ************** OLD POINTERS ******************* */
1041
1042 static void *newdataadr(FileData *fd, void *adr)                /* only direct databocks */
1043 {
1044         return oldnewmap_lookup_and_inc(fd->datamap, adr);
1045 }
1046
1047 static void *newglobadr(FileData *fd, void *adr)                /* direct datablocks with global linking */
1048 {
1049         return oldnewmap_lookup_and_inc(fd->globmap, adr);
1050 }
1051
1052 static void *newimaadr(FileData *fd, void *adr)         /* used to restore image data after undo */
1053 {
1054         if(fd->imamap && adr)
1055                 return oldnewmap_lookup_and_inc(fd->imamap, adr);
1056         return NULL;
1057 }
1058
1059
1060 static void *newlibadr(FileData *fd, void *lib, void *adr)              /* only lib data */
1061 {
1062         return oldnewmap_liblookup(fd->libmap, adr, lib);
1063 }
1064
1065 static void *newlibadr_us(FileData *fd, void *lib, void *adr)   /* increases user number */
1066 {
1067         ID *id= newlibadr(fd, lib, adr);
1068
1069         if(id)
1070                 id->us++;
1071
1072         return id;
1073 }
1074
1075 static void change_idid_adr_fd(FileData *fd, void *old, void *new)
1076 {
1077         int i;
1078         
1079         for (i=0; i<fd->libmap->nentries; i++) {
1080                 OldNew *entry= &fd->libmap->entries[i];
1081                 
1082                 if (old==entry->newp && entry->nr==ID_ID) {
1083                         entry->newp= new;
1084                         if(new) entry->nr= GS( ((ID *)new)->name );
1085                         break;
1086                 }
1087         }
1088 }
1089
1090 static void change_idid_adr(ListBase *mainlist, FileData *basefd, void *old, void *new)
1091 {
1092         Main *mainptr;
1093         
1094         for(mainptr= mainlist->first; mainptr; mainptr= mainptr->next) {
1095                 FileData *fd;
1096                 
1097                 if(mainptr->curlib) fd= mainptr->curlib->filedata;
1098                 else fd= basefd;
1099                 
1100                 if(fd) {
1101                         change_idid_adr_fd(fd, old, new);
1102                 }
1103         }
1104 }
1105
1106 /* assumed; G.main still exists */
1107 void blo_make_image_pointer_map(FileData *fd)
1108 {
1109         Image *ima= G.main->image.first;
1110         Scene *sce= G.main->scene.first;
1111         
1112         fd->imamap= oldnewmap_new();
1113         
1114         for(;ima; ima= ima->id.next) {
1115                 Link *ibuf= ima->ibufs.first;
1116                 for(; ibuf; ibuf= ibuf->next) 
1117                         oldnewmap_insert(fd->imamap, ibuf, ibuf, 0);
1118         }
1119         for(; sce; sce= sce->id.next) {
1120                 if(sce->nodetree) {
1121                         bNode *node;
1122                         for(node= sce->nodetree->nodes.first; node; node= node->next)
1123                                 oldnewmap_insert(fd->imamap, node->preview, node->preview, 0);
1124                 }
1125         }
1126 }
1127
1128 /* set G.main image ibufs to zero if it has been restored */
1129 /* this works because freeing G.main only happens after this call */
1130 void blo_end_image_pointer_map(FileData *fd)
1131 {
1132         OldNew *entry= fd->imamap->entries;
1133         Image *ima= G.main->image.first;
1134         Scene *sce= G.main->scene.first;
1135         int i;
1136         
1137         /* used entries were restored, so we put them to zero */
1138         for (i=0; i<fd->imamap->nentries; i++, entry++) {
1139                 if (entry->nr>0)
1140                         entry->newp= NULL;
1141         }
1142         
1143         for(;ima; ima= ima->id.next) {
1144                 Link *ibuf, *next;
1145                 
1146                 /* this mirrors direct_link_image */
1147                 for(ibuf= ima->ibufs.first; ibuf; ibuf= next) {
1148                         next= ibuf->next;
1149                         if(NULL==newimaadr(fd, ibuf)) { /* so was restored */
1150                                 BLI_remlink(&ima->ibufs, ibuf);
1151                                 ima->bindcode= 0;
1152                         }
1153                 }
1154         }
1155         for(; sce; sce= sce->id.next) {
1156                 if(sce->nodetree) {
1157                         bNode *node;
1158                         for(node= sce->nodetree->nodes.first; node; node= node->next)
1159                                 node->preview= newimaadr(fd, node->preview);
1160                 }
1161         }
1162 }
1163
1164 /* undo file support: add all library pointers in lookup */
1165 void blo_add_library_pointer_map(ListBase *mainlist, FileData *fd)
1166 {
1167         Main *ptr= mainlist->first;
1168         ListBase *lbarray[MAX_LIBARRAY];
1169         
1170         for(ptr= ptr->next; ptr; ptr= ptr->next) {
1171                 int i= set_listbasepointers(ptr, lbarray);
1172                 while(i--) {
1173                         ID *id;
1174                         for(id= lbarray[i]->first; id; id= id->next)
1175                                 oldnewmap_insert(fd->libmap, id, id, GS(id->name));
1176                 }
1177         }
1178 }
1179                 
1180
1181 /* ********** END OLD POINTERS ****************** */
1182 /* ********** READ FILE ****************** */
1183
1184 static void switch_endian_structs(struct SDNA *filesdna, BHead *bhead)
1185 {
1186         int blocksize, nblocks;
1187         char *data;
1188
1189         data= (char *)(bhead+1);
1190         blocksize= filesdna->typelens[ filesdna->structs[bhead->SDNAnr][0] ];
1191
1192         nblocks= bhead->nr;
1193         while(nblocks--) {
1194                 dna_switch_endian_struct(filesdna, bhead->SDNAnr, data);
1195
1196                 data+= blocksize;
1197         }
1198 }
1199
1200 static void *read_struct(FileData *fd, BHead *bh, char *blockname)
1201 {
1202         void *temp= NULL;
1203
1204         if (bh->len) {
1205                 /* switch is based on file dna */
1206                 if (bh->SDNAnr && (fd->flags & FD_FLAGS_SWITCH_ENDIAN))
1207                         switch_endian_structs(fd->filesdna, bh);
1208
1209                 if (fd->compflags[bh->SDNAnr]) {        /* flag==0: doesn't exist anymore */
1210                         if(fd->compflags[bh->SDNAnr]==2) {
1211                                 temp= dna_reconstruct(fd->memsdna, fd->filesdna, fd->compflags, bh->SDNAnr, bh->nr, (bh+1));
1212                         } else {
1213                                 temp= MEM_mallocN(bh->len, blockname);
1214                                 memcpy(temp, (bh+1), bh->len);
1215                         }
1216                 }
1217         }
1218
1219         return temp;
1220 }
1221
1222 static void link_list(FileData *fd, ListBase *lb)               /* only direct data */
1223 {
1224         Link *ln, *prev;
1225
1226         if(lb->first==NULL) return;
1227
1228         lb->first= newdataadr(fd, lb->first);
1229         ln= lb->first;
1230         prev= NULL;
1231         while(ln) {
1232                 ln->next= newdataadr(fd, ln->next);
1233                 ln->prev= prev;
1234                 prev= ln;
1235                 ln= ln->next;
1236         }
1237         lb->last= prev;
1238 }
1239
1240 static void link_glob_list(FileData *fd, ListBase *lb)          /* for glob data */
1241 {
1242         Link *ln, *prev;
1243         void *poin;
1244
1245         if(lb->first==0) return;
1246         poin= newdataadr(fd, lb->first);
1247         if(lb->first) {
1248                 oldnewmap_insert(fd->globmap, lb->first, poin, 0);
1249         }
1250         lb->first= poin;
1251
1252         ln= lb->first;
1253         prev= 0;
1254         while(ln) {
1255                 poin= newdataadr(fd, ln->next);
1256                 if(ln->next) {
1257                         oldnewmap_insert(fd->globmap, ln->next, poin, 0);
1258                 }
1259                 ln->next= poin;
1260                 ln->prev= prev;
1261                 prev= ln;
1262                 ln= ln->next;
1263         }
1264         lb->last= prev;
1265 }
1266
1267 static void test_pointer_array(FileData *fd, void **mat)
1268 {
1269 #if defined(WIN32) && !defined(FREE_WINDOWS)
1270         __int64 *lpoin, *lmat;
1271 #else
1272         long long *lpoin, *lmat;
1273 #endif
1274         int len, *ipoin, *imat;
1275
1276                 /* manually convert the pointer array in
1277                  * the old dna format to a pointer array in
1278                  * the new dna format.
1279                  */
1280         if(*mat) {
1281                 len= MEM_allocN_len(*mat)/fd->filesdna->pointerlen;
1282
1283                 if(fd->filesdna->pointerlen==8 && fd->memsdna->pointerlen==4) {
1284                         ipoin=imat= MEM_mallocN( len*4, "newmatar");
1285                         lpoin= *mat;
1286
1287                         while(len-- > 0) {
1288                                 if((fd->flags & FD_FLAGS_SWITCH_ENDIAN))
1289                                         SWITCH_LONGINT(*lpoin);
1290                                 *ipoin= (int) ((*lpoin) >> 3);
1291                                 ipoin++;
1292                                 lpoin++;
1293                         }
1294                         MEM_freeN(*mat);
1295                         *mat= imat;
1296                 }
1297
1298                 if(fd->filesdna->pointerlen==4 && fd->memsdna->pointerlen==8) {
1299                         lpoin=lmat= MEM_mallocN( len*8, "newmatar");
1300                         ipoin= *mat;
1301
1302                         while(len-- > 0) {
1303                                 *lpoin= *ipoin;
1304                                 ipoin++;
1305                                 lpoin++;
1306                         }
1307                         MEM_freeN(*mat);
1308                         *mat= lmat;
1309                 }
1310         }
1311 }
1312
1313 /* ************ READ ID Properties *************** */
1314
1315 void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, void *fd);
1316 void IDP_LibLinkProperty(IDProperty *prop, int switch_endian, void *fd);
1317
1318 void IDP_DirectLinkArray(IDProperty *prop, int switch_endian, void *fd)
1319 {
1320         int i;
1321
1322         /*since we didn't save the extra buffer, set totallen to len.*/
1323         prop->totallen = prop->len;
1324         prop->data.pointer = newdataadr(fd, prop->data.pointer);
1325
1326         if (switch_endian) {
1327                 for (i=0; i<prop->len; i++) {
1328                         SWITCH_INT(((int*)prop->data.pointer)[i]);
1329                 }
1330         }
1331 }
1332
1333 void IDP_DirectLinkString(IDProperty *prop, int switch_endian, void *fd)
1334 {
1335         /*since we didn't save the extra string buffer, set totallen to len.*/
1336         prop->totallen = prop->len;
1337         prop->data.pointer = newdataadr(fd, prop->data.pointer);
1338 }
1339
1340 void IDP_DirectLinkGroup(IDProperty *prop, int switch_endian, void *fd)
1341 {
1342         ListBase *lb = &prop->data.group;
1343         IDProperty *loop;
1344
1345         link_list(fd, lb);
1346
1347         /*Link child id properties now*/
1348         for (loop=prop->data.group.first; loop; loop=loop->next) {
1349                 IDP_DirectLinkProperty(loop, switch_endian, fd);
1350         }
1351 }
1352
1353 void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, void *fd)
1354 {
1355         switch (prop->type) {
1356                 case IDP_GROUP:
1357                         IDP_DirectLinkGroup(prop, switch_endian, fd);
1358                         break;
1359                 case IDP_STRING:
1360                         IDP_DirectLinkString(prop, switch_endian, fd);
1361                         break;
1362                 case IDP_ARRAY:
1363                         IDP_DirectLinkArray(prop, switch_endian, fd);
1364                         break;
1365         }
1366 }
1367
1368 /*stub function*/
1369 void IDP_LibLinkProperty(IDProperty *prop, int switch_endian, void *fd)
1370 {
1371 }
1372
1373 /* ************ READ Brush *************** */
1374 /* library brush linking after fileread */
1375 static void lib_link_brush(FileData *fd, Main *main)
1376 {
1377         Brush *brush;
1378         MTex *mtex;
1379         int a;
1380         
1381         /* only link ID pointers */
1382         for(brush= main->brush.first; brush; brush= brush->id.next) {
1383                 if(brush->id.flag & LIB_NEEDLINK) {
1384                         brush->id.flag -= LIB_NEEDLINK;
1385
1386                         for(a=0; a<MAX_MTEX; a++) {
1387                                 mtex= brush->mtex[a];
1388                                 if(mtex)
1389                                         mtex->tex= newlibadr_us(fd, brush->id.lib, mtex->tex);
1390                         }
1391                 }
1392         }
1393 }
1394
1395 static void direct_link_brush(FileData *fd, Brush *brush)
1396 {
1397         /* brush itself has been read */
1398         int a;
1399
1400         for(a=0; a<MAX_MTEX; a++)
1401                 brush->mtex[a]= newdataadr(fd, brush->mtex[a]);
1402 }
1403
1404 /* ************ READ CurveMapping *************** */
1405
1406 /* cuma itself has been read! */
1407 static void direct_link_curvemapping(FileData *fd, CurveMapping *cumap)
1408 {
1409         int a;
1410         
1411         /* flag seems to be able to hang? Maybe old files... not bad to clear anyway */
1412         cumap->flag &= ~CUMA_PREMULLED;
1413         
1414         for(a=0; a<CM_TOT; a++) {
1415                 cumap->cm[a].curve= newdataadr(fd, cumap->cm[a].curve);
1416                 cumap->cm[a].table= NULL;
1417         }
1418 }
1419
1420 /* ************ READ NODE TREE *************** */
1421
1422 /* singe node tree (also used for material/scene trees), ntree is not NULL */
1423 static void lib_link_ntree(FileData *fd, ID *id, bNodeTree *ntree)
1424 {
1425         bNode *node;
1426         
1427         for(node= ntree->nodes.first; node; node= node->next)
1428                 node->id= newlibadr_us(fd, id->lib, node->id);
1429 }
1430
1431 /* library ntree linking after fileread */
1432 static void lib_link_nodetree(FileData *fd, Main *main)
1433 {
1434         bNodeTree *ntree;
1435         
1436         /* only link ID pointers */
1437         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
1438                 if(ntree->id.flag & LIB_NEEDLINK) {
1439                         ntree->id.flag -= LIB_NEEDLINK;
1440                         lib_link_ntree(fd, &ntree->id, ntree);
1441                 }
1442         }
1443 }
1444
1445 /* verify types for nodes and groups, all data has to be read */
1446 static void lib_verify_nodetree(Main *main)
1447 {
1448         Scene *sce;
1449         Material *ma;
1450         bNodeTree *ntree;
1451         
1452         /* now create the own typeinfo structs an verify nodes */
1453         /* here we still assume no groups in groups */
1454         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
1455                 ntreeVerifyTypes(ntree);        /* internal nodes, no groups! */
1456                 ntreeMakeOwnType(ntree);        /* for group usage */
1457         }
1458         
1459         /* now verify all types in material trees, groups are set OK now */
1460         for(ma= main->mat.first; ma; ma= ma->id.next) {
1461                 if(ma->nodetree)
1462                         ntreeVerifyTypes(ma->nodetree);
1463         }
1464         /* and scene trees */
1465         for(sce= main->scene.first; sce; sce= sce->id.next) {
1466                 if(sce->nodetree)
1467                         ntreeVerifyTypes(sce->nodetree);
1468         }
1469 }
1470
1471
1472
1473 /* ntree itself has been read! */
1474 static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
1475 {
1476         /* note: writing and reading goes in sync, for speed */
1477         bNode *node;
1478         bNodeSocket *sock;
1479         bNodeLink *link;
1480         
1481         ntree->init= 0;         /* to set callbacks and force setting types */
1482         ntree->owntype= NULL;
1483         ntree->timecursor= NULL;
1484         
1485         link_list(fd, &ntree->nodes);
1486         for(node= ntree->nodes.first; node; node= node->next) {
1487                 node->storage= newdataadr(fd, node->storage);
1488                 if(node->storage) {
1489                         
1490                         /* could be handlerized at some point */
1491                         if(ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
1492                                 direct_link_curvemapping(fd, node->storage);
1493                         else if(ntree->type==NTREE_COMPOSIT) {
1494                                 if( ELEM3(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB))
1495                                         direct_link_curvemapping(fd, node->storage);
1496                                 else if(ELEM3(node->type, CMP_NODE_IMAGE, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
1497                                         ((ImageUser *)node->storage)->ok= 1;
1498                         }
1499                 }
1500                 link_list(fd, &node->inputs);
1501                 link_list(fd, &node->outputs);
1502         }
1503         link_list(fd, &ntree->links);
1504         
1505         /* and we connect the rest */
1506         for(node= ntree->nodes.first; node; node= node->next) {
1507                 node->preview= newimaadr(fd, node->preview);
1508                 node->lasty= 0;
1509                 for(sock= node->inputs.first; sock; sock= sock->next)
1510                         sock->link= newdataadr(fd, sock->link);
1511                 for(sock= node->outputs.first; sock; sock= sock->next)
1512                         sock->ns.data= NULL;
1513         }
1514         for(link= ntree->links.first; link; link= link->next) {
1515                 link->fromnode= newdataadr(fd, link->fromnode);
1516                 link->tonode= newdataadr(fd, link->tonode);
1517                 link->fromsock= newdataadr(fd, link->fromsock);
1518                 link->tosock= newdataadr(fd, link->tosock);
1519         }
1520         
1521         /* type verification is in lib-link */
1522 }
1523
1524 /* ************ READ PACKEDFILE *************** */
1525
1526 static PackedFile *direct_link_packedfile(FileData *fd, PackedFile *oldpf)
1527 {
1528         PackedFile *pf= newdataadr(fd, oldpf);
1529
1530         if (pf) {
1531                 pf->data= newdataadr(fd, pf->data);
1532         }
1533
1534         return pf;
1535 }
1536
1537 /* ************ READ IMAGE PREVIEW *************** */
1538
1539 static PreviewImage *direct_link_preview_image(FileData *fd, PreviewImage *old_prv)
1540 {
1541         PreviewImage *prv= newdataadr(fd, old_prv);
1542
1543         if (prv) {
1544                 prv->rect = newdataadr(fd, prv->rect);
1545         }
1546
1547         return prv;
1548 }
1549
1550 /* ************ READ SCRIPTLINK *************** */
1551
1552 static void lib_link_scriptlink(FileData *fd, ID *id, ScriptLink *slink)
1553 {
1554         int i;
1555
1556         for(i=0; i<slink->totscript; i++) {
1557                 slink->scripts[i]= newlibadr(fd, id->lib, slink->scripts[i]);
1558         }
1559 }
1560
1561 static void direct_link_scriptlink(FileData *fd, ScriptLink *slink)
1562 {
1563         slink->scripts= newdataadr(fd, slink->scripts);
1564         test_pointer_array(fd, (void **)&slink->scripts);
1565         
1566         slink->flag= newdataadr(fd, slink->flag);
1567
1568         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
1569                 int a;
1570
1571                 for(a=0; a<slink->totscript; a++) {
1572                         SWITCH_SHORT(slink->flag[a]);
1573                 }
1574         }
1575 }
1576
1577 /* ************ READ ARMATURE ***************** */
1578
1579 static void lib_link_nlastrips(FileData *fd, ID *id, ListBase *striplist)
1580 {
1581         bActionStrip *strip;
1582         bActionModifier *amod;
1583         
1584         for (strip=striplist->first; strip; strip=strip->next){
1585                 strip->object = newlibadr(fd, id->lib, strip->object);
1586                 strip->act = newlibadr_us(fd, id->lib, strip->act);
1587                 strip->ipo = newlibadr(fd, id->lib, strip->ipo);
1588                 for(amod= strip->modifiers.first; amod; amod= amod->next)
1589                         amod->ob= newlibadr(fd, id->lib, amod->ob);
1590         }
1591 }
1592
1593 static void lib_link_constraint_channels(FileData *fd, ID *id, ListBase *chanbase)
1594 {
1595         bConstraintChannel *chan;
1596
1597         for (chan=chanbase->first; chan; chan=chan->next){
1598                 chan->ipo = newlibadr_us(fd, id->lib, chan->ipo);
1599         }
1600 }
1601
1602 static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
1603 {
1604         bConstraint *con;
1605
1606         for (con = conlist->first; con; con=con->next) {
1607                 /* patch for error introduced by changing constraints (dunno how) */
1608                 /* if con->data type changes, dna cannot resolve the pointer! (ton) */
1609                 if(con->data==NULL) {
1610                         con->type= CONSTRAINT_TYPE_NULL;
1611                 }
1612
1613                 switch (con->type) {
1614                 case CONSTRAINT_TYPE_ACTION:
1615                         {
1616                                 bActionConstraint *data;
1617                                 data= ((bActionConstraint*)con->data);
1618                                 data->tar = newlibadr(fd, id->lib, data->tar);
1619                                 data->act = newlibadr(fd, id->lib, data->act);
1620                         }
1621                         break;
1622                 case CONSTRAINT_TYPE_LOCLIKE:
1623                         {
1624                                 bLocateLikeConstraint *data;
1625                                 data= ((bLocateLikeConstraint*)con->data);
1626                                 data->tar = newlibadr(fd, id->lib, data->tar);
1627                         };
1628                         break;
1629                 case CONSTRAINT_TYPE_ROTLIKE:
1630                         {
1631                                 bRotateLikeConstraint *data;
1632                                 data= ((bRotateLikeConstraint*)con->data);
1633                                 data->tar = newlibadr(fd, id->lib, data->tar);
1634                         };
1635                         break;
1636                 case CONSTRAINT_TYPE_SIZELIKE:
1637                         {
1638                                 bSizeLikeConstraint *data;
1639                                 data= ((bSizeLikeConstraint*)con->data);
1640                                 data->tar = newlibadr(fd, id->lib, data->tar);
1641                         };
1642                         break;
1643                 case CONSTRAINT_TYPE_KINEMATIC:
1644                         {
1645                                 bKinematicConstraint *data;
1646                                 data = ((bKinematicConstraint*)con->data);
1647                                 data->tar = newlibadr(fd, id->lib, data->tar);
1648                         }
1649                         break;
1650                 case CONSTRAINT_TYPE_TRACKTO:
1651                         {
1652                                 bTrackToConstraint *data;
1653                                 data = ((bTrackToConstraint*)con->data);
1654                                 data->tar = newlibadr(fd, id->lib, data->tar);
1655                         }
1656                         break;
1657                 case CONSTRAINT_TYPE_MINMAX:
1658                         {
1659                                 bMinMaxConstraint *data;
1660                                 data = ((bMinMaxConstraint*)con->data);
1661                                 data->tar = newlibadr(fd, id->lib, data->tar);
1662                         }
1663                         break;
1664                 case CONSTRAINT_TYPE_LOCKTRACK:
1665                         {
1666                                 bLockTrackConstraint *data;
1667                                 data= ((bLockTrackConstraint*)con->data);
1668                                 data->tar = newlibadr(fd, id->lib, data->tar);
1669                         };
1670                         break;
1671                 case CONSTRAINT_TYPE_FOLLOWPATH:
1672                         {
1673                                 bFollowPathConstraint *data;
1674                                 data= ((bFollowPathConstraint*)con->data);
1675                                 data->tar = newlibadr(fd, id->lib, data->tar);
1676                         };
1677                         break;
1678                 case CONSTRAINT_TYPE_DISTANCELIMIT:
1679                         {
1680                                 bDistanceLimitConstraint *data;
1681                                 data= ((bDistanceLimitConstraint*)con->data);
1682                                 data->tar = newlibadr(fd, id->lib, data->tar);
1683                         };
1684                         break;
1685                 case CONSTRAINT_TYPE_STRETCHTO:
1686                         {
1687                                 bStretchToConstraint *data;
1688                                 data= ((bStretchToConstraint*)con->data);
1689                                 data->tar = newlibadr(fd, id->lib, data->tar);
1690                         };
1691                         break;
1692                 case CONSTRAINT_TYPE_RIGIDBODYJOINT:
1693                         {
1694                                 bRigidBodyJointConstraint *data;
1695                                 data= ((bRigidBodyJointConstraint*)con->data);
1696                                 data->tar = newlibadr(fd, id->lib, data->tar);
1697                         };
1698                         break;
1699                 case CONSTRAINT_TYPE_CLAMPTO:
1700                         {
1701                                 bClampToConstraint *data;
1702                                 data= ((bClampToConstraint*)con->data);
1703                                 data->tar = newlibadr(fd, id->lib, data->tar);
1704                         };
1705                         break;
1706
1707                 case CONSTRAINT_TYPE_NULL:
1708                         break;
1709                 }
1710         }
1711 }
1712
1713 static void direct_link_constraints(FileData *fd, ListBase *lb)
1714 {
1715         bConstraint *cons;
1716
1717         link_list(fd, lb);
1718         for (cons=lb->first; cons; cons=cons->next) {
1719                 cons->data = newdataadr(fd, cons->data);
1720         }
1721 }
1722
1723 static void lib_link_pose(FileData *fd, Object *ob, bPose *pose)
1724 {
1725         bPoseChannel *pchan;
1726         bArmature *arm= ob->data;
1727         int rebuild;
1728         
1729         if (!pose || !arm)
1730                 return;
1731         
1732         /* always rebuild to match proxy or lib changes */
1733         rebuild= ob->proxy || (ob->id.lib==NULL && arm->id.lib);
1734
1735         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
1736                 lib_link_constraints(fd, (ID *)ob, &pchan->constraints);
1737                 
1738                 /* hurms... loop in a loop, but yah... later... (ton) */
1739                 pchan->bone= get_named_bone(arm, pchan->name);
1740                 
1741                 pchan->custom= newlibadr(fd, arm->id.lib, pchan->custom);
1742                 if(pchan->bone==NULL)
1743                         rebuild= 1;
1744                 else if(ob->id.lib==NULL && arm->id.lib) {
1745                         /* local pose selection copied to armature, bit hackish */
1746                         pchan->bone->flag &= ~(BONE_SELECTED|BONE_ACTIVE);
1747                         pchan->bone->flag |= pchan->selectflag;
1748                 }
1749         }
1750         
1751         if(rebuild) {
1752                 ob->recalc= OB_RECALC;
1753                 pose->flag |= POSE_RECALC;
1754         }
1755 }
1756
1757 static void lib_link_armature(FileData *fd, Main *main)
1758 {
1759         bArmature *arm;
1760
1761         arm= main->armature.first;
1762
1763         while(arm) {
1764                 if(arm->id.flag & LIB_NEEDLINK) {
1765                         arm->id.flag -= LIB_NEEDLINK;
1766                 }
1767                 arm= arm->id.next;
1768         }
1769 }
1770
1771 static void lib_link_action(FileData *fd, Main *main)
1772 {
1773         bAction *act;
1774         bActionChannel *chan;
1775
1776         act= main->action.first;
1777         while(act) {
1778                 if(act->id.flag & LIB_NEEDLINK) {
1779                         act->id.flag -= LIB_NEEDLINK;
1780
1781                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1782                                 chan->ipo= newlibadr_us(fd, act->id.lib, chan->ipo);
1783                                 lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
1784                         }
1785
1786                 }
1787                 act= act->id.next;
1788         }
1789 }
1790
1791 static void direct_link_bones(FileData *fd, Bone* bone)
1792 {
1793         Bone    *child;
1794
1795         bone->parent= newdataadr(fd, bone->parent);
1796
1797         link_list(fd, &bone->childbase);
1798
1799         for (child=bone->childbase.first; child; child=child->next) {
1800                 direct_link_bones(fd, child);
1801         }
1802 }
1803
1804
1805 static void direct_link_action(FileData *fd, bAction *act)
1806 {
1807         bActionChannel *achan;
1808
1809         link_list(fd, &act->chanbase);
1810
1811         for (achan = act->chanbase.first; achan; achan=achan->next)
1812                 link_list(fd, &achan->constraintChannels);
1813
1814 }
1815
1816 static void direct_link_armature(FileData *fd, bArmature *arm)
1817 {
1818         Bone    *bone;
1819
1820         link_list(fd, &arm->bonebase);
1821
1822         bone=arm->bonebase.first;
1823         while (bone) {
1824                 direct_link_bones(fd, bone);
1825                 bone=bone->next;
1826         }
1827 }
1828
1829 /* ************ READ CAMERA ***************** */
1830
1831 static void lib_link_camera(FileData *fd, Main *main)
1832 {
1833         Camera *ca;
1834
1835         ca= main->camera.first;
1836         while(ca) {
1837                 if(ca->id.flag & LIB_NEEDLINK) {
1838
1839                         ca->ipo= newlibadr_us(fd, ca->id.lib, ca->ipo);
1840
1841                         lib_link_scriptlink(fd, &ca->id, &ca->scriptlink);
1842
1843                         ca->id.flag -= LIB_NEEDLINK;
1844                 }
1845                 ca= ca->id.next;
1846         }
1847 }
1848
1849 static void direct_link_camera(FileData *fd, Camera *ca)
1850 {
1851         direct_link_scriptlink(fd, &ca->scriptlink);
1852 }
1853
1854
1855 /* ************ READ LAMP ***************** */
1856
1857 static void lib_link_lamp(FileData *fd, Main *main)
1858 {
1859         Lamp *la;
1860         MTex *mtex;
1861         int a;
1862
1863         la= main->lamp.first;
1864         while(la) {
1865                 if(la->id.flag & LIB_NEEDLINK) {
1866
1867                         for(a=0; a<MAX_MTEX; a++) {
1868                                 mtex= la->mtex[a];
1869                                 if(mtex) {
1870                                         mtex->tex= newlibadr_us(fd, la->id.lib, mtex->tex);
1871                                         mtex->object= newlibadr(fd, la->id.lib, mtex->object);
1872                                 }
1873                         }
1874
1875                         la->ipo= newlibadr_us(fd, la->id.lib, la->ipo);
1876
1877                         lib_link_scriptlink(fd, &la->id, &la->scriptlink);
1878
1879                         la->id.flag -= LIB_NEEDLINK;
1880                 }
1881                 la= la->id.next;
1882         }
1883 }
1884
1885 static void direct_link_lamp(FileData *fd, Lamp *la)
1886 {
1887         int a;
1888
1889         direct_link_scriptlink(fd, &la->scriptlink);
1890
1891         for(a=0; a<MAX_MTEX; a++) {
1892                 la->mtex[a]= newdataadr(fd, la->mtex[a]);
1893         }
1894 }
1895
1896 /* ************ READ keys ***************** */
1897
1898 static void lib_link_key(FileData *fd, Main *main)
1899 {
1900         Key *key;
1901
1902         key= main->key.first;
1903         while(key) {
1904                 if(key->id.flag & LIB_NEEDLINK) {
1905
1906                         key->ipo= newlibadr_us(fd, key->id.lib, key->ipo);
1907                         key->from= newlibadr(fd, key->id.lib, key->from);
1908
1909                         key->id.flag -= LIB_NEEDLINK;
1910                 }
1911                 key= key->id.next;
1912         }
1913 }
1914
1915 static void switch_endian_keyblock(Key *key, KeyBlock *kb)
1916 {
1917         int elemsize, a, b;
1918         char *data, *poin, *cp;
1919
1920         elemsize= key->elemsize;
1921         data= kb->data;
1922
1923         for(a=0; a<kb->totelem; a++) {
1924
1925                 cp= key->elemstr;
1926                 poin= data;
1927
1928                 while( cp[0] ) {        /* cp[0]==amount */
1929
1930                         switch(cp[1]) {         /* cp[1]= type */
1931                         case IPO_FLOAT:
1932                         case IPO_BPOINT:
1933                         case IPO_BEZTRIPLE:
1934                                 b= cp[0];
1935                                 while(b--) {
1936                                         SWITCH_INT((*poin));
1937                                         poin+= 4;
1938                                 }
1939                                 break;
1940                         }
1941
1942                         cp+= 2;
1943
1944                 }
1945                 data+= elemsize;
1946         }
1947 }
1948
1949 static void direct_link_key(FileData *fd, Key *key)
1950 {
1951         KeyBlock *kb;
1952
1953         link_list(fd, &(key->block));
1954
1955         key->refkey= newdataadr(fd, key->refkey);
1956
1957         kb= key->block.first;
1958         while(kb) {
1959
1960                 kb->data= newdataadr(fd, kb->data);
1961
1962                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN)
1963                         switch_endian_keyblock(key, kb);
1964
1965                 kb= kb->next;
1966         }
1967 }
1968
1969 /* ************ READ mball ***************** */
1970
1971 static void lib_link_mball(FileData *fd, Main *main)
1972 {
1973         MetaBall *mb;
1974         int a;
1975
1976         mb= main->mball.first;
1977         while(mb) {
1978                 if(mb->id.flag & LIB_NEEDLINK) {
1979
1980                         for(a=0; a<mb->totcol; a++) mb->mat[a]= newlibadr_us(fd, mb->id.lib, mb->mat[a]);
1981
1982                         mb->ipo= newlibadr_us(fd, mb->id.lib, mb->ipo);
1983
1984                         mb->id.flag -= LIB_NEEDLINK;
1985                 }
1986                 mb= mb->id.next;
1987         }
1988 }
1989
1990 static void direct_link_mball(FileData *fd, MetaBall *mb)
1991 {
1992         mb->mat= newdataadr(fd, mb->mat);
1993         test_pointer_array(fd, (void **)&mb->mat);
1994
1995         link_list(fd, &(mb->elems));
1996
1997         mb->disp.first= mb->disp.last= 0;
1998
1999         mb->bb= 0;
2000 }
2001
2002 /* ************ READ WORLD ***************** */
2003
2004 static void lib_link_world(FileData *fd, Main *main)
2005 {
2006         World *wrld;
2007         MTex *mtex;
2008         int a;
2009
2010         wrld= main->world.first;
2011         while(wrld) {
2012                 if(wrld->id.flag & LIB_NEEDLINK) {
2013
2014                         wrld->ipo= newlibadr_us(fd, wrld->id.lib, wrld->ipo);
2015
2016                         for(a=0; a<MAX_MTEX; a++) {
2017                                 mtex= wrld->mtex[a];
2018                                 if(mtex) {
2019                                         mtex->tex= newlibadr_us(fd, wrld->id.lib, mtex->tex);
2020                                         mtex->object= newlibadr(fd, wrld->id.lib, mtex->object);
2021                                 }
2022                         }
2023
2024                         lib_link_scriptlink(fd, &wrld->id, &wrld->scriptlink);
2025
2026                         wrld->id.flag -= LIB_NEEDLINK;
2027                 }
2028                 wrld= wrld->id.next;
2029         }
2030 }
2031
2032 static void direct_link_world(FileData *fd, World *wrld)
2033 {
2034         int a;
2035
2036         direct_link_scriptlink(fd, &wrld->scriptlink);
2037
2038         for(a=0; a<MAX_MTEX; a++) {
2039                 wrld->mtex[a]= newdataadr(fd, wrld->mtex[a]);
2040         }
2041 }
2042
2043
2044 /* ************ READ IPO ***************** */
2045
2046 static void lib_link_ipo(FileData *fd, Main *main)
2047 {
2048         Ipo *ipo;
2049
2050         ipo= main->ipo.first;
2051         while(ipo) {
2052                 if(ipo->id.flag & LIB_NEEDLINK) {
2053                         IpoCurve *icu;
2054                         for(icu= ipo->curve.first; icu; icu= icu->next) {
2055                                 if(icu->driver)
2056                                         icu->driver->ob= newlibadr(fd, ipo->id.lib, icu->driver->ob);
2057                         }
2058                         ipo->id.flag -= LIB_NEEDLINK;
2059                 }
2060                 ipo= ipo->id.next;
2061         }
2062 }
2063
2064 static void direct_link_ipo(FileData *fd, Ipo *ipo)
2065 {
2066         IpoCurve *icu;
2067
2068         link_list(fd, &(ipo->curve));
2069         icu= ipo->curve.first;
2070         while(icu) {
2071                 icu->bezt= newdataadr(fd, icu->bezt);
2072                 icu->bp= newdataadr(fd, icu->bp);
2073                 icu->driver= newdataadr(fd, icu->driver);
2074                 icu= icu->next;
2075         }
2076 }
2077
2078 /* ************ READ VFONT ***************** */
2079
2080 static void lib_link_vfont(FileData *fd, Main *main)
2081 {
2082         VFont *vf;
2083
2084         vf= main->vfont.first;
2085         while(vf) {
2086                 if(vf->id.flag & LIB_NEEDLINK) {
2087                         vf->id.flag -= LIB_NEEDLINK;
2088                 }
2089                 vf= vf->id.next;
2090         }
2091 }
2092
2093 static void direct_link_vfont(FileData *fd, VFont *vf)
2094 {
2095         vf->data= NULL;
2096         vf->packedfile= direct_link_packedfile(fd, vf->packedfile);
2097 }
2098
2099 /* ************ READ TEXT ****************** */
2100
2101 static void lib_link_text(FileData *fd, Main *main)
2102 {
2103         Text *text;
2104
2105         text= main->text.first;
2106         while(text) {
2107                 if(text->id.flag & LIB_NEEDLINK) {
2108                         text->id.flag -= LIB_NEEDLINK;
2109                 }
2110                 text= text->id.next;
2111         }
2112 }
2113
2114 static void direct_link_text(FileData *fd, Text *text)
2115 {
2116         TextLine *ln;
2117
2118         text->name= newdataadr(fd, text->name);
2119
2120         text->undo_pos= -1;
2121         text->undo_len= TXT_INIT_UNDO;
2122         text->undo_buf= MEM_mallocN(text->undo_len, "undo buf");
2123
2124         text->compiled= NULL;
2125
2126 /*
2127         if(text->flags & TXT_ISEXT) {
2128                 reopen_text(text);
2129         } else {
2130 */
2131
2132         link_list(fd, &text->lines);
2133
2134         text->curl= newdataadr(fd, text->curl);
2135         text->sell= newdataadr(fd, text->sell);
2136
2137         ln= text->lines.first;
2138         while(ln) {
2139                 ln->line= newdataadr(fd, ln->line);
2140                 ln->format= NULL;
2141                 
2142                 if (ln->len != (int) strlen(ln->line)) {
2143                         printf("Error loading text, line lengths differ\n");
2144                         ln->len = strlen(ln->line);
2145                 }
2146
2147                 ln= ln->next;
2148         }
2149
2150         text->flags = (text->flags|TXT_ISTMP) & ~TXT_ISEXT;
2151
2152         text->id.us= 1;
2153 }
2154
2155 /* ************ READ IMAGE ***************** */
2156
2157 static void lib_link_image(FileData *fd, Main *main)
2158 {
2159         Image *ima;
2160
2161         ima= main->image.first;
2162         while (ima) {
2163                 if(ima->id.flag & LIB_NEEDLINK) {
2164                         if (ima->id.properties) IDP_LibLinkProperty(ima->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2165
2166                         ima->id.flag -= LIB_NEEDLINK;
2167                 }
2168                 ima= ima->id.next;
2169         }
2170 }
2171
2172 static void link_ibuf_list(FileData *fd, ListBase *lb)
2173 {
2174         Link *ln, *prev;
2175         
2176         if(lb->first==NULL) return;
2177         
2178         lb->first= newimaadr(fd, lb->first);
2179         ln= lb->first;
2180         prev= NULL;
2181         while(ln) {
2182                 ln->next= newimaadr(fd, ln->next);
2183                 ln->prev= prev;
2184                 prev= ln;
2185                 ln= ln->next;
2186         }
2187         lb->last= prev;
2188 }
2189
2190 static void direct_link_image(FileData *fd, Image *ima)
2191 {
2192         /* for undo system, pointers could be restored */
2193         if(fd->imamap)
2194                 link_ibuf_list(fd, &ima->ibufs);
2195         else
2196                 ima->ibufs.first= ima->ibufs.last= NULL;
2197         
2198         /* if not restored, we keep the binded opengl index */
2199         if(ima->ibufs.first==NULL)
2200                 ima->bindcode= 0;
2201         
2202         ima->anim= NULL;
2203         ima->rr= NULL;
2204         ima->repbind= NULL;
2205         
2206         ima->packedfile = direct_link_packedfile(fd, ima->packedfile);
2207         ima->preview = direct_link_preview_image(fd, ima->preview);
2208         ima->ok= 1;
2209 }
2210
2211
2212 /* ************ READ CURVE ***************** */
2213
2214 static void lib_link_curve(FileData *fd, Main *main)
2215 {
2216         Curve *cu;
2217         int a;
2218
2219         cu= main->curve.first;
2220         while(cu) {
2221                 if(cu->id.flag & LIB_NEEDLINK) {
2222
2223                         for(a=0; a<cu->totcol; a++) cu->mat[a]= newlibadr_us(fd, cu->id.lib, cu->mat[a]);
2224
2225                         cu->bevobj= newlibadr(fd, cu->id.lib, cu->bevobj);
2226                         cu->taperobj= newlibadr(fd, cu->id.lib, cu->taperobj);
2227                         cu->textoncurve= newlibadr(fd, cu->id.lib, cu->textoncurve);
2228                         cu->vfont= newlibadr_us(fd, cu->id.lib, cu->vfont);
2229                         cu->vfontb= newlibadr_us(fd, cu->id.lib, cu->vfontb);                   
2230                         cu->vfonti= newlibadr_us(fd, cu->id.lib, cu->vfonti);
2231                         cu->vfontbi= newlibadr_us(fd, cu->id.lib, cu->vfontbi);
2232
2233                         cu->ipo= newlibadr_us(fd, cu->id.lib, cu->ipo);
2234                         cu->key= newlibadr_us(fd, cu->id.lib, cu->key);
2235
2236                         cu->id.flag -= LIB_NEEDLINK;
2237                 }
2238                 cu= cu->id.next;
2239         }
2240 }
2241
2242
2243 static void switch_endian_knots(Nurb *nu)
2244 {
2245         int len;
2246
2247         if(nu->knotsu) {
2248                 len= KNOTSU(nu);
2249                 while(len--) {
2250                         SWITCH_INT(nu->knotsu[len]);
2251                 }
2252         }
2253         if(nu->knotsv) {
2254                 len= KNOTSV(nu);
2255                 while(len--) {
2256                         SWITCH_INT(nu->knotsv[len]);
2257                 }
2258         }
2259 }
2260
2261 static void direct_link_curve(FileData *fd, Curve *cu)
2262 {
2263         Nurb *nu;
2264         TextBox *tb;
2265
2266         cu->mat= newdataadr(fd, cu->mat);
2267         test_pointer_array(fd, (void **)&cu->mat);
2268         cu->str= newdataadr(fd, cu->str);
2269         cu->strinfo= newdataadr(fd, cu->strinfo);       
2270         cu->tb= newdataadr(fd, cu->tb);
2271
2272         if(cu->vfont==0) link_list(fd, &(cu->nurb));
2273         else {
2274                 cu->nurb.first=cu->nurb.last= 0;
2275
2276                 tb= MEM_callocN(MAXTEXTBOX*sizeof(TextBox), "TextBoxread");
2277                 if (cu->tb) {
2278                         memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox));
2279                         MEM_freeN(cu->tb);
2280                         cu->tb= tb;                     
2281                 } else {
2282                         cu->totbox = 1;
2283                         cu->actbox = 1;
2284                         cu->tb = tb;
2285                         cu->tb[0].w = cu->linewidth;
2286                 }               
2287                 if (cu->wordspace == 0.0) cu->wordspace = 1.0;
2288         }
2289
2290         cu->bev.first=cu->bev.last= 0;
2291         cu->disp.first=cu->disp.last= 0;
2292         cu->path= 0;
2293
2294         nu= cu->nurb.first;
2295         while(nu) {
2296                 nu->bezt= newdataadr(fd, nu->bezt);
2297                 nu->bp= newdataadr(fd, nu->bp);
2298                 nu->knotsu= newdataadr(fd, nu->knotsu);
2299                 nu->knotsv= newdataadr(fd, nu->knotsv);
2300                 if (cu->vfont==0) nu->charidx= nu->mat_nr;
2301
2302                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2303                         switch_endian_knots(nu);
2304                 }
2305
2306                 nu= nu->next;
2307         }
2308         cu->bb= NULL;
2309 }
2310
2311 /* ************ READ TEX ***************** */
2312
2313 static void lib_link_texture(FileData *fd, Main *main)
2314 {
2315         Tex *tex;
2316
2317         tex= main->tex.first;
2318         while(tex) {
2319                 if(tex->id.flag & LIB_NEEDLINK) {
2320
2321                         tex->ima= newlibadr_us(fd, tex->id.lib, tex->ima);
2322                         tex->ipo= newlibadr_us(fd, tex->id.lib, tex->ipo);
2323                         if(tex->env) tex->env->object= newlibadr(fd, tex->id.lib, tex->env->object);
2324
2325                         tex->id.flag -= LIB_NEEDLINK;
2326                 }
2327                 tex= tex->id.next;
2328         }
2329 }
2330
2331 static void direct_link_texture(FileData *fd, Tex *tex)
2332 {
2333         tex->plugin= newdataadr(fd, tex->plugin);
2334         if(tex->plugin) {
2335                 tex->plugin->handle= 0;
2336                 open_plugin_tex(tex->plugin);
2337                 /* initialize data for this instance, if an initialization
2338                  * function exists.
2339                  */
2340                 if (tex->plugin->instance_init)
2341                         tex->plugin->instance_init((void *) tex->plugin->data);
2342         }
2343         tex->coba= newdataadr(fd, tex->coba);
2344         tex->env= newdataadr(fd, tex->env);
2345         if(tex->env) {
2346                 tex->env->ima= NULL;
2347                 memset(tex->env->cube, 0, 6*sizeof(void *));
2348                 tex->env->ok= 0;
2349         }
2350         tex->iuser.ok= 1;
2351 }
2352
2353
2354
2355 /* ************ READ MATERIAL ***************** */
2356
2357 static void lib_link_material(FileData *fd, Main *main)
2358 {
2359         Material *ma;
2360         MTex *mtex;
2361         int a;
2362
2363         ma= main->mat.first;
2364         while(ma) {
2365                 if(ma->id.flag & LIB_NEEDLINK) {
2366                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
2367                         of library blocks that implement this.*/
2368                         if (ma->id.properties) IDP_LibLinkProperty(ma->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2369
2370                         ma->ipo= newlibadr_us(fd, ma->id.lib, ma->ipo);
2371                         ma->group= newlibadr_us(fd, ma->id.lib, ma->group);
2372                         
2373                         for(a=0; a<MAX_MTEX; a++) {
2374                                 mtex= ma->mtex[a];
2375                                 if(mtex) {
2376                                         mtex->tex= newlibadr_us(fd, ma->id.lib, mtex->tex);
2377                                         mtex->object= newlibadr(fd, ma->id.lib, mtex->object);
2378                                 }
2379                         }
2380                         lib_link_scriptlink(fd, &ma->id, &ma->scriptlink);
2381                         
2382                         if(ma->nodetree)
2383                                 lib_link_ntree(fd, &ma->id, ma->nodetree);
2384                         
2385                         ma->id.flag -= LIB_NEEDLINK;
2386                 }
2387                 ma= ma->id.next;
2388         }
2389 }
2390
2391 static void direct_link_material(FileData *fd, Material *ma)
2392 {
2393         int a;
2394
2395         for(a=0; a<MAX_MTEX; a++) {
2396                 ma->mtex[a]= newdataadr(fd, ma->mtex[a]);
2397         }
2398
2399         ma->ramp_col= newdataadr(fd, ma->ramp_col);
2400         ma->ramp_spec= newdataadr(fd, ma->ramp_spec);
2401         
2402         direct_link_scriptlink(fd, &ma->scriptlink);
2403         
2404         ma->nodetree= newdataadr(fd, ma->nodetree);
2405         if(ma->nodetree)
2406                 direct_link_nodetree(fd, ma->nodetree);
2407 }
2408
2409 /* ************ READ MESH ***************** */
2410
2411 static void lib_link_mtface(FileData *fd, Mesh *me, MTFace *mtface, int totface)
2412 {
2413         MTFace *tf= mtface;
2414         int i;
2415
2416         for (i=0; i<totface; i++, tf++) {
2417                 tf->tpage= newlibadr(fd, me->id.lib, tf->tpage);
2418                 if(tf->tpage && tf->tpage->id.us==0)
2419                         tf->tpage->id.us= 1;
2420         }
2421 }
2422
2423 static void lib_link_customdata_mtface(FileData *fd, Mesh *me, CustomData *fdata, int totface)
2424 {
2425         int i;  
2426         for(i=0; i<fdata->totlayer; i++) {
2427                 CustomDataLayer *layer = &fdata->layers[i];
2428                 
2429                 if(layer->type == CD_MTFACE)
2430                         lib_link_mtface(fd, me, layer->data, totface);
2431         }
2432
2433 }
2434
2435 static void lib_link_mesh(FileData *fd, Main *main)
2436 {
2437         Mesh *me;
2438
2439         me= main->mesh.first;
2440         while(me) {
2441                 if(me->id.flag & LIB_NEEDLINK) {
2442                         int i;
2443
2444                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
2445                         of library blocks that implement this.*/
2446                         if (me->id.properties) IDP_LibLinkProperty(me->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2447
2448                         /* this check added for python created meshes */
2449                         if(me->mat) {
2450                                 for(i=0; i<me->totcol; i++) {
2451                                         me->mat[i]= newlibadr_us(fd, me->id.lib, me->mat[i]);
2452                                 }
2453                         }
2454                         else me->totcol= 0;
2455
2456                         me->ipo= newlibadr_us(fd, me->id.lib, me->ipo);
2457                         me->key= newlibadr_us(fd, me->id.lib, me->key);
2458                         me->texcomesh= newlibadr_us(fd, me->id.lib, me->texcomesh);
2459
2460                         lib_link_customdata_mtface(fd, me, &me->fdata, me->totface);
2461                         if(me->mr && me->mr->levels.first)
2462                                 lib_link_customdata_mtface(fd, me, &me->mr->fdata,
2463                                                            ((MultiresLevel*)me->mr->levels.first)->totface);
2464
2465                         me->id.flag -= LIB_NEEDLINK;
2466                 }
2467                 me= me->id.next;
2468         }
2469 }
2470
2471 static void direct_link_dverts(FileData *fd, int count, MDeformVert *mdverts)
2472 {
2473         int     i;
2474
2475         if (!mdverts)
2476                 return;
2477
2478         for (i=0; i<count; i++) {
2479                 mdverts[i].dw=newdataadr(fd, mdverts[i].dw);
2480                 if (!mdverts[i].dw)
2481                         mdverts[i].totweight=0;
2482         }
2483 }
2484
2485 static void direct_link_customdata(FileData *fd, CustomData *data, int count)
2486 {
2487         int i = 0;
2488
2489         data->layers= newdataadr(fd, data->layers);
2490
2491         while (i < data->totlayer) {
2492                 CustomDataLayer *layer = &data->layers[i];
2493
2494                 if (CustomData_verify_versions(data, i)) {
2495                         layer->data = newdataadr(fd, layer->data);
2496                         i++;
2497                 }
2498         }
2499 }
2500
2501 static void direct_link_mesh(FileData *fd, Mesh *mesh)
2502 {
2503         mesh->mat= newdataadr(fd, mesh->mat);
2504         test_pointer_array(fd, (void **)&mesh->mat);
2505
2506         mesh->mvert= newdataadr(fd, mesh->mvert);
2507         mesh->medge= newdataadr(fd, mesh->medge);
2508         mesh->mface= newdataadr(fd, mesh->mface);
2509         mesh->tface= newdataadr(fd, mesh->tface);
2510         mesh->mtface= newdataadr(fd, mesh->mtface);
2511         mesh->mcol= newdataadr(fd, mesh->mcol);
2512         mesh->msticky= newdataadr(fd, mesh->msticky);
2513         mesh->dvert= newdataadr(fd, mesh->dvert);
2514         
2515         /* Partial-mesh visibility (do this before using totvert, totface, or totedge!) */
2516         mesh->pv= newdataadr(fd, mesh->pv);
2517         if(mesh->pv) {
2518                 mesh->pv->vert_map= newdataadr(fd, mesh->pv->vert_map);
2519                 mesh->pv->edge_map= newdataadr(fd, mesh->pv->edge_map);
2520                 mesh->pv->old_faces= newdataadr(fd, mesh->pv->old_faces);
2521                 mesh->pv->old_edges= newdataadr(fd, mesh->pv->old_edges);
2522         }
2523
2524         /* normally direct_link_dverts should be called in direct_link_customdata,
2525            but for backwards compat in do_versions to work we do it here */
2526         direct_link_dverts(fd, mesh->pv ? mesh->pv->totvert : mesh->totvert, mesh->dvert);
2527
2528         direct_link_customdata(fd, &mesh->vdata, mesh->pv ? mesh->pv->totvert : mesh->totvert);
2529         direct_link_customdata(fd, &mesh->edata, mesh->pv ? mesh->pv->totedge : mesh->totedge);
2530         direct_link_customdata(fd, &mesh->fdata, mesh->pv ? mesh->pv->totface : mesh->totface);
2531
2532         mesh->bb= NULL;
2533         mesh->oc= 0;
2534         mesh->mselect= NULL;
2535
2536         /* Multires data */
2537         mesh->mr= newdataadr(fd, mesh->mr);
2538         if(mesh->mr) {
2539                 MultiresLevel *lvl;
2540                 
2541                 link_list(fd, &mesh->mr->levels);
2542                 lvl= mesh->mr->levels.first;
2543                 
2544                 direct_link_customdata(fd, &mesh->mr->vdata, lvl->totvert);
2545                 direct_link_dverts(fd, lvl->totvert, CustomData_get(&mesh->mr->vdata, 0, CD_MDEFORMVERT));
2546                 direct_link_customdata(fd, &mesh->mr->fdata, lvl->totface);
2547                 
2548                 if(mesh->mr->edge_flags)
2549                         mesh->mr->edge_flags= newdataadr(fd, mesh->mr->edge_flags);
2550                 if(mesh->mr->edge_creases)
2551                         mesh->mr->edge_creases= newdataadr(fd, mesh->mr->edge_creases);
2552                 
2553                 if(!mesh->mr->edge_flags)
2554                         mesh->mr->edge_flags= MEM_callocN(sizeof(short)*lvl->totedge, "Multires Edge Flags");
2555                 if(!mesh->mr->edge_creases)
2556                         mesh->mr->edge_creases= MEM_callocN(sizeof(char)*lvl->totedge, "Multires Edge Creases");
2557                         
2558                 for(; lvl; lvl= lvl->next) {
2559                         lvl->verts= newdataadr(fd, lvl->verts);
2560                         lvl->faces= newdataadr(fd, lvl->faces);
2561                         lvl->edges= newdataadr(fd, lvl->edges);
2562                         lvl->colfaces= newdataadr(fd, lvl->colfaces);
2563
2564                         /* Recalculating the maps is faster than reading them from the file */
2565                         multires_calc_level_maps(lvl);
2566                 }
2567         }
2568         
2569         if((fd->flags & FD_FLAGS_SWITCH_ENDIAN) && mesh->tface) {
2570                 TFace *tf= mesh->tface;
2571                 int i;
2572
2573                 for (i=0; i< (mesh->pv ? mesh->pv->totface : mesh->totface); i++, tf++) {
2574                         SWITCH_INT(tf->col[0]);
2575                         SWITCH_INT(tf->col[1]);
2576                         SWITCH_INT(tf->col[2]);
2577                         SWITCH_INT(tf->col[3]);
2578                 }
2579         }
2580 }
2581
2582 /* ************ READ LATTICE ***************** */
2583
2584 static void lib_link_latt(FileData *fd, Main *main)
2585 {
2586         Lattice *lt;
2587         
2588         lt= main->latt.first;
2589         while(lt) {
2590                 if(lt->id.flag & LIB_NEEDLINK) {
2591                         
2592                         lt->ipo= newlibadr_us(fd, lt->id.lib, lt->ipo);
2593                         lt->key= newlibadr_us(fd, lt->id.lib, lt->key);
2594                         
2595                         lt->id.flag -= LIB_NEEDLINK;
2596                 }
2597                 lt= lt->id.next;
2598         }
2599 }
2600
2601 static void direct_link_latt(FileData *fd, Lattice *lt)
2602 {
2603         lt->def= newdataadr(fd, lt->def);
2604         
2605         lt->dvert= newdataadr(fd, lt->dvert);
2606         direct_link_dverts(fd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
2607 }
2608
2609
2610 /* ************ READ OBJECT ***************** */
2611
2612 static void lib_link_modifiers__linkModifiers(void *userData, Object *ob,
2613                                               ID **idpoin)
2614 {
2615         FileData *fd = userData;
2616
2617         *idpoin = newlibadr(fd, ob->id.lib, *idpoin);
2618         /* hardcoded bad exception; non-object modifier data gets user count (texture, displace) */
2619         if(*idpoin && GS((*idpoin)->name)!=ID_OB)
2620                 (*idpoin)->us++;
2621 }
2622 static void lib_link_modifiers(FileData *fd, Object *ob)
2623 {
2624         modifiers_foreachIDLink(ob, lib_link_modifiers__linkModifiers, fd);
2625 }
2626
2627 static void lib_link_object(FileData *fd, Main *main)
2628 {
2629         Object *ob;
2630         PartEff *paf;
2631         bSensor *sens;
2632         bController *cont;
2633         bActuator *act;
2634         void *poin;
2635         int warn=0, a;
2636
2637         ob= main->object.first;
2638         while(ob) {
2639                 if(ob->id.flag & LIB_NEEDLINK) {
2640                         if (ob->id.properties) IDP_LibLinkProperty(ob->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2641
2642                         ob->parent= newlibadr(fd, ob->id.lib, ob->parent);
2643                         ob->track= newlibadr(fd, ob->id.lib, ob->track);
2644                         ob->ipo= newlibadr_us(fd, ob->id.lib, ob->ipo);
2645                         ob->action = newlibadr_us(fd, ob->id.lib, ob->action);
2646                         ob->dup_group= newlibadr_us(fd, ob->id.lib, ob->dup_group);
2647                         
2648                         ob->proxy= newlibadr_us(fd, ob->id.lib, ob->proxy);
2649                         if(ob->proxy) {
2650                                 /* paranoia check, actually a proxy_from pointer should never be written... */
2651                                 if(ob->proxy->id.lib==NULL) {
2652                                         ob->proxy->proxy_from= NULL;
2653                                         ob->proxy= NULL;
2654                                 }
2655                                 else {
2656                                         /* this triggers object_update to always use a copy */
2657                                         ob->proxy->proxy_from= ob;
2658                                         /* force proxy updates after load/undo, a bit weak */
2659                                         ob->recalc= ob->proxy->recalc= OB_RECALC;
2660                                 }
2661                         }
2662                         ob->proxy_group= newlibadr(fd, ob->id.lib, ob->proxy_group);
2663
2664                         poin= ob->data;
2665                         ob->data= newlibadr_us(fd, ob->id.lib, ob->data);
2666                            
2667                         if(ob->data==NULL && poin!=NULL) {
2668                                 ob->type= OB_EMPTY;
2669                                 warn= 1;
2670                                 if(ob->id.lib) printf("Can't find obdata of %s lib %s\n", ob->id.name+2, ob->id.lib->name);
2671                                 else printf("Object %s lost data. Lib:%x\n", ob->id.name+2, (unsigned int) ob->id.lib);
2672                                 
2673                                 if(ob->pose) {
2674                                         free_pose_channels(ob->pose);
2675                                         MEM_freeN(ob->pose);
2676                                         ob->pose= NULL;
2677                                         ob->flag &= ~OB_POSEMODE;
2678                                 }
2679                         }
2680                         for(a=0; a<ob->totcol; a++) ob->mat[a]= newlibadr_us(fd, ob->id.lib, ob->mat[a]);
2681
2682                         ob->id.flag -= LIB_NEEDLINK;
2683                         /* if id.us==0 a new base will be created later on */
2684
2685                         /* WARNING! Also check expand_object(), should reflect the stuff below. */
2686                         lib_link_pose(fd, ob, ob->pose);
2687                         lib_link_constraints(fd, &ob->id, &ob->constraints);
2688                         lib_link_nlastrips(fd, &ob->id, &ob->nlastrips);
2689                         lib_link_constraint_channels(fd, &ob->id, &ob->constraintChannels);
2690
2691                         for(paf= ob->effect.first; paf; paf= paf->next) {
2692                                 if(paf->type==EFF_PARTICLE) {
2693                                         paf->group= newlibadr_us(fd, ob->id.lib, paf->group);
2694                                 }
2695                         }                               
2696
2697                         sens= ob->sensors.first;
2698                         while(sens) {
2699                                 if(ob->id.lib==NULL) {  // done in expand_main
2700                                         for(a=0; a<sens->totlinks; a++) {
2701                                                 sens->links[a]= newglobadr(fd, sens->links[a]);
2702                                         }
2703                                 }
2704                                 if(sens->type==SENS_TOUCH) {
2705                                         bTouchSensor *ts= sens->data;
2706                                         ts->ma= newlibadr(fd, ob->id.lib, ts->ma);
2707                                 }
2708                                 else if(sens->type==SENS_MESSAGE) {
2709                                         bMessageSensor *ms= sens->data;
2710                                         ms->fromObject=
2711                                             newlibadr(fd, ob->id.lib, ms->fromObject);
2712                                 }
2713                                 sens= sens->next;
2714                         }
2715
2716                         cont= ob->controllers.first;
2717                         while(cont) {
2718                                 if(ob->id.lib==NULL) {  // done in expand_main
2719                                         for(a=0; a<cont->totlinks; a++) {
2720                                                 cont->links[a]= newglobadr(fd, cont->links[a]);
2721                                         }
2722                                 }
2723                                 if(cont->type==CONT_PYTHON) {
2724                                         bPythonCont *pc= cont->data;
2725                                         pc->text= newlibadr(fd, ob->id.lib, pc->text);
2726                                 }
2727                                 cont->slinks= NULL;
2728                                 cont->totslinks= 0;
2729
2730                                 cont= cont->next;
2731                         }
2732
2733                         act= ob->actuators.first;
2734                         while(act) {
2735                                 if(act->type==ACT_SOUND) {
2736                                         bSoundActuator *sa= act->data;
2737                                         sa->sound= newlibadr_us(fd, ob->id.lib, sa->sound);
2738                                 }
2739                                 else if(act->type==ACT_CD) {
2740                                         /* bCDActuator *cda= act->data; */
2741                                 }
2742                                 else if(act->type==ACT_GAME) {
2743                                         /* bGameActuator *ga= act->data; */
2744                                 }
2745                                 else if(act->type==ACT_CAMERA) {
2746                                         bCameraActuator *ca= act->data;
2747                                         ca->ob= newlibadr(fd, ob->id.lib, ca->ob);
2748                                 }
2749                                         /* leave this one, it's obsolete but necessary to read for conversion */
2750                                 else if(act->type==ACT_ADD_OBJECT) {
2751                                         bAddObjectActuator *eoa= act->data;
2752                                         if(eoa) eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
2753                                 }
2754                                 else if(act->type==ACT_EDIT_OBJECT) {
2755                                         bEditObjectActuator *eoa= act->data;
2756                                         if(eoa==NULL) {
2757                                                 init_actuator(act);
2758                                         }
2759                                         else {
2760                                                 eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
2761                                                 eoa->me= newlibadr(fd, ob->id.lib, eoa->me);
2762                                         }
2763                                 }
2764                                 else if(act->type==ACT_SCENE) {
2765                                         bSceneActuator *sa= act->data;
2766                                         sa->camera= newlibadr(fd, ob->id.lib, sa->camera);
2767                                         sa->scene= newlibadr(fd, ob->id.lib, sa->scene);
2768                                 }
2769                                 else if(act->type==ACT_ACTION) {
2770                                         bActionActuator *aa= act->data;
2771                                         aa->act= newlibadr(fd, ob->id.lib, aa->act);
2772                                 }
2773                                 else if(act->type==ACT_PROPERTY) {
2774                                         bPropertyActuator *pa= act->data;
2775                                         pa->ob= newlibadr(fd, ob->id.lib, pa->ob);
2776                                 }
2777                                 else if(act->type==ACT_MESSAGE) {
2778                                         bMessageActuator *ma= act->data;
2779                                         ma->toObject= newlibadr(fd, ob->id.lib, ma->toObject);
2780                                 }
2781                                 act= act->next;
2782                         }
2783
2784                         if(ob->fluidsimSettings) {
2785                                 ob->fluidsimSettings->ipo = newlibadr_us(fd, ob->id.lib, ob->fluidsimSettings->ipo);
2786                         }
2787
2788                         lib_link_scriptlink(fd, &ob->id, &ob->scriptlink);
2789                         lib_link_modifiers(fd, ob);
2790                 }
2791                 ob= ob->id.next;
2792         }
2793
2794         if(warn) error("WARNING IN CONSOLE");
2795 }
2796
2797
2798 static void direct_link_pose(FileData *fd, bPose *pose) {
2799
2800         bPoseChannel *pchan;
2801
2802         if (!pose)
2803                 return;
2804
2805         link_list(fd, &pose->chanbase);
2806
2807         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
2808                 pchan->bone= NULL;
2809                 pchan->parent= newdataadr(fd, pchan->parent);
2810                 pchan->child= newdataadr(fd, pchan->child);
2811                 direct_link_constraints(fd, &pchan->constraints);
2812                 pchan->iktree.first= pchan->iktree.last= NULL;
2813                 pchan->path= NULL;
2814         }
2815
2816 }
2817
2818 static void direct_link_modifiers(FileData *fd, ListBase *lb)
2819 {
2820         ModifierData *md;
2821
2822         link_list(fd, lb);
2823
2824         for (md=lb->first; md; md=md->next) {
2825                 md->error = NULL;
2826                 
2827                 /* if modifiers disappear, or for upward compatibility */
2828                 if(NULL==modifierType_getInfo(md->type))
2829                         md->type= eModifierType_None;
2830                         
2831                 if (md->type==eModifierType_Subsurf) {
2832                         SubsurfModifierData *smd = (SubsurfModifierData*) md;
2833
2834                         smd->emCache = smd->mCache = 0;
2835                 } else if (md->type==eModifierType_Hook) {
2836                         HookModifierData *hmd = (HookModifierData*) md;
2837
2838                         hmd->indexar= newdataadr(fd, hmd->indexar);
2839                         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2840                                 int a;
2841                                 for(a=0; a<hmd->totindex; a++) {
2842                                         SWITCH_INT(hmd->indexar[a]);
2843                                 }
2844                         }
2845                 }
2846         }
2847 }
2848
2849 static void direct_link_nlastrips(FileData *fd, ListBase *strips)
2850 {
2851         bActionStrip *strip;
2852         
2853         link_list(fd, strips);
2854         
2855         for(strip= strips->first; strip; strip= strip->next)
2856                 link_list(fd, &strip->modifiers);
2857 }
2858
2859 static void direct_link_object(FileData *fd, Object *ob)
2860 {
2861         PartEff *paf;
2862         bProperty *prop;
2863         bSensor *sens;
2864         bController *cont;
2865         bActuator *act;
2866         int a;
2867         
2868         /* weak weak... this was only meant as draw flag, now is used in give_base too */
2869         ob->flag &= ~OB_FROMGROUP;
2870
2871         ob->disp.first=ob->disp.last= NULL;
2872
2873         ob->pose= newdataadr(fd, ob->pose);
2874         direct_link_pose(fd, ob->pose);
2875
2876         link_list(fd, &ob->defbase);
2877         direct_link_nlastrips(fd, &ob->nlastrips);
2878         link_list(fd, &ob->constraintChannels);
2879
2880         direct_link_scriptlink(fd, &ob->scriptlink);
2881
2882         ob->mat= newdataadr(fd, ob->mat);
2883         test_pointer_array(fd, (void **)&ob->mat);
2884         
2885         /* do it here, below old data gets converted */
2886         direct_link_modifiers(fd, &ob->modifiers);
2887         
2888         link_list(fd, &ob->effect);
2889         paf= ob->effect.first;
2890         while(paf) {
2891                 if(paf->type==EFF_PARTICLE) {
2892                         paf->keys= NULL;
2893                 }
2894                 if(paf->type==EFF_WAVE) {
2895                         WaveEff *wav = (WaveEff*) paf;
2896                         PartEff *next = paf->next;
2897                         WaveModifierData *wmd = (WaveModifierData*) modifier_new(eModifierType_Wave);
2898
2899                         wmd->damp = wav->damp;
2900                         wmd->flag = wav->flag;
2901                         wmd->height = wav->height;
2902                         wmd->lifetime = wav->lifetime;
2903                         wmd->narrow = wav->narrow;
2904                         wmd->speed = wav->speed;
2905                         wmd->startx = wav->startx;
2906                         wmd->starty = wav->startx;
2907                         wmd->timeoffs = wav->timeoffs;
2908                         wmd->width = wav->width;
2909
2910                         BLI_addtail(&ob->modifiers, wmd);
2911
2912                         BLI_remlink(&ob->effect, paf);
2913                         MEM_freeN(paf);
2914
2915                         paf = next;
2916                         continue;
2917                 }
2918                 if(paf->type==EFF_BUILD) {
2919                         BuildEff *baf = (BuildEff*) paf;
2920                         PartEff *next = paf->next;
2921                         BuildModifierData *bmd = (BuildModifierData*) modifier_new(eModifierType_Build);
2922
2923                         bmd->start = baf->sfra;
2924                         bmd->length = baf->len;
2925                         bmd->randomize = 0;
2926                         bmd->seed = 1;
2927
2928                         BLI_addtail(&ob->modifiers, bmd);
2929
2930                         BLI_remlink(&ob->effect, paf);
2931                         MEM_freeN(paf);
2932
2933                         paf = next;
2934                         continue;
2935                 }
2936                 paf= paf->next;
2937         }
2938
2939         ob->pd= newdataadr(fd, ob->pd);
2940         ob->soft= newdataadr(fd, ob->soft);
2941         if(ob->soft) {
2942                 SoftBody *sb= ob->soft;         
2943                 
2944                 sb->bpoint= NULL;       // init pointers so it gets rebuilt nicely
2945                 sb->bspring= NULL;
2946                 sb->scratch= NULL;
2947
2948                 
2949                 sb->keys= newdataadr(fd, sb->keys);
2950                 test_pointer_array(fd, (void **)&sb->keys);
2951                 if(sb->keys) {
2952                         for(a=0; a<sb->totkey; a++) {
2953                                 sb->keys[a]= newdataadr(fd, sb->keys[a]);
2954                         }
2955                 }
2956         }
2957         ob->fluidsimSettings= newdataadr(fd, ob->fluidsimSettings); /* NT */
2958         if(ob->fluidsimSettings) {
2959                 // reinit mesh pointers
2960                 ob->fluidsimSettings->orgMesh = NULL; //ob->data;
2961                 ob->fluidsimSettings->meshSurface = NULL;
2962                 ob->fluidsimSettings->meshBB = NULL;
2963                 ob->fluidsimSettings->meshSurfNormals = NULL;
2964         }
2965         
2966         link_list(fd, &ob->prop);
2967         prop= ob->prop.first;
2968         while(prop) {
2969                 prop->poin= newdataadr(fd, prop->poin);
2970                 if(prop->poin==0) prop->poin= &prop->data;
2971                 prop= prop->next;
2972         }
2973
2974         link_list(fd, &ob->sensors);
2975         sens= ob->sensors.first;
2976         while(sens) {
2977                 sens->data= newdataadr(fd, sens->data);
2978                 sens->links= newdataadr(fd, sens->links);
2979                 test_pointer_array(fd, (void **)&sens->links);
2980                 sens= sens->next;
2981         }
2982
2983         direct_link_constraints(fd, &ob->constraints);
2984
2985         link_glob_list(fd, &ob->controllers);
2986         cont= ob->controllers.first;
2987         while(cont) {
2988                 cont->data= newdataadr(fd, cont->data);
2989                 cont->links= newdataadr(fd, cont->links);
2990                 test_pointer_array(fd, (void **)&cont->links);
2991                 cont= cont->next;
2992         }
2993
2994         link_glob_list(fd, &ob->actuators);
2995         act= ob->actuators.first;
2996         while(act) {
2997                 act->data= newdataadr(fd, act->data);
2998                 act= act->next;
2999         }
3000
3001         link_list(fd, &ob->hooks);
3002         while (ob->hooks.first) {
3003                 ObHook *hook = ob->hooks.first;
3004                 HookModifierData *hmd = (HookModifierData*) modifier_new(eModifierType_Hook);
3005
3006                 hook->indexar= newdataadr(fd, hook->indexar);
3007                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
3008                         int a;
3009                         for(a=0; a<hook->totindex; a++) {
3010                                 SWITCH_INT(hook->indexar[a]);
3011                         }
3012                 }
3013
3014                         /* Do conversion here because if we have loaded
3015                          * a hook we need to make sure it gets converted
3016                          * and free'd, regardless of version.
3017                          */
3018                 VECCOPY(hmd->cent, hook->cent);
3019                 hmd->falloff = hook->falloff;
3020                 hmd->force = hook->force;
3021                 hmd->indexar = hook->indexar;
3022                 hmd->object = hook->parent;
3023                 memcpy(hmd->parentinv, hook->parentinv, sizeof(hmd->parentinv));
3024                 hmd->totindex = hook->totindex;
3025
3026                 BLI_addhead(&ob->modifiers, hmd);
3027                 BLI_remlink(&ob->hooks, hook);
3028
3029                 MEM_freeN(hook);
3030         }
3031         
3032         ob->bb= NULL;
3033         ob->derivedDeform= NULL;
3034         ob->derivedFinal= NULL;
3035 }
3036
3037 /* ************ READ SCENE ***************** */
3038
3039 static void lib_link_scene(FileData *fd, Main *main)
3040 {
3041         Scene *sce;
3042         Base *base, *next;
3043         Editing *ed;
3044         Sequence *seq;
3045         SceneRenderLayer *srl;
3046         int a;
3047         
3048         sce= main->scene.first;
3049         while(sce) {
3050                 if(sce->id.flag & LIB_NEEDLINK) {
3051                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
3052                         of library blocks that implement this.*/
3053                         if (sce->id.properties) IDP_LibLinkProperty(sce->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
3054
3055                         sce->camera= newlibadr(fd, sce->id.lib, sce->camera);
3056                         sce->world= newlibadr_us(fd, sce->id.lib, sce->world);
3057                         sce->set= newlibadr(fd, sce->id.lib, sce->set);
3058                         sce->ima= newlibadr_us(fd, sce->id.lib, sce->ima);
3059                         sce->toolsettings->imapaint.brush=
3060                                 newlibadr_us(fd, sce->id.lib, sce->toolsettings->imapaint.brush);
3061
3062                         /* Sculptdata textures */
3063                         for(a=0; a<MAX_MTEX; ++a) {
3064                                 MTex *mtex= sce->sculptdata.mtex[a];
3065                                 if(mtex)
3066                                         mtex->tex= newlibadr_us(fd, sce->id.lib, mtex->tex);
3067                         }
3068
3069                         for(base= sce->base.first; base; base= next) {
3070                                 next= base->next;
3071
3072                                 /* base->object= newlibadr_us(fd, sce->id.lib, base->object); */
3073                                 base->object= newlibadr_us(fd, sce->id.lib, base->object);
3074                                 
3075                                 /* when save during radiotool, needs cleared */
3076                                 base->flag &= ~OB_RADIO;
3077                                 
3078                                 if(base->object==NULL) {
3079                                         printf("LIB ERROR: base removed\n");
3080                                         BLI_remlink(&sce->base, base);
3081                                         if(base==sce->basact) sce->basact= 0;
3082                                         MEM_freeN(base);
3083                                 }
3084                         }
3085
3086                         ed= sce->ed;
3087                         if(ed) {
3088                                 WHILE_SEQ(&ed->seqbase) {
3089                                         if(seq->ipo) seq->ipo= newlibadr_us(fd, sce->id.lib, seq->ipo);
3090                                         if(seq->scene) seq->scene= newlibadr(fd, sce->id.lib, seq->scene);
3091                                         if(seq->sound) {
3092                                                 seq->sound= newlibadr(fd, sce->id.lib, seq->sound);
3093                                                 if (seq->sound) {
3094                                                         seq->sound->id.us++;
3095                                                         seq->sound->flags |= SOUND_FLAGS_SEQUENCE;
3096                                                 }
3097                                         }
3098                                         seq->anim= 0;
3099                                         seq->hdaudio = 0;
3100                                 }
3101                                 END_SEQ
3102                         }
3103                         
3104                         lib_link_scriptlink(fd, &sce->id, &sce->scriptlink);
3105                         
3106                         if(sce->nodetree)
3107                                 lib_link_ntree(fd, &sce->id, sce->nodetree);
3108                         
3109                         for(srl= sce->r.layers.first; srl; srl= srl->next) {
3110                                 srl->mat_override= newlibadr_us(fd, sce->id.lib, srl->mat_override);
3111                                 srl->light_override= newlibadr_us(fd, sce->id.lib, srl->light_override);
3112                         }
3113                         
3114                         sce->id.flag -= LIB_NEEDLINK;
3115                 }
3116
3117                 sce= sce->id.next;
3118         }
3119 }
3120
3121 static void link_recurs_seq(FileData *fd, ListBase *lb)
3122 {
3123         Sequence *seq;
3124
3125         link_list(fd, lb);
3126         seq= lb->first;
3127         while(seq) {
3128                 if(seq->seqbase.first) link_recurs_seq(fd, &seq->seqbase);
3129                 seq= seq->next;
3130         }
3131 }
3132
3133 static void direct_link_scene(FileData *fd, Scene *sce)
3134 {
3135         Editing *ed;
3136         Sequence *seq;
3137         MetaStack *ms;
3138         StripElem *se;
3139         int a;
3140
3141         sce->theDag = NULL;
3142         sce->dagisvalid = 0;
3143         /* set users to one by default, not in lib-link, this will increase it for compo nodes */
3144         sce->id.us= 1;
3145
3146         link_list(fd, &(sce->base));
3147
3148         sce->basact= newdataadr(fd, sce->basact);
3149
3150         sce->radio= newdataadr(fd, sce->radio);
3151         
3152         sce->toolsettings= newdataadr(fd, sce->toolsettings);
3153
3154         sce->sculptdata.session= NULL;
3155         /* SculptData textures */
3156         for(a=0; a<MAX_MTEX; ++a)
3157                 sce->sculptdata.mtex[a]= newdataadr(fd,sce->sculptdata.mtex[a]);
3158
3159         if(sce->ed) {
3160                 ListBase *old_seqbasep= &((Editing *)sce->ed)->seqbase;
3161                 
3162                 ed= sce->ed= newdataadr(fd, sce->ed);
3163
3164                 /* recursive link sequences, lb will be correctly initialized */
3165                 link_recurs_seq(fd, &ed->seqbase);
3166
3167                 WHILE_SEQ(&ed->seqbase) {
3168                         seq->seq1= newdataadr(fd, seq->seq1);
3169                         seq->seq2= newdataadr(fd, seq->seq2);
3170                         seq->seq3= newdataadr(fd, seq->seq3);
3171                         /* a patch: after introduction of effects with 3 input strips */
3172                         if(seq->seq3==0) seq->seq3= seq->seq2;
3173
3174                         seq->curelem= 0;
3175
3176                         seq->plugin= newdataadr(fd, seq->plugin);
3177                         seq->effectdata= newdataadr(fd, seq->effectdata);
3178                         
3179                         if (seq->type & SEQ_EFFECT) {
3180                                 seq->flag |= SEQ_EFFECT_NOT_LOADED;
3181                         }
3182
3183                         seq->strip= newdataadr(fd, seq->strip);
3184                         if(seq->strip && seq->strip->done==0) {
3185                                 seq->strip->done= 1;
3186
3187                                 /* standard: strips from effects/metas are not written, but are mallocced */
3188
3189                                 if(seq->type==SEQ_IMAGE) {
3190                                         seq->strip->stripdata= newdataadr(fd, seq->strip->stripdata);
3191                                         se= seq->strip->stripdata;
3192                                         if(se) {
3193                                                 for(a=0; a<seq->strip->len; a++, se++) {
3194                                                         se->ok= 1;
3195                                                         se->ibuf= 0;
3196                                                 }
3197                                         }
3198                                 }
3199                                 else if(seq->type==SEQ_MOVIE) {
3200                                         /* only first stripelem is in file */
3201                                         se= newdataadr(fd, seq->strip->stripdata);
3202
3203                                         if(se) {
3204                                                 seq->strip->stripdata= MEM_callocN(seq->len*sizeof(StripElem), "stripelem");
3205                                                 *seq->strip->stripdata= *se;
3206                                                 MEM_freeN(se);
3207
3208                                                 se= seq->strip->stripdata;
3209
3210                                                 for(a=0; a<seq->strip->len; a++, se++) {
3211                                                         se->ok= 1;
3212                                                         se->ibuf= 0;
3213                                                         se->nr= a + 1;
3214                                                 }
3215                                         }
3216                                 }
3217                                 else if(seq->type==SEQ_RAM_SOUND
3218                                         || seq->type == SEQ_HD_SOUND) {
3219                                         /* only first stripelem is in file */
3220                                         se= newdataadr(fd, seq->strip->stripdata);
3221
3222                                         if(se) {
3223                                                 seq->strip->stripdata= MEM_callocN(seq->len*sizeof(StripElem), "stripelem");
3224                                                 *seq->strip->stripdata= *se;
3225                                                 MEM_freeN(se);
3226
3227                                                 se= seq->strip->stripdata;
3228
3229                                                 for(a=0; a<seq->strip->len; a++, se++) {
3230                                                         se->ok= 2; /* why? */
3231                                                         se->ibuf= 0;
3232                                                         se->nr= a + 1;
3233                                                 }
3234                                         }