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