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