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