2.5 merged 20773:21020
[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 #ifdef WIN32
33 #include "winsock2.h"
34 #include "BLI_winstuff.h"
35 #endif
36
37 #include <limits.h>
38 #include <stdio.h> // for printf fopen fwrite fclose sprintf FILE
39 #include <stdlib.h> // for getenv atoi
40 #include <fcntl.h> // for open
41 #include <string.h> // for strrchr strncmp strstr
42 #include <math.h> // for fabs
43
44 #ifndef WIN32
45     #include <unistd.h> // for read close
46     #include <sys/param.h> // for MAXPATHLEN
47 #else
48     #include <io.h> // for open close read
49 #endif
50
51 #include "DNA_anim_types.h"
52 #include "DNA_action_types.h"
53 #include "DNA_armature_types.h"
54 #include "DNA_ID.h"
55 #include "DNA_actuator_types.h"
56 #include "DNA_brush_types.h"
57 #include "DNA_camera_types.h"
58 #include "DNA_cloth_types.h"
59 #include "DNA_color_types.h"
60 #include "DNA_controller_types.h"
61 #include "DNA_constraint_types.h"
62 #include "DNA_curve_types.h"
63 #include "DNA_customdata_types.h"
64 #include "DNA_effect_types.h"
65 #include "DNA_fileglobal_types.h"
66 #include "DNA_genfile.h"
67 #include "DNA_group_types.h"
68 #include "DNA_gpencil_types.h"
69 #include "DNA_ipo_types.h"
70 #include "DNA_image_types.h"
71 #include "DNA_key_types.h"
72 #include "DNA_lattice_types.h"
73 #include "DNA_lamp_types.h"
74 #include "DNA_meta_types.h"
75 #include "DNA_material_types.h"
76 #include "DNA_mesh_types.h"
77 #include "DNA_meshdata_types.h"
78 #include "DNA_modifier_types.h"
79 #include "DNA_nla_types.h"
80 #include "DNA_node_types.h"
81 #include "DNA_object_types.h"
82 #include "DNA_object_force.h"
83 #include "DNA_object_fluidsim.h" // NT
84 #include "DNA_outliner_types.h"
85 #include "DNA_object_force.h"
86 #include "DNA_packedFile_types.h"
87 #include "DNA_particle_types.h"
88 #include "DNA_property_types.h"
89 #include "DNA_text_types.h"
90 #include "DNA_view3d_types.h"
91 #include "DNA_screen_types.h"
92 #include "DNA_sensor_types.h"
93 #include "DNA_sdna_types.h"
94 #include "DNA_scene_types.h"
95 #include "DNA_sequence_types.h"
96 #include "DNA_sound_types.h"
97 #include "DNA_space_types.h"
98 #include "DNA_texture_types.h"
99 #include "DNA_userdef_types.h"
100 #include "DNA_vfont_types.h"
101 #include "DNA_world_types.h"
102 #include "DNA_windowmanager_types.h"
103
104 #include "MEM_guardedalloc.h"
105 #include "BLI_blenlib.h"
106 #include "BLI_arithb.h"
107 #include "BLI_storage_types.h" // for relname flags
108
109 #include "BKE_animsys.h"
110 #include "BKE_action.h"
111 #include "BKE_armature.h"
112 #include "BKE_brush.h"
113 #include "BKE_cdderivedmesh.h"
114 #include "BKE_cloth.h"
115 #include "BKE_colortools.h"
116 #include "BKE_constraint.h"
117 #include "BKE_curve.h"
118 #include "BKE_customdata.h"
119 #include "BKE_deform.h"
120 #include "BKE_depsgraph.h"
121 #include "BKE_effect.h" /* give_parteff */
122 #include "BKE_fcurve.h"
123 #include "BKE_global.h" // for G
124 #include "BKE_group.h"
125 #include "BKE_image.h"
126 #include "BKE_ipo.h" 
127 #include "BKE_key.h" //void set_four_ipo
128 #include "BKE_lattice.h"
129 #include "BKE_library.h" // for wich_libbase
130 #include "BKE_main.h" // for Main
131 #include "BKE_mesh.h" // for ME_ defines (patching)
132 #include "BKE_modifier.h"
133 #include "BKE_multires.h"
134 #include "BKE_node.h" // for tree type defines
135 #include "BKE_object.h"
136 #include "BKE_particle.h"
137 #include "BKE_pointcache.h"
138 #include "BKE_property.h" // for get_ob_property
139 #include "BKE_report.h"
140 #include "BKE_sca.h" // for init_actuator
141 #include "BKE_scene.h"
142 #include "BKE_softbody.h"       // sbNew()
143 #include "BKE_bullet.h"         // bsbNew()
144 #include "BKE_sculpt.h"
145 #include "BKE_sequence.h"
146 #include "BKE_texture.h" // for open_plugin_tex
147 #include "BKE_utildefines.h" // SWITCH_INT DATA ENDB DNA1 O_BINARY GLOB USER TEST REND
148 #include "BKE_idprop.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         if (switch_endian) {
1373                 test_pointer_array(fd, prop->data.pointer);
1374                 array= (IDProperty**) prop->data.pointer;
1375
1376                 for(i=0; i<prop->len; i++)
1377                         IDP_DirectLinkProperty(array[i], switch_endian, fd);
1378         }
1379 }
1380
1381 static void IDP_DirectLinkArray(IDProperty *prop, int switch_endian, FileData *fd)
1382 {
1383         IDProperty **array;
1384         int i;
1385
1386         /*since we didn't save the extra buffer, set totallen to len.*/
1387         prop->totallen = prop->len;
1388         prop->data.pointer = newdataadr(fd, prop->data.pointer);
1389
1390         if (switch_endian) {
1391                 if(prop->subtype == IDP_GROUP) {
1392                         test_pointer_array(fd, prop->data.pointer);
1393                         array= prop->data.pointer;
1394
1395                         for(i=0; i<prop->len; i++)
1396                                 IDP_DirectLinkProperty(array[i], switch_endian, fd);
1397                 }
1398                 else if(prop->subtype == IDP_DOUBLE) {
1399                         for (i=0; i<prop->len; i++) {
1400                                 SWITCH_LONGINT(((double*)prop->data.pointer)[i]);
1401                         }
1402                 } else {
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 SCRIPTLINK *************** */
1568
1569 static void lib_link_scriptlink(FileData *fd, ID *id, ScriptLink *slink)
1570 {
1571         int i;
1572
1573         for(i=0; i<slink->totscript; i++) {
1574                 slink->scripts[i]= newlibadr(fd, id->lib, slink->scripts[i]);
1575         }
1576 }
1577
1578 static void direct_link_scriptlink(FileData *fd, ScriptLink *slink)
1579 {
1580         slink->scripts= newdataadr(fd, slink->scripts);
1581         test_pointer_array(fd, (void **)&slink->scripts);
1582         
1583         slink->flag= newdataadr(fd, slink->flag);
1584
1585         if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
1586                 int a;
1587
1588                 for(a=0; a<slink->totscript; a++) {
1589                         SWITCH_SHORT(slink->flag[a]);
1590                 }
1591         }
1592 }
1593
1594 /* ************ READ ANIMATION STUFF ***************** */
1595
1596 /* Legacy Data Support (for Version Patching) ----------------------------- */
1597
1598 // XXX depreceated - old animation system
1599 static void lib_link_ipo(FileData *fd, Main *main)
1600 {
1601         Ipo *ipo;
1602
1603         ipo= main->ipo.first;
1604         while(ipo) {
1605                 if(ipo->id.flag & LIB_NEEDLINK) {
1606                         IpoCurve *icu;
1607                         for(icu= ipo->curve.first; icu; icu= icu->next) {
1608                                 if(icu->driver)
1609                                         icu->driver->ob= newlibadr(fd, ipo->id.lib, icu->driver->ob);
1610                         }
1611                         ipo->id.flag -= LIB_NEEDLINK;
1612                 }
1613                 ipo= ipo->id.next;
1614         }
1615 }
1616
1617 // XXX depreceated - old animation system
1618 static void direct_link_ipo(FileData *fd, Ipo *ipo)
1619 {
1620         IpoCurve *icu;
1621
1622         link_list(fd, &(ipo->curve));
1623         icu= ipo->curve.first;
1624         while(icu) {
1625                 icu->bezt= newdataadr(fd, icu->bezt);
1626                 icu->bp= newdataadr(fd, icu->bp);
1627                 icu->driver= newdataadr(fd, icu->driver);
1628                 icu= icu->next;
1629         }
1630 }
1631
1632 // XXX depreceated - old animation system
1633 static void lib_link_nlastrips(FileData *fd, ID *id, ListBase *striplist)
1634 {
1635         bActionStrip *strip;
1636         bActionModifier *amod;
1637         
1638         for (strip=striplist->first; strip; strip=strip->next){
1639                 strip->object = newlibadr(fd, id->lib, strip->object);
1640                 strip->act = newlibadr_us(fd, id->lib, strip->act);
1641                 strip->ipo = newlibadr(fd, id->lib, strip->ipo);
1642                 for(amod= strip->modifiers.first; amod; amod= amod->next)
1643                         amod->ob= newlibadr(fd, id->lib, amod->ob);
1644         }
1645 }
1646
1647 // XXX depreceated - old animation system
1648 static void direct_link_nlastrips(FileData *fd, ListBase *strips)
1649 {
1650         bActionStrip *strip;
1651         
1652         link_list(fd, strips);
1653         
1654         for(strip= strips->first; strip; strip= strip->next)
1655                 link_list(fd, &strip->modifiers);
1656 }
1657
1658 // XXX depreceated - old animation system
1659 static void lib_link_constraint_channels(FileData *fd, ID *id, ListBase *chanbase)
1660 {
1661         bConstraintChannel *chan;
1662
1663         for (chan=chanbase->first; chan; chan=chan->next){
1664                 chan->ipo = newlibadr_us(fd, id->lib, chan->ipo);
1665         }
1666 }
1667
1668 /* Data Linking ----------------------------- */
1669
1670 static void lib_link_fmodifiers(FileData *fd, ID *id, ListBase *list)
1671 {
1672         FModifier *fcm;
1673         
1674         for (fcm= list->first; fcm; fcm= fcm->next) {
1675                 /* data for specific modifiers */
1676                 switch (fcm->type) {
1677                         case FMODIFIER_TYPE_PYTHON:
1678                         {
1679                                 FMod_Python *data= (FMod_Python *)fcm->data;
1680                                 data->script = newlibadr(fd, id->lib, data->script);
1681                         }
1682                                 break;
1683                 }
1684         }
1685 }
1686
1687 static void lib_link_fcurves(FileData *fd, ID *id, ListBase *list) 
1688 {
1689         FCurve *fcu;
1690         
1691         /* relink ID-block references... */
1692         for (fcu= list->first; fcu; fcu= fcu->next) {
1693                 /* driver data */
1694                 if (fcu->driver) {
1695                         ChannelDriver *driver= fcu->driver;
1696                         DriverTarget *dtar;
1697                         
1698                         for (dtar= driver->targets.first; dtar; dtar= dtar->next)
1699                                 dtar->id= newlibadr(fd, id->lib, dtar->id); 
1700                 }
1701                 
1702                 /* modifiers */
1703                 lib_link_fmodifiers(fd, id, &fcu->modifiers);
1704         }
1705 }
1706
1707
1708 /* NOTE: this assumes that link_list has already been called on the list */
1709 static void direct_link_fmodifiers(FileData *fd, ListBase *list)
1710 {
1711         FModifier *fcm;
1712         
1713         for (fcm= list->first; fcm; fcm= fcm->next) {
1714                 /* relink general data */
1715                 fcm->data = newdataadr(fd, fcm->data);
1716                 fcm->edata= NULL;
1717                 
1718                 /* do relinking of data for specific types */
1719                 switch (fcm->type) {
1720                         case FMODIFIER_TYPE_GENERATOR:
1721                         {
1722                                 FMod_Generator *data= (FMod_Generator *)fcm->data;
1723                                 
1724                                 data->coefficients= newdataadr(fd, data->coefficients);
1725                         }
1726                                 break;
1727                         case FMODIFIER_TYPE_ENVELOPE:
1728                         {
1729                                 FMod_Envelope *data= (FMod_Envelope *)fcm->data;
1730                                 
1731                                 data->data= newdataadr(fd, data->data);
1732                         }
1733                                 break;
1734                         case FMODIFIER_TYPE_PYTHON:
1735                         {
1736                                 FMod_Python *data= (FMod_Python *)fcm->data;
1737                                 
1738                                 data->prop = newdataadr(fd, data->prop);
1739                                 IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
1740                         }
1741                                 break;
1742                 }
1743         }
1744 }
1745
1746 /* NOTE: this assumes that link_list has already been called on the list */
1747 static void direct_link_fcurves(FileData *fd, ListBase *list)
1748 {
1749         FCurve *fcu;
1750         
1751         /* link F-Curve data to F-Curve again (non ID-libs) */
1752         for (fcu= list->first; fcu; fcu= fcu->next) {
1753                 /* curve data */
1754                 fcu->bezt= newdataadr(fd, fcu->bezt);
1755                 fcu->fpt= newdataadr(fd, fcu->fpt);
1756                 
1757                 /* rna path */
1758                 fcu->rna_path= newdataadr(fd, fcu->rna_path);
1759                 
1760                 /* group */
1761                 fcu->grp= newdataadr(fd, fcu->grp);
1762                 
1763                 /* driver */
1764                 fcu->driver= newdataadr(fd, fcu->driver);
1765                 if (fcu->driver) {
1766                         ChannelDriver *driver= fcu->driver;
1767                         DriverTarget *dtar;
1768                         
1769                         /* relink targets and their paths */
1770                         link_list(fd, &driver->targets);
1771                         for (dtar= driver->targets.first; dtar; dtar= dtar->next)
1772                                 dtar->rna_path= newdataadr(fd, dtar->rna_path);
1773                 }
1774                 
1775                 /* modifiers */
1776                 link_list(fd, &fcu->modifiers);
1777                 direct_link_fmodifiers(fd, &fcu->modifiers);
1778         }
1779 }
1780
1781
1782 static void lib_link_action(FileData *fd, Main *main)
1783 {
1784         bAction *act;
1785         bActionChannel *chan;
1786
1787         for (act= main->action.first; act; act= act->id.next) {
1788                 if (act->id.flag & LIB_NEEDLINK) {
1789                         act->id.flag -= LIB_NEEDLINK;
1790                         
1791 // XXX depreceated - old animation system <<<
1792                         for (chan=act->chanbase.first; chan; chan=chan->next) {
1793                                 chan->ipo= newlibadr_us(fd, act->id.lib, chan->ipo);
1794                                 lib_link_constraint_channels(fd, &act->id, &chan->constraintChannels);
1795                         }
1796 // >>> XXX depreceated - old animation system
1797                         
1798                         lib_link_fcurves(fd, &act->id, &act->curves);
1799                 }
1800         }
1801 }
1802
1803 static void direct_link_action(FileData *fd, bAction *act)
1804 {
1805         bActionChannel *achan; // XXX depreceated - old animation system
1806         bActionGroup *agrp;
1807
1808         link_list(fd, &act->curves);
1809         link_list(fd, &act->chanbase); // XXX depreceated - old animation system
1810         link_list(fd, &act->groups);
1811         link_list(fd, &act->markers);
1812
1813 // XXX depreceated - old animation system <<<
1814         for (achan = act->chanbase.first; achan; achan=achan->next) {
1815                 achan->grp= newdataadr(fd, achan->grp);
1816                 
1817                 link_list(fd, &achan->constraintChannels);
1818         }
1819 // >>> XXX depreceated - old animation system
1820
1821         direct_link_fcurves(fd, &act->curves);
1822         
1823         for (agrp = act->groups.first; agrp; agrp= agrp->next) {
1824                 agrp->channels.first= newdataadr(fd, agrp->channels.first);
1825                 agrp->channels.last= newdataadr(fd, agrp->channels.last);
1826         }
1827 }
1828
1829
1830 static void lib_link_nladata (FileData *fd, ID *id, ListBase *list)
1831 {
1832         NlaTrack *nlt;
1833         NlaStrip *strip;
1834         
1835         /* we only acare about the NLA strips inside the tracks */
1836         for (nlt= list->first; nlt; nlt= nlt->next) {
1837                 for (strip= nlt->strips.first; strip; strip= strip->next) {
1838                         /* reassign the counted-reference to action */
1839                         strip->act = newlibadr_us(fd, id->lib, strip->act);
1840                 }
1841         }
1842 }
1843
1844 /* NOTE: this assumes that link_list has already been called on the list */
1845 static void direct_link_nladata(FileData *fd, ListBase *list)
1846 {
1847         NlaTrack *nlt;
1848         NlaStrip *strip;
1849         
1850         for (nlt= list->first; nlt; nlt= nlt->next) {
1851                 /* relink list of strips */
1852                 link_list(fd, &nlt->strips);
1853                 
1854                 /* relink strip data */
1855                 for (strip= nlt->strips.first; strip; strip= strip->next) {
1856                         /* strip's F-Curves */
1857                         link_list(fd, &strip->fcurves);
1858                         direct_link_fcurves(fd, &strip->fcurves);
1859                         
1860                         /* strip's F-Modifiers */
1861                         link_list(fd, &strip->modifiers);
1862                         direct_link_fcurves(fd, &strip->modifiers);
1863                 }
1864         }
1865 }
1866
1867 /* ------- */
1868
1869 static void lib_link_keyingsets(FileData *fd, ID *id, ListBase *list)
1870 {
1871         KeyingSet *ks;
1872         KS_Path *ksp;
1873         
1874         /* here, we're only interested in the ID pointer stored in some of the paths */
1875         for (ks= list->first; ks; ks= ks->next) {
1876                 for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
1877                         ksp->id= newlibadr(fd, id->lib, ksp->id); 
1878                 }
1879         }
1880 }
1881
1882 /* NOTE: this assumes that link_list has already been called on the list */
1883 static void direct_link_keyingsets(FileData *fd, ListBase *list)
1884 {
1885         KeyingSet *ks;
1886         KS_Path *ksp;
1887         
1888         /* link KeyingSet data to KeyingSet again (non ID-libs) */
1889         for (ks= list->first; ks; ks= ks->next) {
1890                 /* paths */
1891                 link_list(fd, &ks->paths);
1892                 
1893                 for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
1894                         /* rna path */
1895                         ksp->rna_path= newdataadr(fd, ksp->rna_path);
1896                 }
1897         }
1898 }
1899
1900 /* ------- */
1901
1902 static void lib_link_animdata(FileData *fd, ID *id, AnimData *adt)
1903 {
1904         if (adt == NULL)
1905                 return;
1906         
1907         /* link action data */
1908         adt->action= newlibadr_us(fd, id->lib, adt->action);
1909         adt->tmpact= newlibadr_us(fd, id->lib, adt->tmpact);
1910         
1911         /* link drivers */
1912         lib_link_fcurves(fd, id, &adt->drivers);
1913         
1914         /* overrides don't have lib-link for now, so no need to do anything */
1915         
1916         /* link NLA-data */
1917         lib_link_nladata(fd, id, &adt->nla_tracks);
1918 }
1919
1920 static void direct_link_animdata(FileData *fd, AnimData *adt)
1921 {
1922         /* NOTE: must have called newdataadr already before doing this... */
1923         if (adt == NULL)
1924                 return;
1925         
1926         /* link drivers */
1927         link_list(fd, &adt->drivers);
1928         direct_link_fcurves(fd, &adt->drivers);
1929         
1930         /* link overrides */
1931         // TODO...
1932         
1933         /* link NLA-data */
1934         link_list(fd, &adt->nla_tracks);
1935         direct_link_nladata(fd, &adt->nla_tracks);
1936 }       
1937
1938 /* ************ READ NODE TREE *************** */
1939
1940 /* singe node tree (also used for material/scene trees), ntree is not NULL */
1941 static void lib_link_ntree(FileData *fd, ID *id, bNodeTree *ntree)
1942 {
1943         bNode *node;
1944         
1945         if(ntree->adt) lib_link_animdata(fd, &ntree->id, ntree->adt);
1946         
1947         for(node= ntree->nodes.first; node; node= node->next)
1948                 node->id= newlibadr_us(fd, id->lib, node->id);
1949 }
1950
1951 /* library ntree linking after fileread */
1952 static void lib_link_nodetree(FileData *fd, Main *main)
1953 {
1954         bNodeTree *ntree;
1955         
1956         /* only link ID pointers */
1957         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
1958                 if(ntree->id.flag & LIB_NEEDLINK) {
1959                         ntree->id.flag -= LIB_NEEDLINK;
1960                         lib_link_ntree(fd, &ntree->id, ntree);
1961                 }
1962         }
1963 }
1964
1965 /* verify types for nodes and groups, all data has to be read */
1966 /* open = 0: appending/linking, open = 1: open new file (need to clean out dynamic
1967 * typedefs*/
1968 static void lib_verify_nodetree(Main *main, int open)
1969 {
1970         Scene *sce;
1971         Material *ma;
1972         Tex *tx;
1973         bNodeTree *ntree;
1974         
1975         /* this crashes blender on undo/redo
1976                 if(open==1) {
1977                         reinit_nodesystem();
1978                 }*/
1979         
1980         /* now create the own typeinfo structs an verify nodes */
1981         /* here we still assume no groups in groups */
1982         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
1983                 ntreeVerifyTypes(ntree);        /* internal nodes, no groups! */
1984                 ntreeMakeOwnType(ntree);        /* for group usage */
1985         }
1986         
1987         /* now verify all types in material trees, groups are set OK now */
1988         for(ma= main->mat.first; ma; ma= ma->id.next) {
1989                 if(ma->nodetree)
1990                         ntreeVerifyTypes(ma->nodetree);
1991         }
1992         /* and scene trees */
1993         for(sce= main->scene.first; sce; sce= sce->id.next) {
1994                 if(sce->nodetree)
1995                         ntreeVerifyTypes(sce->nodetree);
1996         }
1997         /* and texture trees */
1998         for(tx= main->tex.first; tx; tx= tx->id.next) {
1999                 if(tx->nodetree)
2000                         ntreeVerifyTypes(tx->nodetree);
2001         }
2002 }
2003
2004
2005
2006 /* ntree itself has been read! */
2007 static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
2008 {
2009         /* note: writing and reading goes in sync, for speed */
2010         bNode *node;
2011         bNodeSocket *sock;
2012         bNodeLink *link;
2013         
2014         ntree->init= 0;         /* to set callbacks and force setting types */
2015         ntree->owntype= NULL;
2016         ntree->timecursor= NULL;
2017         
2018         ntree->adt= newdataadr(fd, ntree->adt);
2019         direct_link_animdata(fd, ntree->adt);
2020         
2021         link_list(fd, &ntree->nodes);
2022         for(node= ntree->nodes.first; node; node= node->next) {
2023                 if(node->type == NODE_DYNAMIC) {
2024                         node->custom1= 0;
2025                         node->custom1= BSET(node->custom1, NODE_DYNAMIC_LOADED);
2026                         node->typeinfo= NULL;
2027                 }
2028                 
2029                 node->storage= newdataadr(fd, node->storage);
2030                 if(node->storage) {
2031                         
2032                         /* could be handlerized at some point */
2033                         if(ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
2034                                 direct_link_curvemapping(fd, node->storage);
2035                         else if(ntree->type==NTREE_COMPOSIT) {
2036                                 if( ELEM3(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB))
2037                                         direct_link_curvemapping(fd, node->storage);
2038                                 else if(ELEM3(node->type, CMP_NODE_IMAGE, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
2039                                         ((ImageUser *)node->storage)->ok= 1;
2040                         }
2041                         else if( ntree->type==NTREE_TEXTURE && (node->type==TEX_NODE_CURVE_RGB || node->type==TEX_NODE_CURVE_TIME) ) {
2042                                 direct_link_curvemapping(fd, node->storage);
2043                         }
2044                 }
2045                 link_list(fd, &node->inputs);
2046                 link_list(fd, &node->outputs);
2047         }
2048         link_list(fd, &ntree->links);
2049         
2050         /* and we connect the rest */
2051         for(node= ntree->nodes.first; node; node= node->next) {
2052                 node->preview= newimaadr(fd, node->preview);
2053                 node->lasty= 0;
2054                 for(sock= node->inputs.first; sock; sock= sock->next)
2055                         sock->link= newdataadr(fd, sock->link);
2056                 for(sock= node->outputs.first; sock; sock= sock->next)
2057                         sock->ns.data= NULL;
2058         }
2059         for(link= ntree->links.first; link; link= link->next) {
2060                 link->fromnode= newdataadr(fd, link->fromnode);
2061                 link->tonode= newdataadr(fd, link->tonode);
2062                 link->fromsock= newdataadr(fd, link->fromsock);
2063                 link->tosock= newdataadr(fd, link->tosock);
2064         }
2065         
2066         /* set selin and selout */
2067         for(node= ntree->nodes.first; node; node= node->next) {
2068                 for(sock= node->inputs.first; sock; sock= sock->next) {
2069                         if(sock->flag & SOCK_SEL) {
2070                                 ntree->selin= sock;
2071                                 break;
2072                         }
2073                 }
2074                 for(sock= node->outputs.first; sock; sock= sock->next) {
2075                         if(sock->flag & SOCK_SEL) {
2076                                 ntree->selout= sock;
2077                                 break;
2078                         }
2079                 }
2080         }
2081         
2082         /* type verification is in lib-link */
2083 }
2084
2085 /* ************ READ ARMATURE ***************** */
2086
2087 static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
2088 {
2089         bConstraint *con;
2090
2091         for (con = conlist->first; con; con=con->next) {
2092                 /* patch for error introduced by changing constraints (dunno how) */
2093                 /* if con->data type changes, dna cannot resolve the pointer! (ton) */
2094                 if(con->data==NULL) {
2095                         con->type= CONSTRAINT_TYPE_NULL;
2096                 }
2097                 /* own ipo, all constraints have it */
2098                 con->ipo= newlibadr_us(fd, id->lib, con->ipo); // XXX depreceated - old animation system
2099                 
2100                 switch (con->type) {
2101                 case CONSTRAINT_TYPE_PYTHON:
2102                         {
2103                                 bPythonConstraint *data= (bPythonConstraint*)con->data;
2104                                 bConstraintTarget *ct;
2105                                 
2106                                 for (ct= data->targets.first; ct; ct= ct->next)
2107                                         ct->tar = newlibadr(fd, id->lib, ct->tar);
2108                                         
2109                                 data->text = newlibadr(fd, id->lib, data->text);
2110                                 //IDP_LibLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2111                         }
2112                         break;
2113                 case CONSTRAINT_TYPE_ACTION:
2114                         {
2115                                 bActionConstraint *data;
2116                                 data= ((bActionConstraint*)con->data);
2117                                 data->tar = newlibadr(fd, id->lib, data->tar);
2118                                 data->act = newlibadr(fd, id->lib, data->act);
2119                         }
2120                         break;
2121                 case CONSTRAINT_TYPE_LOCLIKE:
2122                         {
2123                                 bLocateLikeConstraint *data;
2124                                 data= ((bLocateLikeConstraint*)con->data);
2125                                 data->tar = newlibadr(fd, id->lib, data->tar);
2126                         }
2127                         break;
2128                 case CONSTRAINT_TYPE_ROTLIKE:
2129                         {
2130                                 bRotateLikeConstraint *data;
2131                                 data= ((bRotateLikeConstraint*)con->data);
2132                                 data->tar = newlibadr(fd, id->lib, data->tar);
2133                         }
2134                         break;
2135                 case CONSTRAINT_TYPE_SIZELIKE:
2136                         {
2137                                 bSizeLikeConstraint *data;
2138                                 data= ((bSizeLikeConstraint*)con->data);
2139                                 data->tar = newlibadr(fd, id->lib, data->tar);
2140                         }
2141                         break;
2142                 case CONSTRAINT_TYPE_KINEMATIC:
2143                         {
2144                                 bKinematicConstraint *data;
2145                                 data = ((bKinematicConstraint*)con->data);
2146                                 data->tar = newlibadr(fd, id->lib, data->tar);
2147                                 data->poletar = newlibadr(fd, id->lib, data->poletar);
2148                         }
2149                         break;
2150                 case CONSTRAINT_TYPE_TRACKTO:
2151                         {
2152                                 bTrackToConstraint *data;
2153                                 data = ((bTrackToConstraint*)con->data);
2154                                 data->tar = newlibadr(fd, id->lib, data->tar);
2155                         }
2156                         break;
2157                 case CONSTRAINT_TYPE_MINMAX:
2158                         {
2159                                 bMinMaxConstraint *data;
2160                                 data = ((bMinMaxConstraint*)con->data);
2161                                 data->tar = newlibadr(fd, id->lib, data->tar);
2162                         }
2163                         break;
2164                 case CONSTRAINT_TYPE_LOCKTRACK:
2165                         {
2166                                 bLockTrackConstraint *data;
2167                                 data= ((bLockTrackConstraint*)con->data);
2168                                 data->tar = newlibadr(fd, id->lib, data->tar);
2169                         }
2170                         break;
2171                 case CONSTRAINT_TYPE_FOLLOWPATH:
2172                         {
2173                                 bFollowPathConstraint *data;
2174                                 data= ((bFollowPathConstraint*)con->data);
2175                                 data->tar = newlibadr(fd, id->lib, data->tar);
2176                         }
2177                         break;
2178                 case CONSTRAINT_TYPE_STRETCHTO:
2179                         {
2180                                 bStretchToConstraint *data;
2181                                 data= ((bStretchToConstraint*)con->data);
2182                                 data->tar = newlibadr(fd, id->lib, data->tar);
2183                         }
2184                         break;
2185                 case CONSTRAINT_TYPE_RIGIDBODYJOINT:
2186                         {
2187                                 bRigidBodyJointConstraint *data;
2188                                 data= ((bRigidBodyJointConstraint*)con->data);
2189                                 data->tar = newlibadr(fd, id->lib, data->tar);
2190                         }
2191                         break;
2192                 case CONSTRAINT_TYPE_CLAMPTO:
2193                         {
2194                                 bClampToConstraint *data;
2195                                 data= ((bClampToConstraint*)con->data);
2196                                 data->tar = newlibadr(fd, id->lib, data->tar);
2197                         }
2198                         break;
2199                 case CONSTRAINT_TYPE_CHILDOF:
2200                         {
2201                                 bChildOfConstraint *data;
2202                                 data= ((bChildOfConstraint*)con->data);
2203                                 data->tar = newlibadr(fd, id->lib, data->tar);
2204                         }
2205                         break;
2206                 case CONSTRAINT_TYPE_TRANSFORM:
2207                         {
2208                                 bTransformConstraint *data;
2209                                 data= ((bTransformConstraint*)con->data);
2210                                 data->tar = newlibadr(fd, id->lib, data->tar);
2211                         }
2212                         break;
2213                 case CONSTRAINT_TYPE_DISTLIMIT:
2214                         {
2215                                 bDistLimitConstraint *data;
2216                                 data= ((bDistLimitConstraint*)con->data);
2217                                 data->tar = newlibadr(fd, id->lib, data->tar);
2218                         }
2219                         break;
2220                 case CONSTRAINT_TYPE_SHRINKWRAP:
2221                         {
2222                                 bShrinkwrapConstraint *data;
2223                                 data= ((bShrinkwrapConstraint*)con->data);
2224                                 data->target = newlibadr(fd, id->lib, data->target);
2225                         }
2226                         break;
2227                 case CONSTRAINT_TYPE_NULL:
2228                         break;
2229                 }
2230         }
2231 }
2232
2233 static void direct_link_constraints(FileData *fd, ListBase *lb)
2234 {
2235         bConstraint *cons;
2236
2237         link_list(fd, lb);
2238         for (cons=lb->first; cons; cons=cons->next) {
2239                 cons->data = newdataadr(fd, cons->data);
2240                 
2241                 if (cons->type == CONSTRAINT_TYPE_PYTHON) {
2242                         bPythonConstraint *data= cons->data;
2243                         
2244                         link_list(fd, &data->targets);
2245                         
2246                         data->prop = newdataadr(fd, data->prop);
2247                         if (data->prop)
2248                                 IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2249                 }
2250         }
2251 }
2252
2253 static void lib_link_pose(FileData *fd, Object *ob, bPose *pose)
2254 {
2255         bPoseChannel *pchan;
2256         bArmature *arm= ob->data;
2257         int rebuild;
2258         
2259         if (!pose || !arm)
2260                 return;
2261         
2262         /* always rebuild to match proxy or lib changes */
2263         rebuild= ob->proxy || (ob->id.lib==NULL && arm->id.lib);
2264
2265         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
2266                 lib_link_constraints(fd, (ID *)ob, &pchan->constraints);
2267                 
2268                 /* hurms... loop in a loop, but yah... later... (ton) */
2269                 pchan->bone= get_named_bone(arm, pchan->name);
2270                 
2271                 pchan->custom= newlibadr(fd, arm->id.lib, pchan->custom);
2272                 if(pchan->bone==NULL)
2273                         rebuild= 1;
2274                 else if(ob->id.lib==NULL && arm->id.lib) {
2275                         /* local pose selection copied to armature, bit hackish */
2276                         pchan->bone->flag &= ~(BONE_SELECTED|BONE_ACTIVE);
2277                         pchan->bone->flag |= pchan->selectflag;
2278                 }
2279         }
2280         
2281         if(rebuild) {
2282                 ob->recalc= OB_RECALC;
2283                 pose->flag |= POSE_RECALC;
2284         }
2285 }
2286
2287 static void lib_link_armature(FileData *fd, Main *main)
2288 {
2289         bArmature *arm;
2290
2291         arm= main->armature.first;
2292
2293         while(arm) {
2294                 if(arm->id.flag & LIB_NEEDLINK) {
2295                         arm->id.flag -= LIB_NEEDLINK;
2296                 }
2297                 arm= arm->id.next;
2298         }
2299 }
2300
2301 static void direct_link_bones(FileData *fd, Bone* bone)
2302 {
2303         Bone    *child;
2304
2305         bone->parent= newdataadr(fd, bone->parent);
2306
2307         link_list(fd, &bone->childbase);
2308
2309         for (child=bone->childbase.first; child; child=child->next) {
2310                 direct_link_bones(fd, child);
2311         }
2312 }
2313
2314 static void direct_link_armature(FileData *fd, bArmature *arm)
2315 {
2316         Bone    *bone;
2317
2318         link_list(fd, &arm->bonebase);
2319         arm->edbo= NULL;
2320         
2321         bone=arm->bonebase.first;
2322         while (bone) {
2323                 direct_link_bones(fd, bone);
2324                 bone=bone->next;
2325         }
2326 }
2327
2328 /* ************ READ CAMERA ***************** */
2329
2330 static void lib_link_camera(FileData *fd, Main *main)
2331 {
2332         Camera *ca;
2333
2334         ca= main->camera.first;
2335         while(ca) {
2336                 if(ca->id.flag & LIB_NEEDLINK) {
2337                         if (ca->adt) lib_link_animdata(fd, &ca->id, ca->adt);
2338                         
2339                         ca->ipo= newlibadr_us(fd, ca->id.lib, ca->ipo); // XXX depreceated - old animation system
2340                         
2341                         ca->dof_ob= newlibadr_us(fd, ca->id.lib, ca->dof_ob);
2342                         
2343                         lib_link_scriptlink(fd, &ca->id, &ca->scriptlink);
2344                         
2345                         ca->id.flag -= LIB_NEEDLINK;
2346                 }
2347                 ca= ca->id.next;
2348         }
2349 }
2350
2351 static void direct_link_camera(FileData *fd, Camera *ca)
2352 {
2353         ca->adt= newdataadr(fd, ca->adt);
2354         direct_link_animdata(fd, ca->adt);
2355         
2356         direct_link_scriptlink(fd, &ca->scriptlink);
2357 }
2358
2359
2360 /* ************ READ LAMP ***************** */
2361
2362 static void lib_link_lamp(FileData *fd, Main *main)
2363 {
2364         Lamp *la;
2365         MTex *mtex;
2366         int a;
2367
2368         la= main->lamp.first;
2369         while(la) {
2370                 if(la->id.flag & LIB_NEEDLINK) {
2371                         if (la->adt) lib_link_animdata(fd, &la->id, la->adt);
2372                         
2373                         for(a=0; a<MAX_MTEX; a++) {
2374                                 mtex= la->mtex[a];
2375                                 if(mtex) {
2376                                         mtex->tex= newlibadr_us(fd, la->id.lib, mtex->tex);
2377                                         mtex->object= newlibadr(fd, la->id.lib, mtex->object);
2378                                 }
2379                         }
2380                         
2381                         la->ipo= newlibadr_us(fd, la->id.lib, la->ipo); // XXX depreceated - old animation system
2382                         
2383                         lib_link_scriptlink(fd, &la->id, &la->scriptlink);
2384                         
2385                         la->id.flag -= LIB_NEEDLINK;
2386                 }
2387                 la= la->id.next;
2388         }
2389 }
2390
2391 static void direct_link_lamp(FileData *fd, Lamp *la)
2392 {
2393         int a;
2394         
2395         la->adt= newdataadr(fd, la->adt);
2396         direct_link_animdata(fd, la->adt);
2397         
2398         direct_link_scriptlink(fd, &la->scriptlink);
2399
2400         for(a=0; a<MAX_MTEX; a++) {
2401                 la->mtex[a]= newdataadr(fd, la->mtex[a]);
2402         }
2403         
2404         la->curfalloff= newdataadr(fd, la->curfalloff);
2405         if(la->curfalloff)
2406                 direct_link_curvemapping(fd, la->curfalloff);
2407         
2408         la->preview = direct_link_preview_image(fd, la->preview);
2409 }
2410
2411 /* ************ READ keys ***************** */
2412
2413 static void lib_link_key(FileData *fd, Main *main)
2414 {
2415         Key *key;
2416
2417         key= main->key.first;
2418         while(key) {
2419                 if(key->id.flag & LIB_NEEDLINK) {
2420                         if(key->adt) lib_link_animdata(fd, &key->id, key->adt);
2421                         
2422                         key->ipo= newlibadr_us(fd, key->id.lib, key->ipo); // XXX depreceated - old animation system
2423                         key->from= newlibadr(fd, key->id.lib, key->from);
2424
2425                         key->id.flag -= LIB_NEEDLINK;
2426                 }
2427                 key= key->id.next;
2428         }
2429 }
2430
2431 static void switch_endian_keyblock(Key *key, KeyBlock *kb)
2432 {
2433         int elemsize, a, b;
2434         char *data, *poin, *cp;
2435
2436         elemsize= key->elemsize;
2437         data= kb->data;
2438
2439         for(a=0; a<kb->totelem; a++) {
2440
2441                 cp= key->elemstr;
2442                 poin= data;
2443
2444                 while( cp[0] ) {        /* cp[0]==amount */
2445
2446                         switch(cp[1]) {         /* cp[1]= type */
2447                         case IPO_FLOAT:
2448                         case IPO_BPOINT:
2449                         case IPO_BEZTRIPLE:
2450                                 b= cp[0];
2451                                 while(b--) {
2452                                         SWITCH_INT((*poin));
2453                                         poin+= 4;
2454                                 }
2455                                 break;
2456                         }
2457
2458                         cp+= 2;
2459
2460                 }
2461                 data+= elemsize;
2462         }
2463 }
2464
2465 static void direct_link_key(FileData *fd, Key *key)
2466 {
2467         KeyBlock *kb;
2468
2469         link_list(fd, &(key->block));
2470
2471         key->adt= newdataadr(fd, key->adt);
2472         direct_link_animdata(fd, key->adt);
2473         
2474         key->refkey= newdataadr(fd, key->refkey);
2475
2476         kb= key->block.first;
2477         while(kb) {
2478
2479                 kb->data= newdataadr(fd, kb->data);
2480
2481                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN)
2482                         switch_endian_keyblock(key, kb);
2483
2484                 kb= kb->next;
2485         }
2486 }
2487
2488 /* ************ READ mball ***************** */
2489
2490 static void lib_link_mball(FileData *fd, Main *main)
2491 {
2492         MetaBall *mb;
2493         int a;
2494
2495         mb= main->mball.first;
2496         while(mb) {
2497                 if(mb->id.flag & LIB_NEEDLINK) {
2498
2499                         for(a=0; a<mb->totcol; a++) mb->mat[a]= newlibadr_us(fd, mb->id.lib, mb->mat[a]);
2500
2501                         mb->ipo= newlibadr_us(fd, mb->id.lib, mb->ipo); // XXX depreceated - old animation system
2502
2503                         mb->id.flag -= LIB_NEEDLINK;
2504                 }
2505                 mb= mb->id.next;
2506         }
2507 }
2508
2509 static void direct_link_mball(FileData *fd, MetaBall *mb)
2510 {
2511         mb->mat= newdataadr(fd, mb->mat);
2512         test_pointer_array(fd, (void **)&mb->mat);
2513
2514         link_list(fd, &(mb->elems));
2515
2516         mb->disp.first= mb->disp.last= NULL;
2517         mb->editelems= NULL;
2518         mb->bb= NULL;
2519 }
2520
2521 /* ************ READ WORLD ***************** */
2522
2523 static void lib_link_world(FileData *fd, Main *main)
2524 {
2525         World *wrld;
2526         MTex *mtex;
2527         int a;
2528
2529         wrld= main->world.first;
2530         while(wrld) {
2531                 if(wrld->id.flag & LIB_NEEDLINK) {
2532                         if (wrld->adt) lib_link_animdata(fd, &wrld->id, wrld->adt);
2533                         
2534                         wrld->ipo= newlibadr_us(fd, wrld->id.lib, wrld->ipo); // XXX depreceated - old animation system
2535                         
2536                         for(a=0; a<MAX_MTEX; a++) {
2537                                 mtex= wrld->mtex[a];
2538                                 if(mtex) {
2539                                         mtex->tex= newlibadr_us(fd, wrld->id.lib, mtex->tex);
2540                                         mtex->object= newlibadr(fd, wrld->id.lib, mtex->object);
2541                                 }
2542                         }
2543                         
2544                         lib_link_scriptlink(fd, &wrld->id, &wrld->scriptlink);
2545                         
2546                         wrld->id.flag -= LIB_NEEDLINK;
2547                 }
2548                 wrld= wrld->id.next;
2549         }
2550 }
2551
2552 static void direct_link_world(FileData *fd, World *wrld)
2553 {
2554         int a;
2555
2556         wrld->adt= newdataadr(fd, wrld->adt);
2557         direct_link_animdata(fd, wrld->adt);
2558         
2559         direct_link_scriptlink(fd, &wrld->scriptlink);
2560
2561         for(a=0; a<MAX_MTEX; a++) {
2562                 wrld->mtex[a]= newdataadr(fd, wrld->mtex[a]);
2563         }
2564         wrld->preview = direct_link_preview_image(fd, wrld->preview);
2565 }
2566
2567
2568 /* ************ READ VFONT ***************** */
2569
2570 static void lib_link_vfont(FileData *fd, Main *main)
2571 {
2572         VFont *vf;
2573
2574         vf= main->vfont.first;
2575         while(vf) {
2576                 if(vf->id.flag & LIB_NEEDLINK) {
2577                         vf->id.flag -= LIB_NEEDLINK;
2578                 }
2579                 vf= vf->id.next;
2580         }
2581 }
2582
2583 static void direct_link_vfont(FileData *fd, VFont *vf)
2584 {
2585         vf->data= NULL;
2586         vf->packedfile= direct_link_packedfile(fd, vf->packedfile);
2587 }
2588
2589 /* ************ READ TEXT ****************** */
2590
2591 static void lib_link_text(FileData *fd, Main *main)
2592 {
2593         Text *text;
2594
2595         text= main->text.first;
2596         while(text) {
2597                 if(text->id.flag & LIB_NEEDLINK) {
2598                         text->id.flag -= LIB_NEEDLINK;
2599                 }
2600                 text= text->id.next;
2601         }
2602 }
2603
2604 static void direct_link_text(FileData *fd, Text *text)
2605 {
2606         TextLine *ln;
2607
2608         text->name= newdataadr(fd, text->name);
2609
2610         text->undo_pos= -1;
2611         text->undo_len= TXT_INIT_UNDO;
2612         text->undo_buf= MEM_mallocN(text->undo_len, "undo buf");
2613
2614         text->compiled= NULL;
2615
2616 /*
2617         if(text->flags & TXT_ISEXT) {
2618                 reopen_text(text);
2619         } else {
2620 */
2621
2622         link_list(fd, &text->lines);
2623         link_list(fd, &text->markers);
2624
2625         text->curl= newdataadr(fd, text->curl);
2626         text->sell= newdataadr(fd, text->sell);
2627
2628         ln= text->lines.first;
2629         while(ln) {
2630                 ln->line= newdataadr(fd, ln->line);
2631                 ln->format= NULL;
2632                 
2633                 if (ln->len != (int) strlen(ln->line)) {
2634                         printf("Error loading text, line lengths differ\n");
2635                         ln->len = strlen(ln->line);
2636                 }
2637
2638                 ln= ln->next;
2639         }
2640
2641         text->flags = (text->flags) & ~TXT_ISEXT;
2642
2643         text->id.us= 1;
2644 }
2645
2646 /* ************ READ IMAGE ***************** */
2647
2648 static void lib_link_image(FileData *fd, Main *main)
2649 {
2650         Image *ima;
2651
2652         ima= main->image.first;
2653         while (ima) {
2654                 if(ima->id.flag & LIB_NEEDLINK) {
2655                         if (ima->id.properties) IDP_LibLinkProperty(ima->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2656
2657                         ima->id.flag -= LIB_NEEDLINK;
2658                 }
2659                 ima= ima->id.next;
2660         }
2661 }
2662
2663 static void link_ibuf_list(FileData *fd, ListBase *lb)
2664 {
2665         Link *ln, *prev;
2666         
2667         if(lb->first==NULL) return;
2668         
2669         lb->first= newimaadr(fd, lb->first);
2670         ln= lb->first;
2671         prev= NULL;
2672         while(ln) {
2673                 ln->next= newimaadr(fd, ln->next);
2674                 ln->prev= prev;
2675                 prev= ln;
2676                 ln= ln->next;
2677         }
2678         lb->last= prev;
2679 }
2680
2681 static void direct_link_image(FileData *fd, Image *ima)
2682 {
2683         /* for undo system, pointers could be restored */
2684         if(fd->imamap)
2685                 link_ibuf_list(fd, &ima->ibufs);
2686         else
2687                 ima->ibufs.first= ima->ibufs.last= NULL;
2688         
2689         /* if not restored, we keep the binded opengl index */
2690         if(ima->ibufs.first==NULL) {
2691                 ima->bindcode= 0;
2692                 ima->gputexture= NULL;
2693         }
2694         
2695         ima->anim= NULL;
2696         ima->rr= NULL;
2697         ima->repbind= NULL;
2698         
2699         ima->packedfile = direct_link_packedfile(fd, ima->packedfile);
2700         ima->preview = direct_link_preview_image(fd, ima->preview);
2701         ima->ok= 1;
2702 }
2703
2704
2705 /* ************ READ CURVE ***************** */
2706
2707 static void lib_link_curve(FileData *fd, Main *main)
2708 {
2709         Curve *cu;
2710         int a;
2711
2712         cu= main->curve.first;
2713         while(cu) {
2714                 if(cu->id.flag & LIB_NEEDLINK) {
2715                         if(cu->adt) lib_link_animdata(fd, &cu->id, cu->adt);
2716
2717                         for(a=0; a<cu->totcol; a++) cu->mat[a]= newlibadr_us(fd, cu->id.lib, cu->mat[a]);
2718
2719                         cu->bevobj= newlibadr(fd, cu->id.lib, cu->bevobj);
2720                         cu->taperobj= newlibadr(fd, cu->id.lib, cu->taperobj);
2721                         cu->textoncurve= newlibadr(fd, cu->id.lib, cu->textoncurve);
2722                         cu->vfont= newlibadr_us(fd, cu->id.lib, cu->vfont);
2723                         cu->vfontb= newlibadr_us(fd, cu->id.lib, cu->vfontb);                   
2724                         cu->vfonti= newlibadr_us(fd, cu->id.lib, cu->vfonti);
2725                         cu->vfontbi= newlibadr_us(fd, cu->id.lib, cu->vfontbi);
2726
2727                         cu->ipo= newlibadr_us(fd, cu->id.lib, cu->ipo); // XXX depreceated - old animation system
2728                         cu->key= newlibadr_us(fd, cu->id.lib, cu->key);
2729
2730                         cu->id.flag -= LIB_NEEDLINK;
2731                 }
2732                 cu= cu->id.next;
2733         }
2734 }
2735
2736
2737 static void switch_endian_knots(Nurb *nu)
2738 {
2739         int len;
2740
2741         if(nu->knotsu) {
2742                 len= KNOTSU(nu);
2743                 while(len--) {
2744                         SWITCH_INT(nu->knotsu[len]);
2745                 }
2746         }
2747         if(nu->knotsv) {
2748                 len= KNOTSV(nu);
2749                 while(len--) {
2750                         SWITCH_INT(nu->knotsv[len]);
2751                 }
2752         }
2753 }
2754
2755 static void direct_link_curve(FileData *fd, Curve *cu)
2756 {
2757         Nurb *nu;
2758         TextBox *tb;
2759         
2760         cu->adt= newdataadr(fd, cu->adt);
2761         direct_link_animdata(fd, cu->adt);
2762         
2763         cu->mat= newdataadr(fd, cu->mat);
2764         test_pointer_array(fd, (void **)&cu->mat);
2765         cu->str= newdataadr(fd, cu->str);
2766         cu->strinfo= newdataadr(fd, cu->strinfo);       
2767         cu->tb= newdataadr(fd, cu->tb);
2768
2769         if(cu->vfont==0) link_list(fd, &(cu->nurb));
2770         else {
2771                 cu->nurb.first=cu->nurb.last= 0;
2772
2773                 tb= MEM_callocN(MAXTEXTBOX*sizeof(TextBox), "TextBoxread");
2774                 if (cu->tb) {
2775                         memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox));
2776                         MEM_freeN(cu->tb);
2777                         cu->tb= tb;                     
2778                 } else {
2779                         cu->totbox = 1;
2780                         cu->actbox = 1;
2781                         cu->tb = tb;
2782                         cu->tb[0].w = cu->linewidth;
2783                 }               
2784                 if (cu->wordspace == 0.0) cu->wordspace = 1.0;
2785         }
2786
2787         cu->bev.first=cu->bev.last= NULL;
2788         cu->disp.first=cu->disp.last= NULL;
2789         cu->editnurb= NULL;
2790         cu->lastselbp= NULL;
2791         cu->path= NULL;
2792         cu->editfont= NULL;
2793         
2794         nu= cu->nurb.first;
2795         while(nu) {
2796                 nu->bezt= newdataadr(fd, nu->bezt);
2797                 nu->bp= newdataadr(fd, nu->bp);
2798                 nu->knotsu= newdataadr(fd, nu->knotsu);
2799                 nu->knotsv= newdataadr(fd, nu->knotsv);
2800                 if (cu->vfont==0) nu->charidx= nu->mat_nr;
2801
2802                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2803                         switch_endian_knots(nu);
2804                 }
2805
2806                 nu= nu->next;
2807         }
2808         cu->bb= NULL;
2809 }
2810
2811 /* ************ READ TEX ***************** */
2812
2813 static void lib_link_texture(FileData *fd, Main *main)
2814 {
2815         Tex *tex;
2816
2817         tex= main->tex.first;
2818         while(tex) {
2819                 if(tex->id.flag & LIB_NEEDLINK) {
2820                         if(tex->adt) lib_link_animdata(fd, &tex->id, tex->adt);
2821
2822                         tex->ima= newlibadr_us(fd, tex->id.lib, tex->ima);
2823                         tex->ipo= newlibadr_us(fd, tex->id.lib, tex->ipo);
2824                         if(tex->env) tex->env->object= newlibadr(fd, tex->id.lib, tex->env->object);
2825
2826                         if(tex->nodetree)
2827                                 lib_link_ntree(fd, &tex->id, tex->nodetree);
2828                         
2829                         tex->id.flag -= LIB_NEEDLINK;
2830                 }
2831                 tex= tex->id.next;
2832         }
2833 }
2834
2835 static void direct_link_texture(FileData *fd, Tex *tex)
2836 {
2837         tex->adt= newdataadr(fd, tex->adt);
2838         direct_link_animdata(fd, tex->adt);
2839         
2840         tex->plugin= newdataadr(fd, tex->plugin);
2841         if(tex->plugin) {
2842                 tex->plugin->handle= 0;
2843                 open_plugin_tex(tex->plugin);
2844                 /* initialize data for this instance, if an initialization
2845                  * function exists.
2846                  */
2847                 if (tex->plugin->instance_init)
2848                         tex->plugin->instance_init((void *) tex->plugin->data);
2849         }
2850         tex->coba= newdataadr(fd, tex->coba);
2851         tex->env= newdataadr(fd, tex->env);
2852         if(tex->env) {
2853                 tex->env->ima= NULL;
2854                 memset(tex->env->cube, 0, 6*sizeof(void *));
2855                 tex->env->ok= 0;
2856         }
2857         
2858         tex->nodetree= newdataadr(fd, tex->nodetree);
2859         if(tex->nodetree)
2860                 direct_link_nodetree(fd, tex->nodetree);
2861         
2862         tex->preview = direct_link_preview_image(fd, tex->preview);
2863
2864         tex->iuser.ok= 1;
2865 }
2866
2867
2868
2869 /* ************ READ MATERIAL ***************** */
2870
2871 static void lib_link_material(FileData *fd, Main *main)
2872 {
2873         Material *ma;
2874         MTex *mtex;
2875         int a;
2876
2877         ma= main->mat.first;
2878         while(ma) {
2879                 if(ma->id.flag & LIB_NEEDLINK) {
2880                         if(ma->adt) lib_link_animdata(fd, &ma->id, ma->adt);
2881
2882                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
2883                         of library blocks that implement this.*/
2884                         if (ma->id.properties) IDP_LibLinkProperty(ma->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2885
2886                         ma->ipo= newlibadr_us(fd, ma->id.lib, ma->ipo);
2887                         ma->group= newlibadr_us(fd, ma->id.lib, ma->group);
2888                         
2889                         for(a=0; a<MAX_MTEX; a++) {
2890                                 mtex= ma->mtex[a];
2891                                 if(mtex) {
2892                                         mtex->tex= newlibadr_us(fd, ma->id.lib, mtex->tex);
2893                                         mtex->object= newlibadr(fd, ma->id.lib, mtex->object);
2894                                 }
2895                         }
2896                         lib_link_scriptlink(fd, &ma->id, &ma->scriptlink);
2897                         
2898                         if(ma->nodetree)
2899                                 lib_link_ntree(fd, &ma->id, ma->nodetree);
2900                         
2901                         ma->id.flag -= LIB_NEEDLINK;
2902                 }
2903                 ma= ma->id.next;
2904         }
2905 }
2906
2907 static void direct_link_material(FileData *fd, Material *ma)
2908 {
2909         int a;
2910
2911         ma->adt= newdataadr(fd, ma->adt);
2912         direct_link_animdata(fd, ma->adt);
2913         
2914         for(a=0; a<MAX_MTEX; a++) {
2915                 ma->mtex[a]= newdataadr(fd, ma->mtex[a]);
2916         }
2917
2918         ma->ramp_col= newdataadr(fd, ma->ramp_col);
2919         ma->ramp_spec= newdataadr(fd, ma->ramp_spec);
2920         
2921         direct_link_scriptlink(fd, &ma->scriptlink);
2922         
2923         ma->nodetree= newdataadr(fd, ma->nodetree);
2924         if(ma->nodetree)
2925                 direct_link_nodetree(fd, ma->nodetree);
2926
2927         ma->preview = direct_link_preview_image(fd, ma->preview);
2928         ma->gpumaterial.first = ma->gpumaterial.last = NULL;
2929 }
2930
2931 /* ************ READ PARTICLE SETTINGS ***************** */
2932
2933 static void direct_link_pointcache(FileData *fd, PointCache *cache)
2934 {
2935         cache->flag &= ~(PTCACHE_SIMULATION_VALID|PTCACHE_BAKE_EDIT_ACTIVE);
2936         cache->simframe= 0;
2937 }
2938
2939 static void lib_link_particlesettings(FileData *fd, Main *main)
2940 {
2941         ParticleSettings *part;
2942
2943         part= main->particle.first;
2944         while(part) {
2945                 if(part->id.flag & LIB_NEEDLINK) {
2946                         part->ipo= newlibadr_us(fd, part->id.lib, part->ipo); // XXX depreceated - old animation system
2947                         part->dup_ob = newlibadr(fd, part->id.lib, part->dup_ob);
2948                         part->dup_group = newlibadr(fd, part->id.lib, part->dup_group);
2949                         part->eff_group = newlibadr(fd, part->id.lib, part->eff_group);
2950                         part->bb_ob = newlibadr(fd, part->id.lib, part->bb_ob);
2951                         part->id.flag -= LIB_NEEDLINK;
2952                 }
2953                 part= part->id.next;
2954         }
2955 }
2956
2957 static void direct_link_particlesettings(FileData *fd, ParticleSettings *part)
2958 {
2959         part->pd= newdataadr(fd, part->pd);
2960         part->pd2= newdataadr(fd, part->pd2);
2961 }
2962
2963 static void lib_link_particlesystems(FileData *fd, Object *ob, ID *id, ListBase *particles)
2964 {
2965         ParticleSystem *psys, *psysnext;
2966         int a;
2967
2968         for(psys=particles->first; psys; psys=psysnext){
2969                 ParticleData *pa;
2970                 
2971                 psysnext= psys->next;
2972                 
2973                 psys->part = newlibadr_us(fd, id->lib, psys->part);
2974                 if(psys->part) {
2975                         psys->target_ob = newlibadr(fd, id->lib, psys->target_ob);
2976                         psys->keyed_ob = newlibadr(fd, id->lib, psys->keyed_ob);
2977
2978                         for(a=0,pa=psys->particles; a<psys->totpart; a++,pa++){
2979                                 pa->stick_ob=newlibadr(fd, id->lib, pa->stick_ob);
2980                         }
2981                 }
2982                 else {
2983                         /* particle modifier must be removed before particle system */
2984                         ParticleSystemModifierData *psmd= psys_get_modifier(ob,psys);
2985                         BLI_remlink(&ob->modifiers, psmd);
2986                         modifier_free((ModifierData *)psmd);
2987
2988                         BLI_remlink(particles, psys);
2989                         MEM_freeN(psys);
2990                 }
2991         }
2992 }
2993 static void direct_link_particlesystems(FileData *fd, ListBase *particles)
2994 {
2995         ParticleSystem *psys;
2996         int a;
2997
2998         for(psys=particles->first; psys; psys=psys->next) {
2999                 psys->particles=newdataadr(fd,psys->particles);
3000                 if(psys->particles && psys->particles->hair){
3001                         ParticleData *pa = psys->particles;
3002                         for(a=0; a<psys->totpart; a++, pa++)
3003                                 pa->hair=newdataadr(fd,pa->hair);
3004                 }
3005                 if(psys->particles && psys->particles->keys){
3006                         ParticleData *pa = psys->particles;
3007                         for(a=0; a<psys->totpart; a++, pa++) {
3008                                 pa->keys= NULL;
3009                                 pa->totkey= 0;
3010                         }
3011
3012                         psys->flag &= ~PSYS_KEYED;
3013                 }
3014                 psys->child=newdataadr(fd,psys->child);
3015                 psys->effectors.first=psys->effectors.last=0;
3016
3017                 psys->soft= newdataadr(fd, psys->soft);
3018                 if(psys->soft) {
3019                         SoftBody *sb = psys->soft;
3020                         sb->particles = psys;
3021                         sb->bpoint= NULL;       // init pointers so it gets rebuilt nicely
3022                         sb->bspring= NULL;
3023                         sb->scratch= NULL;
3024
3025                         sb->pointcache= newdataadr(fd, sb->pointcache);
3026                         if(sb->pointcache)
3027                                 direct_link_pointcache(fd, sb->pointcache);
3028                 }
3029
3030                 psys->edit = 0;
3031                 psys->free_edit = NULL;
3032                 psys->pathcache = 0;
3033                 psys->childcache = 0;
3034                 psys->pathcachebufs.first = psys->pathcachebufs.last = 0;
3035                 psys->childcachebufs.first = psys->childcachebufs.last = 0;
3036                 psys->reactevents.first = psys->reactevents.last = 0;
3037
3038                 psys->pointcache= newdataadr(fd, psys->pointcache);
3039                 if(psys->pointcache)
3040                         direct_link_pointcache(fd, psys->pointcache);
3041         }
3042         return;
3043 }
3044
3045 /* ************ READ MESH ***************** */
3046
3047 static void lib_link_mtface(FileData *fd, Mesh *me, MTFace *mtface, int totface)
3048 {
3049         MTFace *tf= mtface;
3050         int i;
3051
3052         for (i=0; i<totface; i++, tf++) {
3053                 tf->tpage= newlibadr(fd, me->id.lib, tf->tpage);
3054                 if(tf->tpage && tf->tpage->id.us==0)
3055                         tf->tpage->id.us= 1;
3056         }
3057 }
3058
3059 static void lib_link_customdata_mtface(FileData *fd, Mesh *me, CustomData *fdata, int totface)
3060 {
3061         int i;  
3062         for(i=0; i<fdata->totlayer; i++) {
3063                 CustomDataLayer *layer = &fdata->layers[i];
3064                 
3065                 if(layer->type == CD_MTFACE)
3066                         lib_link_mtface(fd, me, layer->data, totface);
3067         }
3068
3069 }
3070
3071 static void lib_link_mesh(FileData *fd, Main *main)
3072 {
3073         Mesh *me;
3074
3075         me= main->mesh.first;
3076         while(me) {
3077                 if(me->id.flag & LIB_NEEDLINK) {
3078                         int i;
3079
3080                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
3081                         of library blocks that implement this.*/
3082                         if (me->id.properties) IDP_LibLinkProperty(me->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
3083
3084                         /* this check added for python created meshes */
3085                         if(me->mat) {
3086                                 for(i=0; i<me->totcol; i++) {
3087                                         me->mat[i]= newlibadr_us(fd, me->id.lib, me->mat[i]);
3088                                 }
3089                         }
3090                         else me->totcol= 0;
3091
3092                         me->ipo= newlibadr_us(fd, me->id.lib, me->ipo);
3093                         me->key= newlibadr_us(fd, me->id.lib, me->key);
3094                         me->texcomesh= newlibadr_us(fd, me->id.lib, me->texcomesh);
3095
3096                         lib_link_customdata_mtface(fd, me, &me->fdata, me->totface);
3097                         if(me->mr && me->mr->levels.first)
3098                                 lib_link_customdata_mtface(fd, me, &me->mr->fdata,
3099                                                            ((MultiresLevel*)me->mr->levels.first)->totface);
3100
3101                         me->id.flag -= LIB_NEEDLINK;
3102                 }
3103                 me= me->id.next;
3104         }
3105 }
3106
3107 static void direct_link_dverts(FileData *fd, int count, MDeformVert *mdverts)
3108 {
3109         int     i;
3110
3111         if (!mdverts)
3112                 return;
3113
3114         for (i=0; i<count; i++) {
3115                 mdverts[i].dw=newdataadr(fd, mdverts[i].dw);
3116                 if (!mdverts[i].dw)
3117                         mdverts[i].totweight=0;
3118         }
3119 }
3120
3121 static void direct_link_mdisps(FileData *fd, int count, MDisps *mdisps)
3122 {
3123         if(mdisps) {
3124                 int i;
3125
3126                 for(i = 0; i < count; ++i) {
3127                         mdisps[i].disps = newdataadr(fd, mdisps[i].disps);
3128                         if(!mdisps[i].disps)
3129                                 mdisps[i].totdisp = 0;
3130                 }
3131         }       
3132 }
3133
3134 static void direct_link_customdata(FileData *fd, CustomData *data, int count)
3135 {
3136         int i = 0;
3137
3138         data->layers= newdataadr(fd, data->layers);
3139
3140         while (i < data->totlayer) {
3141                 CustomDataLayer *layer = &data->layers[i];
3142
3143                 if (CustomData_verify_versions(data, i)) {
3144                         layer->data = newdataadr(fd, layer->data);
3145                         if(layer->type == CD_MDISPS)
3146                                 direct_link_mdisps(fd, count, layer->data);
3147                         i++;
3148                 }
3149         }
3150 }
3151
3152 static void direct_link_mesh(FileData *fd, Mesh *mesh)
3153 {
3154         mesh->mat= newdataadr(fd, mesh->mat);
3155         test_pointer_array(fd, (void **)&mesh->mat);
3156
3157         mesh->mvert= newdataadr(fd, mesh->mvert);
3158         mesh->medge= newdataadr(fd, mesh->medge);
3159         mesh->mface= newdataadr(fd, mesh->mface);
3160         mesh->tface= newdataadr(fd, mesh->tface);
3161         mesh->mtface= newdataadr(fd, mesh->mtface);
3162         mesh->mcol= newdataadr(fd, mesh->mcol);
3163         mesh->msticky= newdataadr(fd, mesh->msticky);
3164         mesh->dvert= newdataadr(fd, mesh->dvert);
3165         
3166         /* Partial-mesh visibility (do this before using totvert, totface, or totedge!) */
3167         mesh->pv= newdataadr(fd, mesh->pv);
3168         if(mesh->pv) {
3169                 mesh->pv->vert_map= newdataadr(fd, mesh->pv->vert_map);
3170                 mesh->pv->edge_map= newdataadr(fd, mesh->pv->edge_map);
3171                 mesh->pv->old_faces= newdataadr(fd, mesh->pv->old_faces);
3172                 mesh->pv->old_edges= newdataadr(fd, mesh->pv->old_edges);
3173         }
3174
3175         /* normally direct_link_dverts should be called in direct_link_customdata,
3176            but for backwards compat in do_versions to work we do it here */
3177         direct_link_dverts(fd, mesh->pv ? mesh->pv->totvert : mesh->totvert, mesh->dvert);
3178
3179         direct_link_customdata(fd, &mesh->vdata, mesh->pv ? mesh->pv->totvert : mesh->totvert);
3180         direct_link_customdata(fd, &mesh->edata, mesh->pv ? mesh->pv->totedge : mesh->totedge);
3181         direct_link_customdata(fd, &mesh->fdata, mesh->pv ? mesh->pv->totface : mesh->totface);
3182
3183         mesh->bb= NULL;
3184         mesh->mselect = NULL;
3185         mesh->edit_mesh= NULL;
3186         
3187         /* Multires data */
3188         mesh->mr= newdataadr(fd, mesh->mr);
3189         if(mesh->mr) {
3190                 MultiresLevel *lvl;
3191                 
3192                 link_list(fd, &mesh->mr->levels);
3193                 lvl= mesh->mr->levels.first;
3194                 
3195                 direct_link_customdata(fd, &mesh->mr->vdata, lvl->totvert);
3196                 direct_link_dverts(fd, lvl->totvert, CustomData_get(&mesh->mr->vdata, 0, CD_MDEFORMVERT));
3197                 direct_link_customdata(fd, &mesh->mr->fdata, lvl->totface);
3198                 
3199                 if(!mesh->mr->edge_flags)
3200                         mesh->mr->edge_flags= MEM_callocN(sizeof(short)*lvl->totedge, "Multires Edge Flags");
3201                 if(!mesh->mr->edge_creases)
3202                         mesh->mr->edge_creases= MEM_callocN(sizeof(char)*lvl->totedge, "Multires Edge Creases");
3203
3204                 mesh->mr->verts = newdataadr(fd, mesh->mr->verts);
3205                         
3206                 for(; lvl; lvl= lvl->next) {
3207                         lvl->verts= newdataadr(fd, lvl->verts);
3208                         lvl->faces= newdataadr(fd, lvl->faces);
3209                         lvl->edges= newdataadr(fd, lvl->edges);
3210                         lvl->colfaces= newdataadr(fd, lvl->colfaces);
3211                 }
3212         }
3213
3214         /* Gracefully handle corrupted mesh */
3215         if(mesh->mr && !mesh->mr->verts) {
3216                 /* If totals match, simply load the current mesh verts into multires */
3217                 if(mesh->totvert == ((MultiresLevel*)mesh->mr->levels.last)->totvert)
3218                         mesh->mr->verts = MEM_dupallocN(mesh->mvert);
3219                 else {
3220                         /* Otherwise, we can't recover the data, silently remove multires */
3221                         multires_free(mesh->mr);
3222                         mesh->mr = NULL;
3223                 }
3224         }
3225         
3226         if((fd->flags & FD_FLAGS_SWITCH_ENDIAN) && mesh->tface) {
3227                 TFace *tf= mesh->tface;
3228                 unsigned int i;
3229
3230                 for (i=0; i< (mesh->pv ? mesh->pv->totface : mesh->totface); i++, tf++) {
3231                         SWITCH_INT(tf->col[0]);
3232                         SWITCH_INT(tf->col[1]);
3233                         SWITCH_INT(tf->col[2]);
3234                         SWITCH_INT(tf->col[3]);
3235                 }
3236         }
3237 }
3238
3239 /* ************ READ LATTICE ***************** */
3240
3241 static void lib_link_latt(FileData *fd, Main *main)
3242 {
3243         Lattice *lt;
3244         
3245         lt= main->latt.first;
3246         while(lt) {
3247                 if(lt->id.flag & LIB_NEEDLINK) {
3248                         
3249                         lt->ipo= newlibadr_us(fd, lt->id.lib, lt->ipo); // XXX depreceated - old animation system
3250                         lt->key= newlibadr_us(fd, lt->id.lib, lt->key);
3251                         
3252                         lt->id.flag -= LIB_NEEDLINK;
3253                 }
3254                 lt= lt->id.next;
3255         }
3256 }
3257
3258 static void direct_link_latt(FileData *fd, Lattice *lt)
3259 {
3260         lt->def= newdataadr(fd, lt->def);
3261         
3262         lt->dvert= newdataadr(fd, lt->dvert);
3263         direct_link_dverts(fd, lt->pntsu*lt->pntsv*lt->pntsw, lt->dvert);
3264         
3265         lt->editlatt= NULL;
3266 }
3267
3268
3269 /* ************ READ OBJECT ***************** */
3270
3271 static void lib_link_modifiers__linkModifiers(void *userData, Object *ob,
3272                                               ID **idpoin)
3273 {
3274         FileData *fd = userData;
3275
3276         *idpoin = newlibadr(fd, ob->id.lib, *idpoin);
3277         /* hardcoded bad exception; non-object modifier data gets user count (texture, displace) */
3278         if(*idpoin && GS((*idpoin)->name)!=ID_OB)
3279                 (*idpoin)->us++;
3280 }
3281 static void lib_link_modifiers(FileData *fd, Object *ob)
3282 {
3283         modifiers_foreachIDLink(ob, lib_link_modifiers__linkModifiers, fd);