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