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