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