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