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