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