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