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