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