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