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