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