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