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