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