2.5: User Preferences
[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 static void lib_link_nladata_strips(FileData *fd, ID *id, ListBase *list)
1830 {
1831         NlaStrip *strip;
1832         
1833         for (strip= list->first; strip; strip= strip->next) {
1834                 /* check strip's children */
1835                 lib_link_nladata_strips(fd, id, &strip->strips);
1836                 
1837                 /* reassign the counted-reference to action */
1838                 strip->act = newlibadr_us(fd, id->lib, strip->act);
1839         }
1840 }
1841
1842 static void lib_link_nladata(FileData *fd, ID *id, ListBase *list)
1843 {
1844         NlaTrack *nlt;
1845         
1846         /* we only care about the NLA strips inside the tracks */
1847         for (nlt= list->first; nlt; nlt= nlt->next) {
1848                 lib_link_nladata_strips(fd, id, &nlt->strips);
1849         }
1850 }
1851
1852 /* This handles Animato NLA-Strips linking 
1853  * NOTE: this assumes that link_list has already been called on the list 
1854  */
1855 static void direct_link_nladata_strips(FileData *fd, ListBase *list)
1856 {
1857         NlaStrip *strip;
1858         
1859         for (strip= list->first; strip; strip= strip->next) {
1860                 /* strip's child strips */
1861                 link_list(fd, &strip->strips);
1862                 direct_link_nladata_strips(fd, &strip->strips);
1863                 
1864                 /* strip's F-Curves */
1865                 link_list(fd, &strip->fcurves);
1866                 direct_link_fcurves(fd, &strip->fcurves);
1867                 
1868                 /* strip's F-Modifiers */
1869                 link_list(fd, &strip->modifiers);
1870                 direct_link_fcurves(fd, &strip->modifiers);
1871         }
1872 }
1873
1874 /* NOTE: this assumes that link_list has already been called on the list */
1875 static void direct_link_nladata(FileData *fd, ListBase *list)
1876 {
1877         NlaTrack *nlt;
1878         
1879         for (nlt= list->first; nlt; nlt= nlt->next) {
1880                 /* relink list of strips */
1881                 link_list(fd, &nlt->strips);
1882                 
1883                 /* relink strip data */
1884                 direct_link_nladata_strips(fd, &nlt->strips);
1885         }
1886 }
1887
1888 /* ------- */
1889
1890 static void lib_link_keyingsets(FileData *fd, ID *id, ListBase *list)
1891 {
1892         KeyingSet *ks;
1893         KS_Path *ksp;
1894         
1895         /* here, we're only interested in the ID pointer stored in some of the paths */
1896         for (ks= list->first; ks; ks= ks->next) {
1897                 for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
1898                         ksp->id= newlibadr(fd, id->lib, ksp->id); 
1899                 }
1900         }
1901 }
1902
1903 /* NOTE: this assumes that link_list has already been called on the list */
1904 static void direct_link_keyingsets(FileData *fd, ListBase *list)
1905 {
1906         KeyingSet *ks;
1907         KS_Path *ksp;
1908         
1909         /* link KeyingSet data to KeyingSet again (non ID-libs) */
1910         for (ks= list->first; ks; ks= ks->next) {
1911                 /* paths */
1912                 link_list(fd, &ks->paths);
1913                 
1914                 for (ksp= ks->paths.first; ksp; ksp= ksp->next) {
1915                         /* rna path */
1916                         ksp->rna_path= newdataadr(fd, ksp->rna_path);
1917                 }
1918         }
1919 }
1920
1921 /* ------- */
1922
1923 static void lib_link_animdata(FileData *fd, ID *id, AnimData *adt)
1924 {
1925         if (adt == NULL)
1926                 return;
1927         
1928         /* link action data */
1929         adt->action= newlibadr_us(fd, id->lib, adt->action);
1930         adt->tmpact= newlibadr_us(fd, id->lib, adt->tmpact);
1931         
1932         /* link drivers */
1933         lib_link_fcurves(fd, id, &adt->drivers);
1934         
1935         /* overrides don't have lib-link for now, so no need to do anything */
1936         
1937         /* link NLA-data */
1938         lib_link_nladata(fd, id, &adt->nla_tracks);
1939 }
1940
1941 static void direct_link_animdata(FileData *fd, AnimData *adt)
1942 {
1943         /* NOTE: must have called newdataadr already before doing this... */
1944         if (adt == NULL)
1945                 return;
1946         
1947         /* link drivers */
1948         link_list(fd, &adt->drivers);
1949         direct_link_fcurves(fd, &adt->drivers);
1950         
1951         /* link overrides */
1952         // TODO...
1953         
1954         /* link NLA-data */
1955         link_list(fd, &adt->nla_tracks);
1956         direct_link_nladata(fd, &adt->nla_tracks);
1957         
1958         /* clear temp pointers that may have been set... */
1959         // TODO: it's probably only a small cost to reload this anyway...
1960         adt->actstrip= NULL;
1961 }       
1962
1963 /* ************ READ NODE TREE *************** */
1964
1965 /* singe node tree (also used for material/scene trees), ntree is not NULL */
1966 static void lib_link_ntree(FileData *fd, ID *id, bNodeTree *ntree)
1967 {
1968         bNode *node;
1969         
1970         if(ntree->adt) lib_link_animdata(fd, &ntree->id, ntree->adt);
1971         
1972         for(node= ntree->nodes.first; node; node= node->next)
1973                 node->id= newlibadr_us(fd, id->lib, node->id);
1974 }
1975
1976 /* library ntree linking after fileread */
1977 static void lib_link_nodetree(FileData *fd, Main *main)
1978 {
1979         bNodeTree *ntree;
1980         
1981         /* only link ID pointers */
1982         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
1983                 if(ntree->id.flag & LIB_NEEDLINK) {
1984                         ntree->id.flag -= LIB_NEEDLINK;
1985                         lib_link_ntree(fd, &ntree->id, ntree);
1986                 }
1987         }
1988 }
1989
1990 /* verify types for nodes and groups, all data has to be read */
1991 /* open = 0: appending/linking, open = 1: open new file (need to clean out dynamic
1992 * typedefs*/
1993 static void lib_verify_nodetree(Main *main, int open)
1994 {
1995         Scene *sce;
1996         Material *ma;
1997         Tex *tx;
1998         bNodeTree *ntree;
1999         
2000         /* this crashes blender on undo/redo
2001                 if(open==1) {
2002                         reinit_nodesystem();
2003                 }*/
2004         
2005         /* now create the own typeinfo structs an verify nodes */
2006         /* here we still assume no groups in groups */
2007         for(ntree= main->nodetree.first; ntree; ntree= ntree->id.next) {
2008                 ntreeVerifyTypes(ntree);        /* internal nodes, no groups! */
2009                 ntreeMakeOwnType(ntree);        /* for group usage */
2010         }
2011         
2012         /* now verify all types in material trees, groups are set OK now */
2013         for(ma= main->mat.first; ma; ma= ma->id.next) {
2014                 if(ma->nodetree)
2015                         ntreeVerifyTypes(ma->nodetree);
2016         }
2017         /* and scene trees */
2018         for(sce= main->scene.first; sce; sce= sce->id.next) {
2019                 if(sce->nodetree)
2020                         ntreeVerifyTypes(sce->nodetree);
2021         }
2022         /* and texture trees */
2023         for(tx= main->tex.first; tx; tx= tx->id.next) {
2024                 if(tx->nodetree)
2025                         ntreeVerifyTypes(tx->nodetree);
2026         }
2027 }
2028
2029
2030
2031 /* ntree itself has been read! */
2032 static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
2033 {
2034         /* note: writing and reading goes in sync, for speed */
2035         bNode *node;
2036         bNodeSocket *sock;
2037         bNodeLink *link;
2038         
2039         ntree->init= 0;         /* to set callbacks and force setting types */
2040         ntree->owntype= NULL;
2041         ntree->timecursor= NULL;
2042         
2043         ntree->adt= newdataadr(fd, ntree->adt);
2044         direct_link_animdata(fd, ntree->adt);
2045         
2046         link_list(fd, &ntree->nodes);
2047         for(node= ntree->nodes.first; node; node= node->next) {
2048                 if(node->type == NODE_DYNAMIC) {
2049                         node->custom1= 0;
2050                         node->custom1= BSET(node->custom1, NODE_DYNAMIC_LOADED);
2051                         node->typeinfo= NULL;
2052                 }
2053                 
2054                 node->storage= newdataadr(fd, node->storage);
2055                 if(node->storage) {
2056                         
2057                         /* could be handlerized at some point */
2058                         if(ntree->type==NTREE_SHADER && (node->type==SH_NODE_CURVE_VEC || node->type==SH_NODE_CURVE_RGB))
2059                                 direct_link_curvemapping(fd, node->storage);
2060                         else if(ntree->type==NTREE_COMPOSIT) {
2061                                 if( ELEM3(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB))
2062                                         direct_link_curvemapping(fd, node->storage);
2063                                 else if(ELEM3(node->type, CMP_NODE_IMAGE, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
2064                                         ((ImageUser *)node->storage)->ok= 1;
2065                         }
2066                         else if( ntree->type==NTREE_TEXTURE && (node->type==TEX_NODE_CURVE_RGB || node->type==TEX_NODE_CURVE_TIME) ) {
2067                                 direct_link_curvemapping(fd, node->storage);
2068                         }
2069                 }
2070                 link_list(fd, &node->inputs);
2071                 link_list(fd, &node->outputs);
2072         }
2073         link_list(fd, &ntree->links);
2074         
2075         /* and we connect the rest */
2076         for(node= ntree->nodes.first; node; node= node->next) {
2077                 node->preview= newimaadr(fd, node->preview);
2078                 node->lasty= 0;
2079                 for(sock= node->inputs.first; sock; sock= sock->next)
2080                         sock->link= newdataadr(fd, sock->link);
2081                 for(sock= node->outputs.first; sock; sock= sock->next)
2082                         sock->ns.data= NULL;
2083         }
2084         for(link= ntree->links.first; link; link= link->next) {
2085                 link->fromnode= newdataadr(fd, link->fromnode);
2086                 link->tonode= newdataadr(fd, link->tonode);
2087                 link->fromsock= newdataadr(fd, link->fromsock);
2088                 link->tosock= newdataadr(fd, link->tosock);
2089         }
2090         
2091         /* set selin and selout */
2092         for(node= ntree->nodes.first; node; node= node->next) {
2093                 for(sock= node->inputs.first; sock; sock= sock->next) {
2094                         if(sock->flag & SOCK_SEL) {
2095                                 ntree->selin= sock;
2096                                 break;
2097                         }
2098                 }
2099                 for(sock= node->outputs.first; sock; sock= sock->next) {
2100                         if(sock->flag & SOCK_SEL) {
2101                                 ntree->selout= sock;
2102                                 break;
2103                         }
2104                 }
2105         }
2106         
2107         /* type verification is in lib-link */
2108 }
2109
2110 /* ************ READ ARMATURE ***************** */
2111
2112 static void lib_link_constraints(FileData *fd, ID *id, ListBase *conlist)
2113 {
2114         bConstraint *con;
2115
2116         for (con = conlist->first; con; con=con->next) {
2117                 /* patch for error introduced by changing constraints (dunno how) */
2118                 /* if con->data type changes, dna cannot resolve the pointer! (ton) */
2119                 if(con->data==NULL) {
2120                         con->type= CONSTRAINT_TYPE_NULL;
2121                 }
2122                 /* own ipo, all constraints have it */
2123                 con->ipo= newlibadr_us(fd, id->lib, con->ipo); // XXX depreceated - old animation system
2124                 
2125                 switch (con->type) {
2126                 case CONSTRAINT_TYPE_PYTHON:
2127                         {
2128                                 bPythonConstraint *data= (bPythonConstraint*)con->data;
2129                                 bConstraintTarget *ct;
2130                                 
2131                                 for (ct= data->targets.first; ct; ct= ct->next)
2132                                         ct->tar = newlibadr(fd, id->lib, ct->tar);
2133                                         
2134                                 data->text = newlibadr(fd, id->lib, data->text);
2135                                 //IDP_LibLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2136                         }
2137                         break;
2138                 case CONSTRAINT_TYPE_ACTION:
2139                         {
2140                                 bActionConstraint *data;
2141                                 data= ((bActionConstraint*)con->data);
2142                                 data->tar = newlibadr(fd, id->lib, data->tar);
2143                                 data->act = newlibadr(fd, id->lib, data->act);
2144                         }
2145                         break;
2146                 case CONSTRAINT_TYPE_LOCLIKE:
2147                         {
2148                                 bLocateLikeConstraint *data;
2149                                 data= ((bLocateLikeConstraint*)con->data);
2150                                 data->tar = newlibadr(fd, id->lib, data->tar);
2151                         }
2152                         break;
2153                 case CONSTRAINT_TYPE_ROTLIKE:
2154                         {
2155                                 bRotateLikeConstraint *data;
2156                                 data= ((bRotateLikeConstraint*)con->data);
2157                                 data->tar = newlibadr(fd, id->lib, data->tar);
2158                         }
2159                         break;
2160                 case CONSTRAINT_TYPE_SIZELIKE:
2161                         {
2162                                 bSizeLikeConstraint *data;
2163                                 data= ((bSizeLikeConstraint*)con->data);
2164                                 data->tar = newlibadr(fd, id->lib, data->tar);
2165                         }
2166                         break;
2167                 case CONSTRAINT_TYPE_KINEMATIC:
2168                         {
2169                                 bKinematicConstraint *data;
2170                                 data = ((bKinematicConstraint*)con->data);
2171                                 data->tar = newlibadr(fd, id->lib, data->tar);
2172                                 data->poletar = newlibadr(fd, id->lib, data->poletar);
2173                         }
2174                         break;
2175                 case CONSTRAINT_TYPE_TRACKTO:
2176                         {
2177                                 bTrackToConstraint *data;
2178                                 data = ((bTrackToConstraint*)con->data);
2179                                 data->tar = newlibadr(fd, id->lib, data->tar);
2180                         }
2181                         break;
2182                 case CONSTRAINT_TYPE_MINMAX:
2183                         {
2184                                 bMinMaxConstraint *data;
2185                                 data = ((bMinMaxConstraint*)con->data);
2186                                 data->tar = newlibadr(fd, id->lib, data->tar);
2187                         }
2188                         break;
2189                 case CONSTRAINT_TYPE_LOCKTRACK:
2190                         {
2191                                 bLockTrackConstraint *data;
2192                                 data= ((bLockTrackConstraint*)con->data);
2193                                 data->tar = newlibadr(fd, id->lib, data->tar);
2194                         }
2195                         break;
2196                 case CONSTRAINT_TYPE_FOLLOWPATH:
2197                         {
2198                                 bFollowPathConstraint *data;
2199                                 data= ((bFollowPathConstraint*)con->data);
2200                                 data->tar = newlibadr(fd, id->lib, data->tar);
2201                         }
2202                         break;
2203                 case CONSTRAINT_TYPE_STRETCHTO:
2204                         {
2205                                 bStretchToConstraint *data;
2206                                 data= ((bStretchToConstraint*)con->data);
2207                                 data->tar = newlibadr(fd, id->lib, data->tar);
2208                         }
2209                         break;
2210                 case CONSTRAINT_TYPE_RIGIDBODYJOINT:
2211                         {
2212                                 bRigidBodyJointConstraint *data;
2213                                 data= ((bRigidBodyJointConstraint*)con->data);
2214                                 data->tar = newlibadr(fd, id->lib, data->tar);
2215                         }
2216                         break;
2217                 case CONSTRAINT_TYPE_CLAMPTO:
2218                         {
2219                                 bClampToConstraint *data;
2220                                 data= ((bClampToConstraint*)con->data);
2221                                 data->tar = newlibadr(fd, id->lib, data->tar);
2222                         }
2223                         break;
2224                 case CONSTRAINT_TYPE_CHILDOF:
2225                         {
2226                                 bChildOfConstraint *data;
2227                                 data= ((bChildOfConstraint*)con->data);
2228                                 data->tar = newlibadr(fd, id->lib, data->tar);
2229                         }
2230                         break;
2231                 case CONSTRAINT_TYPE_TRANSFORM:
2232                         {
2233                                 bTransformConstraint *data;
2234                                 data= ((bTransformConstraint*)con->data);
2235                                 data->tar = newlibadr(fd, id->lib, data->tar);
2236                         }
2237                         break;
2238                 case CONSTRAINT_TYPE_DISTLIMIT:
2239                         {
2240                                 bDistLimitConstraint *data;
2241                                 data= ((bDistLimitConstraint*)con->data);
2242                                 data->tar = newlibadr(fd, id->lib, data->tar);
2243                         }
2244                         break;
2245                 case CONSTRAINT_TYPE_SHRINKWRAP:
2246                         {
2247                                 bShrinkwrapConstraint *data;
2248                                 data= ((bShrinkwrapConstraint*)con->data);
2249                                 data->target = newlibadr(fd, id->lib, data->target);
2250                         }
2251                         break;
2252                 case CONSTRAINT_TYPE_NULL:
2253                         break;
2254                 }
2255         }
2256 }
2257
2258 static void direct_link_constraints(FileData *fd, ListBase *lb)
2259 {
2260         bConstraint *cons;
2261
2262         link_list(fd, lb);
2263         for (cons=lb->first; cons; cons=cons->next) {
2264                 cons->data = newdataadr(fd, cons->data);
2265                 
2266                 if (cons->type == CONSTRAINT_TYPE_PYTHON) {
2267                         bPythonConstraint *data= cons->data;
2268                         
2269                         link_list(fd, &data->targets);
2270                         
2271                         data->prop = newdataadr(fd, data->prop);
2272                         if (data->prop)
2273                                 IDP_DirectLinkProperty(data->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2274                 }
2275         }
2276 }
2277
2278 static void lib_link_pose(FileData *fd, Object *ob, bPose *pose)
2279 {
2280         bPoseChannel *pchan;
2281         bArmature *arm= ob->data;
2282         int rebuild;
2283         
2284         if (!pose || !arm)
2285                 return;
2286         
2287         /* always rebuild to match proxy or lib changes */
2288         rebuild= ob->proxy || (ob->id.lib==NULL && arm->id.lib);
2289
2290         for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
2291                 lib_link_constraints(fd, (ID *)ob, &pchan->constraints);
2292                 
2293                 /* hurms... loop in a loop, but yah... later... (ton) */
2294                 pchan->bone= get_named_bone(arm, pchan->name);
2295                 
2296                 pchan->custom= newlibadr(fd, arm->id.lib, pchan->custom);
2297                 if(pchan->bone==NULL)
2298                         rebuild= 1;
2299                 else if(ob->id.lib==NULL && arm->id.lib) {
2300                         /* local pose selection copied to armature, bit hackish */
2301                         pchan->bone->flag &= ~(BONE_SELECTED|BONE_ACTIVE);
2302                         pchan->bone->flag |= pchan->selectflag;
2303                 }
2304         }
2305         
2306         if(rebuild) {
2307                 ob->recalc= OB_RECALC;
2308                 pose->flag |= POSE_RECALC;
2309         }
2310 }
2311
2312 static void lib_link_armature(FileData *fd, Main *main)
2313 {
2314         bArmature *arm;
2315
2316         arm= main->armature.first;
2317
2318         while(arm) {
2319                 if(arm->id.flag & LIB_NEEDLINK) {
2320                         arm->id.flag -= LIB_NEEDLINK;
2321                 }
2322                 arm= arm->id.next;
2323         }
2324 }
2325
2326 static void direct_link_bones(FileData *fd, Bone* bone)
2327 {
2328         Bone    *child;
2329
2330         bone->parent= newdataadr(fd, bone->parent);
2331
2332         link_list(fd, &bone->childbase);
2333
2334         for (child=bone->childbase.first; child; child=child->next) {
2335                 direct_link_bones(fd, child);
2336         }
2337 }
2338
2339 static void direct_link_armature(FileData *fd, bArmature *arm)
2340 {
2341         Bone    *bone;
2342
2343         link_list(fd, &arm->bonebase);
2344         arm->edbo= NULL;
2345         
2346         bone=arm->bonebase.first;
2347         while (bone) {
2348                 direct_link_bones(fd, bone);
2349                 bone=bone->next;
2350         }
2351 }
2352
2353 /* ************ READ CAMERA ***************** */
2354
2355 static void lib_link_camera(FileData *fd, Main *main)
2356 {
2357         Camera *ca;
2358
2359         ca= main->camera.first;
2360         while(ca) {
2361                 if(ca->id.flag & LIB_NEEDLINK) {
2362                         if (ca->adt) lib_link_animdata(fd, &ca->id, ca->adt);
2363                         
2364                         ca->ipo= newlibadr_us(fd, ca->id.lib, ca->ipo); // XXX depreceated - old animation system
2365                         
2366                         ca->dof_ob= newlibadr_us(fd, ca->id.lib, ca->dof_ob);
2367                         
2368                         lib_link_scriptlink(fd, &ca->id, &ca->scriptlink);
2369                         
2370                         ca->id.flag -= LIB_NEEDLINK;
2371                 }
2372                 ca= ca->id.next;
2373         }
2374 }
2375
2376 static void direct_link_camera(FileData *fd, Camera *ca)
2377 {
2378         ca->adt= newdataadr(fd, ca->adt);
2379         direct_link_animdata(fd, ca->adt);
2380         
2381         direct_link_scriptlink(fd, &ca->scriptlink);
2382 }
2383
2384
2385 /* ************ READ LAMP ***************** */
2386
2387 static void lib_link_lamp(FileData *fd, Main *main)
2388 {
2389         Lamp *la;
2390         MTex *mtex;
2391         int a;
2392
2393         la= main->lamp.first;
2394         while(la) {
2395                 if(la->id.flag & LIB_NEEDLINK) {
2396                         if (la->adt) lib_link_animdata(fd, &la->id, la->adt);
2397                         
2398                         for(a=0; a<MAX_MTEX; a++) {
2399                                 mtex= la->mtex[a];
2400                                 if(mtex) {
2401                                         mtex->tex= newlibadr_us(fd, la->id.lib, mtex->tex);
2402                                         mtex->object= newlibadr(fd, la->id.lib, mtex->object);
2403                                 }
2404                         }
2405                         
2406                         la->ipo= newlibadr_us(fd, la->id.lib, la->ipo); // XXX depreceated - old animation system
2407                         
2408                         lib_link_scriptlink(fd, &la->id, &la->scriptlink);
2409                         
2410                         la->id.flag -= LIB_NEEDLINK;
2411                 }
2412                 la= la->id.next;
2413         }
2414 }
2415
2416 static void direct_link_lamp(FileData *fd, Lamp *la)
2417 {
2418         int a;
2419         
2420         la->adt= newdataadr(fd, la->adt);
2421         direct_link_animdata(fd, la->adt);
2422         
2423         direct_link_scriptlink(fd, &la->scriptlink);
2424
2425         for(a=0; a<MAX_MTEX; a++) {
2426                 la->mtex[a]= newdataadr(fd, la->mtex[a]);
2427         }
2428         
2429         la->curfalloff= newdataadr(fd, la->curfalloff);
2430         if(la->curfalloff)
2431                 direct_link_curvemapping(fd, la->curfalloff);
2432         
2433         la->preview = direct_link_preview_image(fd, la->preview);
2434 }
2435
2436 /* ************ READ keys ***************** */
2437
2438 static void lib_link_key(FileData *fd, Main *main)
2439 {
2440         Key *key;
2441
2442         key= main->key.first;
2443         while(key) {
2444                 if(key->id.flag & LIB_NEEDLINK) {
2445                         if(key->adt) lib_link_animdata(fd, &key->id, key->adt);
2446                         
2447                         key->ipo= newlibadr_us(fd, key->id.lib, key->ipo); // XXX depreceated - old animation system
2448                         key->from= newlibadr(fd, key->id.lib, key->from);
2449
2450                         key->id.flag -= LIB_NEEDLINK;
2451                 }
2452                 key= key->id.next;
2453         }
2454 }
2455
2456 static void switch_endian_keyblock(Key *key, KeyBlock *kb)
2457 {
2458         int elemsize, a, b;
2459         char *data, *poin, *cp;
2460
2461         elemsize= key->elemsize;
2462         data= kb->data;
2463
2464         for(a=0; a<kb->totelem; a++) {
2465
2466                 cp= key->elemstr;
2467                 poin= data;
2468
2469                 while( cp[0] ) {        /* cp[0]==amount */
2470
2471                         switch(cp[1]) {         /* cp[1]= type */
2472                         case IPO_FLOAT:
2473                         case IPO_BPOINT:
2474                         case IPO_BEZTRIPLE:
2475                                 b= cp[0];
2476                                 while(b--) {
2477                                         SWITCH_INT((*poin));
2478                                         poin+= 4;
2479                                 }
2480                                 break;
2481                         }
2482
2483                         cp+= 2;
2484
2485                 }
2486                 data+= elemsize;
2487         }
2488 }
2489
2490 static void direct_link_key(FileData *fd, Key *key)
2491 {
2492         KeyBlock *kb;
2493
2494         link_list(fd, &(key->block));
2495
2496         key->adt= newdataadr(fd, key->adt);
2497         direct_link_animdata(fd, key->adt);
2498         
2499         key->refkey= newdataadr(fd, key->refkey);
2500
2501         kb= key->block.first;
2502         while(kb) {
2503
2504                 kb->data= newdataadr(fd, kb->data);
2505
2506                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN)
2507                         switch_endian_keyblock(key, kb);
2508
2509                 kb= kb->next;
2510         }
2511 }
2512
2513 /* ************ READ mball ***************** */
2514
2515 static void lib_link_mball(FileData *fd, Main *main)
2516 {
2517         MetaBall *mb;
2518         int a;
2519
2520         mb= main->mball.first;
2521         while(mb) {
2522                 if(mb->id.flag & LIB_NEEDLINK) {
2523
2524                         for(a=0; a<mb->totcol; a++) mb->mat[a]= newlibadr_us(fd, mb->id.lib, mb->mat[a]);
2525
2526                         mb->ipo= newlibadr_us(fd, mb->id.lib, mb->ipo); // XXX depreceated - old animation system
2527
2528                         mb->id.flag -= LIB_NEEDLINK;
2529                 }
2530                 mb= mb->id.next;
2531         }
2532 }
2533
2534 static void direct_link_mball(FileData *fd, MetaBall *mb)
2535 {
2536         mb->mat= newdataadr(fd, mb->mat);
2537         test_pointer_array(fd, (void **)&mb->mat);
2538
2539         link_list(fd, &(mb->elems));
2540
2541         mb->disp.first= mb->disp.last= NULL;
2542         mb->editelems= NULL;
2543         mb->bb= NULL;
2544 }
2545
2546 /* ************ READ WORLD ***************** */
2547
2548 static void lib_link_world(FileData *fd, Main *main)
2549 {
2550         World *wrld;
2551         MTex *mtex;
2552         int a;
2553
2554         wrld= main->world.first;
2555         while(wrld) {
2556                 if(wrld->id.flag & LIB_NEEDLINK) {
2557                         if (wrld->adt) lib_link_animdata(fd, &wrld->id, wrld->adt);
2558                         
2559                         wrld->ipo= newlibadr_us(fd, wrld->id.lib, wrld->ipo); // XXX depreceated - old animation system
2560                         
2561                         for(a=0; a<MAX_MTEX; a++) {
2562                                 mtex= wrld->mtex[a];
2563                                 if(mtex) {
2564                                         mtex->tex= newlibadr_us(fd, wrld->id.lib, mtex->tex);
2565                                         mtex->object= newlibadr(fd, wrld->id.lib, mtex->object);
2566                                 }
2567                         }
2568                         
2569                         lib_link_scriptlink(fd, &wrld->id, &wrld->scriptlink);
2570                         
2571                         wrld->id.flag -= LIB_NEEDLINK;
2572                 }
2573                 wrld= wrld->id.next;
2574         }
2575 }
2576
2577 static void direct_link_world(FileData *fd, World *wrld)
2578 {
2579         int a;
2580
2581         wrld->adt= newdataadr(fd, wrld->adt);
2582         direct_link_animdata(fd, wrld->adt);
2583         
2584         direct_link_scriptlink(fd, &wrld->scriptlink);
2585
2586         for(a=0; a<MAX_MTEX; a++) {
2587                 wrld->mtex[a]= newdataadr(fd, wrld->mtex[a]);
2588         }
2589         wrld->preview = direct_link_preview_image(fd, wrld->preview);
2590 }
2591
2592
2593 /* ************ READ VFONT ***************** */
2594
2595 static void lib_link_vfont(FileData *fd, Main *main)
2596 {
2597         VFont *vf;
2598
2599         vf= main->vfont.first;
2600         while(vf) {
2601                 if(vf->id.flag & LIB_NEEDLINK) {
2602                         vf->id.flag -= LIB_NEEDLINK;
2603                 }
2604                 vf= vf->id.next;
2605         }
2606 }
2607
2608 static void direct_link_vfont(FileData *fd, VFont *vf)
2609 {
2610         vf->data= NULL;
2611         vf->packedfile= direct_link_packedfile(fd, vf->packedfile);
2612 }
2613
2614 /* ************ READ TEXT ****************** */
2615
2616 static void lib_link_text(FileData *fd, Main *main)
2617 {
2618         Text *text;
2619
2620         text= main->text.first;
2621         while(text) {
2622                 if(text->id.flag & LIB_NEEDLINK) {
2623                         text->id.flag -= LIB_NEEDLINK;
2624                 }
2625                 text= text->id.next;
2626         }
2627 }
2628
2629 static void direct_link_text(FileData *fd, Text *text)
2630 {
2631         TextLine *ln;
2632
2633         text->name= newdataadr(fd, text->name);
2634
2635         text->undo_pos= -1;
2636         text->undo_len= TXT_INIT_UNDO;
2637         text->undo_buf= MEM_mallocN(text->undo_len, "undo buf");
2638
2639         text->compiled= NULL;
2640
2641 /*
2642         if(text->flags & TXT_ISEXT) {
2643                 reopen_text(text);
2644         } else {
2645 */
2646
2647         link_list(fd, &text->lines);
2648         link_list(fd, &text->markers);
2649
2650         text->curl= newdataadr(fd, text->curl);
2651         text->sell= newdataadr(fd, text->sell);
2652
2653         ln= text->lines.first;
2654         while(ln) {
2655                 ln->line= newdataadr(fd, ln->line);
2656                 ln->format= NULL;
2657                 
2658                 if (ln->len != (int) strlen(ln->line)) {
2659                         printf("Error loading text, line lengths differ\n");
2660                         ln->len = strlen(ln->line);
2661                 }
2662
2663                 ln= ln->next;
2664         }
2665
2666         text->flags = (text->flags) & ~TXT_ISEXT;
2667
2668         text->id.us= 1;
2669 }
2670
2671 /* ************ READ IMAGE ***************** */
2672
2673 static void lib_link_image(FileData *fd, Main *main)
2674 {
2675         Image *ima;
2676
2677         ima= main->image.first;
2678         while (ima) {
2679                 if(ima->id.flag & LIB_NEEDLINK) {
2680                         if (ima->id.properties) IDP_LibLinkProperty(ima->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2681
2682                         ima->id.flag -= LIB_NEEDLINK;
2683                 }
2684                 ima= ima->id.next;
2685         }
2686 }
2687
2688 static void link_ibuf_list(FileData *fd, ListBase *lb)
2689 {
2690         Link *ln, *prev;
2691         
2692         if(lb->first==NULL) return;
2693         
2694         lb->first= newimaadr(fd, lb->first);
2695         ln= lb->first;
2696         prev= NULL;
2697         while(ln) {
2698                 ln->next= newimaadr(fd, ln->next);
2699                 ln->prev= prev;
2700                 prev= ln;
2701                 ln= ln->next;
2702         }
2703         lb->last= prev;
2704 }
2705
2706 static void direct_link_image(FileData *fd, Image *ima)
2707 {
2708         /* for undo system, pointers could be restored */
2709         if(fd->imamap)
2710                 link_ibuf_list(fd, &ima->ibufs);
2711         else
2712                 ima->ibufs.first= ima->ibufs.last= NULL;
2713         
2714         /* if not restored, we keep the binded opengl index */
2715         if(ima->ibufs.first==NULL) {
2716                 ima->bindcode= 0;
2717                 ima->gputexture= NULL;
2718         }
2719         
2720         ima->anim= NULL;
2721         ima->rr= NULL;
2722         ima->repbind= NULL;
2723         ima->render_text= newdataadr(fd, ima->render_text);
2724         
2725         ima->packedfile = direct_link_packedfile(fd, ima->packedfile);
2726         ima->preview = direct_link_preview_image(fd, ima->preview);
2727         ima->ok= 1;
2728 }
2729
2730
2731 /* ************ READ CURVE ***************** */
2732
2733 static void lib_link_curve(FileData *fd, Main *main)
2734 {
2735         Curve *cu;
2736         int a;
2737
2738         cu= main->curve.first;
2739         while(cu) {
2740                 if(cu->id.flag & LIB_NEEDLINK) {
2741                         if(cu->adt) lib_link_animdata(fd, &cu->id, cu->adt);
2742
2743                         for(a=0; a<cu->totcol; a++) cu->mat[a]= newlibadr_us(fd, cu->id.lib, cu->mat[a]);
2744
2745                         cu->bevobj= newlibadr(fd, cu->id.lib, cu->bevobj);
2746                         cu->taperobj= newlibadr(fd, cu->id.lib, cu->taperobj);
2747                         cu->textoncurve= newlibadr(fd, cu->id.lib, cu->textoncurve);
2748                         cu->vfont= newlibadr_us(fd, cu->id.lib, cu->vfont);
2749                         cu->vfontb= newlibadr_us(fd, cu->id.lib, cu->vfontb);                   
2750                         cu->vfonti= newlibadr_us(fd, cu->id.lib, cu->vfonti);
2751                         cu->vfontbi= newlibadr_us(fd, cu->id.lib, cu->vfontbi);
2752
2753                         cu->ipo= newlibadr_us(fd, cu->id.lib, cu->ipo); // XXX depreceated - old animation system
2754                         cu->key= newlibadr_us(fd, cu->id.lib, cu->key);
2755
2756                         cu->id.flag -= LIB_NEEDLINK;
2757                 }
2758                 cu= cu->id.next;
2759         }
2760 }
2761
2762
2763 static void switch_endian_knots(Nurb *nu)
2764 {
2765         int len;
2766
2767         if(nu->knotsu) {
2768                 len= KNOTSU(nu);
2769                 while(len--) {
2770                         SWITCH_INT(nu->knotsu[len]);
2771                 }
2772         }
2773         if(nu->knotsv) {
2774                 len= KNOTSV(nu);
2775                 while(len--) {
2776                         SWITCH_INT(nu->knotsv[len]);
2777                 }
2778         }
2779 }
2780
2781 static void direct_link_curve(FileData *fd, Curve *cu)
2782 {
2783         Nurb *nu;
2784         TextBox *tb;
2785         
2786         cu->adt= newdataadr(fd, cu->adt);
2787         direct_link_animdata(fd, cu->adt);
2788         
2789         cu->mat= newdataadr(fd, cu->mat);
2790         test_pointer_array(fd, (void **)&cu->mat);
2791         cu->str= newdataadr(fd, cu->str);
2792         cu->strinfo= newdataadr(fd, cu->strinfo);       
2793         cu->tb= newdataadr(fd, cu->tb);
2794
2795         if(cu->vfont==0) link_list(fd, &(cu->nurb));
2796         else {
2797                 cu->nurb.first=cu->nurb.last= 0;
2798
2799                 tb= MEM_callocN(MAXTEXTBOX*sizeof(TextBox), "TextBoxread");
2800                 if (cu->tb) {
2801                         memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox));
2802                         MEM_freeN(cu->tb);
2803                         cu->tb= tb;                     
2804                 } else {
2805                         cu->totbox = 1;
2806                         cu->actbox = 1;
2807                         cu->tb = tb;
2808                         cu->tb[0].w = cu->linewidth;
2809                 }               
2810                 if (cu->wordspace == 0.0) cu->wordspace = 1.0;
2811         }
2812
2813         cu->bev.first=cu->bev.last= NULL;
2814         cu->disp.first=cu->disp.last= NULL;
2815         cu->editnurb= NULL;
2816         cu->lastselbp= NULL;
2817         cu->path= NULL;
2818         cu->editfont= NULL;
2819         
2820         nu= cu->nurb.first;
2821         while(nu) {
2822                 nu->bezt= newdataadr(fd, nu->bezt);
2823                 nu->bp= newdataadr(fd, nu->bp);
2824                 nu->knotsu= newdataadr(fd, nu->knotsu);
2825                 nu->knotsv= newdataadr(fd, nu->knotsv);
2826                 if (cu->vfont==0) nu->charidx= nu->mat_nr;
2827
2828                 if(fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
2829                         switch_endian_knots(nu);
2830                 }
2831
2832                 nu= nu->next;
2833         }
2834         cu->bb= NULL;
2835 }
2836
2837 /* ************ READ TEX ***************** */
2838
2839 static void lib_link_texture(FileData *fd, Main *main)
2840 {
2841         Tex *tex;
2842
2843         tex= main->tex.first;
2844         while(tex) {
2845                 if(tex->id.flag & LIB_NEEDLINK) {
2846                         if(tex->adt) lib_link_animdata(fd, &tex->id, tex->adt);
2847
2848                         tex->ima= newlibadr_us(fd, tex->id.lib, tex->ima);
2849                         tex->ipo= newlibadr_us(fd, tex->id.lib, tex->ipo);
2850                         if(tex->env) tex->env->object= newlibadr(fd, tex->id.lib, tex->env->object);
2851
2852                         if(tex->nodetree)
2853                                 lib_link_ntree(fd, &tex->id, tex->nodetree);
2854                         
2855                         tex->id.flag -= LIB_NEEDLINK;
2856                 }
2857                 tex= tex->id.next;
2858         }
2859 }
2860
2861 static void direct_link_texture(FileData *fd, Tex *tex)
2862 {
2863         tex->adt= newdataadr(fd, tex->adt);
2864         direct_link_animdata(fd, tex->adt);
2865         
2866         tex->plugin= newdataadr(fd, tex->plugin);
2867         if(tex->plugin) {
2868                 tex->plugin->handle= 0;
2869                 open_plugin_tex(tex->plugin);
2870                 /* initialize data for this instance, if an initialization
2871                  * function exists.
2872                  */
2873                 if (tex->plugin->instance_init)
2874                         tex->plugin->instance_init((void *) tex->plugin->data);
2875         }
2876         tex->coba= newdataadr(fd, tex->coba);
2877         tex->env= newdataadr(fd, tex->env);
2878         if(tex->env) {
2879                 tex->env->ima= NULL;
2880                 memset(tex->env->cube, 0, 6*sizeof(void *));
2881                 tex->env->ok= 0;
2882         }
2883         
2884         tex->nodetree= newdataadr(fd, tex->nodetree);
2885         if(tex->nodetree)
2886                 direct_link_nodetree(fd, tex->nodetree);
2887         
2888         tex->preview = direct_link_preview_image(fd, tex->preview);
2889
2890         tex->iuser.ok= 1;
2891 }
2892
2893
2894
2895 /* ************ READ MATERIAL ***************** */
2896
2897 static void lib_link_material(FileData *fd, Main *main)
2898 {
2899         Material *ma;
2900         MTex *mtex;
2901         int a;
2902
2903         ma= main->mat.first;
2904         while(ma) {
2905                 if(ma->id.flag & LIB_NEEDLINK) {
2906                         if(ma->adt) lib_link_animdata(fd, &ma->id, ma->adt);
2907
2908                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
2909                         of library blocks that implement this.*/
2910                         if (ma->id.properties) IDP_LibLinkProperty(ma->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
2911
2912                         ma->ipo= newlibadr_us(fd, ma->id.lib, ma->ipo);
2913                         ma->group= newlibadr_us(fd, ma->id.lib, ma->group);
2914                         
2915                         for(a=0; a<MAX_MTEX; a++) {
2916                                 mtex= ma->mtex[a];
2917                                 if(mtex) {
2918                                         mtex->tex= newlibadr_us(fd, ma->id.lib, mtex->tex);
2919                                         mtex->object= newlibadr(fd, ma->id.lib, mtex->object);
2920                                 }
2921                         }
2922                         lib_link_scriptlink(fd, &ma->id, &ma->scriptlink);
2923                         
2924                         if(ma->nodetree)
2925                                 lib_link_ntree(fd, &ma->id, ma->nodetree);
2926                         
2927                         ma->id.flag -= LIB_NEEDLINK;
2928                 }
2929                 ma= ma->id.next;
2930         }
2931 }
2932
2933 static void direct_link_material(FileData *fd, Material *ma)
2934 {
2935         int a;
2936
2937         ma->adt= newdataadr(fd, ma->adt);
2938         direct_link_animdata(fd, ma->adt);
2939         
2940         for(a=0; a<MAX_MTEX; a++) {
2941                 ma->mtex[a]= newdataadr(fd, ma->mtex[a]);
2942         }
2943
2944         ma->ramp_col= newdataadr(fd, ma->ramp_col);
2945         ma->ramp_spec= newdataadr(fd, ma->ramp_spec);
2946         
2947         direct_link_scriptlink(fd, &ma->scriptlink);
2948         
2949         ma->nodetree= newdataadr(fd, ma->nodetree);
2950         if(ma->nodetree)
2951                 direct_link_nodetree(fd, ma->nodetree);
2952
2953         ma->preview = direct_link_preview_image(fd, ma->preview);
2954         ma->gpumaterial.first = ma->gpumaterial.last = NULL;
2955 }
2956
2957 /* ************ READ PARTICLE SETTINGS ***************** */
2958
2959 static void direct_link_pointcache(FileData *fd, PointCache *cache)
2960 {
2961         if((cache->flag & PTCACHE_DISK_CACHE)==0) {
2962                 PTCacheMem *pm;
2963
2964                 link_list(fd, &cache->mem_cache);
2965
2966                 pm = cache->mem_cache.first;
2967
2968                 for(; pm; pm=pm->next)
2969                         pm->data = newdataadr(fd, pm->data);
2970         }
2971         else
2972                 cache->mem_cache.first = cache->mem_cache.last = NULL;
2973
2974         cache->flag &= ~(PTCACHE_SIMULATION_VALID|PTCACHE_BAKE_EDIT_ACTIVE);
2975         cache->simframe= 0;
2976 }
2977
2978 static void lib_link_particlesettings(FileData *fd, Main *main)
2979 {
2980         ParticleSettings *part;
2981
2982         part= main->particle.first;
2983         while(part) {
2984                 if(part->id.flag & LIB_NEEDLINK) {
2985                         if (part->adt) lib_link_animdata(fd, &part->id, part->adt);
2986                         part->ipo= newlibadr_us(fd, part->id.lib, part->ipo); // XXX depreceated - old animation system
2987                         
2988                         part->dup_ob = newlibadr(fd, part->id.lib, part->dup_ob);
2989                         part->dup_group = newlibadr(fd, part->id.lib, part->dup_group);
2990                         part->eff_group = newlibadr(fd, part->id.lib, part->eff_group);
2991                         part->bb_ob = newlibadr(fd, part->id.lib, part->bb_ob);
2992                         part->id.flag -= LIB_NEEDLINK;
2993                 }
2994                 part= part->id.next;
2995         }
2996 }
2997
2998 static void direct_link_particlesettings(FileData *fd, ParticleSettings *part)
2999 {
3000         part->adt= newdataadr(fd, part->adt);
3001         part->pd= newdataadr(fd, part->pd);
3002         part->pd2= newdataadr(fd, part->pd2);
3003 }
3004
3005 static void lib_link_particlesystems(FileData *fd, Object *ob, ID *id, ListBase *particles)
3006 {
3007         ParticleSystem *psys, *psysnext;
3008         int a;
3009
3010         for(psys=particles->first; psys; psys=psysnext){
3011                 ParticleData *pa;
3012                 
3013                 psysnext= psys->next;
3014                 
3015                 psys->part = newlibadr_us(fd, id->lib, psys->part);
3016                 if(psys->part) {
3017                         KeyedParticleTarget *kpt = psys->keyed_targets.first;
3018
3019                         for(; kpt; kpt=kpt->next)
3020                                 kpt->ob=newlibadr(fd, id->lib, kpt->ob);
3021
3022                         psys->target_ob = newlibadr(fd, id->lib, psys->target_ob);
3023
3024                         for(a=0,pa=psys->particles; a<psys->totpart; a++,pa++){
3025                                 pa->stick_ob=newlibadr(fd, id->lib, pa->stick_ob);
3026                         }
3027
3028
3029                 }
3030                 else {
3031                         /* particle modifier must be removed before particle system */
3032                         ParticleSystemModifierData *psmd= psys_get_modifier(ob,psys);
3033                         BLI_remlink(&ob->modifiers, psmd);
3034                         modifier_free((ModifierData *)psmd);
3035
3036                         BLI_remlink(particles, psys);
3037                         MEM_freeN(psys);
3038                 }
3039         }
3040 }
3041 static void direct_link_particlesystems(FileData *fd, ListBase *particles)
3042 {
3043         ParticleSystem *psys;
3044         int a;
3045
3046         for(psys=particles->first; psys; psys=psys->next) {
3047                 psys->particles=newdataadr(fd,psys->particles);
3048                 if(psys->particles && psys->particles->hair){
3049                         ParticleData *pa = psys->particles;
3050                         for(a=0; a<psys->totpart; a++, pa++)
3051                                 pa->hair=newdataadr(fd,pa->hair);
3052                 }
3053                 if(psys->particles && psys->particles->keys){
3054                         ParticleData *pa = psys->particles;
3055                         for(a=0; a<psys->totpart; a++, pa++) {
3056                                 pa->keys= NULL;
3057                                 pa->totkey= 0;
3058                         }
3059
3060                         psys->flag &= ~PSYS_KEYED;
3061                 }
3062                 psys->child=newdataadr(fd,psys->child);
3063                 psys->effectors.first=psys->effectors.last=0;
3064
3065                 psys->soft= newdataadr(fd, psys->soft);
3066                 if(psys->soft) {
3067                         SoftBody *sb = psys->soft;
3068                         sb->particles = psys;
3069                         sb->bpoint= NULL;       // init pointers so it gets rebuilt nicely
3070                         sb->bspring= NULL;
3071                         sb->scratch= NULL;
3072
3073                         sb->pointcache= newdataadr(fd, sb->pointcache);
3074                         if(sb->pointcache)
3075                                 direct_link_pointcache(fd, sb->pointcache);
3076                 }
3077
3078                 link_list(fd, &psys->keyed_targets);
3079
3080                 psys->edit = 0;
3081                 psys->free_edit = NULL;
3082                 psys->pathcache = 0;
3083                 psys->childcache = 0;
3084                 psys->pathcachebufs.first = psys->pathcachebufs.last = 0;
3085                 psys->childcachebufs.first = psys->childcachebufs.last = 0;
3086                 psys->reactevents.first = psys->reactevents.last = 0;
3087
3088                 psys->pointcache= newdataadr(fd, psys->pointcache);
3089                 if(psys->pointcache)
3090                         direct_link_pointcache(fd, psys->pointcache);
3091         }
3092         return;
3093 }
3094
3095 /* ************ READ MESH ***************** */
3096
3097 static void lib_link_mtface(FileData *fd, Mesh *me, MTFace *mtface, int totface)
3098 {
3099         MTFace *tf= mtface;
3100         int i;
3101
3102         for (i=0; i<totface; i++, tf++) {
3103                 tf->tpage= newlibadr(fd, me->id.lib, tf->tpage);
3104                 if(tf->tpage && tf->tpage->id.us==0)
3105                         tf->tpage->id.us= 1;
3106         }
3107 }
3108
3109 static void lib_link_customdata_mtface(FileData *fd, Mesh *me, CustomData *fdata, int totface)
3110 {
3111         int i;  
3112         for(i=0; i<fdata->totlayer; i++) {
3113                 CustomDataLayer *layer = &fdata->layers[i];
3114                 
3115                 if(layer->type == CD_MTFACE)
3116                         lib_link_mtface(fd, me, layer->data, totface);
3117         }
3118
3119 }
3120
3121 static void lib_link_mesh(FileData *fd, Main *main)
3122 {
3123         Mesh *me;
3124
3125         me= main->mesh.first;
3126         while(me) {
3127                 if(me->id.flag & LIB_NEEDLINK) {
3128                         int i;
3129
3130                         /*Link ID Properties -- and copy this comment EXACTLY for easy finding
3131                         of library blocks that implement this.*/
3132                         if (me->id.properties) IDP_LibLinkProperty(me->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
3133
3134                         /* this check added for python created meshes */
3135                         if(me->mat) {
3136                                 for(i=0; i<me->totcol; i++) {
3137                                         me->mat[i]= newlibadr_us(fd, me->id.lib, me->mat[i]);
3138                                 }
3139                         }
3140                         else me->totcol= 0;
3141
3142                         me->ipo= newlibadr_us(fd, me->id.lib, me->ipo);
3143                         me->key= newlibadr_us(fd, me->id.lib, me->key);
3144                         me->texcomesh= newlibadr_us(fd, me->id.lib, me->texcomesh);
3145
3146                         lib_link_customdata_mtface(fd, me, &me->fdata, me->totface);
3147                         if(me->mr && me->mr->levels.first)
3148                                 lib_link_customdata_mtface(fd, me, &me->mr->fdata,
3149                                                            ((MultiresLevel*)me->mr->levels.first)->totface);
3150
3151                         me->id.flag -= LIB_NEEDLINK;
3152                 }
3153                 me= me->id.next;
3154         }
3155 }
3156
3157 static void direct_link_dverts(FileData *fd, int count, MDeformVert *mdverts)
3158 {
3159         int     i;
3160
3161         if (!mdverts)
3162                 return;
3163
3164         for (i=0; i<count; i++) {
3165                 mdverts[i].dw=newdataadr(fd, mdverts[i].dw);
3166                 if (!mdverts[i].dw)
3167                         mdverts[i].totweight=0;
3168         }
3169 }
3170
3171 static void direct_link_mdisps(FileData *fd, int count, MDisps *mdisps)
3172 {
3173         if(mdisps) {
3174                 int i;
3175
3176                 for(i = 0; i < count; ++i) {
3177                         mdisps[i].disps = newdataadr(fd, mdisps[i].disps);
3178                         if(!mdisps[i].disps)
3179                                 mdisps[i].totdisp = 0;
3180                 }
3181         }       
3182 }
3183
3184 static void direct_link_customdata(FileData *fd, CustomData *data, int count)
3185 {
3186         int i = 0;
3187
3188         data->layers= newdataadr(fd, data->layers);
3189
3190         while (i < data->totlayer) {
3191                 CustomDataLayer *layer = &data->layers[i];
3192
3193                 if (CustomData_verify_versions(data, i)) {
3194                         layer->data = newdataadr(fd, layer->data);
3195                         if(layer->type == CD_MDISPS)
3196                                 direct_link_mdisps(fd, count, layer->data);
3197                         i++;
3198                 }
3199         }
3200 }
3201
3202 static void direct_link_mesh(FileData *fd, Mesh *mesh)
3203 {
3204         mesh->mat= newdataadr(fd, mesh->mat);
3205         test_pointer_array(fd, (void **)&mesh->mat);
3206
3207         mesh->mvert= newdataadr(fd, mesh->mvert);
3208         mesh->medge= newdataadr(fd, mesh->medge);
3209         mesh->mface= newdataadr(fd, mesh->mface);
3210         mesh->tface= newdataadr(fd, mesh->tface);
3211         mesh->mtface= newdataadr(fd, mesh->mtface);
3212         mesh->mcol= newdataadr(fd, mesh->mcol);
3213         mesh->msticky= newdataadr(fd, mesh->msticky);
3214         mesh->dvert= newdataadr(fd, mesh->dvert);
3215         
3216         /* Partial-mesh visibility (do this before using totvert, totface, or totedge!) */
3217         mesh->pv= newdataadr(fd, mesh->pv);
3218         if(mesh->pv) {
3219                 mesh->pv->vert_map= newdataadr(fd, mesh->pv->vert_map);
3220                 mesh->pv->edge_map= newdataadr(fd, mesh->pv->edge_map);
3221                 mesh->pv->old_faces= newdataadr(fd, mesh->pv->old_faces);
3222                 mesh->pv->old_edges= newdataadr(fd, mesh->pv->old_edges);
3223         }
3224
3225         /* normally direct_link_dverts should be called in direct_link_customdata,
3226            but for backwards compat in do_versions to work we do it here */
3227         direct_link_dverts(fd, mesh->pv ? mesh->pv->totvert : mesh->totvert, mesh->dvert);
3228
3229         direct_link_customdata(fd, &mesh->vdata, mesh->pv ? mesh->pv->totvert : mesh->totvert);
3230         direct_link_customdata(fd, &mesh->edata, mesh->pv ? mesh->pv->totedge : mesh->totedge);
3231         direct_link_customdata(fd, &mesh->fdata, mesh->pv ? mesh->pv->totface : mesh->totface);
3232
3233         mesh->bb= NULL;
3234         mesh->mselect = NULL;
3235         mesh->edit_mesh= NULL;
3236         
3237         /* Multires data */
3238         mesh->mr= newdataadr(fd, mesh->mr);
3239         if(mesh->mr) {
3240                 MultiresLevel *lvl;
3241                 
3242                 link_list(fd, &mesh->mr->levels);
3243                 lvl= mesh->mr->levels.first;
3244                 
3245                 direct_link_customdata(fd, &mesh->mr->vdata, lvl->totvert);
3246                 direct_link_dverts(fd, lvl->totvert, CustomData_get(&mesh->mr->vdata, 0, CD_MDEFORMVERT));
3247                 direct_link_customdata(fd, &mesh->mr->fdata, lvl->totface);
3248                 
3249                 mesh->mr->edge_flags= newdataadr(fd, mesh->mr->edge_flags);
3250                 mesh->mr->edge_creases= newdataadr(fd, mesh->mr->edge_creases);
3251
3252                 mesh->mr->verts = newdataadr(fd, mesh->mr->verts);
3253                         
3254                 for(; lvl; lvl= lvl->next) {
3255                         lvl->verts= newdataadr(fd, lvl->verts);
3256                         lvl->faces= newdataadr(fd, lvl->faces);
3257                         lvl->edges= newdataadr(fd, lvl->edges);
3258                         lvl->colfaces= newdataadr(fd, lvl->colfaces);
3259                 }
3260         }
3261
3262         /* Gracefully handle corrupted mesh */
3263         if(mesh->mr && !mesh->mr->verts) {
3264                 /* If totals match, simply load the current mesh verts into multires */
3265                 if(mesh->totvert == ((MultiresLevel*)mesh->mr->levels.last)->totvert)
3266                         mesh->mr->verts = MEM_dupallocN(mesh->mvert);
3267                 else {
3268                         /* Otherwise, we can't recover the data, silently remove multires */
3269                         multires_free(mesh->mr);
3270                         mesh->mr = NULL;
3271                 }
3272         }
3273         
3274         if((fd->flags & FD_FLAGS_SWITCH_ENDIAN) && mesh->tface) {
3275                 TFace *tf= mesh->tface;
3276                 unsigned int i;
3277
3278                 for (i=0; i< (mesh->pv ? mesh->pv->totface : mesh->totface); i++, tf++) {
3279                         SWITCH_INT(tf->col[0]);
3280                         SWITCH_INT(tf->col[1]);
3281                         SWITCH_INT(tf->col[2]);
3282                         SWITCH_INT(tf->col[3]);
3283                 }
3284         }
3285 }