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