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