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