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