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