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