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