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