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