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