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