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